-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
297 lines (276 loc) · 10.2 KB
/
index.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
import { GouterState } from './state/index.js';
/**
* Binds every method of class instance to that instance. Already applied on GouterNavigation and
* GouterLinking to allow extract their methods.
* @param {Record<any, any>} instance any class instance
* @returns {void}
*/
export const bindMethods = (instance) => {
const prototype = Object.getPrototypeOf(instance);
const keys = Object.getOwnPropertyNames(prototype);
for (const key of keys) {
const method = /** @type {Function} */ (instance[key]);
if (typeof method === 'function' && key !== 'constructor') {
const descriptor = Object.getOwnPropertyDescriptor(instance, key);
Object.defineProperty(instance, key, { ...descriptor, value: method.bind(instance) });
}
}
};
/**
* Defines how parent state stack is modified.
* @template {import('./state').GouterConfig} [T=import('./state').GouterConfig]
* @template {keyof T} [N=keyof T]
* @typedef {(parentState: GouterState<T, N>, toState: GouterState<T, N> | null, route: Route<T, N>)
* => GouterState<T, N>[] | null} Navigator
*/
/**
* Defines when navigation from current state should be blocked.
* @template {import('./state').GouterConfig} [T=import('./state').GouterConfig]
* @template {keyof T} [N=keyof T]
* @typedef {(fromState: GouterState<T, N>, toState: GouterState<T> | null) => boolean} Blocker
*/
/**
* `ParamDef` is url parameter definition. It controls how each route parameter is decoded from url
* to state and vice versa. Array parameter could be marked as `list` for better url look.
* @template P
* @typedef {({ list?: never, decode: (str: string) => Exclude<P, undefined>, encode?: (val:
* Exclude<P, undefined>) => string } | (Exclude<P, undefined> extends Array<infer E> ? { list:
* true, decode: ((str: string) => E), encode?: ((val: E) => string) } : never)) | (string extends P
* ? { list?: never, decode?: (str: string) => Exclude<P, undefined>, encode?: (val: Exclude<P,
* undefined>) => string } : never)} ParamDef
*/
/**
* Provides fine state search using `keys` list, callback to `merge` params and callback to `update`
* state.
* @template {import('./state').GouterConfig} T
* @template {keyof T} N
* @typedef GoToOptions
* @prop {(keyof T[N])[]} [keys] Enables search for existing state using list of params keys. Empty
* list always creates new state. Nonempty list will be used to compare existing state params with
* passed ones. Params compared using strict equality.
* @prop {(prevParams: T[N], nextParams: T[N]) => T[N]} [merge] Merges previous and next parameters
* on successful navigation to existing state.
* @prop {(state: GouterState<T, N>) => void} [update] Callback for further state update. Called
* after successful navigation.
*/
/**
* Set of rules, describing how to navigate.
* @template {import('./state').GouterConfig} T
* @template {keyof T} N
* @typedef RouteNavigation
* @prop {Navigator<T, N> | Navigator<T> | Navigator} navigator
* @prop {(keyof T)[]} allowed
* @prop {Blocker<T, N>} [blocker]
*/
/**
* Set of rules, describing how to encode and decode urls.
* @template {import('./state').GouterConfig} T
* @template {keyof T} N
* @typedef RouteLinking
* @prop {{[K in keyof T[N] as undefined extends T[N][K] ? never : K]: ParamDef<T[N][K]>} & {[K in
* `_${string}`]?: string}} [path]
* @prop {{[K in keyof T[N] as undefined extends T[N][K] ? K : never]?: ParamDef<T[N][K]>}} [query]
*/
/**
* Set of helpful route options.
* @template {import('./state').GouterConfig} T
* @template {keyof T} N
* @typedef RouteHelpers
* @prop {(state: GouterState<T, N>, create: GouterNavigation<T, any>['create']) =>
* GouterState<T>[]} [builder]
* @prop {(state: GouterState<T, N>, goTo: GouterNavigation<T, any>['goTo']) => void} [redirector]
*/
/**
* Makes object with required properties skippable.
* @template T
* @typedef {T | {[K in keyof T]?: never}} Skippable
*/
/**
* Set of rules, describing how to navigate, build new state stack, encode and decode urls.
* @template {import('./state').GouterConfig} T
* @template {keyof T} N
* @typedef {Skippable<RouteNavigation<T, N>> & RouteHelpers<T, N> & RouteLinking<T, N>} Route
*/
/**
* Map of names to route configurations. Mainly controls how to navigate between states. Routes
* should be described and passed to `GouterNavigation`.
* @template {import('./state').GouterConfig} T
* @typedef {{[N in keyof T]: Route<T, N>}} Routes
*/
/**
* Provides tools for navigation.
* @template {import('./state').GouterConfig} T
* @template {keyof T} K
*/
export class GouterNavigation {
/**
* Creates tools for navigation.
* @param {Routes<T>} routes map of names to route configurations
* @param {K} rootName root state name
* @param {T[K]} rootParams root state parameters
*/
constructor(routes, rootName, rootParams) {
bindMethods(this);
/**
* map of names to route configurations
* @protected
* @type {Routes<T>}
*/
this.routes = routes;
/**
* root state
* @type {GouterState<T, K>}
*/
this.rootState = this.create(rootName, rootParams);
GouterState.rootStates.add(this.rootState);
}
/**
* Creates state using required `name`, `params` and optional `stack`. When stack is not passed
* and routes has appropriate `builder`, new stack is generated using that builder.
* @template {keyof T} N
* @param {N} name string to distinguish states
* @param {T[N]} params collection of parameters to customize states
* @param {GouterState<T>[]} [stack] optional list of inner states
* @param {number} [focusedIndex] optional index of focused state in stack
* @returns {GouterState<T, N>}
*/
create(name, params, stack, focusedIndex) {
const state = new GouterState(name, params, stack, focusedIndex);
if (!stack) {
const route = this.routes[/** @type {keyof typeof this.routes} */ (name)];
if (route && route.builder) {
const builtStack = route.builder(state, this.create);
state.setStack(builtStack);
}
}
return state;
}
/**
* Main navigation tool. By default it searches for nearest state with passed `name` (and matches
* passed `keys` if any) in stacks of focused states. If existing state not found then new state
* is created if it is allowed in current stack. Params are replaced by passed ones by default,
* however `merge` option may modify this behavior. When navigation is successful optional
* `update` callback is called for further state modification.
* @template {keyof T} N
* @param {N} name
* @param {T[N]} params
* @param {GoToOptions<T, N>} [options]
* @returns {void}
*/
goTo(name, params, options) {
const state = this.create(name, params);
const route = this.routes[name];
if (route && route.redirector) {
route.redirector(state, this.goTo);
}
this.go(state, options || {});
}
/**
* Secondary navigation tool. It's behavior is defined by `navigator` option in route but usually
* it undoes `goTo` changes.
* @returns {void}
*/
goBack() {
this.go(null, {});
}
/**
* Returns current innermost focused state inside root state.
* @returns {GouterState<T>}
*/
getFocusedState() {
/** @type {GouterState<T>} */
let focusedState = this.rootState;
while (focusedState.focusedChild) {
focusedState = focusedState.focusedChild;
}
return focusedState;
}
/**
* Replaces current innermost focused state by new one. If current state has no parent then
* nothing happens.
* @param {GouterState<T>} state
* @returns {void}
*/
replaceFocusedState(state) {
const focusedState = this.getFocusedState();
const { parent } = focusedState;
if (parent) {
const nextStack = parent.stack.slice();
nextStack[parent.focusedIndex] = state.withFocus();
parent.setStack(nextStack);
}
}
/**
* Handles {@link goTo} and {@link goBack} since they have a lot in common.
* @protected
* @param {GouterState<T> | null} toState state for {@link goTo} or null for {@link goBack}
* @param {GoToOptions<T, any>} options
* @returns {void}
*/
go(toState, options) {
let parentState = this.getFocusedState();
for (;;) {
/** @type {Route<any, any>} */
const route = this.routes[parentState.name] || {};
const { blocker } = route;
if (blocker && blocker(parentState, toState)) {
return;
}
const { navigator, allowed } = route;
if (navigator && (!toState || allowed.indexOf(toState.name) >= 0)) {
const { keys } = options;
if (toState && (!keys || keys.length > 0)) {
const { name, params } = toState;
const { stack, focusedIndex } = parentState;
for (let i = 0; i < stack.length; i += 1) {
const stackIndex = focusedIndex - i >= 0 ? focusedIndex - i : i;
const prevState = stack[stackIndex];
if (prevState.name === name) {
const { params: prevParams } = prevState;
let hasMatch = true;
if (keys) {
for (const key of keys) {
if (
prevParams[/** @type {string} */ (key)] !== params[/** @type {string} */ (key)]
) {
hasMatch = false;
break;
}
}
}
if (hasMatch) {
const nextParams = options.merge ? options.merge(prevParams, params) : params;
prevState.setParams(nextParams);
const nextStack = navigator(parentState, prevState, route);
if (nextStack) {
parentState.setStack(nextStack);
prevState.focus();
}
if (options.update) {
options.update(prevState);
}
return;
}
}
}
}
const nextStack = navigator(parentState, toState, route);
if (nextStack) {
parentState.setStack(nextStack);
if (toState) {
toState.focus();
if (options.update) {
options.update(toState);
}
}
return;
}
}
if (parentState.parent) {
parentState = parentState.parent;
} else {
return;
}
}
}
}