2 * Originally based of this code... - refactored for Roo...
5 * @author Benjamin Arthur Lupton <contact@balupton.com>
6 * @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
7 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
11 // this is not initialized automatically..
12 // must call Roo.History.init( { ... options... });
18 // ====================================================================
24 * How long should the interval be before hashchange checks
26 thishashChangeInterval : 100,
30 * How long should the interval be before safari poll checks
32 safariPollInterval : 500,
36 * How long should the interval be before we perform a double check
38 doubleCheckInterval : 500,
42 * Force this.not to append suid
48 * How long should we wait between store calls
54 * How long should we wait between busy events
60 * If true will enable debug messages to be logged
66 * What is the title of the initial state
72 * If true, will force HTMl4 mode (hashtags)
78 * Want to override default options and call init manually.
84 * Which bugs are present
88 * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
89 * https://bugs.webkit.org/show_bug.cgi?id=56249
94 * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
95 * https://bugs.webkit.org/show_bug.cgi?id=42940
100 * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
102 ieDoubleCheck: false,
105 * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
110 // ========================================================================
116 sessionStorage : false, // sessionStorage
118 intervalList : false, // array normally.
121 * Is History enabled?
125 // ====================================================================
130 * The store for all session specific data
136 * 1-1: State ID to State Object
142 * 1-1: State String to State ID
148 * 1-1: State URL to State ID
154 * Store the states in an array
156 storedStates : false,
160 * Saved the states in an array
166 * The list of queues to use
167 * First In, First Out
176 // ====================================================================
180 * History.stateChanged
181 * States whether or not the state has changed since the last double check was initialised
183 stateChanged : false,
186 * History.doubleChecker
187 * Contains the timeout used for the double checks
189 doubleChecker : false,
192 // Initialise History
193 init : function(options)
196 var emptyFunction = function(){};
200 this.initialTitle = window.document.title;
205 this.storedStates=[];
209 Roo.apply(this,options)
211 // Check Load Status of Adapter
212 //if ( typeof this.Adapter === 'undefined' ) {
216 // Check Load Status of Core
217 if ( typeof this.initCore !== 'undefined' ) {
221 // Check Load Status of HTML4 Support
222 if ( typeof this.initHtml4 !== 'undefined' ) {
229 this.enabled = !this.emulated.pushState;
231 if ( this.emulated.pushState ) {
235 this.pushState = emptyFunction;
236 this.replaceState = emptyFunction;
241 this.Adapter.bind(window,'popstate',this.onPopState);
247 if ( this.sessionStorage ) {
250 this.store = JSON.parse(this.sessionStorage.getItem('Roo.History.store'))||{};
255 this.intervalList.push(setInterval(this.onUnload,this.storeInterval));
257 // For Other Browsers
258 this.Adapter.bind(window,'beforeunload',this.onUnload);
259 this.Adapter.bind(window,'unload',this.onUnload);
262 this.onUnload = emptyFunction;
266 this.normalizeStore();
268 * Clear Intervals on exit to prevent memory leaks
270 this.Adapter.bind(window,"unload",this.clearAllIntervals);
273 * Create the initial State
275 this.saveState(this.storeState(this.extractState(this.getLocationHref(),true)));
279 // Non-Native pushState Implementation
280 if ( !this.emulated.pushState ) {
281 // Be aware, the following is only for native pushState implementations
282 // If you are wanting to include something for all browsers
283 // Then include it above this if block
288 if ( this.bugs.safariPoll ) {
289 this.intervalList.push(setInterval(this.safariStatePoll, this.safariPollInterval));
293 * Ensure Cross Browser Compatibility
295 //if ( window.navigator.vendor === 'Apple Computer, Inc.' || (window.navigator.appCodeName||'') === 'Mozilla' ) {
300 * Fix Safari HashChange Issue
304 this.Adapter.bind(window,'hashchange',function(){
305 _this.Adapter.trigger(window,'popstate');
309 if ( this.getHash() ) {
310 this.Adapter.onDomLoad(function(){
311 _this.Adapter.trigger(window,'hashchange');
316 } // !History.emulated.pushState
326 // ========================================================================
330 initCore : function(options){
332 this.intervalList = [];
336 this.sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
337 this.sessionStorage.setItem('TEST', '1');
338 this.sessionStorage.removeItem('TEST');
340 this.sessionStorage = false;
344 if ( typeof this.initCore.initialized !== 'undefined' ) {
349 this.initCore.initialized = true;
358 * Clears all setInterval instances.
360 clearAllIntervals: function()
362 var i, il = this.intervalList;
363 if (typeof il !== "undefined" && il !== null) {
364 for (i = 0; i < il.length; i++) {
365 clearInterval(il[i]);
367 this.intervalList = null;
372 // ====================================================================
376 * debugLog(message,...)
377 * Logs the passed arguments if debug enabled
379 debugLog : function()
381 if ( (this.debug||false) ) {
382 Roo.log.apply(this,arguments);
388 // ====================================================================
392 * getInternetExplorerMajorVersion()
393 * Get's the major version of Internet Explorer
395 * @license Public Domain
396 * @author Benjamin Arthur Lupton <contact@balupton.com>
397 * @author James Padolsey <https://gist.github.com/527683>
399 getInternetExplorerMajorVersion : function(){
400 var result = this.getInternetExplorerMajorVersion.cached =
401 (typeof this.getInternetExplorerMajorVersion.cached !== 'undefined')
402 ? this.getInternetExplorerMajorVersion.cached
405 div = window.document.createElement('div'),
406 all = div.getElementsByTagName('i');
407 while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
408 return (v > 4) ? v : false;
415 * isInternetExplorer()
416 * Are we using Internet Explorer?
418 * @license Public Domain
419 * @author Benjamin Arthur Lupton <contact@balupton.com>
421 isInternetExplorer : function(){
423 this.isInternetExplorer.cached =
424 (typeof this.isInternetExplorer.cached !== 'undefined')
425 ? this.isInternetExplorer.cached
426 : Boolean(this.getInternetExplorerMajorVersion())
432 * Which features require emulating?
440 initEmulated : function()
444 if (this.html4Mode) {
450 this.emulated.pushState = !Boolean(
451 window.history && window.history.pushState && window.history.replaceState
453 (/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(window.navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
454 || (/AppleWebKit\/5([0-2]|3[0-2])/i).test(window.navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
457 this.emulated.hashChange = Boolean(
458 !(('onhashchange' in window) || ('onhashchange' in window.document))
460 (this.isInternetExplorer() && this.getInternetExplorerMajorVersion() < 8)
465 initBugs : function ()
471 * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
472 * https://bugs.webkit.org/show_bug.cgi?id=56249
474 this.bugs.setHash: Boolean(!this.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
477 * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
478 * https://bugs.webkit.org/show_bug.cgi?id=42940
480 this.bugs.safariPoll: Boolean(!this.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
483 * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
485 this.bugs.ieDoubleCheck: Boolean(this.isInternetExplorer() && this.getInternetExplorerMajorVersion() < 8),
488 * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
490 this.bugs.hashEscape: Boolean(this.isInternetExplorer() && this.getInternetExplorerMajorVersion() < 7)
496 * Checks to see if the Object is Empty
497 * @param {Object} obj
500 isEmptyObject = function(obj) {
501 for ( var name in obj ) {
502 if ( obj.hasOwnProperty(name) ) {
511 * Clones a object and eliminate all references to the original contexts
512 * @param {Object} obj
515 cloneObject = function(obj) {
518 hash = JSON.stringify(obj);
519 newObj = JSON.parse(hash);
528 // ====================================================================
533 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
534 * @return {String} rootUrl
536 getRootUrl = function(){
538 var rootUrl = window.document.location.protocol+'//'+(window.document.location.hostname||window.document.location.host);
539 if ( window.document.location.port||false ) {
540 rootUrl += ':'+window.document.location.port;
550 * Fetches the `href` attribute of the `<base href="...">` element if it exists
551 * @return {String} baseHref
553 getBaseHref = function(){
556 baseElements = window.document.getElementsByTagName('base'),
560 // Test for Base Element
561 if ( baseElements.length === 1 ) {
562 // Prepare for Base Element
563 baseElement = baseElements[0];
564 baseHref = baseElement.href.replace(/[^\/]+$/,'');
567 // Adjust trailing slash
568 baseHref = baseHref.replace(/\/+$/,'');
569 if ( baseHref ) baseHref += '/';
577 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
578 * @return {String} baseUrl
580 getBaseUrl = function(){
582 var baseUrl = this.getBaseHref()||this.getBasePageUrl()||this.getRootUrl();
590 * Fetches the URL of the current page
591 * @return {String} pageUrl
593 getPageUrl = function(){
596 State = this.getState(false,false),
597 stateUrl = (State||{}).url||this.getLocationHref(),
601 pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
602 return (/\./).test(part) ? part : part+'/';
611 * Fetches the Url of the directory of the current page
612 * @return {String} basePageUrl
614 getBasePageUrl = function(){
616 var basePageUrl = (this.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
617 return (/[^\/]$/).test(part) ? '' : part;
618 }).replace(/\/+$/,'')+'/';
626 * Ensures that we have an absolute URL and not a relative URL
627 * @param {string} url
628 * @param {Boolean} allowBaseHref
629 * @return {string} fullUrl
631 getFullUrl = function(url,allowBaseHref){
633 var fullUrl = url, firstChar = url.substring(0,1);
634 allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
637 if ( /[a-z]+\:\/\//.test(url) ) {
640 else if ( firstChar === '/' ) {
642 fullUrl = this.getRootUrl()+url.replace(/^\/+/,'');
644 else if ( firstChar === '#' ) {
646 fullUrl = this.getPageUrl().replace(/#.*/,'')+url;
648 else if ( firstChar === '?' ) {
650 fullUrl = this.getPageUrl().replace(/[\?#].*/,'')+url;
654 if ( allowBaseHref ) {
655 fullUrl = this.getBaseUrl()+url.replace(/^(\.\/)+/,'');
657 fullUrl = this.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
659 // We have an if condition above as we do not want hashes
660 // which are relative to the baseHref in our URLs
661 // as if the baseHref changes, then all our bookmarks
662 // would now point to different locations
663 // whereas the basePageUrl will always stay the same
667 return fullUrl.replace(/\#$/,'');
672 * Ensures that we have a relative URL and not a absolute URL
673 * @param {string} url
674 * @return {string} url
676 getShortUrl = function(url){
678 var shortUrl = url, baseUrl = this.getBaseUrl(), rootUrl = this.getRootUrl();
681 if ( this.emulated.pushState ) {
682 // We are in a if statement as when pushState is not emulated
683 // The actual url these short urls are relative to can change
684 // So within the same session, we the url may end up somewhere different
685 shortUrl = shortUrl.replace(baseUrl,'');
689 shortUrl = shortUrl.replace(rootUrl,'/');
691 // Ensure we can still detect it as a state
692 if ( this.isTraditionalAnchor(shortUrl) ) {
693 shortUrl = './'+shortUrl;
697 shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
704 * getLocationHref(document)
705 * Returns a normalized version of document.location.href
706 * accounting for browser inconsistencies, etc.
708 * This URL will be URI-encoded and will include the hash
710 * @param {object} document
711 * @return {string} url
713 getLocationHref = function(doc) {
714 doc = doc || window.document;
716 // most of the time, this will be true
717 if (doc.URL === doc.location.href)
718 return doc.location.href;
720 // some versions of webkit URI-decode document.location.href
721 // but they leave document.URL in an encoded state
722 if (doc.location.href === decodeURIComponent(doc.URL))
725 // FF 3.6 only updates document.URL when a page is reloaded
726 // document.location.href is updated correctly
727 if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
728 return doc.location.href;
730 if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
731 return doc.location.href;
733 return doc.URL || doc.location.href;
740 * Noramlize the store by adding necessary values
742 normalizeStore = function(){
743 this.store.idToState = this.store.idToState||{};
744 this.store.urlToId = this.store.urlToId||{};
745 this.store.stateToId = this.store.stateToId||{};
750 * Get an object containing the data, title and url of the current state
751 * @param {Boolean} friendly
752 * @param {Boolean} create
753 * @return {Object} State
755 getState : function(friendly,create){
757 if ( typeof friendly === 'undefined' ) { friendly = true; }
758 if ( typeof create === 'undefined' ) { create = true; }
761 var State = this.getLastSavedState();
764 if ( !State && create ) {
765 State = this.createStateObject();
770 State = this.cloneObject(State);
771 State.url = this.cleanUrl||State.url;
779 * getIdByState(State)
780 * Gets a ID for a State
781 * @param {State} newState
782 * @return {String} id
784 getIdByState = function(newState){
787 var id = this.extractId(newState.url),
791 // Find ID via State String
792 str = this.getStateString(newState);
793 if ( typeof this.stateToId[str] !== 'undefined' ) {
794 id = this.stateToId[str];
796 else if ( typeof this.store.stateToId[str] !== 'undefined' ) {
797 id = this.store.stateToId[str];
802 id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
803 if ( typeof this.idToState[id] === 'undefined' && typeof this.store.idToState[id] === 'undefined' ) {
808 // Apply the new State to the ID
809 this.stateToId[str] = id;
810 this.idToState[id] = newState;
819 * normalizeState(State)
820 * Expands a State Object
821 * @param {object} State
824 normalizeState = function(oldState){
826 var newState, dataNotEmpty;
829 if ( !oldState || (typeof oldState !== 'object') ) {
834 if ( typeof oldState.normalized !== 'undefined' ) {
839 if ( !oldState.data || (typeof oldState.data !== 'object') ) {
843 // ----------------------------------------------------------------
847 newState.normalized = true;
848 newState.title = oldState.title||'';
849 newState.url = this.getFullUrl(oldState.url?oldState.url:(this.getLocationHref()));
850 newState.hash = this.getShortUrl(newState.url);
851 newState.data = this.cloneObject(oldState.data);
854 newState.id = this.getIdByState(newState);
856 // ----------------------------------------------------------------
859 newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
860 newState.url = newState.cleanUrl;
862 // Check to see if we have more than just a url
863 dataNotEmpty = !this.isEmptyObject(newState.data);
866 if ( (newState.title || dataNotEmpty) && this.disableSuid !== true ) {
868 newState.hash = this.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
869 if ( !/\?/.test(newState.hash) ) {
870 newState.hash += '?';
872 newState.hash += '&_suid='+newState.id;
875 // Create the Hashed URL
876 newState.hashedUrl = this.getFullUrl(newState.hash);
878 // ----------------------------------------------------------------
880 // Update the URL if we have a duplicate
881 if ( (this.emulated.pushState || this.bugs.safariPoll) && this.hasUrlDuplicate(newState) ) {
882 newState.url = newState.hashedUrl;
885 // ----------------------------------------------------------------
892 * createStateObject(data,title,url)
893 * Creates a object based on the data, title and url state params
894 * @param {object} data
895 * @param {string} title
896 * @param {string} url
899 createStateObject = function(data,title,url){
908 State = this.normalizeState(State);
916 * Get a state by it's UID
919 getStateById = function(id){
924 var State = this.idToState[id] || this.store.idToState[id] || undefined;
931 * Get a State's String
932 * @param {State} passedState
934 getStateString = function(passedState){
936 var State, cleanedState, str;
939 State = this.normalizeState(passedState);
944 title: passedState.title,
949 str = JSON.stringify(cleanedState);
957 * @param {State} passedState
958 * @return {String} id
960 getStateId = function(passedState){
965 State = this.normalizeState(passedState);
975 * getHashByState(State)
976 * Creates a Hash for the State Object
977 * @param {State} passedState
978 * @return {String} hash
980 getHashByState = function(passedState){
985 State = this.normalizeState(passedState);
995 * extractId(url_or_hash)
996 * Get a State ID by it's URL or Hash
997 * @param {string} url_or_hash
998 * @return {string} id
1000 this.extractId = function ( url_or_hash ) {
1002 var id,parts,url, tmp;
1006 // If the URL has a #, use the id from before the #
1007 if (url_or_hash.indexOf('#') != -1)
1009 tmp = url_or_hash.split("#")[0];
1016 parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
1017 url = parts ? (parts[1]||url_or_hash) : url_or_hash;
1018 id = parts ? String(parts[2]||'') : '';
1025 * isTraditionalAnchor
1026 * Checks to see if the url is a traditional anchor or not
1027 * @param {String} url_or_hash
1030 isTraditionalAnchor = function(url_or_hash){
1032 var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
1035 return isTraditional;
1040 * Get a State by it's URL or Hash
1041 * @param {String} url_or_hash
1042 * @return {State|null}
1044 extractState = function(url_or_hash,create){
1046 var State = null, id, url;
1047 create = create||false;
1050 id = this.extractId(url_or_hash);
1052 State = this.getStateById(id);
1055 // Fetch SUID returned no State
1058 url = this.getFullUrl(url_or_hash);
1061 id = this.getIdByUrl(url)||false;
1063 State = this.getStateById(id);
1067 if ( !State && create && !this.isTraditionalAnchor(url_or_hash) ) {
1068 State = this.createStateObject(null,null,url);
1078 * Get a State ID by a State URL
1080 getIdByUrl = function(url){
1082 var id = this.urlToId[url] || this.store.urlToId[url] || undefined;
1089 * getLastSavedState()
1090 * Get an object containing the data, title and url of the current state
1091 * @return {Object} State
1093 getLastSavedState = function(){
1094 return this.savedStates[this.savedStates.length-1]||undefined;
1098 * getLastStoredState()
1099 * Get an object containing the data, title and url of the current state
1100 * @return {Object} State
1102 getLastStoredState = function(){
1103 return this.storedStates[this.storedStates.length-1]||undefined;
1108 * Checks if a Url will have a url conflict
1109 * @param {Object} newState
1110 * @return {Boolean} hasDuplicate
1112 hasUrlDuplicate = function(newState) {
1114 var hasDuplicate = false,
1118 oldState = this.extractState(newState.url);
1121 hasDuplicate = oldState && oldState.id !== newState.id;
1124 return hasDuplicate;
1130 * @param {Object} newState
1131 * @return {Object} newState
1133 storeState = function(newState){
1135 this.urlToId[newState.url] = newState.id;
1138 this.storedStates.push(this.cloneObject(newState));
1145 * isLastSavedState(newState)
1146 * Tests to see if the state is the last state
1147 * @param {Object} newState
1148 * @return {boolean} isLast
1150 isLastSavedState = function(newState){
1153 newId, oldState, oldId;
1156 if ( this.savedStates.length ) {
1157 newId = newState.id;
1158 oldState = this.getLastSavedState();
1159 oldId = oldState.id;
1162 isLast = (newId === oldId);
1172 * @param {Object} newState
1173 * @return {boolean} changed
1175 saveState = function(newState){
1177 if ( this.isLastSavedState(newState) ) {
1182 this.savedStates.push(this.cloneObject(newState));
1190 * Gets a state by the index
1191 * @param {integer} index
1194 getStateByIndex = function(index){
1199 if ( typeof index === 'undefined' ) {
1200 // Get the last inserted
1201 State = this.savedStates[this.savedStates.length-1];
1203 else if ( index < 0 ) {
1205 State = this.savedStates[this.savedStates.length+index];
1208 // Get from the beginning
1209 State = this.savedStates[index];
1218 * Gets the current index
1221 getCurrentIndex = function(){
1226 if(this.savedStates.length < 1) {
1230 index = this.savedStates.length-1;
1235 // ====================================================================
1240 * @param {Location=} location
1241 * Gets the current document hash
1242 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
1245 getHash = function(doc){
1246 var url = this.getLocationHref(doc),
1248 hash = this.getHashByUrl(url);
1254 * normalize and Unescape a Hash
1255 * @param {String} hash
1258 unescapeHash = function(hash){
1260 var result = this.normalizeHash(hash);
1263 result = decodeURIComponent(result);
1271 * normalize a hash across browsers
1274 normalizeHash = function(hash){
1276 var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
1284 * Sets the document hash
1285 * @param {string} hash
1286 * @return {Roo.History}
1288 setHash = function(hash,queue){
1293 if ( queue !== false && this.busy() ) {
1294 // Wait + Push to Queue
1295 //this.debug('this.setHash: we must wait', arguments);
1298 callback: this.setHash,
1306 //this.debug('this.setHash: called',hash);
1308 // Make Busy + Continue
1311 // Check if hash is a state
1312 State = this.extractState(hash,true);
1313 if ( State && !this.emulated.pushState ) {
1314 // Hash is a state so skip the setHash
1315 //this.debug('this.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
1318 this.pushState(State.data,State.title,State.url,false);
1320 else if ( this.getHash() !== hash ) {
1321 // Hash is a proper hash, so apply it
1323 // Handle browser bugs
1324 if ( this.bugs.setHash ) {
1325 // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
1327 // Fetch the base page
1328 pageUrl = this.getPageUrl();
1330 // Safari hash apply
1331 this.pushState(null,null,pageUrl+'#'+hash,false);
1334 // Normal hash apply
1335 window.document.location.hash = hash;
1345 * normalize and Escape a Hash
1348 escapeHash = function(hash){
1350 var result = normalizeHash(hash);
1353 result = window.encodeURIComponent(result);
1356 if ( !this.bugs.hashEscape ) {
1357 // Restore common parts
1359 .replace(/\%21/g,'!')
1360 .replace(/\%26/g,'&')
1361 .replace(/\%3D/g,'=')
1362 .replace(/\%3F/g,'?');
1371 * Extracts the Hash from a URL
1372 * @param {string} url
1373 * @return {string} url
1375 getHashByUrl = function(url){
1377 var hash = String(url)
1378 .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
1382 hash = this.unescapeHash(hash);
1390 * Applies the title to the document
1391 * @param {State} newState
1394 setTitle = function(newState){
1396 var title = newState.title,
1401 firstState = this.getStateByIndex(0);
1402 if ( firstState && firstState.url === newState.url ) {
1403 title = firstState.title||this.initialTitle;
1409 window.document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
1411 catch ( Exception ) { }
1412 window.document.title = title;
1419 // ====================================================================
1425 * @param {boolean} value [optional]
1426 * @return {boolean} busy
1428 busy = function(value){
1430 if ( typeof value !== 'undefined' ) {
1431 //this.debug('this.busy: changing ['+(this.busy.flag||false)+'] to ['+(value||false)+']', this.queues.length);
1432 this.busy_flag = value;
1435 else if ( typeof this.busy_flag === 'undefined' ) {
1436 this.busy_flag = false;
1440 if ( !this.busy_flag ) {
1441 // Execute the next item in the queue
1442 window.clearTimeout(this.busy.timeout);
1443 var fireNext = function(){
1445 if ( this.busy_flag ) return;
1446 for ( i=this.queues.length-1; i >= 0; --i ) {
1447 queue = this.queues[i];
1448 if ( queue.length === 0 ) continue;
1449 item = queue.shift();
1450 this.fireQueueItem(item);
1451 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1454 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1458 return this.busy_flag;
1464 * fireQueueItem(item)
1466 * @param {Object} item
1467 * @return {Mixed} result
1469 fireQueueItem = function(item){
1470 return item.callback.apply(item.scope||this,item.args||[]);
1474 * pushQueue(callback,args)
1475 * Add an item to the queue
1476 * @param {Object} item [scope,callback,args,queue]
1478 pushQueue = function(item){
1479 // Prepare the queue
1480 this.queues[item.queue||0] = this.queues[item.queue||0]||[];
1483 this.queues[item.queue||0].push(item);
1490 * queue (item,queue), (func,queue), (func), (item)
1491 * Either firs the item now if not busy, or adds it to the queue
1493 queue = function(item,queue){
1495 if ( typeof item === 'function' ) {
1500 if ( typeof queue !== 'undefined' ) {
1505 if ( this.busy() ) {
1506 this.pushQueue(item);
1508 this.fireQueueItem(item);
1519 clearQueue = function(){
1520 this.busy_flag = false;
1528 * doubleCheckComplete()
1529 * Complete a double check
1530 * @return {Roo.History}
1532 doubleCheckComplete = function(){
1534 this.stateChanged = true;
1537 this.doubleCheckClear();
1544 * doubleCheckClear()
1545 * Clear a double check
1546 * @return {Roo.History}
1548 doubleCheckClear = function(){
1550 if ( this.doubleChecker ) {
1551 window.clearTimeout(this.doubleChecker);
1552 this.doubleChecker = false;
1561 * Create a double check
1562 * @return {Roo.History}
1564 doubleCheck = function(tryAgain){
1566 this.stateChanged = false;
1567 this.doubleCheckClear();
1569 // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
1570 // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
1571 if ( this.bugs.ieDoubleCheck ) {
1573 this.doubleChecker = window.setTimeout(
1575 this.doubleCheckClear();
1576 if ( !this.stateChanged ) {
1577 //this.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
1583 this.doubleCheckInterval
1592 // ====================================================================
1597 * Poll the current state
1598 * @return {Roo.History}
1600 safariStatePoll = function(){
1603 // Get the Last State which has the new URL
1605 urlState = this.extractState(this.getLocationHref()),
1608 // Check for a difference
1609 if ( !this.isLastSavedState(urlState) ) {
1610 newState = urlState;
1616 // Check if we have a state with that url
1619 //this.debug('this.safariStatePoll: new');
1620 newState = this.createStateObject();
1623 // Apply the New State
1624 //this.debug('this.safariStatePoll: trigger');
1625 this.Adapter.trigger(window,'popstate');
1632 // ====================================================================
1637 * Send the browser history back one item
1638 * @param {Integer} queue [optional]
1640 back = function(queue){
1641 //this.debug('this.back: called', arguments);
1644 if ( queue !== false && this.busy() ) {
1645 // Wait + Push to Queue
1646 //this.debug('this.back: we must wait', arguments);
1649 callback: this.back,
1656 // Make Busy + Continue
1659 // Fix certain browser bugs that prevent the state from changing
1660 this.doubleCheck(function(){
1673 * Send the browser history forward one item
1674 * @param {Integer} queue [optional]
1676 forward = function(queue){
1677 //this.debug('this.forward: called', arguments);
1680 if ( queue !== false && this.busy() ) {
1681 // Wait + Push to Queue
1682 //this.debug('this.forward: we must wait', arguments);
1685 callback: this.forward,
1692 // Make Busy + Continue
1696 // Fix certain browser bugs that prevent the state from changing
1697 this.doubleCheck(function(){
1704 // End forward closure
1710 * Send the browser history back or forward index times
1711 * @param {Integer} queue [optional]
1713 go = function(index,queue){
1714 //this.debug('this.go: called', arguments);
1722 for ( i=1; i<=index; ++i ) {
1723 this.forward(queue);
1726 else if ( index < 0 ) {
1728 for ( i=-1; i>=index; --i ) {
1733 throw new Error('History.go: History.go requires a positive or negative integer passed.');
1741 // ====================================================================
1742 // HTML5 State Support
1746 * Use native HTML5 History API Implementation
1750 * onPopState(event,extra)
1751 * Refresh the Current State
1753 onPopState = function(event,extra){
1755 var stateId = false, newState = false, currentHash, currentState;
1757 // Reset the double check
1758 this.doubleCheckComplete();
1760 // Check for a Hash, and handle apporiatly
1761 currentHash = this.getHash();
1762 if ( currentHash ) {
1764 currentState = this.extractState(currentHash||this.getLocationHref(),true);
1765 if ( currentState ) {
1766 // We were able to parse it, it must be a State!
1767 // Let's forward to replaceState
1768 //this.debug('this.onPopState: state anchor', currentHash, currentState);
1769 this.replaceState(currentState.data, currentState.title, currentState.url, false);
1772 // Traditional Anchor
1773 //this.debug('this.onPopState: traditional anchor', currentHash);
1774 this.Adapter.trigger(window,'anchorchange');
1778 // We don't care for hashes
1779 this.expectedStateId = false;
1784 stateId = this.Adapter.extractEventData('state',event,extra) || false;
1788 // Vanilla: Back/forward button was used
1789 newState = this.getStateById(stateId);
1791 else if ( this.expectedStateId ) {
1792 // Vanilla: A new state was pushed, and popstate was called manually
1793 newState = this.getStateById(this.expectedStateId);
1797 newState = this.extractState(this.getLocationHref());
1800 // The State did not exist in our store
1802 // Regenerate the State
1803 newState = this.createStateObject(null,null,this.getLocationHref());
1807 this.expectedStateId = false;
1809 // Check if we are the same state
1810 if ( this.isLastSavedState(newState) ) {
1811 // There has been no change (just the page's hash has finally propagated)
1812 //this.debug('this.onPopState: no change', newState, this.savedStates);
1818 this.storeState(newState);
1819 this.saveState(newState);
1821 // Force update of the title
1822 this.setTitle(newState);
1825 this.Adapter.trigger(window,'statechange');
1839 * pushState(data,title,url)
1840 * Add a new State to the history object, become it, and trigger onpopstate
1841 * We have to trigger for HTML4 compatibility
1842 * @param {object} data
1843 * @param {string} title
1844 * @param {string} url
1847 pushState = function(data,title,url,queue){
1848 //this.debug('this.pushState: called', arguments);
1851 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1852 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1856 if ( queue !== false && this.busy() ) {
1857 // Wait + Push to Queue
1858 //this.debug('this.pushState: we must wait', arguments);
1861 callback: this.pushState,
1868 // Make Busy + Continue
1871 // Create the newState
1872 var newState = this.createStateObject(data,title,url);
1875 if ( this.isLastSavedState(newState) ) {
1876 // Won't be a change
1880 // Store the newState
1881 this.storeState(newState);
1882 this.expectedStateId = newState.id;
1884 // Push the newState
1885 history.pushState(newState.id,newState.title,newState.url);
1888 this.Adapter.trigger(window,'popstate');
1891 // End pushState closure
1896 * replaceState(data,title,url)
1897 * Replace the State and trigger onpopstate
1898 * We have to trigger for HTML4 compatibility
1899 * @param {object} data
1900 * @param {string} title
1901 * @param {string} url
1904 replaceState = function(data,title,url,queue){
1905 //this.debug('this.replaceState: called', arguments);
1908 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1909 throw new Error('this.js does not support states with fragement-identifiers (hashes/anchors).');
1913 if ( queue !== false && this.busy() ) {
1914 // Wait + Push to Queue
1915 //this.debug('this.replaceState: we must wait', arguments);
1918 callback: this.replaceState,
1925 // Make Busy + Continue
1928 // Create the newState
1929 var newState = this.createStateObject(data,title,url);
1932 if ( this.isLastSavedState(newState) ) {
1933 // Won't be a change
1937 // Store the newState
1938 this.storeState(newState);
1939 this.expectedStateId = newState.id;
1941 // Push the newState
1942 history.replaceState(newState.id,newState.title,newState.url);
1945 this.Adapter.trigger(window,'popstate');
1948 // End replaceState closure
1953 // ====================================================================
1957 * Bind for Saving Store
1960 // When the page is closed
1961 onUnload = function(){
1963 var currentStore, item, currentStoreString;
1967 currentStore = JSON.parse(this.sessionStorage.getItem('Roo.History.store'))||{};
1974 currentStore.idToState = currentStore.idToState || {};
1975 currentStore.urlToId = currentStore.urlToId || {};
1976 currentStore.stateToId = currentStore.stateToId || {};
1979 for ( item in this.idToState ) {
1980 if ( !this.idToState.hasOwnProperty(item) ) {
1983 currentStore.idToState[item] = this.idToState[item];
1985 for ( item in this.urlToId ) {
1986 if ( !this.urlToId.hasOwnProperty(item) ) {
1989 currentStore.urlToId[item] = this.urlToId[item];
1991 for ( item in this.stateToId ) {
1992 if ( !this.stateToId.hasOwnProperty(item) ) {
1995 currentStore.stateToId[item] = this.stateToId[item];
1999 this.store = currentStore;
2000 this.normalizeStore();
2002 // In Safari, going into Private Browsing mode causes the
2003 // Session Storage object to still exist but if you try and use
2004 // or set any property/function of it it throws the exception
2005 // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
2006 // add something to storage that exceeded the quota." infinitely
2008 currentStoreString = JSON.stringify(currentStore);
2011 this.sessionStorage.setItem('Roo.History.store', currentStoreString);
2014 if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
2015 if (this.sessionStorage.length) {
2016 // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
2017 // removing/resetting the storage can work.
2018 this.sessionStorage.removeItem('Roo.History.store');
2019 this.sessionStorage.setItem('Roo.History.store', currentStoreString);
2021 // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.