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/>
13 // ====================================================================
19 * How long should the interval be before hashchange checks
21 thishashChangeInterval : 100,
25 * How long should the interval be before safari poll checks
27 safariPollInterval : 500,
31 * How long should the interval be before we perform a double check
33 doubleCheckInterval : 500,
37 * Force this.not to append suid
43 * How long should we wait between store calls
49 * How long should we wait between busy events
55 * If true will enable debug messages to be logged
61 * What is the title of the initial state
67 * If true, will force HTMl4 mode (hashtags)
73 * Want to override default options and call init manually.
79 * Which bugs are present
83 * Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
84 * https://bugs.webkit.org/show_bug.cgi?id=56249
89 * Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
90 * https://bugs.webkit.org/show_bug.cgi?id=42940
95 * MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
100 * MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
105 // ========================================================================
111 sessionStorage : false, // sessionStorage
113 intervalList : false, // array normally.
116 * Is History enabled?
120 // ====================================================================
125 * The store for all session specific data
131 * 1-1: State ID to State Object
137 * 1-1: State String to State ID
143 * 1-1: State URL to State ID
149 * Store the states in an array
151 storedStates : false,
155 * Saved the states in an array
161 * The list of queues to use
162 * First In, First Out
171 // ====================================================================
175 * History.stateChanged
176 * States whether or not the state has changed since the last double check was initialised
178 stateChanged : false,
181 * History.doubleChecker
182 * Contains the timeout used for the double checks
184 doubleChecker : false,
187 // Initialise History
188 init : function(options)
191 var emptyFunction = function(){};
195 this.initialTitle = window.document.title;
200 this.storedStates=[];
204 Roo.apply(this,options)
206 // Check Load Status of Adapter
207 //if ( typeof this.Adapter === 'undefined' ) {
211 // Check Load Status of Core
212 if ( typeof this.initCore !== 'undefined' ) {
216 // Check Load Status of HTML4 Support
217 if ( typeof this.initHtml4 !== 'undefined' ) {
223 this.enabled = !this.emulated.pushState;
225 if ( this.emulated.pushState ) {
229 this.pushState = emptyFunction;
230 this.replaceState = emptyFunction;
233 this.Adapter.bind(window,'popstate',this.onPopState);
239 if ( this.sessionStorage ) {
242 this.store = JSON.parse(this.sessionStorage.getItem('Roo.History.store'))||{};
247 this.intervalList.push(setInterval(this.onUnload,this.storeInterval));
249 // For Other Browsers
250 this.Adapter.bind(window,'beforeunload',this.onUnload);
251 this.Adapter.bind(window,'unload',this.onUnload);
254 this.onUnload = emptyFunction;
258 this.normalizeStore();
260 * Clear Intervals on exit to prevent memory leaks
262 this.Adapter.bind(window,"unload",this.clearAllIntervals);
265 * Create the initial State
267 this.saveState(this.storeState(this.extractState(this.getLocationHref(),true)));
271 // Non-Native pushState Implementation
272 if ( !this.emulated.pushState ) {
273 // Be aware, the following is only for native pushState implementations
274 // If you are wanting to include something for all browsers
275 // Then include it above this if block
280 if ( this.bugs.safariPoll ) {
281 this.intervalList.push(setInterval(this.safariStatePoll, this.safariPollInterval));
285 * Ensure Cross Browser Compatibility
287 //if ( window.navigator.vendor === 'Apple Computer, Inc.' || (window.navigator.appCodeName||'') === 'Mozilla' ) {
292 * Fix Safari HashChange Issue
296 this.Adapter.bind(window,'hashchange',function(){
297 _this.Adapter.trigger(window,'popstate');
301 if ( this.getHash() ) {
302 this.Adapter.onDomLoad(function(){
303 _this.Adapter.trigger(window,'hashchange');
308 } // !History.emulated.pushState
311 }; // History.initCore
323 // ========================================================================
327 initCore : function(options){
329 this.intervalList = [];
333 this.sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
334 this.sessionStorage.setItem('TEST', '1');
335 this.sessionStorage.removeItem('TEST');
337 this.sessionStorage = false;
341 if ( typeof this.initCore.initialized !== 'undefined' ) {
346 this.initCore.initialized = true;
355 * Clears all setInterval instances.
357 clearAllIntervals: function()
359 var i, il = this.intervalList;
360 if (typeof il !== "undefined" && il !== null) {
361 for (i = 0; i < il.length; i++) {
362 clearInterval(il[i]);
364 this.intervalList = null;
369 // ====================================================================
373 * debugLog(message,...)
374 * Logs the passed arguments if debug enabled
376 debugLog : function()
378 if ( (this.debug||false) ) {
379 Roo.log.apply(this,arguments);
385 // ====================================================================
389 * getInternetExplorerMajorVersion()
390 * Get's the major version of Internet Explorer
392 * @license Public Domain
393 * @author Benjamin Arthur Lupton <contact@balupton.com>
394 * @author James Padolsey <https://gist.github.com/527683>
396 getInternetExplorerMajorVersion : function(){
397 var result = this.getInternetExplorerMajorVersion.cached =
398 (typeof this.getInternetExplorerMajorVersion.cached !== 'undefined')
399 ? this.getInternetExplorerMajorVersion.cached
402 div = window.document.createElement('div'),
403 all = div.getElementsByTagName('i');
404 while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
405 return (v > 4) ? v : false;
412 * isInternetExplorer()
413 * Are we using Internet Explorer?
415 * @license Public Domain
416 * @author Benjamin Arthur Lupton <contact@balupton.com>
418 isInternetExplorer : function(){
420 this.isInternetExplorer.cached =
421 (typeof this.isInternetExplorer.cached !== 'undefined')
422 ? this.isInternetExplorer.cached
423 : Boolean(this.getInternetExplorerMajorVersion())
429 * Which features require emulating?
437 initEmulated : function()
441 if (this.html4Mode) {
447 this.emulated.pushState = !Boolean(
448 window.history && window.history.pushState && window.history.replaceState
450 (/ 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) */
451 || (/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 */
454 this.emulated.hashChange = Boolean(
455 !(('onhashchange' in window) || ('onhashchange' in window.document))
457 (this.isInternetExplorer() && this.getInternetExplorerMajorVersion() < 8)
466 * Checks to see if the Object is Empty
467 * @param {Object} obj
470 isEmptyObject = function(obj) {
471 for ( var name in obj ) {
472 if ( obj.hasOwnProperty(name) ) {
481 * Clones a object and eliminate all references to the original contexts
482 * @param {Object} obj
485 cloneObject = function(obj) {
488 hash = JSON.stringify(obj);
489 newObj = JSON.parse(hash);
498 // ====================================================================
503 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
504 * @return {String} rootUrl
506 getRootUrl = function(){
508 var rootUrl = window.document.location.protocol+'//'+(window.document.location.hostname||window.document.location.host);
509 if ( window.document.location.port||false ) {
510 rootUrl += ':'+window.document.location.port;
520 * Fetches the `href` attribute of the `<base href="...">` element if it exists
521 * @return {String} baseHref
523 getBaseHref = function(){
526 baseElements = window.document.getElementsByTagName('base'),
530 // Test for Base Element
531 if ( baseElements.length === 1 ) {
532 // Prepare for Base Element
533 baseElement = baseElements[0];
534 baseHref = baseElement.href.replace(/[^\/]+$/,'');
537 // Adjust trailing slash
538 baseHref = baseHref.replace(/\/+$/,'');
539 if ( baseHref ) baseHref += '/';
547 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
548 * @return {String} baseUrl
550 getBaseUrl = function(){
552 var baseUrl = this.getBaseHref()||this.getBasePageUrl()||this.getRootUrl();
560 * Fetches the URL of the current page
561 * @return {String} pageUrl
563 getPageUrl = function(){
566 State = this.getState(false,false),
567 stateUrl = (State||{}).url||this.getLocationHref(),
571 pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
572 return (/\./).test(part) ? part : part+'/';
581 * Fetches the Url of the directory of the current page
582 * @return {String} basePageUrl
584 getBasePageUrl = function(){
586 var basePageUrl = (this.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
587 return (/[^\/]$/).test(part) ? '' : part;
588 }).replace(/\/+$/,'')+'/';
596 * Ensures that we have an absolute URL and not a relative URL
597 * @param {string} url
598 * @param {Boolean} allowBaseHref
599 * @return {string} fullUrl
601 getFullUrl = function(url,allowBaseHref){
603 var fullUrl = url, firstChar = url.substring(0,1);
604 allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
607 if ( /[a-z]+\:\/\//.test(url) ) {
610 else if ( firstChar === '/' ) {
612 fullUrl = this.getRootUrl()+url.replace(/^\/+/,'');
614 else if ( firstChar === '#' ) {
616 fullUrl = this.getPageUrl().replace(/#.*/,'')+url;
618 else if ( firstChar === '?' ) {
620 fullUrl = this.getPageUrl().replace(/[\?#].*/,'')+url;
624 if ( allowBaseHref ) {
625 fullUrl = this.getBaseUrl()+url.replace(/^(\.\/)+/,'');
627 fullUrl = this.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
629 // We have an if condition above as we do not want hashes
630 // which are relative to the baseHref in our URLs
631 // as if the baseHref changes, then all our bookmarks
632 // would now point to different locations
633 // whereas the basePageUrl will always stay the same
637 return fullUrl.replace(/\#$/,'');
642 * Ensures that we have a relative URL and not a absolute URL
643 * @param {string} url
644 * @return {string} url
646 getShortUrl = function(url){
648 var shortUrl = url, baseUrl = this.getBaseUrl(), rootUrl = this.getRootUrl();
651 if ( this.emulated.pushState ) {
652 // We are in a if statement as when pushState is not emulated
653 // The actual url these short urls are relative to can change
654 // So within the same session, we the url may end up somewhere different
655 shortUrl = shortUrl.replace(baseUrl,'');
659 shortUrl = shortUrl.replace(rootUrl,'/');
661 // Ensure we can still detect it as a state
662 if ( this.isTraditionalAnchor(shortUrl) ) {
663 shortUrl = './'+shortUrl;
667 shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
674 * getLocationHref(document)
675 * Returns a normalized version of document.location.href
676 * accounting for browser inconsistencies, etc.
678 * This URL will be URI-encoded and will include the hash
680 * @param {object} document
681 * @return {string} url
683 getLocationHref = function(doc) {
684 doc = doc || window.document;
686 // most of the time, this will be true
687 if (doc.URL === doc.location.href)
688 return doc.location.href;
690 // some versions of webkit URI-decode document.location.href
691 // but they leave document.URL in an encoded state
692 if (doc.location.href === decodeURIComponent(doc.URL))
695 // FF 3.6 only updates document.URL when a page is reloaded
696 // document.location.href is updated correctly
697 if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
698 return doc.location.href;
700 if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
701 return doc.location.href;
703 return doc.URL || doc.location.href;
710 * Noramlize the store by adding necessary values
712 normalizeStore = function(){
713 this.store.idToState = this.store.idToState||{};
714 this.store.urlToId = this.store.urlToId||{};
715 this.store.stateToId = this.store.stateToId||{};
720 * Get an object containing the data, title and url of the current state
721 * @param {Boolean} friendly
722 * @param {Boolean} create
723 * @return {Object} State
725 getState : function(friendly,create){
727 if ( typeof friendly === 'undefined' ) { friendly = true; }
728 if ( typeof create === 'undefined' ) { create = true; }
731 var State = this.getLastSavedState();
734 if ( !State && create ) {
735 State = this.createStateObject();
740 State = this.cloneObject(State);
741 State.url = this.cleanUrl||State.url;
749 * getIdByState(State)
750 * Gets a ID for a State
751 * @param {State} newState
752 * @return {String} id
754 getIdByState = function(newState){
757 var id = this.extractId(newState.url),
761 // Find ID via State String
762 str = this.getStateString(newState);
763 if ( typeof this.stateToId[str] !== 'undefined' ) {
764 id = this.stateToId[str];
766 else if ( typeof this.store.stateToId[str] !== 'undefined' ) {
767 id = this.store.stateToId[str];
772 id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
773 if ( typeof this.idToState[id] === 'undefined' && typeof this.store.idToState[id] === 'undefined' ) {
778 // Apply the new State to the ID
779 this.stateToId[str] = id;
780 this.idToState[id] = newState;
789 * normalizeState(State)
790 * Expands a State Object
791 * @param {object} State
794 normalizeState = function(oldState){
796 var newState, dataNotEmpty;
799 if ( !oldState || (typeof oldState !== 'object') ) {
804 if ( typeof oldState.normalized !== 'undefined' ) {
809 if ( !oldState.data || (typeof oldState.data !== 'object') ) {
813 // ----------------------------------------------------------------
817 newState.normalized = true;
818 newState.title = oldState.title||'';
819 newState.url = this.getFullUrl(oldState.url?oldState.url:(this.getLocationHref()));
820 newState.hash = this.getShortUrl(newState.url);
821 newState.data = this.cloneObject(oldState.data);
824 newState.id = this.getIdByState(newState);
826 // ----------------------------------------------------------------
829 newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
830 newState.url = newState.cleanUrl;
832 // Check to see if we have more than just a url
833 dataNotEmpty = !this.isEmptyObject(newState.data);
836 if ( (newState.title || dataNotEmpty) && this.disableSuid !== true ) {
838 newState.hash = this.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
839 if ( !/\?/.test(newState.hash) ) {
840 newState.hash += '?';
842 newState.hash += '&_suid='+newState.id;
845 // Create the Hashed URL
846 newState.hashedUrl = this.getFullUrl(newState.hash);
848 // ----------------------------------------------------------------
850 // Update the URL if we have a duplicate
851 if ( (this.emulated.pushState || this.bugs.safariPoll) && this.hasUrlDuplicate(newState) ) {
852 newState.url = newState.hashedUrl;
855 // ----------------------------------------------------------------
862 * createStateObject(data,title,url)
863 * Creates a object based on the data, title and url state params
864 * @param {object} data
865 * @param {string} title
866 * @param {string} url
869 createStateObject = function(data,title,url){
878 State = this.normalizeState(State);
886 * Get a state by it's UID
889 getStateById = function(id){
894 var State = this.idToState[id] || this.store.idToState[id] || undefined;
901 * Get a State's String
902 * @param {State} passedState
904 getStateString = function(passedState){
906 var State, cleanedState, str;
909 State = this.normalizeState(passedState);
914 title: passedState.title,
919 str = JSON.stringify(cleanedState);
927 * @param {State} passedState
928 * @return {String} id
930 getStateId = function(passedState){
935 State = this.normalizeState(passedState);
945 * getHashByState(State)
946 * Creates a Hash for the State Object
947 * @param {State} passedState
948 * @return {String} hash
950 getHashByState = function(passedState){
955 State = this.normalizeState(passedState);
965 * extractId(url_or_hash)
966 * Get a State ID by it's URL or Hash
967 * @param {string} url_or_hash
968 * @return {string} id
970 this.extractId = function ( url_or_hash ) {
972 var id,parts,url, tmp;
976 // If the URL has a #, use the id from before the #
977 if (url_or_hash.indexOf('#') != -1)
979 tmp = url_or_hash.split("#")[0];
986 parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
987 url = parts ? (parts[1]||url_or_hash) : url_or_hash;
988 id = parts ? String(parts[2]||'') : '';
995 * isTraditionalAnchor
996 * Checks to see if the url is a traditional anchor or not
997 * @param {String} url_or_hash
1000 isTraditionalAnchor = function(url_or_hash){
1002 var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
1005 return isTraditional;
1010 * Get a State by it's URL or Hash
1011 * @param {String} url_or_hash
1012 * @return {State|null}
1014 extractState = function(url_or_hash,create){
1016 var State = null, id, url;
1017 create = create||false;
1020 id = this.extractId(url_or_hash);
1022 State = this.getStateById(id);
1025 // Fetch SUID returned no State
1028 url = this.getFullUrl(url_or_hash);
1031 id = this.getIdByUrl(url)||false;
1033 State = this.getStateById(id);
1037 if ( !State && create && !this.isTraditionalAnchor(url_or_hash) ) {
1038 State = this.createStateObject(null,null,url);
1048 * Get a State ID by a State URL
1050 getIdByUrl = function(url){
1052 var id = this.urlToId[url] || this.store.urlToId[url] || undefined;
1059 * getLastSavedState()
1060 * Get an object containing the data, title and url of the current state
1061 * @return {Object} State
1063 getLastSavedState = function(){
1064 return this.savedStates[this.savedStates.length-1]||undefined;
1068 * getLastStoredState()
1069 * Get an object containing the data, title and url of the current state
1070 * @return {Object} State
1072 getLastStoredState = function(){
1073 return this.storedStates[this.storedStates.length-1]||undefined;
1078 * Checks if a Url will have a url conflict
1079 * @param {Object} newState
1080 * @return {Boolean} hasDuplicate
1082 hasUrlDuplicate = function(newState) {
1084 var hasDuplicate = false,
1088 oldState = this.extractState(newState.url);
1091 hasDuplicate = oldState && oldState.id !== newState.id;
1094 return hasDuplicate;
1100 * @param {Object} newState
1101 * @return {Object} newState
1103 storeState = function(newState){
1105 this.urlToId[newState.url] = newState.id;
1108 this.storedStates.push(this.cloneObject(newState));
1115 * isLastSavedState(newState)
1116 * Tests to see if the state is the last state
1117 * @param {Object} newState
1118 * @return {boolean} isLast
1120 isLastSavedState = function(newState){
1123 newId, oldState, oldId;
1126 if ( this.savedStates.length ) {
1127 newId = newState.id;
1128 oldState = this.getLastSavedState();
1129 oldId = oldState.id;
1132 isLast = (newId === oldId);
1142 * @param {Object} newState
1143 * @return {boolean} changed
1145 saveState = function(newState){
1147 if ( this.isLastSavedState(newState) ) {
1152 this.savedStates.push(this.cloneObject(newState));
1160 * Gets a state by the index
1161 * @param {integer} index
1164 getStateByIndex = function(index){
1169 if ( typeof index === 'undefined' ) {
1170 // Get the last inserted
1171 State = this.savedStates[this.savedStates.length-1];
1173 else if ( index < 0 ) {
1175 State = this.savedStates[this.savedStates.length+index];
1178 // Get from the beginning
1179 State = this.savedStates[index];
1188 * Gets the current index
1191 getCurrentIndex = function(){
1196 if(this.savedStates.length < 1) {
1200 index = this.savedStates.length-1;
1205 // ====================================================================
1210 * @param {Location=} location
1211 * Gets the current document hash
1212 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
1215 getHash = function(doc){
1216 var url = this.getLocationHref(doc),
1218 hash = this.getHashByUrl(url);
1224 * normalize and Unescape a Hash
1225 * @param {String} hash
1228 unescapeHash = function(hash){
1230 var result = this.normalizeHash(hash);
1233 result = decodeURIComponent(result);
1241 * normalize a hash across browsers
1244 normalizeHash = function(hash){
1246 var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
1254 * Sets the document hash
1255 * @param {string} hash
1256 * @return {Roo.History}
1258 setHash = function(hash,queue){
1263 if ( queue !== false && this.busy() ) {
1264 // Wait + Push to Queue
1265 //this.debug('this.setHash: we must wait', arguments);
1268 callback: this.setHash,
1276 //this.debug('this.setHash: called',hash);
1278 // Make Busy + Continue
1281 // Check if hash is a state
1282 State = this.extractState(hash,true);
1283 if ( State && !this.emulated.pushState ) {
1284 // Hash is a state so skip the setHash
1285 //this.debug('this.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
1288 this.pushState(State.data,State.title,State.url,false);
1290 else if ( this.getHash() !== hash ) {
1291 // Hash is a proper hash, so apply it
1293 // Handle browser bugs
1294 if ( this.bugs.setHash ) {
1295 // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
1297 // Fetch the base page
1298 pageUrl = this.getPageUrl();
1300 // Safari hash apply
1301 this.pushState(null,null,pageUrl+'#'+hash,false);
1304 // Normal hash apply
1305 window.document.location.hash = hash;
1315 * normalize and Escape a Hash
1318 escapeHash = function(hash){
1320 var result = normalizeHash(hash);
1323 result = window.encodeURIComponent(result);
1326 if ( !this.bugs.hashEscape ) {
1327 // Restore common parts
1329 .replace(/\%21/g,'!')
1330 .replace(/\%26/g,'&')
1331 .replace(/\%3D/g,'=')
1332 .replace(/\%3F/g,'?');
1341 * Extracts the Hash from a URL
1342 * @param {string} url
1343 * @return {string} url
1345 getHashByUrl = function(url){
1347 var hash = String(url)
1348 .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
1352 hash = this.unescapeHash(hash);
1360 * Applies the title to the document
1361 * @param {State} newState
1364 setTitle = function(newState){
1366 var title = newState.title,
1371 firstState = this.getStateByIndex(0);
1372 if ( firstState && firstState.url === newState.url ) {
1373 title = firstState.title||this.initialTitle;
1379 window.document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
1381 catch ( Exception ) { }
1382 window.document.title = title;
1389 // ====================================================================
1395 * @param {boolean} value [optional]
1396 * @return {boolean} busy
1398 busy = function(value){
1400 if ( typeof value !== 'undefined' ) {
1401 //this.debug('this.busy: changing ['+(this.busy.flag||false)+'] to ['+(value||false)+']', this.queues.length);
1402 this.busy_flag = value;
1405 else if ( typeof this.busy_flag === 'undefined' ) {
1406 this.busy_flag = false;
1410 if ( !this.busy_flag ) {
1411 // Execute the next item in the queue
1412 window.clearTimeout(this.busy.timeout);
1413 var fireNext = function(){
1415 if ( this.busy_flag ) return;
1416 for ( i=this.queues.length-1; i >= 0; --i ) {
1417 queue = this.queues[i];
1418 if ( queue.length === 0 ) continue;
1419 item = queue.shift();
1420 this.fireQueueItem(item);
1421 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1424 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1428 return this.busy_flag;
1434 * fireQueueItem(item)
1436 * @param {Object} item
1437 * @return {Mixed} result
1439 fireQueueItem = function(item){
1440 return item.callback.apply(item.scope||this,item.args||[]);
1444 * pushQueue(callback,args)
1445 * Add an item to the queue
1446 * @param {Object} item [scope,callback,args,queue]
1448 pushQueue = function(item){
1449 // Prepare the queue
1450 this.queues[item.queue||0] = this.queues[item.queue||0]||[];
1453 this.queues[item.queue||0].push(item);
1460 * queue (item,queue), (func,queue), (func), (item)
1461 * Either firs the item now if not busy, or adds it to the queue
1463 queue = function(item,queue){
1465 if ( typeof item === 'function' ) {
1470 if ( typeof queue !== 'undefined' ) {
1475 if ( this.busy() ) {
1476 this.pushQueue(item);
1478 this.fireQueueItem(item);
1489 clearQueue = function(){
1490 this.busy_flag = false;
1498 * doubleCheckComplete()
1499 * Complete a double check
1500 * @return {Roo.History}
1502 doubleCheckComplete = function(){
1504 this.stateChanged = true;
1507 this.doubleCheckClear();
1514 * doubleCheckClear()
1515 * Clear a double check
1516 * @return {Roo.History}
1518 doubleCheckClear = function(){
1520 if ( this.doubleChecker ) {
1521 window.clearTimeout(this.doubleChecker);
1522 this.doubleChecker = false;
1531 * Create a double check
1532 * @return {Roo.History}
1534 doubleCheck = function(tryAgain){
1536 this.stateChanged = false;
1537 this.doubleCheckClear();
1539 // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
1540 // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
1541 if ( this.bugs.ieDoubleCheck ) {
1543 this.doubleChecker = window.setTimeout(
1545 this.doubleCheckClear();
1546 if ( !this.stateChanged ) {
1547 //this.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
1553 this.doubleCheckInterval
1562 // ====================================================================
1567 * Poll the current state
1568 * @return {Roo.History}
1570 safariStatePoll = function(){
1573 // Get the Last State which has the new URL
1575 urlState = this.extractState(this.getLocationHref()),
1578 // Check for a difference
1579 if ( !this.isLastSavedState(urlState) ) {
1580 newState = urlState;
1586 // Check if we have a state with that url
1589 //this.debug('this.safariStatePoll: new');
1590 newState = this.createStateObject();
1593 // Apply the New State
1594 //this.debug('this.safariStatePoll: trigger');
1595 this.Adapter.trigger(window,'popstate');
1602 // ====================================================================
1607 * Send the browser history back one item
1608 * @param {Integer} queue [optional]
1610 back = function(queue){
1611 //this.debug('this.back: called', arguments);
1614 if ( queue !== false && this.busy() ) {
1615 // Wait + Push to Queue
1616 //this.debug('this.back: we must wait', arguments);
1619 callback: this.back,
1626 // Make Busy + Continue
1629 // Fix certain browser bugs that prevent the state from changing
1630 this.doubleCheck(function(){
1643 * Send the browser history forward one item
1644 * @param {Integer} queue [optional]
1646 forward = function(queue){
1647 //this.debug('this.forward: called', arguments);
1650 if ( queue !== false && this.busy() ) {
1651 // Wait + Push to Queue
1652 //this.debug('this.forward: we must wait', arguments);
1655 callback: this.forward,
1662 // Make Busy + Continue
1666 // Fix certain browser bugs that prevent the state from changing
1667 this.doubleCheck(function(){
1674 // End forward closure
1680 * Send the browser history back or forward index times
1681 * @param {Integer} queue [optional]
1683 go = function(index,queue){
1684 //this.debug('this.go: called', arguments);
1692 for ( i=1; i<=index; ++i ) {
1693 this.forward(queue);
1696 else if ( index < 0 ) {
1698 for ( i=-1; i>=index; --i ) {
1703 throw new Error('History.go: History.go requires a positive or negative integer passed.');
1711 // ====================================================================
1712 // HTML5 State Support
1716 * Use native HTML5 History API Implementation
1720 * onPopState(event,extra)
1721 * Refresh the Current State
1723 onPopState = function(event,extra){
1725 var stateId = false, newState = false, currentHash, currentState;
1727 // Reset the double check
1728 this.doubleCheckComplete();
1730 // Check for a Hash, and handle apporiatly
1731 currentHash = this.getHash();
1732 if ( currentHash ) {
1734 currentState = this.extractState(currentHash||this.getLocationHref(),true);
1735 if ( currentState ) {
1736 // We were able to parse it, it must be a State!
1737 // Let's forward to replaceState
1738 //this.debug('this.onPopState: state anchor', currentHash, currentState);
1739 this.replaceState(currentState.data, currentState.title, currentState.url, false);
1742 // Traditional Anchor
1743 //this.debug('this.onPopState: traditional anchor', currentHash);
1744 this.Adapter.trigger(window,'anchorchange');
1748 // We don't care for hashes
1749 this.expectedStateId = false;
1754 stateId = this.Adapter.extractEventData('state',event,extra) || false;
1758 // Vanilla: Back/forward button was used
1759 newState = this.getStateById(stateId);
1761 else if ( this.expectedStateId ) {
1762 // Vanilla: A new state was pushed, and popstate was called manually
1763 newState = this.getStateById(this.expectedStateId);
1767 newState = this.extractState(this.getLocationHref());
1770 // The State did not exist in our store
1772 // Regenerate the State
1773 newState = this.createStateObject(null,null,this.getLocationHref());
1777 this.expectedStateId = false;
1779 // Check if we are the same state
1780 if ( this.isLastSavedState(newState) ) {
1781 // There has been no change (just the page's hash has finally propagated)
1782 //this.debug('this.onPopState: no change', newState, this.savedStates);
1788 this.storeState(newState);
1789 this.saveState(newState);
1791 // Force update of the title
1792 this.setTitle(newState);
1795 this.Adapter.trigger(window,'statechange');
1809 * pushState(data,title,url)
1810 * Add a new State to the history object, become it, and trigger onpopstate
1811 * We have to trigger for HTML4 compatibility
1812 * @param {object} data
1813 * @param {string} title
1814 * @param {string} url
1817 pushState = function(data,title,url,queue){
1818 //this.debug('this.pushState: called', arguments);
1821 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1822 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1826 if ( queue !== false && this.busy() ) {
1827 // Wait + Push to Queue
1828 //this.debug('this.pushState: we must wait', arguments);
1831 callback: this.pushState,
1838 // Make Busy + Continue
1841 // Create the newState
1842 var newState = this.createStateObject(data,title,url);
1845 if ( this.isLastSavedState(newState) ) {
1846 // Won't be a change
1850 // Store the newState
1851 this.storeState(newState);
1852 this.expectedStateId = newState.id;
1854 // Push the newState
1855 history.pushState(newState.id,newState.title,newState.url);
1858 this.Adapter.trigger(window,'popstate');
1861 // End pushState closure
1866 * replaceState(data,title,url)
1867 * Replace the State and trigger onpopstate
1868 * We have to trigger for HTML4 compatibility
1869 * @param {object} data
1870 * @param {string} title
1871 * @param {string} url
1874 replaceState = function(data,title,url,queue){
1875 //this.debug('this.replaceState: called', arguments);
1878 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1879 throw new Error('this.js does not support states with fragement-identifiers (hashes/anchors).');
1883 if ( queue !== false && this.busy() ) {
1884 // Wait + Push to Queue
1885 //this.debug('this.replaceState: we must wait', arguments);
1888 callback: this.replaceState,
1895 // Make Busy + Continue
1898 // Create the newState
1899 var newState = this.createStateObject(data,title,url);
1902 if ( this.isLastSavedState(newState) ) {
1903 // Won't be a change
1907 // Store the newState
1908 this.storeState(newState);
1909 this.expectedStateId = newState.id;
1911 // Push the newState
1912 history.replaceState(newState.id,newState.title,newState.url);
1915 this.Adapter.trigger(window,'popstate');
1918 // End replaceState closure
1923 // ====================================================================
1927 * Bind for Saving Store
1930 // When the page is closed
1931 onUnload = function(){
1933 var currentStore, item, currentStoreString;
1937 currentStore = JSON.parse(this.sessionStorage.getItem('Roo.History.store'))||{};
1944 currentStore.idToState = currentStore.idToState || {};
1945 currentStore.urlToId = currentStore.urlToId || {};
1946 currentStore.stateToId = currentStore.stateToId || {};
1949 for ( item in this.idToState ) {
1950 if ( !this.idToState.hasOwnProperty(item) ) {
1953 currentStore.idToState[item] = this.idToState[item];
1955 for ( item in this.urlToId ) {
1956 if ( !this.urlToId.hasOwnProperty(item) ) {
1959 currentStore.urlToId[item] = this.urlToId[item];
1961 for ( item in this.stateToId ) {
1962 if ( !this.stateToId.hasOwnProperty(item) ) {
1965 currentStore.stateToId[item] = this.stateToId[item];
1969 this.store = currentStore;
1970 this.normalizeStore();
1972 // In Safari, going into Private Browsing mode causes the
1973 // Session Storage object to still exist but if you try and use
1974 // or set any property/function of it it throws the exception
1975 // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
1976 // add something to storage that exceeded the quota." infinitely
1978 currentStoreString = JSON.stringify(currentStore);
1981 this.sessionStorage.setItem('Roo.History.store', currentStoreString);
1984 if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
1985 if (this.sessionStorage.length) {
1986 // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
1987 // removing/resetting the storage can work.
1988 this.sessionStorage.removeItem('Roo.History.store');
1989 this.sessionStorage.setItem('Roo.History.store', currentStoreString);
1991 // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
2002 // Try to Initialise History
2003 if (!History.options || !History.options.delayInit) {