/
can-route-pushstate.js
320 lines (281 loc) · 10 KB
/
can-route-pushstate.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
// # can-route-pushstate.js
//
// Plugin for `route` which uses browser `history.pushState` support
// to update window's pathname instead of the `hash`.
//
// It registers itself as binding on `route`, intercepts `click` events
// on `<a>` elements across document and accordingly updates `route` state
// and window's pathname.
/*jshint maxdepth:6, scripturl:true*/
"use strict";
var route = require('can-route');
var bindingProxy = require("can-route/src/binding-proxy");
var canReflect = require("can-reflect");
var KeyTree = require("can-key-tree");
var queues = require("can-queues");
var SimpleObservable = require("can-simple-observable");
var isNode = require('can-globals/is-node/is-node');
var LOCATION = require('can-globals/location/location');
var domEvents = require('can-dom-events');
var diffObject = require('can-util/js/diff-object/diff-object');
var hasPushstate = window.history && window.history.pushState;
var loc = LOCATION();
var validProtocols = { 'http:': true, 'https:': true, '': true };
var usePushStateRouting = hasPushstate && loc && validProtocols[loc.protocol];
// Original methods on `history` that will be overwritten
var methodsToOverwrite = ['pushState', 'replaceState'];
// Always returns clean root, without domain.
var cleanRoot = function () {
var domain = location.protocol + "//" + location.host,
root = bindingProxy.call("root"),
index = root.indexOf(domain);
if (index === 0) {
return root.substr(domain.length);
}
return root;
};
// Handler function for `click` events.
// Checks if a route is matched, if one is, calls `.pushState`
// gets the current url after the root
function getCurrentUrl(){
var root = cleanRoot(),
location = LOCATION(),
loc = (location.pathname + location.search),
index = loc.indexOf(root);
return loc.substr(index + root.length);
}
function PushstateObservable(options) {
/*
* - replaceStateKeys
* - replaceStateOnceKeys
*/
this.options = options;
this.dispatchHandlers = this.dispatchHandlers.bind(this);
var self = this;
this.anchorClickHandler = function(event){
PushstateObservable.prototype.anchorClickHandler.call(self, this, event);
};
this.handlers = new KeyTree([Object,Array],{
onFirst: this.setup.bind(this),
onEmpty: this.teardown.bind(this)
});
}
PushstateObservable.prototype = Object.create(SimpleObservable.prototype);
PushstateObservable.constructor = PushstateObservable;
canReflect.assign(PushstateObservable.prototype,{
/**
* @property {String} can-route-pushstate.root root
* @parent can-route-pushstate.static
*
* @description Configure the base url that will not be modified.
*
* @option {String} Represents the base url that pushstate will prepend to all
* routes. `root` defaults to: `"/"`.
*
* @body
*
* ## Use
*
* By default, a route like:
*
* route(":type/:id")
*
* Matches urls like:
*
* http://domain.com/contact/5
*
* But sometimes, you only want to match pages within a certain directory. For
* example, an application that is a filemanager. You might want to
* specify root and routes like:
*
* route.pushstate.root = "/filemanager/"
* route("file-:fileId");
* route("folder-:fileId")
*
* Which matches urls like:
*
* http://domain.com/filemanager/file-34234
*
*/
// Start of `location.pathname` is the root.
// (Can be configured via `route.bindings.pushstate.root`)
root: "/",
// don't greedily match slashes in routing rules
matchSlashes: false,
paramsMatcher: /^\?(?:[^=]+=[^&]*&)*[^=]+=[^&]*/,
querySeparator: '?',
dispatchHandlers: function() {
var old = this.value;
this.value = getCurrentUrl();
if(old !== this.value) {
queues.enqueueByQueue(this.handlers.getNode([]), this, [this.value, old]
//!steal-remove-start
/* jshint laxcomma: true */
, null
, [ canReflect.getName(this), "changed to", this.value, "from", old ]
/* jshint laxcomma: false */
//!steal-remove-end
);
}
},
anchorClickHandler: function (node, e) {
if (!(e.isDefaultPrevented ? e.isDefaultPrevented() : e.defaultPrevented === true)) {
// Fix for IE showing blank host, but blank host means current host.
var linksHost = node.host || window.location.host;
// href has some JS in it, let it run
if(node.href === "javascript://") {
return;
}
// Do not push state if target is for blank window
if(node.target === '_blank'){
return;
}
// Do not push state if meta key was pressed, mimicking standard browser behavior
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
return;
}
// If link is within the same domain and descendant of `root`
if (window.location.host === linksHost) {
var root = cleanRoot();
// And the link is within the `root`
if (node.pathname.indexOf(root) === 0) {
// Removes root from url.
var nodePathWithSearch = node.pathname + node.search;
var url = nodePathWithSearch.substr(root.length);
// If we've matched a route
if (route.rule(url) !== undefined) {
// Makes it possible to have a link with a hash.
// Calling .pushState will dispatch events, causing
// `can-route` to update its data, and then try to set back
// the url without the hash. We need to retain that.
if(node.href.indexOf("#") >= 0 ) {
this.keepHash = true;
}
// We do not want to call preventDefault() if the link is to the
// same page and just a different hash; see can-route-pushstate#75
var windowPathWithSearch = window.location.pathname + window.location.search;
var shouldCallPreventDefault = nodePathWithSearch !== windowPathWithSearch || node.hash === window.location.hash;
// Now update window.location
window.history.pushState(null, null, node.href);
// Test if you can preventDefault
// our tests can't call .click() b/c this
// freezes phantom.
if (shouldCallPreventDefault && e.preventDefault) {
e.preventDefault();
}
}
}
}
}
},
setup: function(){
if(isNode()) {
return;
}
this.value = getCurrentUrl();
// Intercept routable links.
domEvents.addDelegateListener(document.documentElement, 'click', 'a', this.anchorClickHandler);
var originalMethods = this.originalMethods = {};
var dispatchHandlers = this.dispatchHandlers;
// Rewrites original `pushState`/`replaceState` methods on `history` and keeps pointer to original methods
canReflect.eachKey(methodsToOverwrite, function (method) {
this.originalMethods[method] = window.history[method];
window.history[method] = function (state, title, url) {
// Avoid doubled history states (with pushState).
var absolute = url.indexOf("http") === 0;
var loc = LOCATION();
var searchHash = loc.search + loc.hash;
// If url differs from current call original histoy method and update `route` state.
if ((!absolute && url !== loc.pathname + searchHash) ||
(absolute && url !== loc.href + searchHash)) {
originalMethods[method].apply(window.history, arguments);
dispatchHandlers();
}
};
}, this);
// Bind to `popstate` event, fires on back/forward.
domEvents.addEventListener(window, 'popstate', this.dispatchHandlers);
},
teardown: function(){
domEvents.removeEventListener(document.documentElement, 'click', 'a', this.anchorClickHandler);
canReflect.eachKey(methodsToOverwrite, function (method) {
window.history[method] = this.originalMethods[method];
}, this);
domEvents.removeEventListener(window, 'popstate', this.dispatchHandlers);
},
get: getCurrentUrl,
set: function(path){
var newProps = route.deparam(path);
var oldProps = route.deparam(getCurrentUrl());
var method = "pushState";
var changed;
// Keeps hash if not in path.
if (this.keepHash && path.indexOf("#") === -1 && window.location.hash) {
path += window.location.hash;
}
changed = {};
diffObject(oldProps, newProps)
.forEach(function (patch) {
return changed[patch.property] = true;
});
// check if we should call replaceState or pushState
if( this.options.replaceStateKeys.length ) {
this.options.replaceStateKeys.forEach(function(replaceKey){
if(changed[replaceKey]) {
method = "replaceState";
}
});
}
if( this.options.replaceStateOnceKeys.length ) {
for(var i = this.options.replaceStateOnceKeys.length - 1; i >= 0; i--) {
var replaceOnceKey = this.options.replaceStateOnceKeys[i];
if(changed[replaceOnceKey]) {
method = "replaceState";
// remove so we don't do this again
this.options.replaceStateOnceKeys.splice(i,1);
}
}
}
window.history[method](null, null, bindingProxy.call("root") + path);
}
});
canReflect.assignSymbols(PushstateObservable.prototype,{
"can.getValue": PushstateObservable.prototype.get,
"can.setValue": PushstateObservable.prototype.set,
"can.onValue": PushstateObservable.prototype.on,
"can.offValue": PushstateObservable.prototype.off,
"can.isMapLike": false,
"can.valueHasDependencies": function(){
return true;
},
//!steal-remove-start
"can.getName": function() {
return "PushstateObservable<" + this.value + ">";
},
//!steal-remove-end
});
// Initialize plugin only if browser supports pushstate.
if (usePushStateRouting) {
var options = {
replaceStateOnceKeys: [],
replaceStateKeys: []
};
var pushstateBinding = new PushstateObservable(options);
// Registers itself within `route.bindings`.
route.bindings.pushstate = pushstateBinding;
// Enables plugin, by default `hashchange` binding is used.
route.defaultBinding = "pushstate";
canReflect.assignMap(route, {
replaceStateOn: function() {
canReflect.addValues( options.replaceStateKeys, canReflect.toArray(arguments) );
},
replaceStateOnce: function() {
canReflect.addValues( options.replaceStateOnceKeys, canReflect.toArray(arguments) );
},
replaceStateOff: function() {
canReflect.removeValues( options.replaceStateKeys, canReflect.toArray(arguments) );
canReflect.removeValues( options.replaceStateOnceKeys, canReflect.toArray(arguments) );
}
});
}
module.exports = route;