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' ) {
289 * Fix Safari HashChange Issue
293 this.Adapter.bind(window,'hashchange',function(){
294 this.Adapter.trigger(window,'popstate');
298 if ( this.getHash() ) {
299 this.Adapter.onDomLoad(function(){
300 this.Adapter.trigger(window,'hashchange');
305 } // !History.emulated.pushState
308 }; // History.initCore
320 // ========================================================================
324 initCore : function(options){
326 this.intervalList = [];
330 this.sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
331 this.sessionStorage.setItem('TEST', '1');
332 this.sessionStorage.removeItem('TEST');
334 this.sessionStorage = false;
338 if ( typeof this.initCore.initialized !== 'undefined' ) {
343 this.initCore.initialized = true;
352 * Clears all setInterval instances.
354 clearAllIntervals: function()
356 var i, il = this.intervalList;
357 if (typeof il !== "undefined" && il !== null) {
358 for (i = 0; i < il.length; i++) {
359 clearInterval(il[i]);
361 this.intervalList = null;
366 // ====================================================================
370 * debugLog(message,...)
371 * Logs the passed arguments if debug enabled
373 debugLog : function()
375 if ( (this.debug||false) ) {
376 Roo.log.apply(this,arguments);
382 // ====================================================================
386 * getInternetExplorerMajorVersion()
387 * Get's the major version of Internet Explorer
389 * @license Public Domain
390 * @author Benjamin Arthur Lupton <contact@balupton.com>
391 * @author James Padolsey <https://gist.github.com/527683>
393 getInternetExplorerMajorVersion : function(){
394 var result = this.getInternetExplorerMajorVersion.cached =
395 (typeof this.getInternetExplorerMajorVersion.cached !== 'undefined')
396 ? this.getInternetExplorerMajorVersion.cached
399 div = window.document.createElement('div'),
400 all = div.getElementsByTagName('i');
401 while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
402 return (v > 4) ? v : false;
409 * isInternetExplorer()
410 * Are we using Internet Explorer?
412 * @license Public Domain
413 * @author Benjamin Arthur Lupton <contact@balupton.com>
415 isInternetExplorer : function(){
417 this.isInternetExplorer.cached =
418 (typeof this.isInternetExplorer.cached !== 'undefined')
419 ? this.isInternetExplorer.cached
420 : Boolean(this.getInternetExplorerMajorVersion())
426 * Which features require emulating?
434 initEmulated : function()
438 if (this.html4Mode) {
444 this.emulated.pushState = !Boolean(
445 window.history && window.history.pushState && window.history.replaceState
447 (/ 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) */
448 || (/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 */
451 this.emulated.hashChange = Boolean(
452 !(('onhashchange' in window) || ('onhashchange' in window.document))
454 (this.isInternetExplorer() && this.getInternetExplorerMajorVersion() < 8)
463 * Checks to see if the Object is Empty
464 * @param {Object} obj
467 isEmptyObject = function(obj) {
468 for ( var name in obj ) {
469 if ( obj.hasOwnProperty(name) ) {
478 * Clones a object and eliminate all references to the original contexts
479 * @param {Object} obj
482 cloneObject = function(obj) {
485 hash = JSON.stringify(obj);
486 newObj = JSON.parse(hash);
495 // ====================================================================
500 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
501 * @return {String} rootUrl
503 getRootUrl = function(){
505 var rootUrl = window.document.location.protocol+'//'+(window.document.location.hostname||window.document.location.host);
506 if ( window.document.location.port||false ) {
507 rootUrl += ':'+window.document.location.port;
517 * Fetches the `href` attribute of the `<base href="...">` element if it exists
518 * @return {String} baseHref
520 getBaseHref = function(){
523 baseElements = window.document.getElementsByTagName('base'),
527 // Test for Base Element
528 if ( baseElements.length === 1 ) {
529 // Prepare for Base Element
530 baseElement = baseElements[0];
531 baseHref = baseElement.href.replace(/[^\/]+$/,'');
534 // Adjust trailing slash
535 baseHref = baseHref.replace(/\/+$/,'');
536 if ( baseHref ) baseHref += '/';
544 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
545 * @return {String} baseUrl
547 getBaseUrl = function(){
549 var baseUrl = this.getBaseHref()||this.getBasePageUrl()||this.getRootUrl();
557 * Fetches the URL of the current page
558 * @return {String} pageUrl
560 getPageUrl = function(){
563 State = this.getState(false,false),
564 stateUrl = (State||{}).url||this.getLocationHref(),
568 pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
569 return (/\./).test(part) ? part : part+'/';
578 * Fetches the Url of the directory of the current page
579 * @return {String} basePageUrl
581 getBasePageUrl = function(){
583 var basePageUrl = (this.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
584 return (/[^\/]$/).test(part) ? '' : part;
585 }).replace(/\/+$/,'')+'/';
593 * Ensures that we have an absolute URL and not a relative URL
594 * @param {string} url
595 * @param {Boolean} allowBaseHref
596 * @return {string} fullUrl
598 getFullUrl = function(url,allowBaseHref){
600 var fullUrl = url, firstChar = url.substring(0,1);
601 allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
604 if ( /[a-z]+\:\/\//.test(url) ) {
607 else if ( firstChar === '/' ) {
609 fullUrl = this.getRootUrl()+url.replace(/^\/+/,'');
611 else if ( firstChar === '#' ) {
613 fullUrl = this.getPageUrl().replace(/#.*/,'')+url;
615 else if ( firstChar === '?' ) {
617 fullUrl = this.getPageUrl().replace(/[\?#].*/,'')+url;
621 if ( allowBaseHref ) {
622 fullUrl = this.getBaseUrl()+url.replace(/^(\.\/)+/,'');
624 fullUrl = this.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
626 // We have an if condition above as we do not want hashes
627 // which are relative to the baseHref in our URLs
628 // as if the baseHref changes, then all our bookmarks
629 // would now point to different locations
630 // whereas the basePageUrl will always stay the same
634 return fullUrl.replace(/\#$/,'');
639 * Ensures that we have a relative URL and not a absolute URL
640 * @param {string} url
641 * @return {string} url
643 getShortUrl = function(url){
645 var shortUrl = url, baseUrl = this.getBaseUrl(), rootUrl = this.getRootUrl();
648 if ( this.emulated.pushState ) {
649 // We are in a if statement as when pushState is not emulated
650 // The actual url these short urls are relative to can change
651 // So within the same session, we the url may end up somewhere different
652 shortUrl = shortUrl.replace(baseUrl,'');
656 shortUrl = shortUrl.replace(rootUrl,'/');
658 // Ensure we can still detect it as a state
659 if ( this.isTraditionalAnchor(shortUrl) ) {
660 shortUrl = './'+shortUrl;
664 shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
671 * getLocationHref(document)
672 * Returns a normalized version of document.location.href
673 * accounting for browser inconsistencies, etc.
675 * This URL will be URI-encoded and will include the hash
677 * @param {object} document
678 * @return {string} url
680 getLocationHref = function(doc) {
681 doc = doc || window.document;
683 // most of the time, this will be true
684 if (doc.URL === doc.location.href)
685 return doc.location.href;
687 // some versions of webkit URI-decode document.location.href
688 // but they leave document.URL in an encoded state
689 if (doc.location.href === decodeURIComponent(doc.URL))
692 // FF 3.6 only updates document.URL when a page is reloaded
693 // document.location.href is updated correctly
694 if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
695 return doc.location.href;
697 if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
698 return doc.location.href;
700 return doc.URL || doc.location.href;
707 * Noramlize the store by adding necessary values
709 normalizeStore = function(){
710 this.store.idToState = this.store.idToState||{};
711 this.store.urlToId = this.store.urlToId||{};
712 this.store.stateToId = this.store.stateToId||{};
717 * Get an object containing the data, title and url of the current state
718 * @param {Boolean} friendly
719 * @param {Boolean} create
720 * @return {Object} State
722 getState : function(friendly,create){
724 if ( typeof friendly === 'undefined' ) { friendly = true; }
725 if ( typeof create === 'undefined' ) { create = true; }
728 var State = this.getLastSavedState();
731 if ( !State && create ) {
732 State = this.createStateObject();
737 State = this.cloneObject(State);
738 State.url = this.cleanUrl||State.url;
746 * getIdByState(State)
747 * Gets a ID for a State
748 * @param {State} newState
749 * @return {String} id
751 getIdByState = function(newState){
754 var id = this.extractId(newState.url),
758 // Find ID via State String
759 str = this.getStateString(newState);
760 if ( typeof this.stateToId[str] !== 'undefined' ) {
761 id = this.stateToId[str];
763 else if ( typeof this.store.stateToId[str] !== 'undefined' ) {
764 id = this.store.stateToId[str];
769 id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
770 if ( typeof this.idToState[id] === 'undefined' && typeof this.store.idToState[id] === 'undefined' ) {
775 // Apply the new State to the ID
776 this.stateToId[str] = id;
777 this.idToState[id] = newState;
786 * normalizeState(State)
787 * Expands a State Object
788 * @param {object} State
791 normalizeState = function(oldState){
793 var newState, dataNotEmpty;
796 if ( !oldState || (typeof oldState !== 'object') ) {
801 if ( typeof oldState.normalized !== 'undefined' ) {
806 if ( !oldState.data || (typeof oldState.data !== 'object') ) {
810 // ----------------------------------------------------------------
814 newState.normalized = true;
815 newState.title = oldState.title||'';
816 newState.url = this.getFullUrl(oldState.url?oldState.url:(this.getLocationHref()));
817 newState.hash = this.getShortUrl(newState.url);
818 newState.data = this.cloneObject(oldState.data);
821 newState.id = this.getIdByState(newState);
823 // ----------------------------------------------------------------
826 newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
827 newState.url = newState.cleanUrl;
829 // Check to see if we have more than just a url
830 dataNotEmpty = !this.isEmptyObject(newState.data);
833 if ( (newState.title || dataNotEmpty) && this.disableSuid !== true ) {
835 newState.hash = this.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
836 if ( !/\?/.test(newState.hash) ) {
837 newState.hash += '?';
839 newState.hash += '&_suid='+newState.id;
842 // Create the Hashed URL
843 newState.hashedUrl = this.getFullUrl(newState.hash);
845 // ----------------------------------------------------------------
847 // Update the URL if we have a duplicate
848 if ( (this.emulated.pushState || this.bugs.safariPoll) && this.hasUrlDuplicate(newState) ) {
849 newState.url = newState.hashedUrl;
852 // ----------------------------------------------------------------
859 * createStateObject(data,title,url)
860 * Creates a object based on the data, title and url state params
861 * @param {object} data
862 * @param {string} title
863 * @param {string} url
866 createStateObject = function(data,title,url){
875 State = this.normalizeState(State);
883 * Get a state by it's UID
886 getStateById = function(id){
891 var State = this.idToState[id] || this.store.idToState[id] || undefined;
898 * Get a State's String
899 * @param {State} passedState
901 getStateString = function(passedState){
903 var State, cleanedState, str;
906 State = this.normalizeState(passedState);
911 title: passedState.title,
916 str = JSON.stringify(cleanedState);
924 * @param {State} passedState
925 * @return {String} id
927 getStateId = function(passedState){
932 State = this.normalizeState(passedState);
942 * getHashByState(State)
943 * Creates a Hash for the State Object
944 * @param {State} passedState
945 * @return {String} hash
947 getHashByState = function(passedState){
952 State = this.normalizeState(passedState);
962 * extractId(url_or_hash)
963 * Get a State ID by it's URL or Hash
964 * @param {string} url_or_hash
965 * @return {string} id
967 this.extractId = function ( url_or_hash ) {
969 var id,parts,url, tmp;
973 // If the URL has a #, use the id from before the #
974 if (url_or_hash.indexOf('#') != -1)
976 tmp = url_or_hash.split("#")[0];
983 parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
984 url = parts ? (parts[1]||url_or_hash) : url_or_hash;
985 id = parts ? String(parts[2]||'') : '';
992 * isTraditionalAnchor
993 * Checks to see if the url is a traditional anchor or not
994 * @param {String} url_or_hash
997 isTraditionalAnchor = function(url_or_hash){
999 var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
1002 return isTraditional;
1007 * Get a State by it's URL or Hash
1008 * @param {String} url_or_hash
1009 * @return {State|null}
1011 extractState = function(url_or_hash,create){
1013 var State = null, id, url;
1014 create = create||false;
1017 id = this.extractId(url_or_hash);
1019 State = this.getStateById(id);
1022 // Fetch SUID returned no State
1025 url = this.getFullUrl(url_or_hash);
1028 id = this.getIdByUrl(url)||false;
1030 State = this.getStateById(id);
1034 if ( !State && create && !this.isTraditionalAnchor(url_or_hash) ) {
1035 State = this.createStateObject(null,null,url);
1045 * Get a State ID by a State URL
1047 getIdByUrl = function(url){
1049 var id = this.urlToId[url] || this.store.urlToId[url] || undefined;
1056 * getLastSavedState()
1057 * Get an object containing the data, title and url of the current state
1058 * @return {Object} State
1060 getLastSavedState = function(){
1061 return this.savedStates[this.savedStates.length-1]||undefined;
1065 * getLastStoredState()
1066 * Get an object containing the data, title and url of the current state
1067 * @return {Object} State
1069 getLastStoredState = function(){
1070 return this.storedStates[this.storedStates.length-1]||undefined;
1075 * Checks if a Url will have a url conflict
1076 * @param {Object} newState
1077 * @return {Boolean} hasDuplicate
1079 hasUrlDuplicate = function(newState) {
1081 var hasDuplicate = false,
1085 oldState = this.extractState(newState.url);
1088 hasDuplicate = oldState && oldState.id !== newState.id;
1091 return hasDuplicate;
1097 * @param {Object} newState
1098 * @return {Object} newState
1100 storeState = function(newState){
1102 this.urlToId[newState.url] = newState.id;
1105 this.storedStates.push(this.cloneObject(newState));
1112 * isLastSavedState(newState)
1113 * Tests to see if the state is the last state
1114 * @param {Object} newState
1115 * @return {boolean} isLast
1117 isLastSavedState = function(newState){
1120 newId, oldState, oldId;
1123 if ( this.savedStates.length ) {
1124 newId = newState.id;
1125 oldState = this.getLastSavedState();
1126 oldId = oldState.id;
1129 isLast = (newId === oldId);
1139 * @param {Object} newState
1140 * @return {boolean} changed
1142 saveState = function(newState){
1144 if ( this.isLastSavedState(newState) ) {
1149 this.savedStates.push(this.cloneObject(newState));
1157 * Gets a state by the index
1158 * @param {integer} index
1161 getStateByIndex = function(index){
1166 if ( typeof index === 'undefined' ) {
1167 // Get the last inserted
1168 State = this.savedStates[this.savedStates.length-1];
1170 else if ( index < 0 ) {
1172 State = this.savedStates[this.savedStates.length+index];
1175 // Get from the beginning
1176 State = this.savedStates[index];
1185 * Gets the current index
1188 getCurrentIndex = function(){
1193 if(this.savedStates.length < 1) {
1197 index = this.savedStates.length-1;
1202 // ====================================================================
1207 * @param {Location=} location
1208 * Gets the current document hash
1209 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
1212 getHash = function(doc){
1213 var url = this.getLocationHref(doc),
1215 hash = this.getHashByUrl(url);
1221 * normalize and Unescape a Hash
1222 * @param {String} hash
1225 unescapeHash = function(hash){
1227 var result = this.normalizeHash(hash);
1230 result = decodeURIComponent(result);
1238 * normalize a hash across browsers
1241 normalizeHash = function(hash){
1243 var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
1251 * Sets the document hash
1252 * @param {string} hash
1253 * @return {Roo.History}
1255 setHash = function(hash,queue){
1260 if ( queue !== false && this.busy() ) {
1261 // Wait + Push to Queue
1262 //this.debug('this.setHash: we must wait', arguments);
1265 callback: this.setHash,
1273 //this.debug('this.setHash: called',hash);
1275 // Make Busy + Continue
1278 // Check if hash is a state
1279 State = this.extractState(hash,true);
1280 if ( State && !this.emulated.pushState ) {
1281 // Hash is a state so skip the setHash
1282 //this.debug('this.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
1285 this.pushState(State.data,State.title,State.url,false);
1287 else if ( this.getHash() !== hash ) {
1288 // Hash is a proper hash, so apply it
1290 // Handle browser bugs
1291 if ( this.bugs.setHash ) {
1292 // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
1294 // Fetch the base page
1295 pageUrl = this.getPageUrl();
1297 // Safari hash apply
1298 this.pushState(null,null,pageUrl+'#'+hash,false);
1301 // Normal hash apply
1302 window.document.location.hash = hash;
1312 * normalize and Escape a Hash
1315 escapeHash = function(hash){
1317 var result = normalizeHash(hash);
1320 result = window.encodeURIComponent(result);
1323 if ( !this.bugs.hashEscape ) {
1324 // Restore common parts
1326 .replace(/\%21/g,'!')
1327 .replace(/\%26/g,'&')
1328 .replace(/\%3D/g,'=')
1329 .replace(/\%3F/g,'?');
1338 * Extracts the Hash from a URL
1339 * @param {string} url
1340 * @return {string} url
1342 getHashByUrl = function(url){
1344 var hash = String(url)
1345 .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
1349 hash = this.unescapeHash(hash);
1357 * Applies the title to the document
1358 * @param {State} newState
1361 setTitle = function(newState){
1363 var title = newState.title,
1368 firstState = this.getStateByIndex(0);
1369 if ( firstState && firstState.url === newState.url ) {
1370 title = firstState.title||this.initialTitle;
1376 window.document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
1378 catch ( Exception ) { }
1379 window.document.title = title;
1386 // ====================================================================
1392 * @param {boolean} value [optional]
1393 * @return {boolean} busy
1395 busy = function(value){
1397 if ( typeof value !== 'undefined' ) {
1398 //this.debug('this.busy: changing ['+(this.busy.flag||false)+'] to ['+(value||false)+']', this.queues.length);
1399 this.busy_flag = value;
1402 else if ( typeof this.busy_flag === 'undefined' ) {
1403 this.busy_flag = false;
1407 if ( !this.busy_flag ) {
1408 // Execute the next item in the queue
1409 window.clearTimeout(this.busy.timeout);
1410 var fireNext = function(){
1412 if ( this.busy_flag ) return;
1413 for ( i=this.queues.length-1; i >= 0; --i ) {
1414 queue = this.queues[i];
1415 if ( queue.length === 0 ) continue;
1416 item = queue.shift();
1417 this.fireQueueItem(item);
1418 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1421 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1425 return this.busy_flag;
1431 * fireQueueItem(item)
1433 * @param {Object} item
1434 * @return {Mixed} result
1436 fireQueueItem = function(item){
1437 return item.callback.apply(item.scope||this,item.args||[]);
1441 * pushQueue(callback,args)
1442 * Add an item to the queue
1443 * @param {Object} item [scope,callback,args,queue]
1445 pushQueue = function(item){
1446 // Prepare the queue
1447 this.queues[item.queue||0] = this.queues[item.queue||0]||[];
1450 this.queues[item.queue||0].push(item);
1457 * queue (item,queue), (func,queue), (func), (item)
1458 * Either firs the item now if not busy, or adds it to the queue
1460 queue = function(item,queue){
1462 if ( typeof item === 'function' ) {
1467 if ( typeof queue !== 'undefined' ) {
1472 if ( this.busy() ) {
1473 this.pushQueue(item);
1475 this.fireQueueItem(item);
1486 clearQueue = function(){
1487 this.busy_flag = false;
1495 * doubleCheckComplete()
1496 * Complete a double check
1497 * @return {Roo.History}
1499 doubleCheckComplete = function(){
1501 this.stateChanged = true;
1504 this.doubleCheckClear();
1511 * doubleCheckClear()
1512 * Clear a double check
1513 * @return {Roo.History}
1515 doubleCheckClear = function(){
1517 if ( this.doubleChecker ) {
1518 window.clearTimeout(this.doubleChecker);
1519 this.doubleChecker = false;
1528 * Create a double check
1529 * @return {Roo.History}
1531 doubleCheck = function(tryAgain){
1533 this.stateChanged = false;
1534 this.doubleCheckClear();
1536 // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
1537 // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
1538 if ( this.bugs.ieDoubleCheck ) {
1540 this.doubleChecker = window.setTimeout(
1542 this.doubleCheckClear();
1543 if ( !this.stateChanged ) {
1544 //this.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
1550 this.doubleCheckInterval
1559 // ====================================================================
1564 * Poll the current state
1565 * @return {Roo.History}
1567 safariStatePoll = function(){
1570 // Get the Last State which has the new URL
1572 urlState = this.extractState(this.getLocationHref()),
1575 // Check for a difference
1576 if ( !this.isLastSavedState(urlState) ) {
1577 newState = urlState;
1583 // Check if we have a state with that url
1586 //this.debug('this.safariStatePoll: new');
1587 newState = this.createStateObject();
1590 // Apply the New State
1591 //this.debug('this.safariStatePoll: trigger');
1592 this.Adapter.trigger(window,'popstate');
1599 // ====================================================================
1604 * Send the browser history back one item
1605 * @param {Integer} queue [optional]
1607 back = function(queue){
1608 //this.debug('this.back: called', arguments);
1611 if ( queue !== false && this.busy() ) {
1612 // Wait + Push to Queue
1613 //this.debug('this.back: we must wait', arguments);
1616 callback: this.back,
1623 // Make Busy + Continue
1626 // Fix certain browser bugs that prevent the state from changing
1627 this.doubleCheck(function(){
1640 * Send the browser history forward one item
1641 * @param {Integer} queue [optional]
1643 forward = function(queue){
1644 //this.debug('this.forward: called', arguments);
1647 if ( queue !== false && this.busy() ) {
1648 // Wait + Push to Queue
1649 //this.debug('this.forward: we must wait', arguments);
1652 callback: this.forward,
1659 // Make Busy + Continue
1663 // Fix certain browser bugs that prevent the state from changing
1664 this.doubleCheck(function(){
1671 // End forward closure
1677 * Send the browser history back or forward index times
1678 * @param {Integer} queue [optional]
1680 go = function(index,queue){
1681 //this.debug('this.go: called', arguments);
1689 for ( i=1; i<=index; ++i ) {
1690 this.forward(queue);
1693 else if ( index < 0 ) {
1695 for ( i=-1; i>=index; --i ) {
1700 throw new Error('History.go: History.go requires a positive or negative integer passed.');
1708 // ====================================================================
1709 // HTML5 State Support
1713 * Use native HTML5 History API Implementation
1717 * onPopState(event,extra)
1718 * Refresh the Current State
1720 onPopState = function(event,extra){
1722 var stateId = false, newState = false, currentHash, currentState;
1724 // Reset the double check
1725 this.doubleCheckComplete();
1727 // Check for a Hash, and handle apporiatly
1728 currentHash = this.getHash();
1729 if ( currentHash ) {
1731 currentState = this.extractState(currentHash||this.getLocationHref(),true);
1732 if ( currentState ) {
1733 // We were able to parse it, it must be a State!
1734 // Let's forward to replaceState
1735 //this.debug('this.onPopState: state anchor', currentHash, currentState);
1736 this.replaceState(currentState.data, currentState.title, currentState.url, false);
1739 // Traditional Anchor
1740 //this.debug('this.onPopState: traditional anchor', currentHash);
1741 this.Adapter.trigger(window,'anchorchange');
1745 // We don't care for hashes
1746 this.expectedStateId = false;
1751 stateId = this.Adapter.extractEventData('state',event,extra) || false;
1755 // Vanilla: Back/forward button was used
1756 newState = this.getStateById(stateId);
1758 else if ( this.expectedStateId ) {
1759 // Vanilla: A new state was pushed, and popstate was called manually
1760 newState = this.getStateById(this.expectedStateId);
1764 newState = this.extractState(this.getLocationHref());
1767 // The State did not exist in our store
1769 // Regenerate the State
1770 newState = this.createStateObject(null,null,this.getLocationHref());
1774 this.expectedStateId = false;
1776 // Check if we are the same state
1777 if ( this.isLastSavedState(newState) ) {
1778 // There has been no change (just the page's hash has finally propagated)
1779 //this.debug('this.onPopState: no change', newState, this.savedStates);
1785 this.storeState(newState);
1786 this.saveState(newState);
1788 // Force update of the title
1789 this.setTitle(newState);
1792 this.Adapter.trigger(window,'statechange');
1806 * pushState(data,title,url)
1807 * Add a new State to the history object, become it, and trigger onpopstate
1808 * We have to trigger for HTML4 compatibility
1809 * @param {object} data
1810 * @param {string} title
1811 * @param {string} url
1814 pushState = function(data,title,url,queue){
1815 //this.debug('this.pushState: called', arguments);
1818 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1819 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1823 if ( queue !== false && this.busy() ) {
1824 // Wait + Push to Queue
1825 //this.debug('this.pushState: we must wait', arguments);
1828 callback: this.pushState,
1835 // Make Busy + Continue
1838 // Create the newState
1839 var newState = this.createStateObject(data,title,url);
1842 if ( this.isLastSavedState(newState) ) {
1843 // Won't be a change
1847 // Store the newState
1848 this.storeState(newState);
1849 this.expectedStateId = newState.id;
1851 // Push the newState
1852 history.pushState(newState.id,newState.title,newState.url);
1855 this.Adapter.trigger(window,'popstate');
1858 // End pushState closure
1863 * replaceState(data,title,url)
1864 * Replace the State and trigger onpopstate
1865 * We have to trigger for HTML4 compatibility
1866 * @param {object} data
1867 * @param {string} title
1868 * @param {string} url
1871 replaceState = function(data,title,url,queue){
1872 //this.debug('this.replaceState: called', arguments);
1875 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1876 throw new Error('this.js does not support states with fragement-identifiers (hashes/anchors).');
1880 if ( queue !== false && this.busy() ) {
1881 // Wait + Push to Queue
1882 //this.debug('this.replaceState: we must wait', arguments);
1885 callback: this.replaceState,
1892 // Make Busy + Continue
1895 // Create the newState
1896 var newState = this.createStateObject(data,title,url);
1899 if ( this.isLastSavedState(newState) ) {
1900 // Won't be a change
1904 // Store the newState
1905 this.storeState(newState);
1906 this.expectedStateId = newState.id;
1908 // Push the newState
1909 history.replaceState(newState.id,newState.title,newState.url);
1912 this.Adapter.trigger(window,'popstate');
1915 // End replaceState closure
1920 // ====================================================================
1924 * Bind for Saving Store
1927 // When the page is closed
1928 onUnload = function(){
1930 var currentStore, item, currentStoreString;
1934 currentStore = JSON.parse(this.sessionStorage.getItem('Roo.History.store'))||{};
1941 currentStore.idToState = currentStore.idToState || {};
1942 currentStore.urlToId = currentStore.urlToId || {};
1943 currentStore.stateToId = currentStore.stateToId || {};
1946 for ( item in this.idToState ) {
1947 if ( !this.idToState.hasOwnProperty(item) ) {
1950 currentStore.idToState[item] = this.idToState[item];
1952 for ( item in this.urlToId ) {
1953 if ( !this.urlToId.hasOwnProperty(item) ) {
1956 currentStore.urlToId[item] = this.urlToId[item];
1958 for ( item in this.stateToId ) {
1959 if ( !this.stateToId.hasOwnProperty(item) ) {
1962 currentStore.stateToId[item] = this.stateToId[item];
1966 this.store = currentStore;
1967 this.normalizeStore();
1969 // In Safari, going into Private Browsing mode causes the
1970 // Session Storage object to still exist but if you try and use
1971 // or set any property/function of it it throws the exception
1972 // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
1973 // add something to storage that exceeded the quota." infinitely
1975 currentStoreString = JSON.stringify(currentStore);
1978 this.sessionStorage.setItem('Roo.History.store', currentStoreString);
1981 if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
1982 if (this.sessionStorage.length) {
1983 // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
1984 // removing/resetting the storage can work.
1985 this.sessionStorage.removeItem('Roo.History.store');
1986 this.sessionStorage.setItem('Roo.History.store', currentStoreString);
1988 // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
1999 // Try to Initialise History
2000 if (!History.options || !History.options.delayInit) {