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
318 // ========================================================================
322 initCore : function(options){
324 this.intervalList = [];
328 this.sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
329 this.sessionStorage.setItem('TEST', '1');
330 this.sessionStorage.removeItem('TEST');
332 this.sessionStorage = false;
336 if ( typeof this.initCore.initialized !== 'undefined' ) {
341 this.initCore.initialized = true;
350 * Clears all setInterval instances.
352 clearAllIntervals: function()
354 var i, il = this.intervalList;
355 if (typeof il !== "undefined" && il !== null) {
356 for (i = 0; i < il.length; i++) {
357 clearInterval(il[i]);
359 this.intervalList = null;
364 // ====================================================================
368 * debugLog(message,...)
369 * Logs the passed arguments if debug enabled
371 debugLog : function()
373 if ( (this.debug||false) ) {
374 Roo.log.apply(this,arguments);
380 // ====================================================================
384 * getInternetExplorerMajorVersion()
385 * Get's the major version of Internet Explorer
387 * @license Public Domain
388 * @author Benjamin Arthur Lupton <contact@balupton.com>
389 * @author James Padolsey <https://gist.github.com/527683>
391 getInternetExplorerMajorVersion : function(){
392 var result = this.getInternetExplorerMajorVersion.cached =
393 (typeof this.getInternetExplorerMajorVersion.cached !== 'undefined')
394 ? this.getInternetExplorerMajorVersion.cached
397 div = window.document.createElement('div'),
398 all = div.getElementsByTagName('i');
399 while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
400 return (v > 4) ? v : false;
407 * isInternetExplorer()
408 * Are we using Internet Explorer?
410 * @license Public Domain
411 * @author Benjamin Arthur Lupton <contact@balupton.com>
413 isInternetExplorer : function(){
415 this.isInternetExplorer.cached =
416 (typeof this.isInternetExplorer.cached !== 'undefined')
417 ? this.isInternetExplorer.cached
418 : Boolean(this.getInternetExplorerMajorVersion())
424 * Which features require emulating?
432 initEmulated : function()
436 if (this.html4Mode) {
442 this.emulated.pushState = !Boolean(
443 window.history && window.history.pushState && window.history.replaceState
445 (/ 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) */
446 || (/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 */
449 this.emulated.hashChange = Boolean(
450 !(('onhashchange' in window) || ('onhashchange' in window.document))
452 (this.isInternetExplorer() && this.getInternetExplorerMajorVersion() < 8)
461 * Checks to see if the Object is Empty
462 * @param {Object} obj
465 isEmptyObject = function(obj) {
466 for ( var name in obj ) {
467 if ( obj.hasOwnProperty(name) ) {
476 * Clones a object and eliminate all references to the original contexts
477 * @param {Object} obj
480 cloneObject = function(obj) {
483 hash = JSON.stringify(obj);
484 newObj = JSON.parse(hash);
493 // ====================================================================
498 * Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
499 * @return {String} rootUrl
501 getRootUrl = function(){
503 var rootUrl = window.document.location.protocol+'//'+(window.document.location.hostname||window.document.location.host);
504 if ( window.document.location.port||false ) {
505 rootUrl += ':'+window.document.location.port;
515 * Fetches the `href` attribute of the `<base href="...">` element if it exists
516 * @return {String} baseHref
518 getBaseHref = function(){
521 baseElements = window.document.getElementsByTagName('base'),
525 // Test for Base Element
526 if ( baseElements.length === 1 ) {
527 // Prepare for Base Element
528 baseElement = baseElements[0];
529 baseHref = baseElement.href.replace(/[^\/]+$/,'');
532 // Adjust trailing slash
533 baseHref = baseHref.replace(/\/+$/,'');
534 if ( baseHref ) baseHref += '/';
542 * Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
543 * @return {String} baseUrl
545 getBaseUrl = function(){
547 var baseUrl = this.getBaseHref()||this.getBasePageUrl()||this.getRootUrl();
555 * Fetches the URL of the current page
556 * @return {String} pageUrl
558 getPageUrl = function(){
561 State = this.getState(false,false),
562 stateUrl = (State||{}).url||this.getLocationHref(),
566 pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
567 return (/\./).test(part) ? part : part+'/';
576 * Fetches the Url of the directory of the current page
577 * @return {String} basePageUrl
579 getBasePageUrl = function(){
581 var basePageUrl = (this.getLocationHref()).replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
582 return (/[^\/]$/).test(part) ? '' : part;
583 }).replace(/\/+$/,'')+'/';
591 * Ensures that we have an absolute URL and not a relative URL
592 * @param {string} url
593 * @param {Boolean} allowBaseHref
594 * @return {string} fullUrl
596 getFullUrl = function(url,allowBaseHref){
598 var fullUrl = url, firstChar = url.substring(0,1);
599 allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
602 if ( /[a-z]+\:\/\//.test(url) ) {
605 else if ( firstChar === '/' ) {
607 fullUrl = this.getRootUrl()+url.replace(/^\/+/,'');
609 else if ( firstChar === '#' ) {
611 fullUrl = this.getPageUrl().replace(/#.*/,'')+url;
613 else if ( firstChar === '?' ) {
615 fullUrl = this.getPageUrl().replace(/[\?#].*/,'')+url;
619 if ( allowBaseHref ) {
620 fullUrl = this.getBaseUrl()+url.replace(/^(\.\/)+/,'');
622 fullUrl = this.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
624 // We have an if condition above as we do not want hashes
625 // which are relative to the baseHref in our URLs
626 // as if the baseHref changes, then all our bookmarks
627 // would now point to different locations
628 // whereas the basePageUrl will always stay the same
632 return fullUrl.replace(/\#$/,'');
637 * Ensures that we have a relative URL and not a absolute URL
638 * @param {string} url
639 * @return {string} url
641 getShortUrl = function(url){
643 var shortUrl = url, baseUrl = this.getBaseUrl(), rootUrl = this.getRootUrl();
646 if ( this.emulated.pushState ) {
647 // We are in a if statement as when pushState is not emulated
648 // The actual url these short urls are relative to can change
649 // So within the same session, we the url may end up somewhere different
650 shortUrl = shortUrl.replace(baseUrl,'');
654 shortUrl = shortUrl.replace(rootUrl,'/');
656 // Ensure we can still detect it as a state
657 if ( this.isTraditionalAnchor(shortUrl) ) {
658 shortUrl = './'+shortUrl;
662 shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
669 * getLocationHref(document)
670 * Returns a normalized version of document.location.href
671 * accounting for browser inconsistencies, etc.
673 * This URL will be URI-encoded and will include the hash
675 * @param {object} document
676 * @return {string} url
678 getLocationHref = function(doc) {
679 doc = doc || window.document;
681 // most of the time, this will be true
682 if (doc.URL === doc.location.href)
683 return doc.location.href;
685 // some versions of webkit URI-decode document.location.href
686 // but they leave document.URL in an encoded state
687 if (doc.location.href === decodeURIComponent(doc.URL))
690 // FF 3.6 only updates document.URL when a page is reloaded
691 // document.location.href is updated correctly
692 if (doc.location.hash && decodeURIComponent(doc.location.href.replace(/^[^#]+/, "")) === doc.location.hash)
693 return doc.location.href;
695 if (doc.URL.indexOf('#') == -1 && doc.location.href.indexOf('#') != -1)
696 return doc.location.href;
698 return doc.URL || doc.location.href;
705 * Noramlize the store by adding necessary values
707 normalizeStore = function(){
708 this.store.idToState = this.store.idToState||{};
709 this.store.urlToId = this.store.urlToId||{};
710 this.store.stateToId = this.store.stateToId||{};
715 * Get an object containing the data, title and url of the current state
716 * @param {Boolean} friendly
717 * @param {Boolean} create
718 * @return {Object} State
720 getState : function(friendly,create){
722 if ( typeof friendly === 'undefined' ) { friendly = true; }
723 if ( typeof create === 'undefined' ) { create = true; }
726 var State = this.getLastSavedState();
729 if ( !State && create ) {
730 State = this.createStateObject();
735 State = this.cloneObject(State);
736 State.url = this.cleanUrl||State.url;
744 * getIdByState(State)
745 * Gets a ID for a State
746 * @param {State} newState
747 * @return {String} id
749 getIdByState = function(newState){
752 var id = this.extractId(newState.url),
756 // Find ID via State String
757 str = this.getStateString(newState);
758 if ( typeof this.stateToId[str] !== 'undefined' ) {
759 id = this.stateToId[str];
761 else if ( typeof this.store.stateToId[str] !== 'undefined' ) {
762 id = this.store.stateToId[str];
767 id = (new Date()).getTime() + String(Math.random()).replace(/\D/g,'');
768 if ( typeof this.idToState[id] === 'undefined' && typeof this.store.idToState[id] === 'undefined' ) {
773 // Apply the new State to the ID
774 this.stateToId[str] = id;
775 this.idToState[id] = newState;
784 * normalizeState(State)
785 * Expands a State Object
786 * @param {object} State
789 normalizeState = function(oldState){
791 var newState, dataNotEmpty;
794 if ( !oldState || (typeof oldState !== 'object') ) {
799 if ( typeof oldState.normalized !== 'undefined' ) {
804 if ( !oldState.data || (typeof oldState.data !== 'object') ) {
808 // ----------------------------------------------------------------
812 newState.normalized = true;
813 newState.title = oldState.title||'';
814 newState.url = this.getFullUrl(oldState.url?oldState.url:(this.getLocationHref()));
815 newState.hash = this.getShortUrl(newState.url);
816 newState.data = this.cloneObject(oldState.data);
819 newState.id = this.getIdByState(newState);
821 // ----------------------------------------------------------------
824 newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
825 newState.url = newState.cleanUrl;
827 // Check to see if we have more than just a url
828 dataNotEmpty = !this.isEmptyObject(newState.data);
831 if ( (newState.title || dataNotEmpty) && this.disableSuid !== true ) {
833 newState.hash = this.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
834 if ( !/\?/.test(newState.hash) ) {
835 newState.hash += '?';
837 newState.hash += '&_suid='+newState.id;
840 // Create the Hashed URL
841 newState.hashedUrl = this.getFullUrl(newState.hash);
843 // ----------------------------------------------------------------
845 // Update the URL if we have a duplicate
846 if ( (this.emulated.pushState || this.bugs.safariPoll) && this.hasUrlDuplicate(newState) ) {
847 newState.url = newState.hashedUrl;
850 // ----------------------------------------------------------------
857 * createStateObject(data,title,url)
858 * Creates a object based on the data, title and url state params
859 * @param {object} data
860 * @param {string} title
861 * @param {string} url
864 createStateObject = function(data,title,url){
873 State = this.normalizeState(State);
881 * Get a state by it's UID
884 getStateById = function(id){
889 var State = this.idToState[id] || this.store.idToState[id] || undefined;
896 * Get a State's String
897 * @param {State} passedState
899 getStateString = function(passedState){
901 var State, cleanedState, str;
904 State = this.normalizeState(passedState);
909 title: passedState.title,
914 str = JSON.stringify(cleanedState);
922 * @param {State} passedState
923 * @return {String} id
925 getStateId = function(passedState){
930 State = this.normalizeState(passedState);
940 * getHashByState(State)
941 * Creates a Hash for the State Object
942 * @param {State} passedState
943 * @return {String} hash
945 getHashByState = function(passedState){
950 State = this.normalizeState(passedState);
960 * extractId(url_or_hash)
961 * Get a State ID by it's URL or Hash
962 * @param {string} url_or_hash
963 * @return {string} id
965 this.extractId = function ( url_or_hash ) {
967 var id,parts,url, tmp;
971 // If the URL has a #, use the id from before the #
972 if (url_or_hash.indexOf('#') != -1)
974 tmp = url_or_hash.split("#")[0];
981 parts = /(.*)\&_suid=([0-9]+)$/.exec(tmp);
982 url = parts ? (parts[1]||url_or_hash) : url_or_hash;
983 id = parts ? String(parts[2]||'') : '';
990 * isTraditionalAnchor
991 * Checks to see if the url is a traditional anchor or not
992 * @param {String} url_or_hash
995 isTraditionalAnchor = function(url_or_hash){
997 var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
1000 return isTraditional;
1005 * Get a State by it's URL or Hash
1006 * @param {String} url_or_hash
1007 * @return {State|null}
1009 extractState = function(url_or_hash,create){
1011 var State = null, id, url;
1012 create = create||false;
1015 id = this.extractId(url_or_hash);
1017 State = this.getStateById(id);
1020 // Fetch SUID returned no State
1023 url = this.getFullUrl(url_or_hash);
1026 id = this.getIdByUrl(url)||false;
1028 State = this.getStateById(id);
1032 if ( !State && create && !this.isTraditionalAnchor(url_or_hash) ) {
1033 State = this.createStateObject(null,null,url);
1043 * Get a State ID by a State URL
1045 getIdByUrl = function(url){
1047 var id = this.urlToId[url] || this.store.urlToId[url] || undefined;
1054 * getLastSavedState()
1055 * Get an object containing the data, title and url of the current state
1056 * @return {Object} State
1058 getLastSavedState = function(){
1059 return this.savedStates[this.savedStates.length-1]||undefined;
1063 * getLastStoredState()
1064 * Get an object containing the data, title and url of the current state
1065 * @return {Object} State
1067 getLastStoredState = function(){
1068 return this.storedStates[this.storedStates.length-1]||undefined;
1073 * Checks if a Url will have a url conflict
1074 * @param {Object} newState
1075 * @return {Boolean} hasDuplicate
1077 hasUrlDuplicate = function(newState) {
1079 var hasDuplicate = false,
1083 oldState = this.extractState(newState.url);
1086 hasDuplicate = oldState && oldState.id !== newState.id;
1089 return hasDuplicate;
1095 * @param {Object} newState
1096 * @return {Object} newState
1098 storeState = function(newState){
1100 this.urlToId[newState.url] = newState.id;
1103 this.storedStates.push(this.cloneObject(newState));
1110 * isLastSavedState(newState)
1111 * Tests to see if the state is the last state
1112 * @param {Object} newState
1113 * @return {boolean} isLast
1115 isLastSavedState = function(newState){
1118 newId, oldState, oldId;
1121 if ( this.savedStates.length ) {
1122 newId = newState.id;
1123 oldState = this.getLastSavedState();
1124 oldId = oldState.id;
1127 isLast = (newId === oldId);
1137 * @param {Object} newState
1138 * @return {boolean} changed
1140 saveState = function(newState){
1142 if ( this.isLastSavedState(newState) ) {
1147 this.savedStates.push(this.cloneObject(newState));
1155 * Gets a state by the index
1156 * @param {integer} index
1159 getStateByIndex = function(index){
1164 if ( typeof index === 'undefined' ) {
1165 // Get the last inserted
1166 State = this.savedStates[this.savedStates.length-1];
1168 else if ( index < 0 ) {
1170 State = this.savedStates[this.savedStates.length+index];
1173 // Get from the beginning
1174 State = this.savedStates[index];
1183 * Gets the current index
1186 getCurrentIndex = function(){
1191 if(this.savedStates.length < 1) {
1195 index = this.savedStates.length-1;
1200 // ====================================================================
1205 * @param {Location=} location
1206 * Gets the current document hash
1207 * Note: unlike location.hash, this is guaranteed to return the escaped hash in all browsers
1210 getHash = function(doc){
1211 var url = this.getLocationHref(doc),
1213 hash = this.getHashByUrl(url);
1219 * normalize and Unescape a Hash
1220 * @param {String} hash
1223 unescapeHash = function(hash){
1225 var result = this.normalizeHash(hash);
1228 result = decodeURIComponent(result);
1236 * normalize a hash across browsers
1239 normalizeHash = function(hash){
1241 var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
1249 * Sets the document hash
1250 * @param {string} hash
1251 * @return {Roo.History}
1253 setHash = function(hash,queue){
1258 if ( queue !== false && this.busy() ) {
1259 // Wait + Push to Queue
1260 //this.debug('this.setHash: we must wait', arguments);
1263 callback: this.setHash,
1271 //this.debug('this.setHash: called',hash);
1273 // Make Busy + Continue
1276 // Check if hash is a state
1277 State = this.extractState(hash,true);
1278 if ( State && !this.emulated.pushState ) {
1279 // Hash is a state so skip the setHash
1280 //this.debug('this.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
1283 this.pushState(State.data,State.title,State.url,false);
1285 else if ( this.getHash() !== hash ) {
1286 // Hash is a proper hash, so apply it
1288 // Handle browser bugs
1289 if ( this.bugs.setHash ) {
1290 // Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
1292 // Fetch the base page
1293 pageUrl = this.getPageUrl();
1295 // Safari hash apply
1296 this.pushState(null,null,pageUrl+'#'+hash,false);
1299 // Normal hash apply
1300 window.document.location.hash = hash;
1310 * normalize and Escape a Hash
1313 escapeHash = function(hash){
1315 var result = normalizeHash(hash);
1318 result = window.encodeURIComponent(result);
1321 if ( !this.bugs.hashEscape ) {
1322 // Restore common parts
1324 .replace(/\%21/g,'!')
1325 .replace(/\%26/g,'&')
1326 .replace(/\%3D/g,'=')
1327 .replace(/\%3F/g,'?');
1336 * Extracts the Hash from a URL
1337 * @param {string} url
1338 * @return {string} url
1340 getHashByUrl = function(url){
1342 var hash = String(url)
1343 .replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
1347 hash = this.unescapeHash(hash);
1355 * Applies the title to the document
1356 * @param {State} newState
1359 setTitle = function(newState){
1361 var title = newState.title,
1366 firstState = this.getStateByIndex(0);
1367 if ( firstState && firstState.url === newState.url ) {
1368 title = firstState.title||this.initialTitle;
1374 window.document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
1376 catch ( Exception ) { }
1377 window.document.title = title;
1384 // ====================================================================
1390 * @param {boolean} value [optional]
1391 * @return {boolean} busy
1393 busy = function(value){
1395 if ( typeof value !== 'undefined' ) {
1396 //this.debug('this.busy: changing ['+(this.busy.flag||false)+'] to ['+(value||false)+']', this.queues.length);
1397 this.busy_flag = value;
1400 else if ( typeof this.busy_flag === 'undefined' ) {
1401 this.busy_flag = false;
1405 if ( !this.busy_flag ) {
1406 // Execute the next item in the queue
1407 window.clearTimeout(this.busy.timeout);
1408 var fireNext = function(){
1410 if ( this.busy_flag ) return;
1411 for ( i=this.queues.length-1; i >= 0; --i ) {
1412 queue = this.queues[i];
1413 if ( queue.length === 0 ) continue;
1414 item = queue.shift();
1415 this.fireQueueItem(item);
1416 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1419 this.busy.timeout = window.setTimeout(fireNext,this.busyDelay);
1423 return this.busy_flag;
1429 * fireQueueItem(item)
1431 * @param {Object} item
1432 * @return {Mixed} result
1434 fireQueueItem = function(item){
1435 return item.callback.apply(item.scope||this,item.args||[]);
1439 * pushQueue(callback,args)
1440 * Add an item to the queue
1441 * @param {Object} item [scope,callback,args,queue]
1443 pushQueue = function(item){
1444 // Prepare the queue
1445 this.queues[item.queue||0] = this.queues[item.queue||0]||[];
1448 this.queues[item.queue||0].push(item);
1455 * queue (item,queue), (func,queue), (func), (item)
1456 * Either firs the item now if not busy, or adds it to the queue
1458 queue = function(item,queue){
1460 if ( typeof item === 'function' ) {
1465 if ( typeof queue !== 'undefined' ) {
1470 if ( this.busy() ) {
1471 this.pushQueue(item);
1473 this.fireQueueItem(item);
1484 clearQueue = function(){
1485 this.busy_flag = false;
1493 * doubleCheckComplete()
1494 * Complete a double check
1495 * @return {Roo.History}
1497 doubleCheckComplete = function(){
1499 this.stateChanged = true;
1502 this.doubleCheckClear();
1509 * doubleCheckClear()
1510 * Clear a double check
1511 * @return {Roo.History}
1513 doubleCheckClear = function(){
1515 if ( this.doubleChecker ) {
1516 window.clearTimeout(this.doubleChecker);
1517 this.doubleChecker = false;
1526 * Create a double check
1527 * @return {Roo.History}
1529 doubleCheck = function(tryAgain){
1531 this.stateChanged = false;
1532 this.doubleCheckClear();
1534 // Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
1535 // Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
1536 if ( this.bugs.ieDoubleCheck ) {
1538 this.doubleChecker = window.setTimeout(
1540 this.doubleCheckClear();
1541 if ( !this.stateChanged ) {
1542 //this.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
1548 this.doubleCheckInterval
1557 // ====================================================================
1562 * Poll the current state
1563 * @return {Roo.History}
1565 safariStatePoll = function(){
1568 // Get the Last State which has the new URL
1570 urlState = this.extractState(this.getLocationHref()),
1573 // Check for a difference
1574 if ( !this.isLastSavedState(urlState) ) {
1575 newState = urlState;
1581 // Check if we have a state with that url
1584 //this.debug('this.safariStatePoll: new');
1585 newState = this.createStateObject();
1588 // Apply the New State
1589 //this.debug('this.safariStatePoll: trigger');
1590 this.Adapter.trigger(window,'popstate');
1597 // ====================================================================
1602 * Send the browser history back one item
1603 * @param {Integer} queue [optional]
1605 back = function(queue){
1606 //this.debug('this.back: called', arguments);
1609 if ( queue !== false && this.busy() ) {
1610 // Wait + Push to Queue
1611 //this.debug('this.back: we must wait', arguments);
1614 callback: this.back,
1621 // Make Busy + Continue
1624 // Fix certain browser bugs that prevent the state from changing
1625 this.doubleCheck(function(){
1638 * Send the browser history forward one item
1639 * @param {Integer} queue [optional]
1641 forward = function(queue){
1642 //this.debug('this.forward: called', arguments);
1645 if ( queue !== false && this.busy() ) {
1646 // Wait + Push to Queue
1647 //this.debug('this.forward: we must wait', arguments);
1650 callback: this.forward,
1657 // Make Busy + Continue
1661 // Fix certain browser bugs that prevent the state from changing
1662 this.doubleCheck(function(){
1669 // End forward closure
1675 * Send the browser history back or forward index times
1676 * @param {Integer} queue [optional]
1678 go = function(index,queue){
1679 //this.debug('this.go: called', arguments);
1687 for ( i=1; i<=index; ++i ) {
1688 this.forward(queue);
1691 else if ( index < 0 ) {
1693 for ( i=-1; i>=index; --i ) {
1698 throw new Error('History.go: History.go requires a positive or negative integer passed.');
1706 // ====================================================================
1707 // HTML5 State Support
1711 * Use native HTML5 History API Implementation
1715 * onPopState(event,extra)
1716 * Refresh the Current State
1718 onPopState = function(event,extra){
1720 var stateId = false, newState = false, currentHash, currentState;
1722 // Reset the double check
1723 this.doubleCheckComplete();
1725 // Check for a Hash, and handle apporiatly
1726 currentHash = this.getHash();
1727 if ( currentHash ) {
1729 currentState = this.extractState(currentHash||this.getLocationHref(),true);
1730 if ( currentState ) {
1731 // We were able to parse it, it must be a State!
1732 // Let's forward to replaceState
1733 //this.debug('this.onPopState: state anchor', currentHash, currentState);
1734 this.replaceState(currentState.data, currentState.title, currentState.url, false);
1737 // Traditional Anchor
1738 //this.debug('this.onPopState: traditional anchor', currentHash);
1739 this.Adapter.trigger(window,'anchorchange');
1743 // We don't care for hashes
1744 this.expectedStateId = false;
1749 stateId = this.Adapter.extractEventData('state',event,extra) || false;
1753 // Vanilla: Back/forward button was used
1754 newState = this.getStateById(stateId);
1756 else if ( this.expectedStateId ) {
1757 // Vanilla: A new state was pushed, and popstate was called manually
1758 newState = this.getStateById(this.expectedStateId);
1762 newState = this.extractState(this.getLocationHref());
1765 // The State did not exist in our store
1767 // Regenerate the State
1768 newState = this.createStateObject(null,null,this.getLocationHref());
1772 this.expectedStateId = false;
1774 // Check if we are the same state
1775 if ( this.isLastSavedState(newState) ) {
1776 // There has been no change (just the page's hash has finally propagated)
1777 //this.debug('this.onPopState: no change', newState, this.savedStates);
1783 this.storeState(newState);
1784 this.saveState(newState);
1786 // Force update of the title
1787 this.setTitle(newState);
1790 this.Adapter.trigger(window,'statechange');
1804 * pushState(data,title,url)
1805 * Add a new State to the history object, become it, and trigger onpopstate
1806 * We have to trigger for HTML4 compatibility
1807 * @param {object} data
1808 * @param {string} title
1809 * @param {string} url
1812 pushState = function(data,title,url,queue){
1813 //this.debug('this.pushState: called', arguments);
1816 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1817 throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
1821 if ( queue !== false && this.busy() ) {
1822 // Wait + Push to Queue
1823 //this.debug('this.pushState: we must wait', arguments);
1826 callback: this.pushState,
1833 // Make Busy + Continue
1836 // Create the newState
1837 var newState = this.createStateObject(data,title,url);
1840 if ( this.isLastSavedState(newState) ) {
1841 // Won't be a change
1845 // Store the newState
1846 this.storeState(newState);
1847 this.expectedStateId = newState.id;
1849 // Push the newState
1850 history.pushState(newState.id,newState.title,newState.url);
1853 this.Adapter.trigger(window,'popstate');
1856 // End pushState closure
1861 * replaceState(data,title,url)
1862 * Replace the State and trigger onpopstate
1863 * We have to trigger for HTML4 compatibility
1864 * @param {object} data
1865 * @param {string} title
1866 * @param {string} url
1869 replaceState = function(data,title,url,queue){
1870 //this.debug('this.replaceState: called', arguments);
1873 if ( this.getHashByUrl(url) && this.emulated.pushState ) {
1874 throw new Error('this.js does not support states with fragement-identifiers (hashes/anchors).');
1878 if ( queue !== false && this.busy() ) {
1879 // Wait + Push to Queue
1880 //this.debug('this.replaceState: we must wait', arguments);
1883 callback: this.replaceState,
1890 // Make Busy + Continue
1893 // Create the newState
1894 var newState = this.createStateObject(data,title,url);
1897 if ( this.isLastSavedState(newState) ) {
1898 // Won't be a change
1902 // Store the newState
1903 this.storeState(newState);
1904 this.expectedStateId = newState.id;
1906 // Push the newState
1907 history.replaceState(newState.id,newState.title,newState.url);
1910 this.Adapter.trigger(window,'popstate');
1913 // End replaceState closure
1918 // ====================================================================
1922 * Bind for Saving Store
1925 // When the page is closed
1926 onUnload = function(){
1928 var currentStore, item, currentStoreString;
1932 currentStore = JSON.parse(this.sessionStorage.getItem('Roo.History.store'))||{};
1939 currentStore.idToState = currentStore.idToState || {};
1940 currentStore.urlToId = currentStore.urlToId || {};
1941 currentStore.stateToId = currentStore.stateToId || {};
1944 for ( item in this.idToState ) {
1945 if ( !this.idToState.hasOwnProperty(item) ) {
1948 currentStore.idToState[item] = this.idToState[item];
1950 for ( item in this.urlToId ) {
1951 if ( !this.urlToId.hasOwnProperty(item) ) {
1954 currentStore.urlToId[item] = this.urlToId[item];
1956 for ( item in this.stateToId ) {
1957 if ( !this.stateToId.hasOwnProperty(item) ) {
1960 currentStore.stateToId[item] = this.stateToId[item];
1964 this.store = currentStore;
1965 this.normalizeStore();
1967 // In Safari, going into Private Browsing mode causes the
1968 // Session Storage object to still exist but if you try and use
1969 // or set any property/function of it it throws the exception
1970 // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to
1971 // add something to storage that exceeded the quota." infinitely
1973 currentStoreString = JSON.stringify(currentStore);
1976 this.sessionStorage.setItem('Roo.History.store', currentStoreString);
1979 if (e.code === DOMException.QUOTA_EXCEEDED_ERR) {
1980 if (this.sessionStorage.length) {
1981 // Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
1982 // removing/resetting the storage can work.
1983 this.sessionStorage.removeItem('Roo.History.store');
1984 this.sessionStorage.setItem('Roo.History.store', currentStoreString);
1986 // Otherwise, we're probably private browsing in Safari, so we'll ignore the exception.
1997 // Try to Initialise History
1998 if (!History.options || !History.options.delayInit) {