2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 YUI.add('history', function(Y) {
14 * The Browser History Utility provides the ability to use the back/forward
15 * navigation buttons in a DHTML application. It also allows a DHTML
16 * application to be bookmarked in a specific state.
18 * This utility requires the following static markup:
20 * <iframe id="yui-history-iframe" src="path-to-real-asset-in-same-domain"></iframe>
21 * <input id="yui-history-field" type="hidden">
27 * This class represents an instance of the browser history utility.
33 var win = Y.config.win,
36 encode = encodeURIComponent,
37 decode = decodeURIComponent,
41 // YUI Compressor helper...
42 E_MISSING_OR_INVALID_ARG = 'Missing or invalid argument',
44 // Regular expression used to parse query strings and such.
45 REGEXP = /([^=&]+)=([^&]*)/g,
47 // A few private variables...
52 * @event history:ready
53 * @description Fires when the browser history utility is ready
56 EV_HISTORY_READY = 'history:ready',
59 * @event history:globalStateChange
60 * @description Fires when the global state of the page has changed (that is,
61 * when the state of at least one browser history module has changed)
64 EV_HISTORY_GLOBAL_STATE_CHANGE = 'history:globalStateChange',
67 * @event history:moduleStateChange
68 * @description Fires when the state of a history module object has changed
71 EV_HISTORY_MODULE_STATE_CHANGE = 'history:moduleStateChange';
74 if (!YUI.Env.history) {
76 YUI.Env.history = G = {
78 // Flag used to tell whether the history utility is ready to be used.
81 // List of registered modules.
84 // INPUT field (with type="hidden" or type="text") or TEXTAREA.
85 // This field keeps the value of the initial state, current state
86 // the list of all states across pages within a single browser session.
89 // Hidden IFrame used to store the browsing history on IE6/7.
96 * Returns the portion of the hash after the '#' symbol.
98 * @return {string} The hash portion of the document's location
102 // We branch at runtime for Gecko since window.location.hash in Gecko
103 // returns a decoded string, and we want all encoding untouched.
104 _getHash = function () {
105 var m = /#(.*)$/.exec(win.location.href);
106 return m && m[1] ? m[1] : '';
109 _getHash = function () {
110 return win.location.hash.substr(1);
115 * Stores the initial state and current state for all registered modules
116 * in the (hidden) form field specified during initialization.
117 * @method _storeStates
120 function _storeStates() {
121 var initialStates = [], currentStates = [];
123 Y.Object.each(G._modules, function (module, moduleId) {
124 initialStates.push(moduleId + '=' + module.initialState);
125 currentStates.push(moduleId + '=' + module.currentState);
128 G._stateField.set('value', initialStates.join('&') + '|' + currentStates.join('&'));
132 * Sets the new currentState attribute of all modules depending on the new fully
133 * qualified state. Also notifies the modules which current state has changed.
134 * @method _handleFQStateChange
135 * @param {string} fqstate fully qualified state
138 function _handleFQStateChange(fqstate) {
139 var m, states = [], globalStateChanged = false;
143 REGEXP.lastIndex = 0;
144 while ((m = REGEXP.exec(fqstate))) {
148 Y.Object.each(G._modules, function (module, moduleId) {
149 var currentState = states[moduleId];
151 if (!currentState || module.currentState !== currentState) {
152 module.currentState = currentState || module.initialState;
153 module.fire(EV_HISTORY_MODULE_STATE_CHANGE, decode(module.currentState));
154 globalStateChanged = true;
160 Y.Object.each(G._modules, function (module, moduleId) {
161 if (module.currentState !== module.initialState) {
162 module.currentState = module.initialState;
163 module.fire(EV_HISTORY_MODULE_STATE_CHANGE, decode(module.currentState));
164 globalStateChanged = true;
169 if (globalStateChanged) {
170 H.fire(EV_HISTORY_GLOBAL_STATE_CHANGE);
175 * Update the IFrame with our new state.
176 * @method _updateIFrame
178 * @return {boolean} true if successful. false otherwise.
180 function _updateIFrame(fqstate) {
183 html = '<html><body>' + fqstate + '</body></html>';
186 doc = G._historyIFrame.get('contentWindow.document');
187 // TODO: The Node API should expose these methods in the very near future...
189 doc.invoke('write', html, '', '', '', ''); // see bug #2447937
198 * Periodically checks whether our internal IFrame is ready to be used
199 * @method _checkIframeLoaded
202 function _checkIframeLoaded() {
203 var elem, fqstate, hash;
205 if (!G._historyIFrame.get('contentWindow.document')) {
206 // Check again in 10 msec...
207 setTimeout(_checkIframeLoaded, 10);
211 // Periodically check whether a navigate operation has been
212 // requested on the main window. This will happen when
213 // History.navigate has been called or after the user
214 // has hit the back/forward button.
215 elem = G._historyIFrame.get('contentWindow.document.body');
216 // We must use innerText, and not innerHTML because our string contains
217 // the "&" character (which would end up being escaped as "&") and
218 // the string comparison would fail...
219 fqstate = elem ? elem.get('innerText') : null;
223 setInterval(function () {
224 var newfqstate, states, newHash;
226 elem = G._historyIFrame.get('contentWindow.document.body');
227 // See my comment above about using innerText instead of innerHTML...
228 newfqstate = elem ? elem.get('innerText') : null;
230 newHash = _getHash();
232 if (newfqstate !== fqstate) {
234 fqstate = newfqstate;
235 _handleFQStateChange(fqstate);
239 Y.Object.each(G._modules, function (module, moduleId) {
240 states.push(moduleId + '=' + module.initialState);
242 newHash = states.join('&');
247 // Allow the state to be bookmarked by setting the top window's
248 // URL fragment identifier. Note that here, we are on IE < 8
249 // which does not touch the browser history when changing the
250 // hash (unlike all the other browsers).
251 win.location.hash = hash = newHash;
255 } else if (newHash !== hash) {
257 // The hash has changed. The user might have clicked on a link,
258 // or modified the URL directly, or opened the same application
259 // bookmarked in a specific state using a bookmark. However, we
260 // know the hash change was not caused by a hit on the back or
261 // forward buttons, or by a call to navigate() (because it would
262 // have been handled above) We must handle these cases, which is
263 // why we also need to keep track of hash changes on IE!
265 // Note that IE6 has some major issues with this kind of user
266 // interaction (the history stack gets completely messed up)
267 // but it seems to work fine on IE7.
271 // Now, store a new history entry. The following will cause the
272 // code above to execute, doing all the dirty work for us...
273 _updateIFrame(newHash);
279 H.fire(EV_HISTORY_READY);
283 * Finish up the initialization of the browser utility library.
284 * @method _initialize
287 function _initialize() {
288 var m, parts, moduleId, module, initialState, currentState, hash;
290 // Decode the content of our storage field...
291 parts = G._stateField.get('value').split('|');
293 if (parts.length > 1) {
295 REGEXP.lastIndex = 0;
296 while ((m = REGEXP.exec(parts[0]))) {
299 module = G._modules[moduleId];
301 module.initialState = initialState;
305 REGEXP.lastIndex = 0;
306 while ((m = REGEXP.exec(parts[1]))) {
309 module = G._modules[moduleId];
311 module.currentState = currentState;
316 // IE8 in IE7 mode defines window.onhashchange, but never fires it...
317 if (!Y.Lang.isUndefined(win.onhashchange) &&
318 (Y.Lang.isUndefined(doc.documentMode) || doc.documentMode > 7)) {
320 // The HTML5 way of handling DHTML history...
321 win.onhashchange = function () {
322 var hash = _getHash();
323 _handleFQStateChange(hash);
328 H.fire(EV_HISTORY_READY);
330 } else if (_useIFrame) {
332 // IE < 8 or IE8 in quirks mode or IE7 standards mode
333 _checkIframeLoaded();
337 // Periodically check whether a navigate operation has been
338 // requested on the main window. This will happen when
339 // History.navigate has been called, or after the user
340 // has hit the back/forward button.
342 // On Gecko and Opera, we just need to watch the hash...
345 setInterval(function () {
346 var newHash = _getHash();
347 if (newHash !== hash) {
349 _handleFQStateChange(hash);
355 H.fire(EV_HISTORY_READY);
363 * Registers a new module.
365 * @param {string} moduleId Non-empty string uniquely identifying the
366 * module you wish to register.
367 * @param {string} initialState The initial state of the specified
368 * module corresponding to its earliest history entry.
369 * @return {History.Module} The newly registered module
371 register: function (moduleId, initialState) {
374 if (!Y.Lang.isString(moduleId) || Y.Lang.trim(moduleId) === '' || !Y.Lang.isString(initialState)) {
375 throw new Error(E_MISSING_OR_INVALID_ARG);
378 moduleId = encode(moduleId);
379 initialState = encode(initialState);
381 if (G._modules[moduleId]) {
382 // The module seems to have already been registered.
386 // Note: A module CANNOT be registered once the browser history
387 // utility has been initialized. This is related to reading and
388 // writing state values from/to the input field. Relaxing this
389 // rule would potentially create situations rather complicated
395 module = new H.Module(moduleId, initialState);
396 G._modules[moduleId] = module;
401 * Initializes the Browser History Manager. Call this method
402 * from a script block located right after the opening body tag.
404 * @param {string|HTML Element} stateField <input type="hidden"> used
405 * to store application states. Must be in the static markup.
406 * @param {string|HTML Element} historyIFrame IFrame used to store
407 * the history (only required for IE6/7)
410 initialize: function (stateField, historyIFrame) {
414 // The browser history utility has already been initialized.
418 stateField = Y.get(stateField);
420 throw new Error(E_MISSING_OR_INVALID_ARG);
423 tagName = stateField.get('tagName').toUpperCase();
424 type = stateField.get('type');
426 if (tagName !== 'TEXTAREA' && (tagName !== 'INPUT' || type !== 'hidden' && type !== 'text')) {
427 throw new Error(E_MISSING_OR_INVALID_ARG);
430 // IE < 8 or IE8 in quirks mode or IE7 standards mode
431 if (Y.UA.ie && (Y.Lang.isUndefined(doc.documentMode) || doc.documentMode < 8)) {
433 historyIFrame = Y.get(historyIFrame);
434 if (!historyIFrame || historyIFrame.get('tagName').toUpperCase() !== 'IFRAME') {
435 throw new Error(E_MISSING_OR_INVALID_ARG);
439 if (Y.UA.opera && !Y.Lang.isUndefined(win.history.navigationMode)) {
440 // Disable Opera's fast back/forward navigation mode and put
441 // it in compatible mode. This makes anchor-based history
442 // navigation work after the page has been navigated away
443 // from and re-activated, at the cost of slowing down
444 // back/forward navigation to and from that page.
445 win.history.navigationMode = 'compatible';
448 G._stateField = stateField;
449 G._historyIFrame = historyIFrame;
451 Y.on('domready', _initialize);
456 * Stores a new entry in the browser history by changing the state of a registered module.
458 * @param {string} module Non-empty string representing your module.
459 * @param {string} state String representing the new state of the specified module.
460 * @return {boolean} Indicates whether the new state was successfully added to the history.
463 navigate: function (moduleId, state) {
466 if (!Y.Lang.isString(moduleId) || !Y.Lang.isString(state)) {
467 throw new Error(E_MISSING_OR_INVALID_ARG);
470 // The ncoding of module id and state takes place in mutiNavigate.
472 states[moduleId] = state;
474 return H.multiNavigate(states);
478 * Stores a new entry in the browser history by changing the state
479 * of several registered modules in one atomic operation.
480 * @method multiNavigate
481 * @param {object} states Associative array of module-state pairs to set simultaneously.
482 * @return {boolean} Indicates whether the new state was successfully added to the history.
485 multiNavigate: function (states) {
486 var newStates = [], fqstate, globalStateChanged = false;
492 Y.Object.each(G._modules, function (module, moduleId) {
493 var state, decodedModuleId = decode(moduleId);
495 if (!states.hasOwnProperty(decodedModuleId)) {
496 // The caller did not wish to modify the state of this
497 // module. We must however include it in fqstate!
498 state = module.currentState;
500 state = encode(states[decodedModuleId]);
501 if (state !== module.upcomingState) {
502 module.upcomingState = state;
503 globalStateChanged = true;
507 newStates.push(moduleId + '=' + state);
510 if (!globalStateChanged) {
511 // Nothing changed, so don't do anything.
515 fqstate = newStates.join('&');
518 return _updateIFrame(fqstate);
520 win.location.hash = fqstate;
526 * Returns the current state of the specified module.
527 * @method getCurrentState
528 * @param {string} moduleId Non-empty string representing your module.
529 * @return {string} The current state of the specified module.
532 getCurrentState: function (moduleId) {
535 if (!Y.Lang.isString(moduleId)) {
536 throw new Error(E_MISSING_OR_INVALID_ARG);
543 moduleId = encode(moduleId);
544 module = G._modules[moduleId];
549 return decode(module.currentState);
553 * Returns the state of a module according to the URL fragment
554 * identifier. This method is useful to initialize your modules
555 * if your application was bookmarked from a particular state.
556 * @method getBookmarkedState
557 * @param {string} moduleId Non-empty string representing your module.
558 * @return {string} The bookmarked state of the specified module.
561 getBookmarkedState: function (moduleId) {
564 if (!Y.Lang.isString(moduleId)) {
565 throw new Error(E_MISSING_OR_INVALID_ARG);
568 moduleId = encode(moduleId);
570 // Use location.href instead of location.hash which is already
571 // URL-decoded, which creates problems if the state value
572 // contained special characters...
573 h = win.location.href;
578 REGEXP.lastIndex = 0;
579 while ((m = REGEXP.exec(h))) {
580 if (m[1] === moduleId) {
590 * Returns the value of the specified query string parameter.
591 * This method is not used internally by the Browser History Manager.
592 * However, it is provided here as a helper since many applications
593 * using the Browser History Manager will want to read the value of
594 * url parameters to initialize themselves.
595 * @method getQueryStringParameter
596 * @param {string} paramName Name of the parameter we want to look up.
597 * @param {string} queryString Optional URL to look at. If not specified,
598 * this method uses the URL in the address bar.
599 * @return {string} The value of the specified parameter, or null.
602 getQueryStringParameter: function (paramName, url) {
605 url = url || win.location.href;
607 i = url.indexOf('?');
608 q = i >= 0 ? url.substr(i + 1) : url;
610 // Remove the hash if any
611 i = q.lastIndexOf('#');
612 q = i >= 0 ? q.substr(0, i) : q;
614 REGEXP.lastIndex = 0;
615 while ((m = REGEXP.exec(q))) {
616 if (m[1] === paramName) {
626 // Make Y.History an event target
627 Y.mix(H, Y.Event.Target.prototype);
628 Y.Event.Target.call(H);
632 * This class represents a browser history module.
633 * @class History.Module
635 * @param id {String} the module identifier
636 * @param initialState {String} the module's initial state
638 H.Module = function (id, initialState) {
640 Y.Event.Target.call(this);
643 * The module identifier
650 * The module's initial state
654 this.initialState = initialState;
657 * The module's current state
661 this.currentState = initialState;
664 * The module's upcoming state. There can be a slight delay between the
665 * time a state is changed, and the time a state change is detected.
666 * This property allows us to not fire the module state changed event
667 * multiple times, making client code simpler.
672 this.upcomingState = initialState;
675 Y.mix(H.Module, Y.Event.Target, false, null, 1);
680 }, '3.0.0' ,{skinnable:false, use:['event', 'node']});