2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('history-base', function(Y) {
11 * Provides browser history management functionality using a simple
12 * add/replace/get paradigm. This can be used to ensure that the browser's back
13 * and forward buttons work as the user expects and to provide bookmarkable URLs
14 * that return the user to the current application state, even in an Ajax
15 * application that doesn't perform full-page refreshes.
22 * Provides global state management backed by an object, but with no browser
23 * history integration. For actual browser history integration and back/forward
24 * support, use the history-html5 or history-hash modules.
27 * @submodule history-base
31 * @param {Object} config (optional) configuration object, which may contain
32 * zero or more of the following properties:
35 * <dt>initialState (Object)</dt>
37 * Initial state to set, as an object hash of key/value pairs. This will be
38 * merged into the current global state.
45 GlobalEnv = YUI.namespace('Env.History'),
49 docMode = doc.documentMode,
52 DEFAULT_OPTIONS = {merge: true},
53 EVT_CHANGE = 'change',
55 SRC_REPLACE = 'replace';
57 function HistoryBase() {
58 this._init.apply(this, arguments);
61 Y.augment(HistoryBase, Y.EventTarget, null, null, {
68 if (!GlobalEnv._state) {
69 GlobalEnv._state = {};
72 // -- Private Methods ----------------------------------------------------------
75 * Returns <code>true</code> if <i>value</i> is a simple object and not a
76 * function or an array.
78 * @method _isSimpleObject
79 * @param {mixed} value
83 function _isSimpleObject(value) {
84 return Lang.type(value) === 'object';
87 // -- Public Static Properties -------------------------------------------------
90 * Name of this component.
96 HistoryBase.NAME = 'historyBase';
99 * Constant used to identify state changes originating from the
100 * <code>add()</code> method.
107 HistoryBase.SRC_ADD = SRC_ADD;
110 * Constant used to identify state changes originating from the
111 * <code>replace()</code> method.
113 * @property SRC_REPLACE
118 HistoryBase.SRC_REPLACE = SRC_REPLACE;
121 * Whether or not this browser supports the HTML5 History API.
128 // All HTML5-capable browsers except Gecko 2+ (Firefox 4+) correctly return
129 // true for 'onpopstate' in win. In order to support Gecko 2, we fall back to a
130 // UA sniff for now. (current as of Firefox 4.0b2)
131 HistoryBase.html5 = !!(win.history && win.history.pushState &&
132 win.history.replaceState && ('onpopstate' in win || Y.UA.gecko >= 2));
135 * Whether or not this browser supports the <code>window.onhashchange</code>
136 * event natively. Note that even if this is <code>true</code>, you may
137 * still want to use HistoryHash's synthetic <code>hashchange</code> event
138 * since it normalizes implementation differences and fixes spec violations
139 * across various browsers.
141 * @property nativeHashChange
146 // Most browsers that support hashchange expose it on the window. Opera 10.6+
147 // exposes it on the document (but you can still attach to it on the window).
149 // IE8 supports the hashchange event, but only in IE8 Standards
150 // Mode. However, IE8 in IE7 compatibility mode still defines the
151 // event but never fires it, so we can't just detect the event. We also can't
152 // just UA sniff for IE8, since other browsers support this event as well.
153 HistoryBase.nativeHashChange = ('onhashchange' in win || 'onhashchange' in doc) &&
154 (!docMode || docMode > 7);
156 Y.mix(HistoryBase.prototype, {
157 // -- Initialization -------------------------------------------------------
160 * Initializes this HistoryBase instance. This method is called by the
164 * @param {Object} config configuration object
167 _init: function (config) {
171 * Configuration object provided by the user on instantiation, or an
172 * empty object if one wasn't provided.
179 config = this._config = config || {};
182 * Resolved initial state: a merge of the user-supplied initial state
183 * (if any) and any initial state provided by a subclass. This may
184 * differ from <code>_config.initialState</code>. If neither the config
185 * nor a subclass supplies an initial state, this property will be
188 * @property _initialState
193 initialState = this._initialState = this._initialState ||
194 config.initialState || null;
197 * Fired when the state changes. To be notified of all state changes
198 * regardless of the History or YUI instance that generated them,
199 * subscribe to this event on <code>Y.Global</code>. If you would rather
200 * be notified only about changes generated by this specific History
201 * instance, subscribe to this event on the instance.
203 * @event history:change
204 * @param {EventFacade} e Event facade with the following additional
208 * <dt>changed (Object)</dt>
210 * Object hash of state items that have been added or changed. The
211 * key is the item key, and the value is an object containing
212 * <code>newVal</code> and <code>prevVal</code> properties
213 * representing the values of the item both before and after the
214 * change. If the item was newly added, <code>prevVal</code> will be
215 * <code>undefined</code>.
218 * <dt>newVal (Object)</dt>
220 * Object hash of key/value pairs of all state items after the
224 * <dt>prevVal (Object)</dt>
226 * Object hash of key/value pairs of all state items before the
230 * <dt>removed (Object)</dt>
232 * Object hash of key/value pairs of state items that have been
233 * removed. Values are the old values prior to removal.
236 * <dt>src (String)</dt>
238 * The source of the event. This can be used to selectively ignore
239 * events generated by certain sources.
243 this.publish(EVT_CHANGE, {
245 defaultFn: this._defChangeFn
248 // If initialState was provided, merge it into the current state.
250 this.add(initialState);
254 // -- Public Methods -------------------------------------------------------
257 * Adds a state entry with new values for the specified keys. By default,
258 * the new state will be merged into the existing state, and new values will
259 * override existing values. Specifying a <code>null</code> or
260 * <code>undefined</code> value will cause that key to be removed from the
264 * @param {Object} state Object hash of key/value pairs.
265 * @param {Object} options (optional) Zero or more of the following options:
267 * <dt>merge (Boolean)</dt>
270 * If <code>true</code> (the default), the new state will be merged
271 * into the existing state. New values will override existing values,
272 * and <code>null</code> or <code>undefined</code> values will be
273 * removed from the state.
277 * If <code>false</code>, the existing state will be discarded as a
278 * whole and the new state will take its place.
285 var args = YArray(arguments, 0, true);
286 args.unshift(SRC_ADD);
287 return this._change.apply(this, args);
291 * Adds a state entry with a new value for a single key. By default, the new
292 * value will be merged into the existing state values, and will override an
293 * existing value with the same key if there is one. Specifying a
294 * <code>null</code> or <code>undefined</code> value will cause the key to
295 * be removed from the new state entry.
298 * @param {String} key State parameter key.
299 * @param {String} value New value.
300 * @param {Object} options (optional) Zero or more options. See
301 * <code>add()</code> for a list of supported options.
304 addValue: function (key, value, options) {
307 return this._change(SRC_ADD, state, options);
311 * Returns the current value of the state parameter specified by <i>key</i>,
312 * or an object hash of key/value pairs for all current state parameters if
313 * no key is specified.
316 * @param {String} key (optional) State parameter key.
317 * @return {Object|String} Value of the specified state parameter, or an
318 * object hash of key/value pairs for all current state parameters.
320 get: function (key) {
321 var state = GlobalEnv._state,
322 isObject = _isSimpleObject(state);
325 return isObject && Obj.owns(state, key) ? state[key] : undefined;
327 return isObject ? Y.mix({}, state, true) : state; // mix provides a fast shallow clone.
332 * Same as <code>add()</code> except that a new browser history entry will
333 * not be created. Instead, the current history entry will be replaced with
337 * @param {Object} state Object hash of key/value pairs.
338 * @param {Object} options (optional) Zero or more options. See
339 * <code>add()</code> for a list of supported options.
342 replace: function () {
343 var args = YArray(arguments, 0, true);
344 args.unshift(SRC_REPLACE);
345 return this._change.apply(this, args);
349 * Same as <code>addValue()</code> except that a new browser history entry
350 * will not be created. Instead, the current history entry will be replaced
351 * with the new state.
353 * @method replaceValue
354 * @param {String} key State parameter key.
355 * @param {String} value New value.
356 * @param {Object} options (optional) Zero or more options. See
357 * <code>add()</code> for a list of supported options.
360 replaceValue: function (key, value, options) {
363 return this._change(SRC_REPLACE, state, options);
366 // -- Protected Methods ----------------------------------------------------
369 * Changes the state. This method provides a common implementation shared by
370 * the public methods for changing state.
373 * @param {String} src Source of the change, for inclusion in event facades
374 * to facilitate filtering.
375 * @param {Object} state Object hash of key/value pairs.
376 * @param {Object} options (optional) Zero or more options. See
377 * <code>add()</code> for a list of supported options.
381 _change: function (src, state, options) {
382 options = options ? Y.merge(DEFAULT_OPTIONS, options) : DEFAULT_OPTIONS;
384 if (options.merge && _isSimpleObject(state) &&
385 _isSimpleObject(GlobalEnv._state)) {
386 state = Y.merge(GlobalEnv._state, state);
389 this._resolveChanges(src, state, options);
394 * Called by _resolveChanges() when the state has changed. This method takes
395 * care of actually firing the necessary events.
397 * @method _fireEvents
398 * @param {String} src Source of the changes, for inclusion in event facades
399 * to facilitate filtering.
400 * @param {Object} changes Resolved changes.
401 * @param {Object} options Zero or more options. See <code>add()</code> for
402 * a list of supported options.
405 _fireEvents: function (src, changes, options) {
406 // Fire the global change event.
407 this.fire(EVT_CHANGE, {
409 changed : changes.changed,
410 newVal : changes.newState,
411 prevVal : changes.prevState,
412 removed : changes.removed,
416 // Fire change/remove events for individual items.
417 Obj.each(changes.changed, function (value, key) {
418 this._fireChangeEvent(src, key, value);
421 Obj.each(changes.removed, function (value, key) {
422 this._fireRemoveEvent(src, key, value);
427 * Fires a dynamic "[key]Change" event.
429 * @method _fireChangeEvent
430 * @param {String} src source of the change, for inclusion in event facades
431 * to facilitate filtering
432 * @param {String} key key of the item that was changed
433 * @param {Object} value object hash containing <i>newVal</i> and
434 * <i>prevVal</i> properties for the changed item
437 _fireChangeEvent: function (src, key, value) {
440 * Dynamic event fired when an individual history item is added or
441 * changed. The name of this event depends on the name of the key that
442 * changed. To listen to change events for a key named "foo", subscribe
443 * to the <code>fooChange</code> event; for a key named "bar", subscribe
444 * to <code>barChange</code>, etc.
448 * Key-specific events are only fired for instance-level changes; that
449 * is, changes that were made via the same History instance on which the
450 * event is subscribed. To be notified of changes made by other History
451 * instances, subscribe to the global <code>history:change</code> event.
455 * @param {EventFacade} e Event facade with the following additional
459 * <dt>newVal (mixed)</dt>
461 * The new value of the item after the change.
464 * <dt>prevVal (mixed)</dt>
466 * The previous value of the item before the change, or
467 * <code>undefined</code> if the item was just added and has no
471 * <dt>src (String)</dt>
473 * The source of the event. This can be used to selectively ignore
474 * events generated by certain sources.
478 this.fire(key + 'Change', {
479 newVal : value.newVal,
480 prevVal: value.prevVal,
486 * Fires a dynamic "[key]Remove" event.
488 * @method _fireRemoveEvent
489 * @param {String} src source of the change, for inclusion in event facades
490 * to facilitate filtering
491 * @param {String} key key of the item that was removed
492 * @param {mixed} value value of the item prior to its removal
495 _fireRemoveEvent: function (src, key, value) {
498 * Dynamic event fired when an individual history item is removed. The
499 * name of this event depends on the name of the key that was removed.
500 * To listen to remove events for a key named "foo", subscribe to the
501 * <code>fooRemove</code> event; for a key named "bar", subscribe to
502 * <code>barRemove</code>, etc.
506 * Key-specific events are only fired for instance-level changes; that
507 * is, changes that were made via the same History instance on which the
508 * event is subscribed. To be notified of changes made by other History
509 * instances, subscribe to the global <code>history:change</code> event.
513 * @param {EventFacade} e Event facade with the following additional
517 * <dt>prevVal (mixed)</dt>
519 * The value of the item before it was removed.
522 * <dt>src (String)</dt>
524 * The source of the event. This can be used to selectively ignore
525 * events generated by certain sources.
529 this.fire(key + 'Remove', {
536 * Resolves the changes (if any) between <i>newState</i> and the current
537 * state and fires appropriate events if things have changed.
539 * @method _resolveChanges
540 * @param {String} src source of the changes, for inclusion in event facades
541 * to facilitate filtering
542 * @param {Object} newState object hash of key/value pairs representing the
544 * @param {Object} options Zero or more options. See <code>add()</code> for
545 * a list of supported options.
548 _resolveChanges: function (src, newState, options) {
551 prevState = GlobalEnv._state,
562 if (_isSimpleObject(newState) && _isSimpleObject(prevState)) {
563 // Figure out what was added or changed.
564 Obj.each(newState, function (newVal, key) {
565 var prevVal = prevState[key];
567 if (newVal !== prevVal) {
577 // Figure out what was removed.
578 Obj.each(prevState, function (prevVal, key) {
579 if (!Obj.owns(newState, key) || newState[key] === null) {
580 delete newState[key];
581 removed[key] = prevVal;
586 isChanged = newState !== prevState;
590 this._fireEvents(src, {
593 prevState: prevState,
600 * Stores the specified state. Don't call this method directly; go through
601 * _resolveChanges() to ensure that changes are resolved and all events are
604 * @method _storeState
605 * @param {String} src source of the changes
606 * @param {Object} newState new state to store
607 * @param {Object} options Zero or more options. See <code>add()</code> for
608 * a list of supported options.
611 _storeState: function (src, newState) {
612 // Note: the src and options params aren't used here, but they are used
614 GlobalEnv._state = newState || {};
617 // -- Protected Event Handlers ---------------------------------------------
620 * Default <code>history:change</code> event handler.
622 * @method _defChangeFn
623 * @param {EventFacade} e state change event facade
626 _defChangeFn: function (e) {
627 this._storeState(e.src, e.newVal, e._options);
631 Y.HistoryBase = HistoryBase;
634 }, '3.3.0' ,{requires:['event-custom-complex']});
635 YUI.add('history-hash', function(Y) {
638 * Provides browser history management backed by
639 * <code>window.location.hash</code>, as well as convenience methods for working
640 * with the location hash and a synthetic <code>hashchange</code> event that
641 * normalizes differences across browsers.
644 * @submodule history-hash
647 * @extends HistoryBase
649 * @param {Object} config (optional) Configuration object. See the HistoryBase
650 * documentation for details.
653 var HistoryBase = Y.HistoryBase,
657 GlobalEnv = YUI.namespace('Env.HistoryHash'),
665 location = win.location,
666 useHistoryHTML5 = Y.config.useHistoryHTML5;
668 function HistoryHash() {
669 HistoryHash.superclass.constructor.apply(this, arguments);
672 Y.extend(HistoryHash, HistoryBase, {
673 // -- Initialization -------------------------------------------------------
674 _init: function (config) {
675 var bookmarkedState = HistoryHash.parseHash();
677 // If an initialState was provided, merge the bookmarked state into it
678 // (the bookmarked state wins).
679 config = config || {};
681 this._initialState = config.initialState ?
682 Y.merge(config.initialState, bookmarkedState) : bookmarkedState;
684 // Subscribe to the synthetic hashchange event (defined below) to handle
686 Y.after('hashchange', Y.bind(this._afterHashChange, this), win);
688 HistoryHash.superclass._init.apply(this, arguments);
691 // -- Protected Methods ----------------------------------------------------
692 _change: function (src, state, options) {
693 // Stringify all values to ensure that comparisons don't fail after
694 // they're coerced to strings in the location hash.
695 YObject.each(state, function (value, key) {
696 if (Lang.isValue(value)) {
697 state[key] = value.toString();
701 return HistoryHash.superclass._change.call(this, src, state, options);
704 _storeState: function (src, newState) {
705 var decode = HistoryHash.decode,
706 newHash = HistoryHash.createHash(newState);
708 HistoryHash.superclass._storeState.apply(this, arguments);
710 // Update the location hash with the changes, but only if the new hash
711 // actually differs from the current hash (this avoids creating multiple
712 // history entries for a single state).
714 // We always compare decoded hashes, since it's possible that the hash
715 // could be set incorrectly to a non-encoded value outside of
717 if (src !== SRC_HASH && decode(HistoryHash.getHash()) !== decode(newHash)) {
718 HistoryHash[src === HistoryBase.SRC_REPLACE ? 'replaceHash' : 'setHash'](newHash);
722 // -- Protected Event Handlers ---------------------------------------------
725 * Handler for hashchange events.
727 * @method _afterHashChange
731 _afterHashChange: function (e) {
732 this._resolveChanges(SRC_HASH, HistoryHash.parseHash(e.newHash), {});
735 // -- Public Static Properties ---------------------------------------------
739 * Constant used to identify state changes originating from
740 * <code>hashchange</code> events.
751 * Prefix to prepend when setting the hash fragment. For example, if the
752 * prefix is <code>!</code> and the hash fragment is set to
753 * <code>#foo=bar&baz=quux</code>, the final hash fragment in the URL will
754 * become <code>#!foo=bar&baz=quux</code>. This can be used to help make an
755 * Ajax application crawlable in accordance with Google's guidelines at
756 * <a href="http://code.google.com/web/ajaxcrawling/">http://code.google.com/web/ajaxcrawling/</a>.
760 * Note that this prefix applies to all HistoryHash instances. It's not
761 * possible for individual instances to use their own prefixes since they
762 * all operate on the same URL.
765 * @property hashPrefix
772 // -- Protected Static Properties ------------------------------------------
775 * Regular expression used to parse location hash/query strings.
777 * @property _REGEX_HASH
783 _REGEX_HASH: /([^\?#&]+)=([^&]+)/g,
785 // -- Public Static Methods ------------------------------------------------
788 * Creates a location hash string from the specified object of key/value
792 * @param {Object} params object of key/value parameter pairs
793 * @return {String} location hash string
796 createHash: function (params) {
797 var encode = HistoryHash.encode,
800 YObject.each(params, function (value, key) {
801 if (Lang.isValue(value)) {
802 hash.push(encode(key) + '=' + encode(value));
806 return hash.join('&');
810 * Wrapper around <code>decodeURIComponent()</code> that also converts +
814 * @param {String} string string to decode
815 * @return {String} decoded string
818 decode: function (string) {
819 return decodeURIComponent(string.replace(/\+/g, ' '));
823 * Wrapper around <code>encodeURIComponent()</code> that converts spaces to
827 * @param {String} string string to encode
828 * @return {String} encoded string
831 encode: function (string) {
832 return encodeURIComponent(string).replace(/%20/g, '+');
836 * Gets the raw (not decoded) current location hash, minus the preceding '#'
837 * character and the hashPrefix (if one is set).
840 * @return {String} current location hash
843 getHash: (Y.UA.gecko ? function () {
844 // Gecko's window.location.hash returns a decoded string and we want all
845 // encoding untouched, so we need to get the hash value from
846 // window.location.href instead. We have to use UA sniffing rather than
847 // feature detection, since the only way to detect this would be to
848 // actually change the hash.
849 var matches = /#(.*)$/.exec(location.href),
850 hash = matches && matches[1] || '',
851 prefix = HistoryHash.hashPrefix;
853 return prefix && hash.indexOf(prefix) === 0 ?
854 hash.replace(prefix, '') : hash;
856 var hash = location.hash.substr(1),
857 prefix = HistoryHash.hashPrefix;
859 // Slight code duplication here, but execution speed is of the essence
860 // since getHash() is called every 50ms to poll for changes in browsers
861 // that don't support native onhashchange. An additional function call
862 // would add unnecessary overhead.
863 return prefix && hash.indexOf(prefix) === 0 ?
864 hash.replace(prefix, '') : hash;
868 * Gets the current bookmarkable URL.
871 * @return {String} current bookmarkable URL
874 getUrl: function () {
875 return location.href;
879 * Parses a location hash string into an object of key/value parameter
880 * pairs. If <i>hash</i> is not specified, the current location hash will
884 * @param {String} hash (optional) location hash string
885 * @return {Object} object of parsed key/value parameter pairs
888 parseHash: function (hash) {
889 var decode = HistoryHash.decode,
895 prefix = HistoryHash.hashPrefix,
898 hash = Lang.isValue(hash) ? hash : HistoryHash.getHash();
901 prefixIndex = hash.indexOf(prefix);
903 if (prefixIndex === 0 || (prefixIndex === 1 && hash.charAt(0) === '#')) {
904 hash = hash.replace(prefix, '');
908 matches = hash.match(HistoryHash._REGEX_HASH) || [];
910 for (i = 0, len = matches.length; i < len; ++i) {
911 param = matches[i].split('=');
912 params[decode(param[0])] = decode(param[1]);
919 * Replaces the browser's current location hash with the specified hash
920 * and removes all forward navigation states, without creating a new browser
921 * history entry. Automatically prepends the <code>hashPrefix</code> if one
924 * @method replaceHash
925 * @param {String} hash new location hash
928 replaceHash: function (hash) {
929 if (hash.charAt(0) === '#') {
930 hash = hash.substr(1);
933 location.replace('#' + (HistoryHash.hashPrefix || '') + hash);
937 * Sets the browser's location hash to the specified string. Automatically
938 * prepends the <code>hashPrefix</code> if one is set.
941 * @param {String} hash new location hash
944 setHash: function (hash) {
945 if (hash.charAt(0) === '#') {
946 hash = hash.substr(1);
949 location.hash = (HistoryHash.hashPrefix || '') + hash;
953 // -- Synthetic hashchange Event -----------------------------------------------
955 // TODO: YUIDoc currently doesn't provide a good way to document synthetic DOM
956 // events. For now, we're just documenting the hashchange event on the YUI
957 // object, which is about the best we can do until enhancements are made to
962 * Synthetic <code>window.onhashchange</code> event that normalizes differences
963 * across browsers and provides support for browsers that don't natively support
964 * <code>onhashchange</code>.
968 * This event is provided by the <code>history-hash</code> module.
972 * <strong>Usage example:</strong>
976 * YUI().use('history-hash', function (Y) {
977 * Y.on('hashchange', function (e) {
978 * // Handle hashchange events on the current window.
979 * }, Y.config.win);
984 * @param {EventFacade} e Event facade with the following additional
990 * Previous hash fragment value before the change.
995 * Previous URL (including the hash fragment) before the change.
1000 * New hash fragment value after the change.
1005 * New URL (including the hash fragment) after the change.
1012 hashNotifiers = GlobalEnv._notifiers;
1014 if (!hashNotifiers) {
1015 hashNotifiers = GlobalEnv._notifiers = [];
1018 Y.Event.define('hashchange', {
1019 on: function (node, subscriber, notifier) {
1020 // Ignore this subscription if the node is anything other than the
1021 // window or document body, since those are the only elements that
1022 // should support the hashchange event. Note that the body could also be
1023 // a frameset, but that's okay since framesets support hashchange too.
1024 if (node.compareTo(win) || node.compareTo(Y.config.doc.body)) {
1025 hashNotifiers.push(notifier);
1029 detach: function (node, subscriber, notifier) {
1030 var index = YArray.indexOf(hashNotifiers, notifier);
1033 hashNotifiers.splice(index, 1);
1038 oldHash = HistoryHash.getHash();
1039 oldUrl = HistoryHash.getUrl();
1041 if (HistoryBase.nativeHashChange) {
1042 // Wrap the browser's native hashchange event.
1043 Y.Event.attach('hashchange', function (e) {
1044 var newHash = HistoryHash.getHash(),
1045 newUrl = HistoryHash.getUrl();
1047 // Iterate over a copy of the hashNotifiers array since a subscriber
1048 // could detach during iteration and cause the array to be re-indexed.
1049 YArray.each(hashNotifiers.concat(), function (notifier) {
1063 // Begin polling for location hash changes if there's not already a global
1065 if (!GlobalEnv._hashPoll) {
1066 if (Y.UA.webkit && !Y.UA.chrome &&
1067 navigator.vendor.indexOf('Apple') !== -1) {
1068 // Attach a noop unload handler to disable Safari's back/forward
1069 // cache. This works around a nasty Safari bug when the back button
1070 // is used to return from a page on another domain, but results in
1071 // slightly worse performance. This bug is not present in Chrome.
1073 // Unfortunately a UA sniff is unavoidable here, but the
1074 // consequences of a false positive are minor.
1076 // Current as of Safari 5.0 (6533.16).
1077 // See: https://bugs.webkit.org/show_bug.cgi?id=34679
1078 Y.on('unload', function () {}, win);
1081 GlobalEnv._hashPoll = Y.later(50, null, function () {
1082 var newHash = HistoryHash.getHash(),
1085 if (oldHash !== newHash) {
1086 newUrl = HistoryHash.getUrl();
1088 YArray.each(hashNotifiers.concat(), function (notifier) {
1104 Y.HistoryHash = HistoryHash;
1106 // HistoryHash will never win over HistoryHTML5 unless useHistoryHTML5 is false.
1107 if (useHistoryHTML5 === false || (!Y.History && useHistoryHTML5 !== true &&
1108 (!HistoryBase.html5 || !Y.HistoryHTML5))) {
1109 Y.History = HistoryHash;
1113 }, '3.3.0' ,{requires:['event-synthetic', 'history-base', 'yui-later']});
1114 YUI.add('history-hash-ie', function(Y) {
1117 * Improves IE6/7 support in history-hash by using a hidden iframe to create
1118 * entries in IE's browser history. This module is only needed if IE6/7 support
1119 * is necessary; it's not needed for any other browser.
1122 * @submodule history-hash-ie
1126 // Combination of a UA sniff to ensure this is IE (or a browser that wants us to
1127 // treat it like IE) and feature detection for native hashchange support (false
1128 // for IE < 8 or IE8/9 in IE7 mode).
1129 if (Y.UA.ie && !Y.HistoryBase.nativeHashChange) {
1131 GlobalEnv = YUI.namespace('Env.HistoryHash'),
1132 HistoryHash = Y.HistoryHash,
1134 iframe = GlobalEnv._iframe,
1136 location = win.location,
1140 * Gets the raw (not decoded) current location hash from the IE iframe,
1141 * minus the preceding '#' character and the hashPrefix (if one is set).
1143 * @method getIframeHash
1144 * @return {String} current iframe hash
1147 HistoryHash.getIframeHash = function () {
1148 if (!iframe || !iframe.contentWindow) {
1152 var prefix = HistoryHash.hashPrefix,
1153 hash = iframe.contentWindow.location.hash.substr(1);
1155 return prefix && hash.indexOf(prefix) === 0 ?
1156 hash.replace(prefix, '') : hash;
1160 * Updates the history iframe with the specified hash.
1162 * @method _updateIframe
1163 * @param {String} hash location hash
1164 * @param {Boolean} replace (optional) if <code>true</code>, the current
1165 * history state will be replaced without adding a new history entry
1170 HistoryHash._updateIframe = function (hash, replace) {
1171 var iframeDoc = iframe && iframe.contentWindow && iframe.contentWindow.document,
1172 iframeLocation = iframeDoc && iframeDoc.location;
1174 if (!iframeDoc || !iframeLocation) {
1179 iframeDoc.open().close();
1182 iframeLocation.replace(hash.charAt(0) === '#' ? hash : '#' + hash);
1184 iframeLocation.hash = hash;
1188 Do.after(HistoryHash._updateIframe, HistoryHash, 'replaceHash', HistoryHash, true);
1191 Y.on('domready', function () {
1192 // Create a hidden iframe to store history state, following the
1193 // iframe-hiding recommendations from
1194 // http://www.paciellogroup.com/blog/?p=604.
1196 // This iframe will allow history navigation within the current page
1197 // context. After navigating to another page, all but the most
1198 // recent history state will be lost.
1200 // Earlier versions of the YUI History Utility attempted to work
1201 // around this limitation by having the iframe load a static
1202 // resource. This workaround was extremely fragile and tended to
1203 // break frequently (and silently) since it was entirely dependent
1204 // on IE's inconsistent handling of iframe history.
1206 // Since this workaround didn't work much of the time anyway and
1207 // added significant complexity, it has been removed, and IE6 and 7
1208 // now get slightly degraded history support.
1210 iframe = GlobalEnv._iframe = Y.Node.getDOMNode(Y.Node.create(
1211 '<iframe src="javascript:0" style="display:none" height="0" width="0" tabindex="-1" title="empty"/>'
1214 // Append the iframe to the documentElement rather than the body.
1215 // Keeping it outside the body prevents scrolling on the initial
1216 // page load (hat tip to Ben Alman and jQuery BBQ for this
1218 Y.config.doc.documentElement.appendChild(iframe);
1220 // Update the iframe with the initial location hash, if any. This
1221 // will create an initial history entry that the user can return to
1222 // after the state has changed.
1223 HistoryHash._updateIframe(HistoryHash.getHash() || '#');
1225 // Listen for hashchange events and keep the iframe's hash in sync
1226 // with the parent frame's hash.
1227 Y.on('hashchange', function (e) {
1228 lastUrlHash = e.newHash;
1230 if (HistoryHash.getIframeHash() !== lastUrlHash) {
1231 HistoryHash._updateIframe(lastUrlHash);
1235 // Watch the iframe hash in order to detect back/forward navigation.
1236 Y.later(50, null, function () {
1237 var iframeHash = HistoryHash.getIframeHash();
1239 if (iframeHash !== lastUrlHash) {
1240 HistoryHash.setHash(iframeHash);
1248 }, '3.3.0' ,{requires:['history-hash', 'node-base']});
1249 YUI.add('history-html5', function(Y) {
1252 * Provides browser history management using the HTML5 history API.
1255 * @submodule history-html5
1261 * Provides browser history management using the HTML5 history API.
1265 * When calling the <code>add()</code>, <code>addValue()</code>,
1266 * <code>replace()</code>, or <code>replaceValue()</code> methods on
1267 * <code>HistoryHTML5</code>, the following additional options are supported:
1271 * <dt><strong>title (String)</strong></dt>
1273 * Title to use for the new history entry. Browsers will typically display
1274 * this title to the user in the detailed history window or in a dropdown
1275 * menu attached to the back/forward buttons. If not specified, the title
1276 * of the current document will be used.
1279 * <dt><strong>url (String)</strong></dt>
1281 * URL to display to the user for the new history entry. This URL will be
1282 * visible in the browser's address bar and will be the bookmarked URL if
1283 * the user bookmarks the page. It may be a relative path ("foo/bar"), an
1284 * absolute path ("/foo/bar"), or a full URL ("http://example.com/foo/bar").
1285 * If you specify a full URL, the origin <i>must</i> be the same as the
1286 * origin of the current page, or an error will occur. If no URL is
1287 * specified, the current URL will not be changed.
1291 * @class HistoryHTML5
1292 * @extends HistoryBase
1294 * @param {Object} config (optional) Configuration object. The following
1295 * <code>HistoryHTML5</code>-specific properties are supported in addition to
1296 * those supported by <code>HistoryBase</code>:
1299 * <dt><strong>enableSessionFallback (Boolean)</strong></dt>
1302 * Set this to <code>true</code> to store the most recent history state in
1303 * sessionStorage in order to seamlessly restore the previous state (if any)
1304 * when <code>HistoryHTML5</code> is instantiated after a
1305 * <code>window.onpopstate</code> event has already fired.
1309 * By default, this setting is <code>false</code>.
1315 var HistoryBase = Y.HistoryBase,
1319 useHistoryHTML5 = Y.config.useHistoryHTML5,
1321 JSON = Y.JSON || win.JSON, // prefer YUI JSON, but fall back to native
1323 ENABLE_FALLBACK = 'enableSessionFallback',
1324 SESSION_KEY = 'YUI_HistoryHTML5_state',
1325 SRC_POPSTATE = 'popstate',
1326 SRC_REPLACE = HistoryBase.SRC_REPLACE;
1328 function HistoryHTML5() {
1329 HistoryHTML5.superclass.constructor.apply(this, arguments);
1332 Y.extend(HistoryHTML5, HistoryBase, {
1333 // -- Initialization -------------------------------------------------------
1334 _init: function (config) {
1335 Y.on('popstate', this._onPopState, win, this);
1337 HistoryHTML5.superclass._init.apply(this, arguments);
1339 // If window.onload has already fired and the sessionStorage fallback is
1340 // enabled, try to restore the last state from sessionStorage. This
1341 // works around a shortcoming of the HTML5 history API: it's impossible
1342 // to get the current state if the popstate event fires before you've
1343 // subscribed to it. Since popstate fires immediately after onload,
1344 // the last state may be lost if you return to a page from another page.
1345 if (config && config[ENABLE_FALLBACK] && YUI.Env.windowLoaded) {
1346 // Gecko will throw an error if you attempt to reference
1347 // sessionStorage on a page served from a file:// URL, so we have to
1350 // See http://yuilibrary.com/projects/yui3/ticket/2529165
1352 sessionStorage = win.sessionStorage;
1355 this._loadSessionState();
1359 // -- Protected Methods ----------------------------------------------------
1362 * Returns a string unique to the current URL pathname that's suitable for
1363 * use as a session storage key.
1365 * @method _getSessionKey
1369 _getSessionKey: function () {
1370 return SESSION_KEY + '_' + win.location.pathname;
1374 * Attempts to load a state entry stored in session storage.
1376 * @method _loadSessionState
1379 _loadSessionState: function () {
1380 var lastState = JSON && sessionStorage &&
1381 sessionStorage[this._getSessionKey()];
1385 this._resolveChanges(SRC_POPSTATE, JSON.parse(lastState) || null);
1391 * Stores the specified state entry in session storage if the
1392 * <code>enableSessionFallback</code> config property is <code>true</code>
1393 * and either <code>Y.JSON</code> or native JSON support is available and
1394 * session storage is supported.
1396 * @method _storeSessionState
1397 * @param {mixed} state State to store. May be any type serializable to
1401 _storeSessionState: function (state) {
1402 if (this._config[ENABLE_FALLBACK] && JSON && sessionStorage) {
1403 sessionStorage[this._getSessionKey()] = JSON.stringify(state || null);
1408 * Overrides HistoryBase's <code>_storeState()</code> and pushes or replaces
1409 * a history entry using the HTML5 history API when necessary.
1411 * @method _storeState
1412 * @param {String} src Source of the changes.
1413 * @param {Object} newState New state to store.
1414 * @param {Object} options Zero or more options.
1417 _storeState: function (src, newState, options) {
1418 if (src !== SRC_POPSTATE) {
1419 win.history[src === SRC_REPLACE ? 'replaceState' : 'pushState'](
1420 newState, options.title || doc.title || '', options.url || null
1424 this._storeSessionState(newState);
1425 HistoryHTML5.superclass._storeState.apply(this, arguments);
1428 // -- Protected Event Handlers ---------------------------------------------
1431 * Handler for popstate events.
1433 * @method _onPopState
1437 _onPopState: function (e) {
1438 var state = e._event.state;
1440 this._storeSessionState(state);
1441 this._resolveChanges(SRC_POPSTATE, state || null);
1444 // -- Public Static Properties ---------------------------------------------
1445 NAME: 'historyhtml5',
1448 * Constant used to identify state changes originating from
1449 * <code>popstate</code> events.
1451 * @property SRC_POPSTATE
1456 SRC_POPSTATE: SRC_POPSTATE
1459 if (!Y.Node.DOM_EVENTS.popstate) {
1460 Y.Node.DOM_EVENTS.popstate = 1;
1463 Y.HistoryHTML5 = HistoryHTML5;
1467 * If <code>true</code>, the <code>Y.History</code> alias will always point to
1468 * <code>Y.HistoryHTML5</code> when the history-html5 module is loaded, even if
1469 * the current browser doesn't support HTML5 history.
1473 * If <code>false</code>, the <code>Y.History</code> alias will always point to
1474 * <code>Y.HistoryHash</code> when the history-hash module is loaded, even if
1475 * the current browser supports HTML5 history.
1479 * If neither <code>true</code> nor <code>false</code>, the
1480 * <code>Y.History</code> alias will point to the best available history adapter
1481 * that the browser supports. This is the default behavior.
1484 * @property useHistoryHTML5
1490 // HistoryHTML5 will always win over HistoryHash unless useHistoryHTML5 is false
1491 // or HTML5 history is not supported.
1492 if (useHistoryHTML5 === true || (useHistoryHTML5 !== false &&
1493 HistoryBase.html5)) {
1494 Y.History = HistoryHTML5;
1498 }, '3.3.0' ,{optional:['json'], requires:['event-base', 'history-base', 'node-base']});
1501 YUI.add('history', function(Y){}, '3.3.0' ,{use:['history-base', 'history-hash', 'history-hash-ie', 'history-html5']});