aberdeen 1.0.13 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -5
- package/dist/aberdeen.d.ts +58 -100
- package/dist/aberdeen.js +201 -184
- package/dist/aberdeen.js.map +3 -3
- package/dist/dispatcher.d.ts +54 -0
- package/dist/dispatcher.js +65 -0
- package/dist/dispatcher.js.map +10 -0
- package/dist/route.d.ts +79 -30
- package/dist/route.js +162 -135
- package/dist/route.js.map +3 -3
- package/dist-min/aberdeen.js +5 -5
- package/dist-min/aberdeen.js.map +3 -3
- package/dist-min/dispatcher.js +4 -0
- package/dist-min/dispatcher.js.map +10 -0
- package/dist-min/route.js +2 -2
- package/dist-min/route.js.map +3 -3
- package/package.json +6 -1
- package/src/aberdeen.ts +303 -349
- package/src/dispatcher.ts +130 -0
- package/src/route.ts +272 -181
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Symbol to return when a custom {@link Dispatcher.addRoute} matcher cannot match a segment.
|
|
3
|
+
*/
|
|
4
|
+
export const matchFailed: unique symbol = Symbol("matchFailed");
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Special {@link Dispatcher.addRoute} matcher that matches the rest of the segments as an array of strings.
|
|
8
|
+
*/
|
|
9
|
+
export const matchRest: unique symbol = Symbol("matchRest");
|
|
10
|
+
|
|
11
|
+
type Matcher = string | ((segment: string) => any) | typeof matchRest;
|
|
12
|
+
|
|
13
|
+
type ExtractParamType<M> = M extends string
|
|
14
|
+
? never : (
|
|
15
|
+
M extends ((segment: string) => infer R)
|
|
16
|
+
? Exclude<R, typeof matchFailed>
|
|
17
|
+
: (M extends typeof matchRest ? string[] : never)
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
type ParamsFromMatchers<T extends Matcher[]> = T extends [infer M1, ...infer Rest]
|
|
21
|
+
? (
|
|
22
|
+
M1 extends Matcher
|
|
23
|
+
? (
|
|
24
|
+
ExtractParamType<M1> extends never
|
|
25
|
+
? ParamsFromMatchers<Rest extends Matcher[] ? Rest : []>
|
|
26
|
+
: [ExtractParamType<M1>, ...ParamsFromMatchers<Rest extends Matcher[] ? Rest : []>]
|
|
27
|
+
) : never
|
|
28
|
+
) : [];
|
|
29
|
+
|
|
30
|
+
interface DispatcherRoute {
|
|
31
|
+
matchers: Matcher[];
|
|
32
|
+
handler: (...params: any[]) => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Simple route matcher and dispatcher.
|
|
37
|
+
*
|
|
38
|
+
* Example usage:
|
|
39
|
+
*
|
|
40
|
+
* ```ts
|
|
41
|
+
* const dispatcher = new Dispatcher();
|
|
42
|
+
*
|
|
43
|
+
* dispatcher.addRoute("user", Number, "stream", String, (id, stream) => {
|
|
44
|
+
* console.log(`User ${id}, stream ${stream}`);
|
|
45
|
+
* });
|
|
46
|
+
*
|
|
47
|
+
* dispatcher.dispatch(["user", "42", "stream", "music"]);
|
|
48
|
+
* // Logs: User 42, stream music
|
|
49
|
+
*
|
|
50
|
+
* dispatcher.addRoute("search", matchRest, (terms: string[]) => {
|
|
51
|
+
* console.log("Search terms:", terms);
|
|
52
|
+
* });
|
|
53
|
+
*
|
|
54
|
+
* dispatcher.dispatch(["search", "classical", "piano"]);
|
|
55
|
+
* // Logs: Search terms: [ 'classical', 'piano' ]
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
export class Dispatcher {
|
|
59
|
+
private routes: Array<DispatcherRoute> = [];
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Add a route with matchers and a handler function.
|
|
63
|
+
* @param args An array of matchers followed by a handler function. Each matcher can be:
|
|
64
|
+
* - A string: matches exactly that string.
|
|
65
|
+
* - A function: takes a string segment and returns a value (of any type) if it matches, or {@link matchFailed} if it doesn't match. The return value (if not `matchFailed` and not `NaN`) is passed as a parameter to the handler function. The built-in functions `Number` and `String` can be used to match numeric and string segments respectively.
|
|
66
|
+
* - The special {@link matchRest} symbol: matches the rest of the segments as an array of strings. Only one `matchRest` is allowed, and it must be the last matcher.
|
|
67
|
+
* @template T - Array of matcher types.
|
|
68
|
+
* @template H - Handler function type, inferred from the matchers.
|
|
69
|
+
*/
|
|
70
|
+
addRoute<T extends Matcher[], H extends (...args: ParamsFromMatchers<T>) => void>(...args: [...T, H]): void {
|
|
71
|
+
const matchers = args.slice(0, -1) as Matcher[];
|
|
72
|
+
const handler = args[args.length - 1] as (...args: any) => any;
|
|
73
|
+
|
|
74
|
+
if (typeof handler !== "function") {
|
|
75
|
+
throw new Error("Last argument should be a handler function");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const restCount = matchers.filter(m => m === matchRest).length;
|
|
79
|
+
if (restCount > 1) {
|
|
80
|
+
throw new Error("Only one matchRest is allowed");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
this.routes.push({ matchers, handler });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Dispatches the given segments to the first route handler that matches.
|
|
88
|
+
* @param segments Array of string segments to match against the added routes. When using this class with the Aberdeen `route` module, one would typically pass `route.current.p`.
|
|
89
|
+
* @returns True if a matching route was found and handled, false otherwise.
|
|
90
|
+
*/
|
|
91
|
+
dispatch(segments: string[]): boolean {
|
|
92
|
+
for (const route of this.routes) {
|
|
93
|
+
const args = matchRoute(route, segments);
|
|
94
|
+
if (args) {
|
|
95
|
+
route.handler(...args);
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function matchRoute(route: DispatcherRoute, segments: string[]): any[] | undefined {
|
|
104
|
+
const args: any[] = [];
|
|
105
|
+
let segmentIndex = 0;
|
|
106
|
+
|
|
107
|
+
for (const matcher of route.matchers) {
|
|
108
|
+
if (matcher === matchRest) {
|
|
109
|
+
const len = segments.length - (route.matchers.length - 1);
|
|
110
|
+
if (len < 0) return;
|
|
111
|
+
args.push(segments.slice(segmentIndex, segmentIndex + len));
|
|
112
|
+
segmentIndex += len;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (segmentIndex >= segments.length) return;
|
|
117
|
+
const segment = segments[segmentIndex];
|
|
118
|
+
|
|
119
|
+
if (typeof matcher === "string") {
|
|
120
|
+
if (segment !== matcher) return;
|
|
121
|
+
} else if (typeof matcher === "function") {
|
|
122
|
+
const result = matcher(segment);
|
|
123
|
+
if (result === matchFailed || (typeof result === 'number' && isNaN(result))) return;
|
|
124
|
+
args.push(result);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
segmentIndex++;
|
|
128
|
+
}
|
|
129
|
+
return args; // success!
|
|
130
|
+
}
|
package/src/route.ts
CHANGED
|
@@ -1,229 +1,320 @@
|
|
|
1
|
-
import {
|
|
2
|
-
clean,
|
|
3
|
-
clone,
|
|
4
|
-
getParentElement,
|
|
5
|
-
immediateObserve,
|
|
6
|
-
observe,
|
|
7
|
-
proxy,
|
|
8
|
-
runQueue,
|
|
9
|
-
unproxy,
|
|
10
|
-
} from "./aberdeen.js";
|
|
1
|
+
import {clean, getParentElement, $, proxy, runQueue, unproxy, copy, merge, clone, leakScope} from "./aberdeen.js";
|
|
11
2
|
|
|
12
|
-
|
|
13
|
-
* The class for the singleton `route` object.
|
|
14
|
-
*
|
|
15
|
-
*/
|
|
3
|
+
type NavType = "load" | "back" | "forward" | "go";
|
|
16
4
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The class for the global `route` object.
|
|
7
|
+
*/
|
|
8
|
+
export interface Route {
|
|
9
|
+
/** The current path of the URL as a string. For instance `"/"` or `"/users/123/feed"`. Paths are normalized to always start with a `/` and never end with a `/` (unless it's the root path). */
|
|
10
|
+
path: string;
|
|
11
|
+
/** An convenience array containing path segments, mapping to `path`. For instance `[]` (for `"/"`) or `['users', '123', 'feed']` (for `"/users/123/feed"`). */
|
|
12
|
+
p: string[];
|
|
13
|
+
/** The hash fragment including the leading `#`, or an empty string. For instance `"#my_section"` or `""`. */
|
|
14
|
+
hash: string;
|
|
15
|
+
/** The query string interpreted as search parameters. So `"a=x&b=y"` becomes `{a: "x", b: "y"}`. */
|
|
16
|
+
search: Record<string, string>;
|
|
17
|
+
/** An object to be used for any additional data you want to associate with the current page. Data should be JSON-compatible. */
|
|
18
|
+
state: Record<string, any>;
|
|
30
19
|
/** The navigation depth of the current session. Starts at 1. Writing to this property has no effect. */
|
|
31
|
-
depth
|
|
20
|
+
depth: number;
|
|
32
21
|
/** The navigation action that got us to this page. Writing to this property has no effect.
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
- `"push"`: Force creation of a new browser history entry.
|
|
40
|
-
- `"replace"`: Update the current history entry, even when updates to other keys would normally cause a *push*.
|
|
41
|
-
- `"back"`: Unwind the history (like repeatedly pressing the *back* button) until we find a page that matches the given `path` and `id` (or that is the first page in our stack), and then *replace* that state by the full given state.
|
|
42
|
-
The `mode` key can be written to `route` but will be immediately and silently removed.
|
|
43
|
-
*/
|
|
44
|
-
mode: "push" | "replace" | "back" | undefined;
|
|
22
|
+
- `"load"`: An initial page load.
|
|
23
|
+
- `"back"` or `"forward"`: When we navigated backwards or forwards in the stack.
|
|
24
|
+
- `"go"`: When we added a new page on top of the stack.
|
|
25
|
+
Mostly useful for page transition animations. Writing to this property has no effect.
|
|
26
|
+
*/
|
|
27
|
+
nav: NavType;
|
|
45
28
|
}
|
|
46
29
|
|
|
30
|
+
let log: (...args: any) => void = () => {};
|
|
31
|
+
|
|
47
32
|
/**
|
|
48
|
-
*
|
|
33
|
+
* Configure logging on route changes.
|
|
34
|
+
* @param value `true` to enable logging to console, `false` to disable logging, or a custom logging function. Defaults to `false`.
|
|
49
35
|
*/
|
|
50
|
-
export
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Reflect changes to the browser URL (back/forward navigation) in the `route` and `stack`.
|
|
58
|
-
function handleLocationUpdate(event?: PopStateEvent) {
|
|
59
|
-
const state = event?.state || {};
|
|
60
|
-
let nav: "load" | "back" | "forward" | "push" = "load";
|
|
61
|
-
if (state.route?.nonce == null) {
|
|
62
|
-
state.route = {
|
|
63
|
-
nonce: Math.floor(Math.random() * Number.MAX_SAFE_INTEGER),
|
|
64
|
-
depth: 1,
|
|
65
|
-
};
|
|
66
|
-
history.replaceState(state, "");
|
|
67
|
-
} else if (stateRoute.nonce === state.route.nonce) {
|
|
68
|
-
nav = state.route.depth > stateRoute.depth ? "forward" : "back";
|
|
36
|
+
export function setLog(value: boolean | ((...args: any[]) => void)) {
|
|
37
|
+
if (value === true) {
|
|
38
|
+
log = console.log.bind(console, 'aberdeen router');
|
|
39
|
+
} else if (value === false) {
|
|
40
|
+
log = () => {};
|
|
41
|
+
} else {
|
|
42
|
+
log = value;
|
|
69
43
|
}
|
|
70
|
-
|
|
44
|
+
}
|
|
71
45
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
46
|
+
function getRouteFromBrowser(): Route {
|
|
47
|
+
return toCanonRoute({
|
|
48
|
+
path: location.pathname,
|
|
49
|
+
hash: location.hash,
|
|
50
|
+
search: Object.fromEntries(new URLSearchParams(location.search)),
|
|
51
|
+
state: history.state?.state || {},
|
|
52
|
+
}, "load", (history.state?.stack?.length || 0) + 1);
|
|
53
|
+
}
|
|
78
54
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
55
|
+
/**
|
|
56
|
+
* Deep compare `a` and `b`. If `partial` is true, objects contained in `b` may be a subset
|
|
57
|
+
* of their counterparts in `a` and still be considered equal.
|
|
58
|
+
*/
|
|
59
|
+
function equal(a: any, b: any, partial: boolean): boolean {
|
|
60
|
+
if (a===b) return true;
|
|
61
|
+
if (typeof a !== "object" || !a || typeof b !== "object" || !b) return false; // otherwise they would have been equal
|
|
62
|
+
if (a.constructor !== b.constructor) return false;
|
|
63
|
+
if (b instanceof Array) {
|
|
64
|
+
if (a.length !== b.length) return false;
|
|
65
|
+
for(let i = 0; i < b.length; i++) {
|
|
66
|
+
if (!equal(a[i], b[i], partial)) return false;
|
|
67
|
+
}
|
|
68
|
+
} else {
|
|
69
|
+
for(const k of Object.keys(b)) {
|
|
70
|
+
if (!equal(a[k], b[k], partial)) return false;
|
|
71
|
+
}
|
|
72
|
+
if (!partial) {
|
|
73
|
+
for(const k of Object.keys(a)) {
|
|
74
|
+
if (!b.hasOwnProperty(k)) return false;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
82
77
|
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
83
80
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
route.hash = location.hash;
|
|
88
|
-
route.id = state.id;
|
|
89
|
-
route.aux = state.aux;
|
|
90
|
-
route.depth = stateRoute.depth;
|
|
91
|
-
route.nav = nav;
|
|
92
|
-
|
|
93
|
-
// Forward or back event. Redraw synchronously, because we can!
|
|
94
|
-
if (event) runQueue();
|
|
81
|
+
function getUrl(target: Route) {
|
|
82
|
+
const search = new URLSearchParams(target.search).toString();
|
|
83
|
+
return (search ? `${target.path}?${search}` : target.path) + target.hash;
|
|
95
84
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
// We want to to this immediately, so that user-code running immediately after a user-code
|
|
101
|
-
// initiated `set` will see the canonical form (instead of doing a rerender shortly after,
|
|
102
|
-
// or crashing due to non-canonical data).
|
|
103
|
-
function updatePath(): void {
|
|
104
|
-
let path = route.path;
|
|
105
|
-
if (path == null && unproxy(route).p) {
|
|
106
|
-
updateP();
|
|
107
|
-
return;
|
|
108
|
-
}
|
|
109
|
-
path = `${path || "/"}`;
|
|
85
|
+
|
|
86
|
+
function toCanonRoute(target: Partial<Route>, nav: NavType, depth: number): Route {
|
|
87
|
+
let path = target.path || (target.p || []).join("/") || "/";
|
|
88
|
+
path = (""+path).replace(/\/+$/, "");
|
|
110
89
|
if (!path.startsWith("/")) path = `/${path}`;
|
|
111
|
-
|
|
112
|
-
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
path,
|
|
93
|
+
hash: target.hash && target.hash !=="#" ? (target.hash.startsWith("#") ? target.hash : "#" + target.hash) : "",
|
|
94
|
+
p: path.length > 1 ? path.slice(1).replace(/\/+$/, "").split("/") : [],
|
|
95
|
+
nav,
|
|
96
|
+
search: typeof target.search === 'object' && target.search ? clone(target.search) : {},
|
|
97
|
+
state: typeof target.state === 'object' && target.state ? clone(target.state) : {},
|
|
98
|
+
depth,
|
|
99
|
+
};
|
|
113
100
|
}
|
|
114
|
-
immediateObserve(updatePath);
|
|
115
101
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
102
|
+
|
|
103
|
+
type RouteTarget = string | (string|number)[] | Partial<Omit<Omit<Route,"p">,"search"> & {
|
|
104
|
+
/** An convenience array containing path segments, mapping to `path`. For instance `[]` (for `"/"`) or `['users', 123, 'feed']` (for `"/users/123/feed"`). Values may be integers but will be converted to strings.*/
|
|
105
|
+
p: (string|number)[],
|
|
106
|
+
/** The query string interpreted as search parameters. So `"a=x&b=y"` becomes `{a: "x", b: "y", c: 42}`. Values may be integers but will be converted to strings. */
|
|
107
|
+
search: Record<string,string|number>,
|
|
108
|
+
}>;
|
|
109
|
+
|
|
110
|
+
function targetToPartial(target: RouteTarget) {
|
|
111
|
+
// Convert shortcut values to objects
|
|
112
|
+
if (typeof target === 'string') {
|
|
113
|
+
target = {path: target};
|
|
114
|
+
} else if (target instanceof Array) {
|
|
115
|
+
target = {p: target};
|
|
121
116
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
route.path = `/${p.join("/")}`;
|
|
117
|
+
// Convert numbers in p and search to strings
|
|
118
|
+
if (target.p) {
|
|
119
|
+
target.p = target.p.map(String);
|
|
120
|
+
}
|
|
121
|
+
if (target.search) {
|
|
122
|
+
for(const key of Object.keys(target.search)) {
|
|
123
|
+
target.search[key] = String(target.search[key]);
|
|
124
|
+
}
|
|
131
125
|
}
|
|
126
|
+
return target as Partial<Route>;
|
|
132
127
|
}
|
|
133
|
-
immediateObserve(updateP);
|
|
134
128
|
|
|
135
|
-
immediateObserve(() => {
|
|
136
|
-
if (!route.search || typeof route.search !== "object") route.search = {};
|
|
137
|
-
});
|
|
138
129
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
130
|
+
/**
|
|
131
|
+
* Navigate to a new URL by pushing a new history entry.
|
|
132
|
+
*
|
|
133
|
+
* Note that this happens synchronously, immediately updating `route` and processing any reactive updates based on that.
|
|
134
|
+
*
|
|
135
|
+
* @param target A subset of the {@link Route} properties to navigate to. If neither `p` nor `path` is given, the current path is used. For other properties, an empty/default value is assumed if not given. For convenience:
|
|
136
|
+
* - You may pass a string instead of an object, which is interpreted as the `path`.
|
|
137
|
+
* - You may pass an array instead of an object, which is interpreted as the `p` array.
|
|
138
|
+
* - If you pass `p`, it may contain numbers, which will be converted to strings.
|
|
139
|
+
* - If you pass `search`, its values may be numbers, which will be converted to strings.
|
|
140
|
+
*
|
|
141
|
+
* Examples:
|
|
142
|
+
* ```js
|
|
143
|
+
* // Navigate to /users/123
|
|
144
|
+
* route.go("/users/123");
|
|
145
|
+
*
|
|
146
|
+
* // Navigate to /users/123?tab=feed#top
|
|
147
|
+
* route.go({p: ["users", 123], search: {tab: "feed"}, hash: "top"});
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
export function go(target: RouteTarget): void {
|
|
151
|
+
const stack: string[] = history.state?.stack || [];
|
|
152
152
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
153
|
+
prevStack = stack.concat(JSON.stringify(unproxy(current)));
|
|
154
|
+
|
|
155
|
+
const newRoute: Route = toCanonRoute(targetToPartial(target), "go", prevStack.length + 1);
|
|
156
|
+
copy(current, newRoute);
|
|
157
|
+
|
|
158
|
+
log('go', newRoute);
|
|
159
|
+
history.pushState({state: newRoute.state, stack: prevStack}, "", getUrl(newRoute));
|
|
160
|
+
|
|
161
|
+
runQueue();
|
|
158
162
|
}
|
|
159
163
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
164
|
+
/**
|
|
165
|
+
* Modify the current route by merging `target` into it (using {@link merge}), pushing a new history entry.
|
|
166
|
+
*
|
|
167
|
+
* This is useful for things like opening modals or side panels, where you want a browser back action to return to the previous state.
|
|
168
|
+
*
|
|
169
|
+
* @param target Same as for {@link go}, but merged into the current route instead deleting all state.
|
|
170
|
+
*/
|
|
171
|
+
export function push(target: RouteTarget): void {
|
|
172
|
+
let copy = clone(unproxy(current));
|
|
173
|
+
merge(copy, targetToPartial(target));
|
|
174
|
+
go(copy);
|
|
175
|
+
}
|
|
171
176
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
+
/**
|
|
178
|
+
* Try to go back in history to the first entry that matches the given target. If none is found, the given state will replace the current page. This is useful for "cancel" or "close" actions that should return to the previous page if possible, but create a new page if not (for instance when arriving at the current page through a direct link).
|
|
179
|
+
*
|
|
180
|
+
* Consider using {@link up} to go up in the path hierarchy.
|
|
181
|
+
*
|
|
182
|
+
* @param target The target route to go back to. May be a subset of {@link Route}, or a string (for `path`), or an array of strings (for `p`).
|
|
183
|
+
*/
|
|
184
|
+
export function back(target: RouteTarget = {}): void {
|
|
185
|
+
const partial = targetToPartial(target);
|
|
186
|
+
const stack: string[] = history.state?.stack || [];
|
|
187
|
+
for(let i = stack.length - 1; i >= 0; i--) {
|
|
188
|
+
const histRoute: Route = JSON.parse(stack[i]);
|
|
189
|
+
if (equal(histRoute, partial, true)) {
|
|
190
|
+
const pages = i - stack.length;
|
|
191
|
+
log(`back`, pages, histRoute);
|
|
192
|
+
history.go(pages);
|
|
177
193
|
return;
|
|
178
194
|
}
|
|
179
|
-
mode = "replace";
|
|
180
|
-
// We'll replace the state async, to give the history.go the time to take affect first.
|
|
181
|
-
//setTimeout(() => history.replaceState(state, '', url), 0)
|
|
182
195
|
}
|
|
183
196
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
197
|
+
const newRoute = toCanonRoute(partial, "back", stack.length + 1);
|
|
198
|
+
log(`back not found, replacing`, partial);
|
|
199
|
+
copy(current, newRoute);
|
|
200
|
+
}
|
|
187
201
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
202
|
+
/**
|
|
203
|
+
* Navigate up in the path hierarchy, by going back to the first history entry
|
|
204
|
+
* that has a shorter path than the current one. If there's none, we just shorten
|
|
205
|
+
* the current path.
|
|
206
|
+
*
|
|
207
|
+
* Note that going back in browser history happens asynchronously, so `route` will not be updated immediately.
|
|
208
|
+
*/
|
|
209
|
+
export function up(stripCount: number = 1): void {
|
|
210
|
+
const currentP = unproxy(current).p;
|
|
211
|
+
const stack: string[] = history.state?.stack || [];
|
|
212
|
+
for(let i = stack.length - 1; i >= 0; i--) {
|
|
213
|
+
const histRoute: Route = JSON.parse(stack[i]);
|
|
214
|
+
if (histRoute.p.length < currentP.length && equal(histRoute.p, currentP.slice(0, histRoute.p.length), false)) {
|
|
215
|
+
// This route is shorter and matches the start of the current path
|
|
216
|
+
log(`up to ${i+1} / ${stack.length}`, histRoute);
|
|
217
|
+
history.go(i - stack.length);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
196
220
|
}
|
|
221
|
+
// Replace current route with /
|
|
222
|
+
const newRoute = toCanonRoute({p: currentP.slice(0, currentP.length - stripCount)}, "back", stack.length + 1);
|
|
223
|
+
log(`up not found, replacing`, newRoute);
|
|
224
|
+
copy(current, newRoute);
|
|
197
225
|
}
|
|
198
226
|
|
|
199
|
-
// This deferred-mode observer will update the URL and history based on `route` changes.
|
|
200
|
-
observe(updateHistory);
|
|
201
|
-
|
|
202
227
|
/**
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
228
|
+
* Restore and store the vertical and horizontal scroll position for
|
|
229
|
+
* the parent element to the page state.
|
|
230
|
+
*
|
|
231
|
+
* @param {string} name - A unique (within this page) name for this
|
|
232
|
+
* scrollable element. Defaults to 'main'.
|
|
233
|
+
*
|
|
234
|
+
* The scroll position will be persisted in `route.aux.scroll.<name>`.
|
|
235
|
+
*/
|
|
211
236
|
export function persistScroll(name = "main") {
|
|
212
237
|
const el = getParentElement();
|
|
213
238
|
el.addEventListener("scroll", onScroll);
|
|
214
239
|
clean(() => el.removeEventListener("scroll", onScroll));
|
|
215
|
-
|
|
216
|
-
const restore = unproxy(
|
|
240
|
+
|
|
241
|
+
const restore = unproxy(current).state.scroll?.[name];
|
|
217
242
|
if (restore) {
|
|
243
|
+
log("restoring scroll", name, restore);
|
|
218
244
|
Object.assign(el, restore);
|
|
219
245
|
}
|
|
220
|
-
|
|
246
|
+
|
|
221
247
|
function onScroll() {
|
|
222
|
-
|
|
223
|
-
if (!route.aux.scroll) route.aux.scroll = {};
|
|
224
|
-
route.aux.scroll[name] = {
|
|
248
|
+
(current.state.scroll ||= {})[name] = {
|
|
225
249
|
scrollTop: el.scrollTop,
|
|
226
250
|
scrollLeft: el.scrollLeft,
|
|
227
251
|
};
|
|
228
252
|
}
|
|
229
253
|
}
|
|
254
|
+
|
|
255
|
+
let prevStack: string[];
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The global {@link Route} object reflecting the current URL and browser history state. Changes you make to this affect the current browser history item (modifying the URL if needed).
|
|
259
|
+
*/
|
|
260
|
+
export const current: Route = proxy({}) as Route;
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Reset the router to its initial state, based on the current browser state. Intended for testing purposes only.
|
|
264
|
+
* @internal
|
|
265
|
+
* */
|
|
266
|
+
export function reset() {
|
|
267
|
+
prevStack = history.state?.stack || [];
|
|
268
|
+
const initRoute = getRouteFromBrowser();
|
|
269
|
+
log('initial', initRoute);
|
|
270
|
+
copy(unproxy(current), initRoute);
|
|
271
|
+
}
|
|
272
|
+
reset();
|
|
273
|
+
|
|
274
|
+
// Handle browser history back and forward
|
|
275
|
+
window.addEventListener("popstate", function(event: PopStateEvent) {
|
|
276
|
+
const newRoute = getRouteFromBrowser();
|
|
277
|
+
|
|
278
|
+
// If the stack length changes, and at least the top-most shared entry is the same,
|
|
279
|
+
// we'll interpret this as a "back" or "forward" navigation.
|
|
280
|
+
const stack: string[] = history.state?.stack || [];
|
|
281
|
+
if (stack.length !== prevStack.length) {
|
|
282
|
+
const maxIndex = Math.min(prevStack.length, stack.length) - 1;
|
|
283
|
+
if (maxIndex < 0 || stack[maxIndex] === prevStack[maxIndex]) {
|
|
284
|
+
newRoute.nav = stack.length < prevStack.length ? "back" : "forward";
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
// else nav will be "load"
|
|
288
|
+
|
|
289
|
+
prevStack = stack;
|
|
290
|
+
log('popstate', newRoute);
|
|
291
|
+
copy(current, newRoute);
|
|
292
|
+
|
|
293
|
+
runQueue();
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
// Make sure these observers are never cleaned up, not even by `unmountAll`.
|
|
297
|
+
leakScope(() => {
|
|
298
|
+
// Sync `p` to `path`. We need to do this in a separate, higher-priority observer,
|
|
299
|
+
// so that setting `route.p` will not be immediately overruled by the pre-existing `route.path`.
|
|
300
|
+
$(() => {
|
|
301
|
+
current.path = "/" + Array.from(current.p).join("/");
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
// Do a replaceState based on changes to proxy
|
|
305
|
+
$(() => {
|
|
306
|
+
|
|
307
|
+
// First normalize `route`
|
|
308
|
+
const stack = history.state?.stack || [];
|
|
309
|
+
const newRoute = toCanonRoute(current, unproxy(current).nav, stack.length + 1);
|
|
310
|
+
copy(current, newRoute);
|
|
311
|
+
|
|
312
|
+
// Then replace the current browser state if something actually changed
|
|
313
|
+
const state = {state: newRoute.state, stack};
|
|
314
|
+
const url = getUrl(newRoute);
|
|
315
|
+
if (url !== location.pathname + location.search + location.hash || !equal(history.state, state, false)) {
|
|
316
|
+
log('replaceState', newRoute, state, url);
|
|
317
|
+
history.replaceState(state, "", url);
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
});
|