1 | (function (global, factory) {
|
2 | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
3 | typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
4 | (global = global || self, factory(global.Curi = {}));
|
5 | }(this, function (exports) { 'use strict';
|
6 |
|
7 | function pathname(route, params) {
|
8 | return route.methods.pathname(params);
|
9 | }
|
10 |
|
11 | function isAsyncRoute(route) {
|
12 | return typeof route.methods.resolve !== "undefined";
|
13 | }
|
14 | function isExternalRedirect(redirect) {
|
15 | return "externalURL" in redirect;
|
16 | }
|
17 |
|
18 | function finishResponse(route, match, resolvedResults, router, external) {
|
19 | var _a = resolvedResults || {}, _b = _a.resolved, resolved = _b === void 0 ? null : _b, _c = _a.error, error = _c === void 0 ? null : _c;
|
20 | var response = {
|
21 | data: undefined,
|
22 | body: undefined,
|
23 | meta: undefined
|
24 | };
|
25 | for (var key in match) {
|
26 | response[key] = match[key];
|
27 | }
|
28 | if (!route.methods.respond) {
|
29 | return response;
|
30 | }
|
31 | var results = route.methods.respond({
|
32 | resolved: resolved,
|
33 | error: error,
|
34 | match: match,
|
35 | external: external
|
36 | });
|
37 | if (!results) {
|
38 | {
|
39 | console.warn("\"" + match.name + "\"'s response function did not return anything. Did you forget to include a return statement?");
|
40 | }
|
41 | return response;
|
42 | }
|
43 | {
|
44 | var validProperties_1 = {
|
45 | meta: true,
|
46 | body: true,
|
47 | data: true,
|
48 | redirect: true
|
49 | };
|
50 | Object.keys(results).forEach(function (property) {
|
51 | if (!validProperties_1.hasOwnProperty(property)) {
|
52 | console.warn("\"" + property + "\" is not a valid response property. The valid properties are:\n\n " + Object.keys(validProperties_1).join(", "));
|
53 | }
|
54 | });
|
55 | }
|
56 | response["meta"] = results["meta"];
|
57 | response["body"] = results["body"];
|
58 | response["data"] = results["data"];
|
59 | if (results["redirect"]) {
|
60 | response["redirect"] = createRedirect(results["redirect"], router);
|
61 | }
|
62 | return response;
|
63 | }
|
64 | function createRedirect(redirect, router) {
|
65 | if (isExternalRedirect(redirect)) {
|
66 | return redirect;
|
67 | }
|
68 | var name = redirect.name, params = redirect.params, query = redirect.query, hash = redirect.hash, state = redirect.state;
|
69 | var url = router.url({ name: name, params: params, query: query, hash: hash });
|
70 | return {
|
71 | name: name,
|
72 | params: params,
|
73 | query: query,
|
74 | hash: hash,
|
75 | state: state,
|
76 | url: url
|
77 | };
|
78 | }
|
79 |
|
80 | function createRouter(historyConstructor, routes, options) {
|
81 | if (options === void 0) { options = {}; }
|
82 | var latestResponse;
|
83 | var latestNavigation;
|
84 | var history = historyConstructor(function (pendingNav) {
|
85 | var navigation = {
|
86 | action: pendingNav.action,
|
87 | previous: latestResponse
|
88 | };
|
89 | var matched = routes.match(pendingNav.location);
|
90 | if (!matched) {
|
91 | {
|
92 | console.warn("The current location (" + pendingNav.location.pathname + ") has no matching route, " +
|
93 | 'so a response could not be emitted. A catch-all route ({ path: "(.*)" }) ' +
|
94 | "can be used to match locations with no other matching route.");
|
95 | }
|
96 | pendingNav.finish();
|
97 | finishAndResetNavCallbacks();
|
98 | return;
|
99 | }
|
100 | var route = matched.route, match = matched.match;
|
101 | if (!isAsyncRoute(route)) {
|
102 | finalizeResponseAndEmit(route, match, pendingNav, navigation, null);
|
103 | }
|
104 | else {
|
105 | announceAsyncNav();
|
106 | route.methods
|
107 | .resolve(match, options.external)
|
108 | .then(function (resolved) { return ({ resolved: resolved, error: null }); }, function (error) { return ({ error: error, resolved: null }); })
|
109 | .then(function (resolved) {
|
110 | if (pendingNav.cancelled) {
|
111 | return;
|
112 | }
|
113 | finalizeResponseAndEmit(route, match, pendingNav, navigation, resolved);
|
114 | });
|
115 | }
|
116 | }, options.history || {});
|
117 | function finalizeResponseAndEmit(route, match, pending, navigation, resolved) {
|
118 | asyncNavComplete();
|
119 | pending.finish();
|
120 | var response = finishResponse(route, match, resolved, router, options.external);
|
121 | finishAndResetNavCallbacks();
|
122 | emitImmediate(response, navigation);
|
123 | }
|
124 | var _a = options.invisibleRedirects, invisibleRedirects = _a === void 0 ? false : _a;
|
125 | function emitImmediate(response, navigation) {
|
126 | if (!response.redirect ||
|
127 | !invisibleRedirects ||
|
128 | isExternalRedirect(response.redirect)) {
|
129 | latestResponse = response;
|
130 | latestNavigation = navigation;
|
131 | var emit = { response: response, navigation: navigation, router: router };
|
132 | callObservers(emit);
|
133 | callOneTimersAndSideEffects(emit);
|
134 | }
|
135 | if (response.redirect !== undefined &&
|
136 | !isExternalRedirect(response.redirect)) {
|
137 | history.navigate(response.redirect, "replace");
|
138 | }
|
139 | }
|
140 | function callObservers(emitted) {
|
141 | observers.forEach(function (fn) {
|
142 | fn(emitted);
|
143 | });
|
144 | }
|
145 | function callOneTimersAndSideEffects(emitted) {
|
146 | oneTimers.splice(0).forEach(function (fn) {
|
147 | fn(emitted);
|
148 | });
|
149 | if (options.sideEffects) {
|
150 | options.sideEffects.forEach(function (fn) {
|
151 | fn(emitted);
|
152 | });
|
153 | }
|
154 | }
|
155 |
|
156 | var observers = [];
|
157 | var oneTimers = [];
|
158 | function observe(fn, options) {
|
159 | var _a = (options || {}).initial, initial = _a === void 0 ? true : _a;
|
160 | observers.push(fn);
|
161 | if (latestResponse && initial) {
|
162 | fn({
|
163 | response: latestResponse,
|
164 | navigation: latestNavigation,
|
165 | router: router
|
166 | });
|
167 | }
|
168 | return function () {
|
169 | observers = observers.filter(function (obs) {
|
170 | return obs !== fn;
|
171 | });
|
172 | };
|
173 | }
|
174 | function once(fn, options) {
|
175 | var _a = (options || {}).initial, initial = _a === void 0 ? true : _a;
|
176 | if (latestResponse && initial) {
|
177 | fn({
|
178 | response: latestResponse,
|
179 | navigation: latestNavigation,
|
180 | router: router
|
181 | });
|
182 | }
|
183 | else {
|
184 | oneTimers.push(fn);
|
185 | }
|
186 | }
|
187 |
|
188 | function url(details) {
|
189 | var name = details.name, params = details.params, hash = details.hash, query = details.query;
|
190 | var pathname$1;
|
191 | if (name) {
|
192 | var route = router.route(name);
|
193 | if (route) {
|
194 | pathname$1 = pathname(route, params);
|
195 | }
|
196 | }
|
197 | return history.url({ pathname: pathname$1, hash: hash, query: query });
|
198 | }
|
199 |
|
200 | var cancelCallback;
|
201 | var finishCallback;
|
202 | function navigate(details) {
|
203 | cancelAndResetNavCallbacks();
|
204 | var url = details.url, state = details.state, method = details.method;
|
205 | history.navigate({ url: url, state: state }, method);
|
206 | if (details.cancelled || details.finished) {
|
207 | cancelCallback = details.cancelled;
|
208 | finishCallback = details.finished;
|
209 | return resetCallbacks;
|
210 | }
|
211 | }
|
212 | function cancelAndResetNavCallbacks() {
|
213 | if (cancelCallback) {
|
214 | cancelCallback();
|
215 | }
|
216 | resetCallbacks();
|
217 | }
|
218 | function finishAndResetNavCallbacks() {
|
219 | if (finishCallback) {
|
220 | finishCallback();
|
221 | }
|
222 | resetCallbacks();
|
223 | }
|
224 | function resetCallbacks() {
|
225 | cancelCallback = undefined;
|
226 | finishCallback = undefined;
|
227 | }
|
228 |
|
229 | var cancelWith;
|
230 | var asyncNavNotifiers = [];
|
231 | function cancel(fn) {
|
232 | asyncNavNotifiers.push(fn);
|
233 | return function () {
|
234 | asyncNavNotifiers = asyncNavNotifiers.filter(function (can) {
|
235 | return can !== fn;
|
236 | });
|
237 | };
|
238 | }
|
239 |
|
240 |
|
241 | function announceAsyncNav() {
|
242 | if (asyncNavNotifiers.length && cancelWith === undefined) {
|
243 | cancelWith = function () {
|
244 | history.cancel();
|
245 | asyncNavComplete();
|
246 | cancelAndResetNavCallbacks();
|
247 | };
|
248 | asyncNavNotifiers.forEach(function (fn) {
|
249 | fn(cancelWith);
|
250 | });
|
251 | }
|
252 | }
|
253 | function asyncNavComplete() {
|
254 | if (cancelWith) {
|
255 | cancelWith = undefined;
|
256 | asyncNavNotifiers.forEach(function (fn) {
|
257 | fn();
|
258 | });
|
259 | }
|
260 | }
|
261 | var router = {
|
262 | route: routes.route,
|
263 | history: history,
|
264 | external: options.external,
|
265 | observe: observe,
|
266 | once: once,
|
267 | cancel: cancel,
|
268 | url: url,
|
269 | navigate: navigate,
|
270 | current: function () {
|
271 | return {
|
272 | response: latestResponse,
|
273 | navigation: latestNavigation
|
274 | };
|
275 | },
|
276 | destroy: function () {
|
277 | history.destroy();
|
278 | }
|
279 | };
|
280 | history.current();
|
281 | return router;
|
282 | }
|
283 |
|
284 | |
285 |
|
286 |
|
287 | var pathToRegexp_1 = pathToRegexp;
|
288 | var parse_1 = parse;
|
289 | var compile_1 = compile;
|
290 | var tokensToFunction_1 = tokensToFunction;
|
291 | var tokensToRegExp_1 = tokensToRegExp;
|
292 |
|
293 | |
294 |
|
295 |
|
296 | var DEFAULT_DELIMITER = '/';
|
297 | var DEFAULT_DELIMITERS = './';
|
298 |
|
299 | |
300 |
|
301 |
|
302 |
|
303 |
|
304 | var PATH_REGEXP = new RegExp([
|
305 |
|
306 |
|
307 | '(\\\\.)',
|
308 |
|
309 |
|
310 |
|
311 |
|
312 |
|
313 | '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?'
|
314 | ].join('|'), 'g');
|
315 |
|
316 | |
317 |
|
318 |
|
319 |
|
320 |
|
321 |
|
322 |
|
323 | function parse (str, options) {
|
324 | var tokens = [];
|
325 | var key = 0;
|
326 | var index = 0;
|
327 | var path = '';
|
328 | var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER;
|
329 | var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS;
|
330 | var pathEscaped = false;
|
331 | var res;
|
332 |
|
333 | while ((res = PATH_REGEXP.exec(str)) !== null) {
|
334 | var m = res[0];
|
335 | var escaped = res[1];
|
336 | var offset = res.index;
|
337 | path += str.slice(index, offset);
|
338 | index = offset + m.length;
|
339 |
|
340 |
|
341 | if (escaped) {
|
342 | path += escaped[1];
|
343 | pathEscaped = true;
|
344 | continue
|
345 | }
|
346 |
|
347 | var prev = '';
|
348 | var next = str[index];
|
349 | var name = res[2];
|
350 | var capture = res[3];
|
351 | var group = res[4];
|
352 | var modifier = res[5];
|
353 |
|
354 | if (!pathEscaped && path.length) {
|
355 | var k = path.length - 1;
|
356 |
|
357 | if (delimiters.indexOf(path[k]) > -1) {
|
358 | prev = path[k];
|
359 | path = path.slice(0, k);
|
360 | }
|
361 | }
|
362 |
|
363 |
|
364 | if (path) {
|
365 | tokens.push(path);
|
366 | path = '';
|
367 | pathEscaped = false;
|
368 | }
|
369 |
|
370 | var partial = prev !== '' && next !== undefined && next !== prev;
|
371 | var repeat = modifier === '+' || modifier === '*';
|
372 | var optional = modifier === '?' || modifier === '*';
|
373 | var delimiter = prev || defaultDelimiter;
|
374 | var pattern = capture || group;
|
375 |
|
376 | tokens.push({
|
377 | name: name || key++,
|
378 | prefix: prev,
|
379 | delimiter: delimiter,
|
380 | optional: optional,
|
381 | repeat: repeat,
|
382 | partial: partial,
|
383 | pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?'
|
384 | });
|
385 | }
|
386 |
|
387 |
|
388 | if (path || index < str.length) {
|
389 | tokens.push(path + str.substr(index));
|
390 | }
|
391 |
|
392 | return tokens
|
393 | }
|
394 |
|
395 | |
396 |
|
397 |
|
398 |
|
399 |
|
400 |
|
401 |
|
402 | function compile (str, options) {
|
403 | return tokensToFunction(parse(str, options))
|
404 | }
|
405 |
|
406 | |
407 |
|
408 |
|
409 | function tokensToFunction (tokens) {
|
410 |
|
411 | var matches = new Array(tokens.length);
|
412 |
|
413 |
|
414 | for (var i = 0; i < tokens.length; i++) {
|
415 | if (typeof tokens[i] === 'object') {
|
416 | matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
|
417 | }
|
418 | }
|
419 |
|
420 | return function (data, options) {
|
421 | var path = '';
|
422 | var encode = (options && options.encode) || encodeURIComponent;
|
423 |
|
424 | for (var i = 0; i < tokens.length; i++) {
|
425 | var token = tokens[i];
|
426 |
|
427 | if (typeof token === 'string') {
|
428 | path += token;
|
429 | continue
|
430 | }
|
431 |
|
432 | var value = data ? data[token.name] : undefined;
|
433 | var segment;
|
434 |
|
435 | if (Array.isArray(value)) {
|
436 | if (!token.repeat) {
|
437 | throw new TypeError('Expected "' + token.name + '" to not repeat, but got array')
|
438 | }
|
439 |
|
440 | if (value.length === 0) {
|
441 | if (token.optional) continue
|
442 |
|
443 | throw new TypeError('Expected "' + token.name + '" to not be empty')
|
444 | }
|
445 |
|
446 | for (var j = 0; j < value.length; j++) {
|
447 | segment = encode(value[j], token);
|
448 |
|
449 | if (!matches[i].test(segment)) {
|
450 | throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"')
|
451 | }
|
452 |
|
453 | path += (j === 0 ? token.prefix : token.delimiter) + segment;
|
454 | }
|
455 |
|
456 | continue
|
457 | }
|
458 |
|
459 | if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
460 | segment = encode(String(value), token);
|
461 |
|
462 | if (!matches[i].test(segment)) {
|
463 | throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"')
|
464 | }
|
465 |
|
466 | path += token.prefix + segment;
|
467 | continue
|
468 | }
|
469 |
|
470 | if (token.optional) {
|
471 |
|
472 | if (token.partial) path += token.prefix;
|
473 |
|
474 | continue
|
475 | }
|
476 |
|
477 | throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string'))
|
478 | }
|
479 |
|
480 | return path
|
481 | }
|
482 | }
|
483 |
|
484 | |
485 |
|
486 |
|
487 |
|
488 |
|
489 |
|
490 | function escapeString (str) {
|
491 | return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')
|
492 | }
|
493 |
|
494 | |
495 |
|
496 |
|
497 |
|
498 |
|
499 |
|
500 | function escapeGroup (group) {
|
501 | return group.replace(/([=!:$/()])/g, '\\$1')
|
502 | }
|
503 |
|
504 | |
505 |
|
506 |
|
507 |
|
508 |
|
509 |
|
510 | function flags (options) {
|
511 | return options && options.sensitive ? '' : 'i'
|
512 | }
|
513 |
|
514 | |
515 |
|
516 |
|
517 |
|
518 |
|
519 |
|
520 |
|
521 | function regexpToRegexp (path, keys) {
|
522 | if (!keys) return path
|
523 |
|
524 |
|
525 | var groups = path.source.match(/\((?!\?)/g);
|
526 |
|
527 | if (groups) {
|
528 | for (var i = 0; i < groups.length; i++) {
|
529 | keys.push({
|
530 | name: i,
|
531 | prefix: null,
|
532 | delimiter: null,
|
533 | optional: false,
|
534 | repeat: false,
|
535 | partial: false,
|
536 | pattern: null
|
537 | });
|
538 | }
|
539 | }
|
540 |
|
541 | return path
|
542 | }
|
543 |
|
544 | |
545 |
|
546 |
|
547 |
|
548 |
|
549 |
|
550 |
|
551 |
|
552 | function arrayToRegexp (path, keys, options) {
|
553 | var parts = [];
|
554 |
|
555 | for (var i = 0; i < path.length; i++) {
|
556 | parts.push(pathToRegexp(path[i], keys, options).source);
|
557 | }
|
558 |
|
559 | return new RegExp('(?:' + parts.join('|') + ')', flags(options))
|
560 | }
|
561 |
|
562 | |
563 |
|
564 |
|
565 |
|
566 |
|
567 |
|
568 |
|
569 |
|
570 | function stringToRegexp (path, keys, options) {
|
571 | return tokensToRegExp(parse(path, options), keys, options)
|
572 | }
|
573 |
|
574 | |
575 |
|
576 |
|
577 |
|
578 |
|
579 |
|
580 |
|
581 |
|
582 | function tokensToRegExp (tokens, keys, options) {
|
583 | options = options || {};
|
584 |
|
585 | var strict = options.strict;
|
586 | var start = options.start !== false;
|
587 | var end = options.end !== false;
|
588 | var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER);
|
589 | var delimiters = options.delimiters || DEFAULT_DELIMITERS;
|
590 | var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|');
|
591 | var route = start ? '^' : '';
|
592 | var isEndDelimited = tokens.length === 0;
|
593 |
|
594 |
|
595 | for (var i = 0; i < tokens.length; i++) {
|
596 | var token = tokens[i];
|
597 |
|
598 | if (typeof token === 'string') {
|
599 | route += escapeString(token);
|
600 | isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1;
|
601 | } else {
|
602 | var capture = token.repeat
|
603 | ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*'
|
604 | : token.pattern;
|
605 |
|
606 | if (keys) keys.push(token);
|
607 |
|
608 | if (token.optional) {
|
609 | if (token.partial) {
|
610 | route += escapeString(token.prefix) + '(' + capture + ')?';
|
611 | } else {
|
612 | route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?';
|
613 | }
|
614 | } else {
|
615 | route += escapeString(token.prefix) + '(' + capture + ')';
|
616 | }
|
617 | }
|
618 | }
|
619 |
|
620 | if (end) {
|
621 | if (!strict) route += '(?:' + delimiter + ')?';
|
622 |
|
623 | route += endsWith === '$' ? '$' : '(?=' + endsWith + ')';
|
624 | } else {
|
625 | if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?';
|
626 | if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')';
|
627 | }
|
628 |
|
629 | return new RegExp(route, flags(options))
|
630 | }
|
631 |
|
632 | |
633 |
|
634 |
|
635 |
|
636 |
|
637 |
|
638 |
|
639 |
|
640 |
|
641 |
|
642 |
|
643 |
|
644 | function pathToRegexp (path, keys, options) {
|
645 | if (path instanceof RegExp) {
|
646 | return regexpToRegexp(path, keys)
|
647 | }
|
648 |
|
649 | if (Array.isArray(path)) {
|
650 | return arrayToRegexp( (path), keys, options)
|
651 | }
|
652 |
|
653 | return stringToRegexp( (path), keys, options)
|
654 | }
|
655 | pathToRegexp_1.parse = parse_1;
|
656 | pathToRegexp_1.compile = compile_1;
|
657 | pathToRegexp_1.tokensToFunction = tokensToFunction_1;
|
658 | pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
|
659 |
|
660 | var withLeadingSlash = function (path) {
|
661 | return path.charAt(0) === "/" ? path : "/" + path;
|
662 | };
|
663 | var withTrailingSlash = function (path) {
|
664 | return path.charAt(path.length - 1) === "/" ? path : path + "/";
|
665 | };
|
666 | var join = function (beginning, end) {
|
667 | return withTrailingSlash(beginning) + end;
|
668 | };
|
669 |
|
670 | function createRoute(props, map, parent) {
|
671 | if (parent === void 0) { parent = {
|
672 | path: "",
|
673 | keys: []
|
674 | }; }
|
675 | {
|
676 | if (props.name in map) {
|
677 | throw new Error("Multiple routes have the name \"" + props.name + "\". Route names must be unique.");
|
678 | }
|
679 | if (props.path.charAt(0) === "/") {
|
680 | throw new Error("Route paths cannot start with a forward slash (/). (Received \"" + props.path + "\")");
|
681 | }
|
682 | }
|
683 | var fullPath = withLeadingSlash(join(parent.path, props.path));
|
684 | var _a = props.pathOptions || {}, _b = _a.match, matchOptions = _b === void 0 ? {} : _b, _c = _a.compile, compileOptions = _c === void 0 ? {} : _c;
|
685 |
|
686 | var exact = matchOptions.end == null || matchOptions.end;
|
687 | if (props.children && props.children.length) {
|
688 | matchOptions.end = false;
|
689 | }
|
690 | var keys = [];
|
691 | var re = pathToRegexp_1(withLeadingSlash(props.path), keys, matchOptions);
|
692 | var keyNames = keys.map(function (key) { return key.name; });
|
693 | if (parent.keys.length) {
|
694 | keyNames = parent.keys.concat(keyNames);
|
695 | }
|
696 | var childRoutes = [];
|
697 | var children = [];
|
698 | if (props.children && props.children.length) {
|
699 | childRoutes = props.children.map(function (child) {
|
700 | return createRoute(child, map, {
|
701 | path: fullPath,
|
702 | keys: keyNames
|
703 | });
|
704 | });
|
705 | children = childRoutes.map(function (child) { return child.public; });
|
706 | }
|
707 | var compiled = pathToRegexp_1.compile(fullPath);
|
708 | var route = {
|
709 | public: {
|
710 | name: props.name,
|
711 | keys: keyNames,
|
712 | parent: undefined,
|
713 | children: children,
|
714 | methods: {
|
715 | resolve: props.resolve,
|
716 | respond: props.respond,
|
717 | pathname: function (params) {
|
718 | return compiled(params, compileOptions);
|
719 | }
|
720 | },
|
721 | extra: props.extra
|
722 | },
|
723 | matching: {
|
724 | re: re,
|
725 | keys: keys,
|
726 | exact: exact,
|
727 | parsers: props.params || {},
|
728 | children: childRoutes
|
729 | }
|
730 | };
|
731 | map[props.name] = route.public;
|
732 | if (childRoutes.length) {
|
733 | childRoutes.forEach(function (child) {
|
734 | child.public.parent = route.public;
|
735 | });
|
736 | }
|
737 | return route;
|
738 | }
|
739 |
|
740 | function matchLocation(location, routes) {
|
741 | for (var i = 0, len = routes.length; i < len; i++) {
|
742 | var routeMatches = matchRoute(routes[i], location.pathname);
|
743 | if (routeMatches.length) {
|
744 | return createMatch(routeMatches, location);
|
745 | }
|
746 | }
|
747 | }
|
748 | function matchRoute(route, pathname) {
|
749 | var _a = route.matching, re = _a.re, children = _a.children, exact = _a.exact;
|
750 | var regExpMatch = re.exec(pathname);
|
751 | if (!regExpMatch) {
|
752 | return [];
|
753 | }
|
754 | var matchedSegment = regExpMatch[0], parsed = regExpMatch.slice(1);
|
755 | var matches = [{ route: route, parsed: parsed }];
|
756 | var remainder = pathname.slice(matchedSegment.length);
|
757 | if (!children.length || remainder === "") {
|
758 | return matches;
|
759 | }
|
760 |
|
761 | var fullSegments = withLeadingSlash(remainder);
|
762 | for (var i = 0, length_1 = children.length; i < length_1; i++) {
|
763 | var matched = matchRoute(children[i], fullSegments);
|
764 | if (matched.length) {
|
765 | return matches.concat(matched);
|
766 | }
|
767 | }
|
768 | return exact ? [] : matches;
|
769 | }
|
770 | function createMatch(routeMatches, location) {
|
771 | var route = routeMatches[routeMatches.length - 1].route.public;
|
772 | return {
|
773 | route: route,
|
774 | match: {
|
775 | location: location,
|
776 | name: route.name,
|
777 | params: routeMatches.reduce(function (params, _a) {
|
778 | var route = _a.route, parsed = _a.parsed;
|
779 | parsed.forEach(function (param, index) {
|
780 | var name = route.matching.keys[index].name;
|
781 | var fn = route.matching.parsers[name] || decodeURIComponent;
|
782 | params[name] = fn(param);
|
783 | });
|
784 | return params;
|
785 | }, {})
|
786 | }
|
787 | };
|
788 | }
|
789 |
|
790 | function prepareRoutes(routes) {
|
791 | var mappedRoutes = {};
|
792 | var prepared = routes.map(function (route) { return createRoute(route, mappedRoutes); });
|
793 | return {
|
794 | match: function (location) {
|
795 | return matchLocation(location, prepared);
|
796 | },
|
797 | route: function (name) {
|
798 | if (!(name in mappedRoutes)) {
|
799 | console.warn("Attempting to use route \"" + name + "\", but no route with that name exists.");
|
800 | }
|
801 | return mappedRoutes[name];
|
802 | }
|
803 | };
|
804 | }
|
805 |
|
806 | function announce(fmt, mode) {
|
807 | if (mode === void 0) { mode = "assertive"; }
|
808 | var announcer = document.createElement("div");
|
809 | announcer.setAttribute("aria-live", mode);
|
810 |
|
811 | announcer.setAttribute("style", [
|
812 | "border: 0 !important;",
|
813 | "clip: rect(1px, 1px, 1px, 1px) !important;",
|
814 | "-webkit-clip-path: inset(50%) !important;",
|
815 | "clip-path: inset(50%) !important;",
|
816 | "height: 1px !important;",
|
817 | "overflow: hidden !important;",
|
818 | "padding: 0 !important;",
|
819 | "position: absolute !important;",
|
820 | "width: 1px !important;",
|
821 | "white-space: nowrap !important;",
|
822 | "top: 0;"
|
823 | ].join(" "));
|
824 | document.body.appendChild(announcer);
|
825 | return function (emitted) {
|
826 | announcer.textContent = fmt(emitted);
|
827 | };
|
828 | }
|
829 |
|
830 | function scroll() {
|
831 | return function (_a) {
|
832 | var response = _a.response, navigation = _a.navigation;
|
833 | if (navigation.action === "pop") {
|
834 | return;
|
835 | }
|
836 |
|
837 | setTimeout(function () {
|
838 | var hash = response.location.hash;
|
839 | if (hash !== "") {
|
840 | var element = document.getElementById(hash);
|
841 | if (element && element.scrollIntoView) {
|
842 | element.scrollIntoView();
|
843 | return;
|
844 | }
|
845 | }
|
846 |
|
847 |
|
848 |
|
849 | window.scrollTo(0, 0);
|
850 | }, 0);
|
851 | };
|
852 | }
|
853 |
|
854 | function title(callback) {
|
855 | return function (emitted) {
|
856 | document.title = callback(emitted);
|
857 | };
|
858 | }
|
859 |
|
860 | exports.announce = announce;
|
861 | exports.createRouter = createRouter;
|
862 | exports.prepareRoutes = prepareRoutes;
|
863 | exports.scroll = scroll;
|
864 | exports.title = title;
|
865 |
|
866 | Object.defineProperty(exports, '__esModule', { value: true });
|
867 |
|
868 | }));
|