-
Notifications
You must be signed in to change notification settings - Fork 1
/
browser.js
375 lines (329 loc) · 10.4 KB
/
browser.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
var Url = require("url");
var pathToRegexp = require("path-to-regexp");
var browserEnv = require("./lib/dom_event_handler");
var historyEnv = require("./lib/history");
var urlParser = require("./lib/url_parser");
/**
* handler - create a route handler
* @param {String} method http method (GET, POST, PUT, DELETE)
* @param {String} path path to navigate to
* @param {Function} fn middleware function
* @param {Function} next call the next item in the middleware stack
* @returns {undefined}
*/
function addRouteHandler (method, path, fn) {
// If using router.use(middleware) then set a catch all path
if (!fn) {
fn = path;
path = "/*";
}
var re = pathToRegexp(path);
var keys = re.keys;
/**
* Construct a routeHandler
* @param {String} _method HTTP method of the incoming request
* @param {String} _path url path of the incoming request
* @returns {false|Function} express like middleware
*/
function routeHandler (_method, _path) {
// Check the method matches
if (method !== "use" && method !== _method) {
return false;
}
// Check the path matches
var pathname = Url.parse(_path).pathname;
var results = re.exec(pathname);
if (!results) {
return false;
}
/**
* Wrap a route handler
* @param {Error} [err] optional error denoting should pass request to error handling middleware
* @param {Object} req request object
* @param {Object} res response object
* @param {Function} next continuation function called with an optional error param
* @returns {Void} next will be called
*/
return function handler () {
var err, req, res, next;
if (arguments.length === 4) {
err = arguments[0];
req = arguments[1];
res = arguments[2];
next = arguments[3];
} else {
req = arguments[0];
res = arguments[1];
next = arguments[2];
}
var params = {};
keys.forEach(function (key, idx) {
params[key.name] = results[idx+1];
});
req.params = params;
if (err) {
// Bypass any handlers which don't accept the express error argument signature
if (fn.length < 4) {
next(err);
} else {
fn(err, req, res, next);
}
} else {
if (fn.length < 4) {
fn(req, res, next);
} else {
next();
}
}
};
}
this.routes.push(routeHandler);
}
/**
* go - peform a request to router
* @param {String} path path to navigate to
* @param {Object} opts navigation options
* @param {String} opts.method http method (GET, POST, PUT, DELETE)
* @param {Boolean} opts.replace replace the last item in pushstate history
* @param {Boolean} opts.silent if silent the router handler isn't triggered
* @param {Object} opts.body request body to send
* @param {Object} opts.locals extra data such as a flash message
* @returns {Boolean} if the request was sent
*/
function go (path, opts) {
var self = this;
// If not navigating anywhere return
if (!path || path === "") {
return false;
}
opts = opts || {};
var method = opts.method || "get";
var silent = false;
if (typeof opts.silent !== "undefined") {
silent = opts.silent;
}
var replace = false;
if (typeof opts.replace !== "undefined") {
replace = opts.replace;
}
var redirect = false;
if (typeof opts.redirect !== "undefined") {
redirect = opts.redirect;
}
var body = opts.body || {};
var locals = opts.locals || {};
var parsedUrl = urlParser(path);
var url = parsedUrl.format(parsedUrl);
// If redirecting to self catch and do a full navigation
var lastRoute = this.history[this.history.length - 1];
if (lastRoute && lastRoute.method === method && lastRoute.path === url) {
if (this.selfRedirectCount >= 50) {
console.warn("isoRouter: Tried to navigate to same path more than 50 times.");
return false;
} else {
this.selfRedirectCount++;
}
}
// If navigating to a different host then want to do full navigation
if ((parsedUrl.host && window.location && parsedUrl.host !== window.location.hostname) || opts.hard) {
window.location.href = url;
return false;
}
// request object, similar to express
var req = {
__id: this.reqIdx++,
method: method,
body: body,
protocol: window.location.protocol.replace(":", ""),
hostname: window.location.hostname,
headers: {
host: window.location.host,
cookie: document.cookie,
referer: lastRoute ? lastRoute.path : null
},
locals: locals,
originalUrl: url,
path: parsedUrl.pathname,
query: parsedUrl.query,
url: url
};
// response object, similar to express
var res = {
// Data to pass through middleware
locals: {},
// Mimic functionality of express res.redirect
redirect: function (url) {
var address = url;
var status = 302;
var redirectOpts = {};
// allow status / url
if (arguments.length === 2) {
if (typeof arguments[0] === "number") {
status = arguments[0];
address = arguments[1];
} else {
status = arguments[1];
}
} else if (arguments.length === 3) {
address = arguments[0];
status = arguments[1];
redirectOpts = arguments[2];
}
this.statusCode = status;
// If no replace is specified, defualt to true
var shouldRedirect = typeof redirectOpts.redirect !== "undefined" ? redirectOpts.redirect : true;
return go.call(self, address, {
silent: redirectOpts.silent,
replace: redirectOpts.replace,
redirect: shouldRedirect,
body: redirectOpts.body || body,
locals: redirectOpts.locals || locals
});
}
};
// opts.replace will replace the url without without triggering the route
if (replace === true) {
historyEnv.redirect(url);
return true;
}
// opts.redirect will replace the last url and trigger the route
if (redirect === true) {
historyEnv.redirect(url);
}
// opts.silent will trigger the route without changing the url
else if (silent === false) {
historyEnv.go(url);
}
// Find the matching route based on url and method
var foundHandlers = this.routes.map(function (handler) {
return handler(req.method, req.path);
}).filter(function (handler) {
return handler;
});
// Create a next callback which iterates through middlewares
var idx = 0;
function next (err) {
var func = foundHandlers[idx];
idx++;
if (err) {
// Trigger the before navigate event
self.emit("error", err, req, res);
func(err, req, res, next);
} else {
func(req, res, next);
}
}
if (foundHandlers.length > 0) {
// Trigger the before navigate event
this.emit("navigate", req, res);
// Store the history
this.history.push({
method: method,
path: url
});
if (!opts.preventScrollReset) {
if (parsedUrl.hash) {
document.getElementById(parsedUrl.hash.replace("#", "")).scrollIntoView();
} else {
// Reset scroll position
window.scrollTo(0,0);
}
}
// Iterate through the middlewares and routes
next();
// Return true so it's easy to determine if a route was found
// This means we can do things like `preventDefault` on events
return true;
} else {
return false;
}
}
/**
* add an event listener
* @param {String} eventName name of event to listen for
* @param {Function} func function to trigger on event
* @returns {Function} return the listener function for reference
*/
function addListener (eventName, func) {
if (this.listeners[eventName]) {
this.listeners[eventName].push(func);
}
return func;
}
/**
* add an event listener
* @param {String} eventName name of event to listen for
* @param {Function} func function to trigger on event
* @returns {Void} no return
*/
function removelistener (eventName, func) {
if (this.listeners[eventName]) {
var pos = this.listeners[eventName].indexOf(func);
if (pos !== -1) {
this.listeners[eventName].splice(pos, 1);
}
}
}
/**
* clientRouter - create an express compliant router for use in the browser
* @param {Object} opts router configuration options
* @param {String} opts.inject dom selector for element to replace on navigation
* @returns {Object} express router
*/
module.exports = function clientRouter (opts) {
opts = opts || {};
var domEventHandler, router;
// Setup the context
var ctx = {
// Store for event listeners
listeners: {
navigate: [], // event listeners for navigation events
error: [] // event listeners for error events
},
// Trigger an event to all relevant listeners
emit: function () {
var args = Array.prototype.slice.call(arguments);
var eventName = args[0];
if (this.listeners[eventName]) {
this.listeners[eventName].forEach(function (listener) {
listener.apply(null, args.slice(1));
});
}
},
routes: [], // Array of route handlers to be run through on each request
history: [], // Array of objects containing request method and path
selfRedirectCount: 0, // Count of how many times the same url has been hit
reqIdx: 0 // incrementing count of each request
};
function removeDomEventHandler () {
if (domEventHandler) {
domEventHandler.destroy();
}
}
// Expose the router API
router = {
get: addRouteHandler.bind(ctx, "get"),
post: addRouteHandler.bind(ctx, "post"),
put: addRouteHandler.bind(ctx, "put"),
delete: addRouteHandler.bind(ctx, "delete"),
use: addRouteHandler.bind(ctx, "use"),
go: go.bind(ctx),
addEventListener: addListener.bind(ctx),
removeEventListener: removelistener.bind(ctx),
trigger: ctx.emit.bind(ctx),
removeDomEventHandler: removeDomEventHandler,
history: historyEnv
};
// When the url changes (such as back button) want to trigger the appropriate handler
window.addEventListener("popstate", function () {
var url = document.location.pathname + document.location.search;
router.go(url, {
silent: true
});
});
// Injects a delegate event listener onto window or a specific node
if (opts.inject) {
domEventHandler = browserEnv.call(router, opts.inject);
}
return router;
};