-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshredder.js
481 lines (408 loc) · 16 KB
/
shredder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*!!
Shredder is a hacked version of Hasher enabling
http://site.com/#/page-1
and
http://site.com/page-1
to answer with the same content.
There are multiple reasons for this, the most urgent of them being SEO.
Stay up to date with this question:
https://github.com/millermedeiros/Hasher/issues/69
Everything else here is the same as original hasher, except this around line 100:
if(href.charAt(host.length+1) === "#") {
var result = _hashValRegexp.exec(hasher.getURL());
} else {
var clean = href.replace(host, '')
var result = []
result.push(clean)
result.push(clean)
}
was originally just:
var result = _hashValRegexp.exec(hasher.getURL());
* Hasher <http://github.com/millermedeiros/hasher>
* @author Miller Medeiros
* @version 1.2.0 (2013/11/11 03:18 PM)
* Released under the MIT License
*/
;(function () {
var factory = function(signals){
/*jshint white:false*/
/*global signals:false, window:false*/
/**
* Hasher
* @namespace History Manager for rich-media applications.
* @name hasher
*/
var hasher = (function(window){
//--------------------------------------------------------------------------------------
// Private Vars
//--------------------------------------------------------------------------------------
var
// frequency that it will check hash value on IE 6-7 since it doesn't
// support the hashchange event
POOL_INTERVAL = 25,
// local storage for brevity and better compression --------------------------------
document = window.document,
history = window.history,
Signal = signals.Signal,
// local vars ----------------------------------------------------------------------
hasher,
_hash,
_checkInterval,
_isActive,
_frame, //iframe used for legacy IE (6-7)
_checkHistory,
_hashValRegexp = /#(.*)$/,
_baseUrlRegexp = /(\?.*)|(\#.*)/,
_hashRegexp = /^\#/,
// sniffing/feature detection -------------------------------------------------------
//hack based on this: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
_isIE = (!+"\v1"),
// hashchange is supported by FF3.6+, IE8+, Chrome 5+, Safari 5+ but
// feature detection fails on IE compatibility mode, so we need to
// check documentMode
_isHashChangeSupported = ('onhashchange' in window) && document.documentMode !== 7,
//check if is IE6-7 since hash change is only supported on IE8+ and
//changing hash value on IE6-7 doesn't generate history record.
_isLegacyIE = _isIE && !_isHashChangeSupported,
_isLocal = (location.protocol === 'file:');
//--------------------------------------------------------------------------------------
// Private Methods
//--------------------------------------------------------------------------------------
function _escapeRegExp(str){
return String(str || '').replace(/\W/g, "\\$&");
}
function _trimHash(hash){
if (!hash) return '';
var regexp = new RegExp('^' + _escapeRegExp(hasher.prependHash) + '|' + _escapeRegExp(hasher.appendHash) + '$', 'g');
return hash.replace(regexp, '');
}
function _getWindowHash(){
//parsed full URL instead of getting window.location.hash because Firefox decode hash value (and all the other browsers don't)
//also because of IE8 bug with hash query in local file [issue #6]
var host = window.location.protocol + "//" + window.location.host
var href = window.location.href
if(href.indexOf("#") !== -1) {
var result = _hashValRegexp.exec(hasher.getURL());
} else {
var clean = href.replace(host, '')
var result = []
result.push(clean)
result.push(clean)
}
var path = (result && result[1]) || '';
try {
return hasher.raw? path : decodeURIComponent(path);
} catch (e) {
// in case user did not set `hasher.raw` and decodeURIComponent
// throws an error (see #57)
return path;
}
}
function _getFrameHash(){
return (_frame)? _frame.contentWindow.frameHash : null;
}
function _createFrame(){
_frame = document.createElement('iframe');
_frame.src = 'about:blank';
_frame.style.display = 'none';
document.body.appendChild(_frame);
}
function _updateFrame(){
if(_frame && _hash !== _getFrameHash()){
var frameDoc = _frame.contentWindow.document;
frameDoc.open();
//update iframe content to force new history record.
//based on Really Simple History, SWFAddress and YUI.history.
frameDoc.write('<html><head><title>' + document.title + '</title><script type="text/javascript">var frameHash="' + _hash + '";</script></head><body> </body></html>');
frameDoc.close();
}
}
function _registerChange(newHash, isReplace){
if(_hash !== newHash){
var oldHash = _hash;
_hash = newHash; //should come before event dispatch to make sure user can get proper value inside event handler
if(_isLegacyIE){
if(!isReplace){
_updateFrame();
} else {
_frame.contentWindow.frameHash = newHash;
}
}
hasher.changed.dispatch(_trimHash(newHash), _trimHash(oldHash));
}
}
if (_isLegacyIE) {
/**
* @private
*/
_checkHistory = function(){
var windowHash = _getWindowHash(),
frameHash = _getFrameHash();
if(frameHash !== _hash && frameHash !== windowHash){
//detect changes made pressing browser history buttons.
//Workaround since history.back() and history.forward() doesn't
//update hash value on IE6/7 but updates content of the iframe.
//needs to trim hash since value stored already have
//prependHash + appendHash for fast check.
hasher.setHash(_trimHash(frameHash));
} else if (windowHash !== _hash){
//detect if hash changed (manually or using setHash)
_registerChange(windowHash);
}
};
} else {
/**
* @private
*/
_checkHistory = function(){
var windowHash = _getWindowHash();
if(windowHash !== _hash){
_registerChange(windowHash);
}
};
}
function _addListener(elm, eType, fn){
if(elm.addEventListener){
elm.addEventListener(eType, fn, false);
} else if (elm.attachEvent){
elm.attachEvent('on' + eType, fn);
}
}
function _removeListener(elm, eType, fn){
if(elm.removeEventListener){
elm.removeEventListener(eType, fn, false);
} else if (elm.detachEvent){
elm.detachEvent('on' + eType, fn);
}
}
function _makePath(paths){
paths = Array.prototype.slice.call(arguments);
var path = paths.join(hasher.separator);
path = path? hasher.prependHash + path.replace(_hashRegexp, '') + hasher.appendHash : path;
return path;
}
function _encodePath(path){
//used encodeURI instead of encodeURIComponent to preserve '?', '/',
//'#'. Fixes Safari bug [issue #8]
path = encodeURI(path);
if(_isIE && _isLocal){
//fix IE8 local file bug [issue #6]
path = path.replace(/\?/, '%3F');
}
return path;
}
//--------------------------------------------------------------------------------------
// Public (API)
//--------------------------------------------------------------------------------------
hasher = /** @lends hasher */ {
/**
* hasher Version Number
* @type string
* @constant
*/
VERSION : '1.2.0',
/**
* Boolean deciding if hasher encodes/decodes the hash or not.
* <ul>
* <li>default value: false;</li>
* </ul>
* @type boolean
*/
raw : false,
/**
* String that should always be added to the end of Hash value.
* <ul>
* <li>default value: '';</li>
* <li>will be automatically removed from `hasher.getHash()`</li>
* <li>avoid conflicts with elements that contain ID equal to hash value;</li>
* </ul>
* @type string
*/
appendHash : '',
/**
* String that should always be added to the beginning of Hash value.
* <ul>
* <li>default value: '/';</li>
* <li>will be automatically removed from `hasher.getHash()`</li>
* <li>avoid conflicts with elements that contain ID equal to hash value;</li>
* </ul>
* @type string
*/
prependHash : '/',
/**
* String used to split hash paths; used by `hasher.getHashAsArray()` to split paths.
* <ul>
* <li>default value: '/';</li>
* </ul>
* @type string
*/
separator : '/',
/**
* Signal dispatched when hash value changes.
* - pass current hash as 1st parameter to listeners and previous hash value as 2nd parameter.
* @type signals.Signal
*/
changed : new Signal(),
/**
* Signal dispatched when hasher is stopped.
* - pass current hash as first parameter to listeners
* @type signals.Signal
*/
stopped : new Signal(),
/**
* Signal dispatched when hasher is initialized.
* - pass current hash as first parameter to listeners.
* @type signals.Signal
*/
initialized : new Signal(),
/**
* Start listening/dispatching changes in the hash/history.
* <ul>
* <li>hasher won't dispatch CHANGE events by manually typing a new value or pressing the back/forward buttons before calling this method.</li>
* </ul>
*/
init : function(){
if(_isActive) return;
_hash = _getWindowHash();
//thought about branching/overloading hasher.init() to avoid checking multiple times but
//don't think worth doing it since it probably won't be called multiple times.
if(_isHashChangeSupported){
_addListener(window, 'hashchange', _checkHistory);
}else {
if(_isLegacyIE){
if(! _frame){
_createFrame();
}
_updateFrame();
}
_checkInterval = setInterval(_checkHistory, POOL_INTERVAL);
}
_isActive = true;
hasher.initialized.dispatch(_trimHash(_hash));
},
/**
* Stop listening/dispatching changes in the hash/history.
* <ul>
* <li>hasher won't dispatch CHANGE events by manually typing a new value or pressing the back/forward buttons after calling this method, unless you call hasher.init() again.</li>
* <li>hasher will still dispatch changes made programatically by calling hasher.setHash();</li>
* </ul>
*/
stop : function(){
if(! _isActive) return;
if(_isHashChangeSupported){
_removeListener(window, 'hashchange', _checkHistory);
}else{
clearInterval(_checkInterval);
_checkInterval = null;
}
_isActive = false;
hasher.stopped.dispatch(_trimHash(_hash));
},
/**
* @return {boolean} If hasher is listening to changes on the browser history and/or hash value.
*/
isActive : function(){
return _isActive;
},
/**
* @return {string} Full URL.
*/
getURL : function(){
return window.location.href;
},
/**
* @return {string} Retrieve URL without query string and hash.
*/
getBaseURL : function(){
return hasher.getURL().replace(_baseUrlRegexp, ''); //removes everything after '?' and/or '#'
},
/**
* Set Hash value, generating a new history record.
* @param {...string} path Hash value without '#'. Hasher will join
* path segments using `hasher.separator` and prepend/append hash value
* with `hasher.appendHash` and `hasher.prependHash`
* @example hasher.setHash('lorem', 'ipsum', 'dolor') -> '#/lorem/ipsum/dolor'
*/
setHash : function(path){
path = _makePath.apply(null, arguments);
if(path !== _hash){
// we should store raw value
_registerChange(path);
if (path === _hash) {
// we check if path is still === _hash to avoid error in
// case of multiple consecutive redirects [issue #39]
if (! hasher.raw) {
path = _encodePath(path);
}
window.location.hash = '#' + path;
}
}
},
/**
* Set Hash value without keeping previous hash on the history record.
* Similar to calling `window.location.replace("#/hash")` but will also work on IE6-7.
* @param {...string} path Hash value without '#'. Hasher will join
* path segments using `hasher.separator` and prepend/append hash value
* with `hasher.appendHash` and `hasher.prependHash`
* @example hasher.replaceHash('lorem', 'ipsum', 'dolor') -> '#/lorem/ipsum/dolor'
*/
replaceHash : function(path){
path = _makePath.apply(null, arguments);
if(path !== _hash){
// we should store raw value
_registerChange(path, true);
if (path === _hash) {
// we check if path is still === _hash to avoid error in
// case of multiple consecutive redirects [issue #39]
if (! hasher.raw) {
path = _encodePath(path);
}
window.location.replace('#' + path);
}
}
},
/**
* @return {string} Hash value without '#', `hasher.appendHash` and `hasher.prependHash`.
*/
getHash : function(){
//didn't used actual value of the `window.location.hash` to avoid breaking the application in case `window.location.hash` isn't available and also because value should always be synched.
return _trimHash(_hash);
},
/**
* @return {Array.<string>} Hash value split into an Array.
*/
getHashAsArray : function(){
return hasher.getHash().split(hasher.separator);
},
/**
* Removes all event listeners, stops hasher and destroy hasher object.
* - IMPORTANT: hasher won't work after calling this method, hasher Object will be deleted.
*/
dispose : function(){
hasher.stop();
hasher.initialized.dispose();
hasher.stopped.dispose();
hasher.changed.dispose();
_frame = hasher = window.hasher = null;
},
/**
* @return {string} A string representation of the object.
*/
toString : function(){
return '[hasher version="'+ hasher.VERSION +'" hash="'+ hasher.getHash() +'"]';
}
};
hasher.initialized.memorize = true; //see #33
return hasher;
}(window));
return hasher;
};
if (typeof define === 'function' && define.amd) {
define(['signals'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('signals'));
} else {
/*jshint sub:true */
window['hasher'] = factory(window['signals']);
}
}());