-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathhistory.js
More file actions
329 lines (278 loc) · 9.3 KB
/
history.js
File metadata and controls
329 lines (278 loc) · 9.3 KB
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
//= require <prototype>
//
// NOTE: In case the version number doesn't tip you off... this is really
// preliminary code. I welcome you to try it out and tell me if it sucks;
// I'll try to make it suck less. Thanks!
//
// Prototype History Manager
// =========================
//
// A port of YUI's Browser History Manager with a slightly different API.
//
// INSTRUCTIONS:
// First: to get this working across all browsers you need both a hidden
// INPUT field _and_ a hidden IFRAME. Somewhere on your page (preferably
// at the bottom) you'll need to tell the history manager where these things
// are. For example:
//
// <input type="hidden" id="history_field" />
// <iframe id="history_iframe" style="display: none;"></iframe>
// <script type="text/javascript" charset="utf-8">
// History.stateField = $('history_manager');
// History.iframe = $('history_iframe');
// </script>
//
// The `History` object functions as an instance of Hash. While the page is
// loading, any calls to `History.set` will determine the _initial_ value
// of any key-value pair. After the window load event fires, any key/value
// pairs are serialized and placed into the URL hash.
//
// Now, whenever `History.set` is called, the URL hash will change, and the
// browser will treat that change as a "page navigation."
//
// Whenever the value of a key changes, whether by updating the value through
// `History.set`, using Back/Forward, or hacking the URL, the history manager
// will fire a custom event for each key that changed, in the form of
// `hash:changed:[name_of_key]`. The event object's `memo` property will
// have several properties: `initialState`, `previousState`, and
// `currentState`, informing you what the value used to be and what it is now.
//
//
// DETAILED EXAMPLE:
//
// (during page load)
// History.set("foo", "bar");
// History.set("baz", "thud");
//
// (when page loads)
// URL hash set to "#foo=bar&baz=thud"
//
// (later...)
// History.set("foo", "blerg");
// URL hash set to "#foo=blerg&baz=thud"
// `document` fires custom event: `hash:changed:foo`
// event.memo.initialState: "bar"
// event.memo.previousState: "bar"
// event.memo.currentState: "blerg"
//
// (later still...)
// User clicks on Back button
// URL hash set to "#foo=bar&baz=thud"
// `document` fires custom event: `hash:changed:foo`
// event.memo.initialState: "bar"
// event.memo.previousState: "blerg"
// event.memo.currentState: "bar"
//
//
(function() {
var VERSION = "0.1";
var _iframe = null;
var _stateField = null;
var _initialized = false;
var _uniqueStates = [];
var _originalHash = null;
var _historyHash = null;
var DEBUG = false;
function _debug() {
if (!DEBUG) return;
return console.log.apply(console, arguments);
}
function _initialize() {
_stateField = History.stateField;
_iframe = History.iframe;
_debug("in _initialize");
// Unserialize the hash from the hidden field.
_historyHash = new $HistoryHash(_stateField.value);
_historyHash.updateWithURLHash(_getHash());
if (Prototype.Browser.IE) {
_checkIFrameLoaded();
} else {
// Poll for hash changes.
var counter = history.length, hash = _getHash();
window.setInterval( function() {
var newHash = _getHash(), newCounter = history.length;
if (newHash !== hash) {
hash = newHash;
_historyHash.updateWithURLHash(newHash);
_storeStates();
} else if (newCounter !== counter && Prototype.Browser.WebKit) {
hash = newHash, counter = newCounter;
var uniqueState = _uniqueStates[counter - 1];
_historyHash.updateWithURLHash(uniqueState);
_storeStates();
}
}, 50);
// At this point, window.History is an ordinary hash. Extract its
// values, then replace it with a $HistoryHash instance.
_originalHash = window.History;
_historyHash.update(_originalHash.toObject());
window._old = _originalHash;
window.History = _historyHash;
window.History.VERSION = VERSION;
_initialized = true;
}
}
function _getHash() {
var href = top.location.href, i = href.indexOf("#");
return i >= 0 ? href.substr(i + 1) : null;
}
function _setHash(hash) {
top.location.hash = hash;
}
function _updateHash(historyHash) {
_setHash(historyHash.toURLHash());
}
function _storeStates() {
var initialStates = [], currentStates = [];
_historyHash.each( function(pair) {
initialStates.push([pair.key, pair.value.initialState].join('='));
currentStates.push([pair.key, pair.value.currentState].join('='));
});
_stateField.value = initialStates.join("&") + "|" + currentStates.join("&");
if (Prototype.Browser.WebKit) {
_stateField.value += "|" + _uniqueStates.join(",");
}
}
function _updateIFrame(uniqueState) {
var html = '<html><body><div id="state">' + uniqueState +
'</div></body></html>';
try {
var doc = _iframe.contentWindow.document;
doc.open();
doc.write(html);
doc.close();
} catch (e) {
return false;
}
}
function _getUniqueStateForIE() {
var doc = _iframe.contentWindow.document;
var elem = doc.getElementById("state");
return elem ? elem.innerText : null;
}
function _checkIFrameLoaded() {
if (!_iframe.contentWindow || _iframe.contentWindow.document) {
// Not ready yet. Keep trying.
window.setTimeout(_checkIFrameLoaded, 10);
return;
}
var uniqueState = _getUniqueStateForIE();
var hash = _getHash();
// Keep polling to see if the values we have above are no longer
// current. If so, fire off the observers.
window.setInterval( function() {
var newUniqueState = _getUniqueStateForIE();
var newHash = _getHash();
if (newUniqueState !== uniqueState) {
uniqueState = newUniqueState;
_historyHash.updateWithURLHash(uniqueState);
hash = newHash;
_setHash(hash);
_storeStates();
} else if (newHash !== hash) {
// Hash changed on its own.
hash = newHash;
_updateIFrame(newHash);
_historyHash.updateWithURLHash(hash);
}
}, 50);
_initialized = true;
}
var $HistoryHash = Class.create(Hash, {
initialize: function(uniqueState) {
this.uniqueState = uniqueState;
this._object = {};
var parts = uniqueState.split("|");
var initialStates = {};
var currentStates = {};
if (parts.length >= 2) {
var iParts = parts[0].split("&");
iParts.each( function(part) {
var pair = part.split("=");
initialStates[pair[0]] = pair[1];
});
var cParts = parts[1].split("&");
cParts.each( function(part) {
var pair = part.split("=");
currentStates[pair[0]] = pair[1];
});
}
this._object = {};
Object.keys(currentStates).each( function(state) {
this._object[state] = {
initialState: initialStates[state],
currentState: currentStates[state]
};
}, this);
},
updateWithURLHash: function(hash) {
if (!hash) {
return;
}
var pairs = hash.split('&');
pairs.each( function(p) {
pair = p.split('=');
this.set(pair[0], pair[1]);
}, this);
},
/**
* History.set(key, value)
*
* Sets a key/value pair, updating the URL and triggering a new
* navigation state in the browser.
* - key (String): The key to set.
* - value (String): The value to set.
**/
set: function($super, key, value) {
var item;
if (this.get(key) === null) {
if (_initialized) {
throw new Error("New key cannot be set after initialization!");
} else {
item = { initialState: value };
}
} else {
item = this._object[key];
}
if (item.currentState && item.currentState !== value) {
_debug("in set", arguments);
// Value has changed. Fire an event.
var memo = Object.clone(item);
memo.previousState = item.currentState;
memo.currentState = value;
document.fire("hash:changed:" + key, memo);
}
item.currentState = value;
item = $super(key, item);
_updateHash(this);
document.fire("hash:changed", this.toObject());
return item;
},
/**
* Hash.get(key)
* Retrieves the _current_ value of the item in the URL hash with the
* given key.
* - key (String): The key to retrieve.
**/
get: function($super, key) {
var value = $super(key);
return value ? value.currentState : null;
},
toURLHash: function() {
function toURLPair(pair) {
return [pair.key, pair.value.currentState].join('=');
}
return "#" + this.map(toURLPair).join('&');
},
toObject: function() {
var obj = {};
this.each( function(pair) {
obj[pair.key] = pair.value.currentState;
}, this);
return obj;
}
});
Event.observe(window, 'load', _initialize);
window.History = new Hash();
window.History.VERSION = VERSION;
})();