ui5-lib-guard-router 1.6.2 → 1.7.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/{dist/.ui5 → .ui5}/build-manifest.json +56 -8
- package/CHANGELOG.md +190 -0
- package/README.md +695 -327
- package/dist/index.d.ts +9 -5
- package/dist/resources/ui5/guard/router/.library +1 -1
- package/dist/resources/ui5/guard/router/GuardConfig-dbg.js +222 -0
- package/dist/resources/ui5/guard/router/GuardConfig-dbg.js.map +1 -0
- package/dist/resources/ui5/guard/router/GuardConfig.d.ts +89 -0
- package/dist/resources/ui5/guard/router/GuardConfig.d.ts.map +1 -0
- package/dist/resources/ui5/guard/router/GuardConfig.js +2 -0
- package/dist/resources/ui5/guard/router/GuardConfig.js.map +1 -0
- package/dist/resources/ui5/guard/router/GuardModules-dbg.js +253 -0
- package/dist/resources/ui5/guard/router/GuardModules-dbg.js.map +1 -0
- package/dist/resources/ui5/guard/router/GuardModules.d.ts +72 -0
- package/dist/resources/ui5/guard/router/GuardModules.d.ts.map +1 -0
- package/dist/resources/ui5/guard/router/GuardModules.js +2 -0
- package/dist/resources/ui5/guard/router/GuardModules.js.map +1 -0
- package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js +122 -121
- package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js.map +1 -1
- package/dist/resources/ui5/guard/router/GuardPipeline.d.ts +45 -26
- package/dist/resources/ui5/guard/router/GuardPipeline.d.ts.map +1 -1
- package/dist/resources/ui5/guard/router/GuardPipeline.js +1 -1
- package/dist/resources/ui5/guard/router/GuardPipeline.js.map +1 -1
- package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js +3 -3
- package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js.map +1 -1
- package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts +3 -3
- package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts.map +1 -1
- package/dist/resources/ui5/guard/router/NavigationOutcome.js.map +1 -1
- package/dist/resources/ui5/guard/router/PatternTree-dbg.js +156 -0
- package/dist/resources/ui5/guard/router/PatternTree-dbg.js.map +1 -0
- package/dist/resources/ui5/guard/router/PatternTree.d.ts +71 -0
- package/dist/resources/ui5/guard/router/PatternTree.d.ts.map +1 -0
- package/dist/resources/ui5/guard/router/PatternTree.js +2 -0
- package/dist/resources/ui5/guard/router/PatternTree.js.map +1 -0
- package/dist/resources/ui5/guard/router/RouteMeta-dbg.js +84 -0
- package/dist/resources/ui5/guard/router/RouteMeta-dbg.js.map +1 -0
- package/dist/resources/ui5/guard/router/RouteMeta.d.ts +33 -0
- package/dist/resources/ui5/guard/router/RouteMeta.d.ts.map +1 -0
- package/dist/resources/ui5/guard/router/RouteMeta.js +2 -0
- package/dist/resources/ui5/guard/router/RouteMeta.js.map +1 -0
- package/dist/resources/ui5/guard/router/Router-dbg.js +882 -1020
- package/dist/resources/ui5/guard/router/Router-dbg.js.map +1 -1
- package/dist/resources/ui5/guard/router/Router.d.ts +360 -211
- package/dist/resources/ui5/guard/router/Router.d.ts.map +1 -1
- package/dist/resources/ui5/guard/router/Router.js +1 -1
- package/dist/resources/ui5/guard/router/Router.js.map +1 -1
- package/dist/resources/ui5/guard/router/library-dbg.js +1 -1
- package/dist/resources/ui5/guard/router/library-dbg.js.map +1 -1
- package/dist/resources/ui5/guard/router/library-preload.js +8 -4
- package/dist/resources/ui5/guard/router/library-preload.js.map +1 -1
- package/dist/resources/ui5/guard/router/library.js +1 -1
- package/dist/resources/ui5/guard/router/library.js.map +1 -1
- package/dist/resources/ui5/guard/router/manifest.json +5 -2
- package/dist/resources/ui5/guard/router/types-dbg.js.map +1 -1
- package/dist/resources/ui5/guard/router/types.d.ts +94 -39
- package/dist/resources/ui5/guard/router/types.d.ts.map +1 -1
- package/package.json +10 -6
- package/src/GuardConfig.ts +272 -0
- package/src/GuardModules.ts +249 -0
- package/src/GuardPipeline.ts +155 -128
- package/src/NavigationOutcome.ts +3 -3
- package/src/PatternTree.ts +145 -0
- package/src/RouteMeta.ts +82 -0
- package/src/Router.ts +1089 -1130
- package/src/manifest.json +5 -2
- package/src/types.ts +79 -22
- package/tsconfig.json +0 -11
package/src/Router.ts
CHANGED
|
@@ -1,42 +1,112 @@
|
|
|
1
1
|
import MobileRouter from "sap/m/routing/Router";
|
|
2
2
|
import Log from "sap/base/Log";
|
|
3
3
|
import coreLibrary from "sap/ui/core/library";
|
|
4
|
-
import
|
|
4
|
+
import HashChanger from "sap/ui/core/routing/HashChanger";
|
|
5
|
+
import History from "sap/ui/core/routing/History";
|
|
6
|
+
import type { HashChangerBase$HashChangedEvent } from "sap/ui/core/routing/HashChangerBase";
|
|
7
|
+
import type { ComponentTargetParameters, RouteInfo, Router$RouteMatchedEvent } from "sap/ui/core/routing/Router";
|
|
8
|
+
import type Route from "sap/ui/core/routing/Route";
|
|
5
9
|
import type { $RouteSettings } from "sap/ui/core/routing/Route";
|
|
10
|
+
import type UIComponent from "sap/ui/core/UIComponent";
|
|
6
11
|
import type {
|
|
7
12
|
GuardFn,
|
|
8
13
|
GuardContext,
|
|
9
14
|
GuardNavToOptions,
|
|
10
|
-
GuardResult,
|
|
11
15
|
GuardRedirect,
|
|
12
16
|
GuardRouter,
|
|
13
|
-
|
|
14
|
-
Inheritance,
|
|
17
|
+
GuardRouterConfig,
|
|
15
18
|
LeaveGuardFn,
|
|
16
|
-
ManifestRouteGuardConfig,
|
|
17
|
-
NavToPreflightMode,
|
|
18
19
|
NavigationResult,
|
|
19
20
|
Router$NavigationSettledEvent,
|
|
20
21
|
RouteGuardConfig,
|
|
21
|
-
UnknownRouteRegistrationPolicy,
|
|
22
22
|
} from "./types";
|
|
23
23
|
import NavigationOutcome from "./NavigationOutcome";
|
|
24
|
-
import GuardPipeline, { type GuardDecision, isPromiseLike } from "./GuardPipeline";
|
|
24
|
+
import GuardPipeline, { type GuardDecision, isPromiseLike, isPromiseResolver, LOG_COMPONENT } from "./GuardPipeline";
|
|
25
|
+
import { type GuardDescriptor, isRecord, parseGuardRouterConfig, type ResolvedGuardRouterOptions } from "./GuardConfig";
|
|
26
|
+
import { createLazyGuards, loadGuardModules } from "./GuardModules";
|
|
27
|
+
import { byRouteDepth, expandForNewRoute, expandToDescendants, type RoutePattern } from "./PatternTree";
|
|
28
|
+
import RouteMetaStore, { EMPTY_META } from "./RouteMeta";
|
|
25
29
|
|
|
26
30
|
const HistoryDirection = coreLibrary.routing.HistoryDirection;
|
|
31
|
+
type Direction = ReturnType<History["getDirection"]>;
|
|
27
32
|
|
|
28
|
-
|
|
33
|
+
/**
|
|
34
|
+
* The router config as UI5 gets it: the caller's object without `guardRouter`. It is a view and
|
|
35
|
+
* not a copy, because UIComponent adds `targetParent` (the ID of the root view) to its config
|
|
36
|
+
* object after it has constructed the router, and the native router reads it from that object.
|
|
37
|
+
*/
|
|
38
|
+
function withoutGuardRouter(config: object): object {
|
|
39
|
+
const hidden = (key: PropertyKey): boolean => key === "guardRouter";
|
|
40
|
+
return new Proxy(config, {
|
|
41
|
+
get: (target, key, receiver): unknown => (hidden(key) ? undefined : Reflect.get(target, key, receiver)),
|
|
42
|
+
has: (target, key) => !hidden(key) && Reflect.has(target, key),
|
|
43
|
+
ownKeys: (target) => Reflect.ownKeys(target).filter((key) => !hidden(key)),
|
|
44
|
+
getOwnPropertyDescriptor: (target, key) =>
|
|
45
|
+
hidden(key) ? undefined : Reflect.getOwnPropertyDescriptor(target, key),
|
|
46
|
+
});
|
|
47
|
+
}
|
|
29
48
|
|
|
30
49
|
function isRouteGuardConfig(guard: GuardFn | RouteGuardConfig): guard is RouteGuardConfig {
|
|
31
50
|
return typeof guard === "object" && guard !== null;
|
|
32
51
|
}
|
|
33
52
|
|
|
53
|
+
/** A step through the browser history (back, forward): how far it went, and the URL it arrived at. */
|
|
54
|
+
interface HistoryStep {
|
|
55
|
+
readonly offset: number;
|
|
56
|
+
readonly href: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The step through the browser history that brought the browser to the URL it shows, if a step did. */
|
|
60
|
+
let lastStep: HistoryStep | null = null;
|
|
61
|
+
/** The URL of a step that a router is taking back, until the browser reports the next URL change. */
|
|
62
|
+
let undoneHref: string | null = null;
|
|
63
|
+
|
|
64
|
+
// The Navigation API tells how far a step through the history went, before UI5 learns of the
|
|
65
|
+
// hash change. UI5's History only infers it, and wrongly once an entry lacks its state. Without
|
|
66
|
+
// the API (Firefox before 147, Safari before 26.2) no step is known and the entry is replaced.
|
|
67
|
+
window.navigation?.addEventListener("currententrychange", (event) => {
|
|
68
|
+
const href = window.location.href;
|
|
69
|
+
if (undoneHref !== href) undoneHref = null;
|
|
70
|
+
const entry = window.navigation.currentEntry;
|
|
71
|
+
if (entry && event.navigationType === "traverse") {
|
|
72
|
+
lastStep = { offset: entry.index - event.from.index, href };
|
|
73
|
+
} else if (lastStep?.href !== href) {
|
|
74
|
+
// Not an entry whose state alone is replaced, as UI5's History does after a step.
|
|
75
|
+
lastStep = null;
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
/** What it takes to undo the hash change that an uncommitted navigation arrived with. */
|
|
80
|
+
interface HashChangeUndo {
|
|
81
|
+
/** The hash of the root hash changer after the first change that this takes back. */
|
|
82
|
+
readonly first: string;
|
|
83
|
+
/**
|
|
84
|
+
* The hash of the root hash changer before that change, with the hashes of nested routers.
|
|
85
|
+
* The root hash changer reports it with the change, after the routers have parsed their part.
|
|
86
|
+
*/
|
|
87
|
+
fullHash: string | undefined;
|
|
88
|
+
/** The hash of the root hash changer after the change. */
|
|
89
|
+
readonly shown: string;
|
|
90
|
+
/** Whether the router has started to put the URL back, and the hash change that does it is still to come. */
|
|
91
|
+
started: boolean;
|
|
92
|
+
/** The step through the browser history that the change was, if it was one. */
|
|
93
|
+
readonly step: HistoryStep | null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A manifest guard entry of a route, with the declared entry it stems from: itself, or the entry of an ancestor route. */
|
|
97
|
+
interface ManifestGuardDescriptor extends GuardDescriptor {
|
|
98
|
+
readonly source: GuardDescriptor;
|
|
99
|
+
}
|
|
100
|
+
|
|
34
101
|
/** Snapshot of an in-flight navigation being evaluated by the guard pipeline. */
|
|
35
102
|
interface NavigationAttempt {
|
|
36
103
|
readonly hash: string;
|
|
37
|
-
readonly route: string;
|
|
38
104
|
readonly controller: AbortController;
|
|
39
105
|
readonly generation: number;
|
|
106
|
+
/** Whether the URL shows a hash that never committed, so that it must be restored unless this attempt moves it. */
|
|
107
|
+
readonly restoreHash: boolean;
|
|
108
|
+
/** How the browser got to the hash that started the navigation; `undefined` after `navTo()` or `parse()`. */
|
|
109
|
+
readonly direction: Direction | undefined;
|
|
40
110
|
}
|
|
41
111
|
|
|
42
112
|
interface PhaseIdle {
|
|
@@ -46,388 +116,47 @@ interface PhaseIdle {
|
|
|
46
116
|
interface PhaseEvaluating {
|
|
47
117
|
readonly kind: "evaluating";
|
|
48
118
|
readonly attempt: NavigationAttempt;
|
|
119
|
+
/** Whether the navigation waits for async guards: the native router would be matching its route by now. */
|
|
120
|
+
readonly postponed?: true;
|
|
49
121
|
}
|
|
50
122
|
|
|
51
123
|
interface PhaseCommitting {
|
|
52
124
|
readonly kind: "committing";
|
|
53
|
-
readonly hash: string;
|
|
54
125
|
readonly route: string;
|
|
126
|
+
/** The hash of the route: `parse()` commits the navigation when it receives this hash. */
|
|
127
|
+
readonly hash: string;
|
|
55
128
|
readonly origin: "preflight" | "redirect" | "parse";
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
/** Type guard for plain objects. */
|
|
63
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
64
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
65
|
-
const proto = Object.getPrototypeOf(value);
|
|
66
|
-
return proto === Object.prototype || proto === null;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** Create a type-narrowing validator for a finite set of string literal values. */
|
|
70
|
-
function isOneOf<T extends string>(...values: T[]): (v: unknown) => v is T {
|
|
71
|
-
const set: ReadonlySet<string> = new Set(values);
|
|
72
|
-
return (v: unknown): v is T => typeof v === "string" && set.has(v);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const isUnknownRouteRegistrationPolicy = isOneOf<UnknownRouteRegistrationPolicy>("ignore", "warn", "throw");
|
|
76
|
-
const isNavToPreflightMode = isOneOf<NavToPreflightMode>("guard", "bypass", "off");
|
|
77
|
-
const isGuardLoading = isOneOf<GuardLoading>("block", "lazy");
|
|
78
|
-
const isInheritance = isOneOf<Inheritance>("none", "pattern-tree");
|
|
79
|
-
|
|
80
|
-
/** Matches a standalone optional (`:param:`) or rest (`:param*:`) segment. */
|
|
81
|
-
const OPTIONAL_OR_REST_SEGMENT = /^:[^:]*\*?:$/;
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Strips inline query and optional-query suffixes from a segment.
|
|
85
|
-
*
|
|
86
|
-
* UI5 (crossroads.js) allows query parameters to attach directly to a
|
|
87
|
-
* path segment without a `/` separator:
|
|
88
|
-
* - `product{?query}` → mandatory query on `product`
|
|
89
|
-
* - `product:?query:` → optional query on `product`
|
|
90
|
-
* - `{id}{?query}` → mandatory param + mandatory query
|
|
91
|
-
*
|
|
92
|
-
* For pattern-tree ancestry we only care about the path portion,
|
|
93
|
-
* so these suffixes are stripped.
|
|
94
|
-
*/
|
|
95
|
-
function stripInlineQuery(seg: string): string {
|
|
96
|
-
// Strip mandatory query `{?...}` suffix
|
|
97
|
-
const mqIdx = seg.indexOf("{?");
|
|
98
|
-
if (mqIdx !== -1) return seg.slice(0, mqIdx);
|
|
99
|
-
// Strip optional query `:?...:` suffix
|
|
100
|
-
const oqIdx = seg.indexOf(":?");
|
|
101
|
-
if (oqIdx !== -1) return seg.slice(0, oqIdx);
|
|
102
|
-
return seg;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* Extract mandatory path segments from a UI5 route pattern.
|
|
107
|
-
*
|
|
108
|
-
* Splits on `/`, strips inline query suffixes, then drops empty segments,
|
|
109
|
-
* standalone optional (`:param:`), and rest (`:param*:`) segments.
|
|
110
|
-
*/
|
|
111
|
-
function patternSegments(pattern: string): string[] {
|
|
112
|
-
return pattern
|
|
113
|
-
.split("/")
|
|
114
|
-
.map(stripInlineQuery)
|
|
115
|
-
.filter((seg) => seg !== "" && !OPTIONAL_OR_REST_SEGMENT.test(seg));
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Check if `ancestorPattern` is a URL-tree ancestor of `candidatePattern`.
|
|
120
|
-
*
|
|
121
|
-
* Both patterns are reduced to their mandatory path segments and compared
|
|
122
|
-
* positionally. Mandatory parameter segments (`{paramA}`, `{paramB}`) are
|
|
123
|
-
* treated as equivalent regardless of name, so `employees/{empId}` is
|
|
124
|
-
* recognized as an ancestor of `employees/{id}/resume`.
|
|
125
|
-
*/
|
|
126
|
-
function isPatternAncestor(ancestorPattern: string, candidatePattern: string): boolean {
|
|
127
|
-
if (ancestorPattern === "") return true;
|
|
128
|
-
const ancestorSegments = patternSegments(ancestorPattern);
|
|
129
|
-
if (ancestorSegments.length === 0) return false;
|
|
130
|
-
const candidateSegments = patternSegments(candidatePattern);
|
|
131
|
-
if (candidateSegments.length <= ancestorSegments.length) return false;
|
|
132
|
-
return ancestorSegments.every((seg, i) => {
|
|
133
|
-
const candidateSeg = candidateSegments[i];
|
|
134
|
-
if (seg === candidateSeg) return true;
|
|
135
|
-
// Treat any two mandatory parameter segments as equivalent
|
|
136
|
-
return seg.startsWith("{") && candidateSeg.startsWith("{");
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/** Parsed guard declaration from the manifest `guards` block. */
|
|
141
|
-
interface GuardDescriptor {
|
|
142
|
-
readonly route: string; // "*" for global, route name for per-route
|
|
143
|
-
readonly type: "enter" | "leave";
|
|
144
|
-
readonly modulePath: string;
|
|
145
|
-
readonly name: string;
|
|
146
|
-
readonly exportKey?: string;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* Resolve a guard module path to a slash-separated AMD module path.
|
|
151
|
-
*
|
|
152
|
-
* Inspired by `sap.ui.core.routing.Target._getEffectiveObjectName()`,
|
|
153
|
-
* which skips namespace prepending for `"module:"`-prefixed paths. This
|
|
154
|
-
* function goes further: it also converts dots to slashes in a single
|
|
155
|
-
* step, so both dot notation (`module:some.lib.guard`) and slash
|
|
156
|
-
* notation (`module:some/lib/guard`) are accepted.
|
|
157
|
-
*
|
|
158
|
-
* - Paths prefixed with `"module:"` are treated as absolute (the prefix
|
|
159
|
-
* is stripped, dots become slashes).
|
|
160
|
-
* - All other paths are prefixed with the component namespace, then dots
|
|
161
|
-
* become slashes.
|
|
162
|
-
*/
|
|
163
|
-
function resolveGuardModulePath(dotPath: string, componentNamespace: string): string {
|
|
164
|
-
if (dotPath.startsWith("module:")) {
|
|
165
|
-
return dotPath.slice("module:".length).replace(/\./g, "/");
|
|
166
|
-
}
|
|
167
|
-
const fullDotPath = componentNamespace ? componentNamespace + "." + dotPath : dotPath;
|
|
168
|
-
return fullDotPath.replace(/\./g, "/");
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* Split a manifest guard entry on the first `#` to separate the module path
|
|
173
|
-
* from an optional export key, then derive a human-readable guard name.
|
|
174
|
-
*/
|
|
175
|
-
function parseGuardEntry(
|
|
176
|
-
entry: string,
|
|
177
|
-
componentNamespace: string,
|
|
178
|
-
): { modulePath: string; name: string; exportKey?: string } {
|
|
179
|
-
const hashIndex = entry.indexOf("#");
|
|
180
|
-
const rawPath = hashIndex === -1 ? entry : entry.slice(0, hashIndex);
|
|
181
|
-
const exportKey = hashIndex === -1 ? undefined : entry.slice(hashIndex + 1);
|
|
182
|
-
|
|
183
|
-
const modulePath = resolveGuardModulePath(rawPath, componentNamespace);
|
|
184
|
-
|
|
185
|
-
// Name: export key if present, otherwise last segment of the dot path
|
|
186
|
-
const lastSegment = rawPath.split(".").pop() ?? rawPath;
|
|
187
|
-
const name = exportKey ?? lastSegment;
|
|
188
|
-
|
|
189
|
-
return { modulePath, name, exportKey };
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
interface ResolvedGuardExport {
|
|
193
|
-
readonly name: string;
|
|
194
|
-
readonly fn: GuardFn;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/** Log a warning about a guard module entry in the manifest. */
|
|
198
|
-
function guardWarning(modulePath: string, detail: string): void {
|
|
199
|
-
Log.warning(`guardRouter.guards: "${modulePath}" ${detail}`, undefined, LOG_COMPONENT);
|
|
129
|
+
/** How the browser got to the history entry that the route replaces (see {@link RedirectChainContext.direction}). */
|
|
130
|
+
readonly direction?: Direction;
|
|
131
|
+
/** Whether the URL showed a hash that never committed when `navTo()` wrote the hash (see {@link NavigationAttempt.restoreHash}). */
|
|
132
|
+
readonly restoreHash: boolean;
|
|
133
|
+
/** What the root hash changer showed before `navTo()` wrote the hash: the write is undone with it. */
|
|
134
|
+
readonly writtenOver?: string;
|
|
200
135
|
}
|
|
201
136
|
|
|
202
137
|
/**
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
* Shapes:
|
|
206
|
-
* - function → single guard
|
|
207
|
-
* - Array → ordered guards (non-functions warned and skipped)
|
|
208
|
-
* - plain object → named guards in key order (non-functions warned and skipped)
|
|
209
|
-
*
|
|
210
|
-
* When `exportKey` is set, only the matching export is returned.
|
|
211
|
-
* When `exportKey` is set on a function export, the key is ignored with a debug warning.
|
|
138
|
+
* An allowed navigation waits for UI5 to write its hash. With component targets UI5 does that
|
|
139
|
+
* once the nested components are loaded, and never if one of them fails to load.
|
|
212
140
|
*/
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
exportKey?: string,
|
|
218
|
-
): ResolvedGuardExport[] {
|
|
219
|
-
const moduleName = modulePath.split("/").pop() ?? modulePath;
|
|
220
|
-
|
|
221
|
-
// Shape 1: function
|
|
222
|
-
if (typeof moduleExport === "function") {
|
|
223
|
-
if (exportKey !== undefined) {
|
|
224
|
-
Log.debug(
|
|
225
|
-
`guardRouter.guards: "${modulePath}#${exportKey}" is a single function, ignoring export key`,
|
|
226
|
-
undefined,
|
|
227
|
-
LOG_COMPONENT,
|
|
228
|
-
);
|
|
229
|
-
}
|
|
230
|
-
return [{ name: descriptorName, fn: moduleExport as GuardFn }];
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// Shape 2: array
|
|
234
|
-
if (Array.isArray(moduleExport)) {
|
|
235
|
-
if (moduleExport.length === 0) {
|
|
236
|
-
guardWarning(modulePath, "exported an empty array, skipping");
|
|
237
|
-
return [];
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
if (exportKey !== undefined) {
|
|
241
|
-
const index = parseInt(exportKey, 10);
|
|
242
|
-
if (Number.isNaN(index) || index < 0 || index >= moduleExport.length) {
|
|
243
|
-
guardWarning(modulePath, `#${exportKey} - index out of range, skipping`);
|
|
244
|
-
return [];
|
|
245
|
-
}
|
|
246
|
-
const entry = moduleExport[index] as unknown;
|
|
247
|
-
if (typeof entry !== "function") {
|
|
248
|
-
guardWarning(modulePath, `#${exportKey} is not a function, skipping`);
|
|
249
|
-
return [];
|
|
250
|
-
}
|
|
251
|
-
return [{ name: `${moduleName}#${exportKey}`, fn: entry as GuardFn }];
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
const results: ResolvedGuardExport[] = [];
|
|
255
|
-
for (let i = 0; i < moduleExport.length; i++) {
|
|
256
|
-
const entry = moduleExport[i] as unknown;
|
|
257
|
-
if (typeof entry !== "function") {
|
|
258
|
-
guardWarning(modulePath, `[${i}] is not a function, skipping`);
|
|
259
|
-
continue;
|
|
260
|
-
}
|
|
261
|
-
results.push({ name: `${moduleName}#${i}`, fn: entry as GuardFn });
|
|
262
|
-
}
|
|
263
|
-
return results;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// Shape 3: plain object
|
|
267
|
-
if (isRecord(moduleExport)) {
|
|
268
|
-
const entries = Object.entries(moduleExport);
|
|
269
|
-
if (entries.length === 0) {
|
|
270
|
-
guardWarning(modulePath, "exported an empty object, skipping");
|
|
271
|
-
return [];
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
if (exportKey !== undefined) {
|
|
275
|
-
let value: unknown = moduleExport[exportKey];
|
|
276
|
-
let resolvedName = exportKey;
|
|
277
|
-
if (value === undefined) {
|
|
278
|
-
const index = parseInt(exportKey, 10);
|
|
279
|
-
if (!Number.isNaN(index) && index >= 0 && index < entries.length) {
|
|
280
|
-
const [key, val] = entries[index];
|
|
281
|
-
value = val;
|
|
282
|
-
resolvedName = key;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
if (value === undefined) {
|
|
286
|
-
guardWarning(modulePath, `#${exportKey} - key not found, skipping`);
|
|
287
|
-
return [];
|
|
288
|
-
}
|
|
289
|
-
if (typeof value !== "function") {
|
|
290
|
-
guardWarning(modulePath, `#${exportKey} is not a function, skipping`);
|
|
291
|
-
return [];
|
|
292
|
-
}
|
|
293
|
-
return [{ name: resolvedName, fn: value as GuardFn }];
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
const results: ResolvedGuardExport[] = [];
|
|
297
|
-
for (const [key, value] of entries) {
|
|
298
|
-
if (typeof value !== "function") {
|
|
299
|
-
guardWarning(modulePath, `.${key} is not a function, skipping`);
|
|
300
|
-
continue;
|
|
301
|
-
}
|
|
302
|
-
results.push({ name: key, fn: value as GuardFn });
|
|
303
|
-
}
|
|
304
|
-
return results;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
guardWarning(modulePath, "did not export a function, array, or plain object, skipping");
|
|
308
|
-
return [];
|
|
141
|
+
interface PhaseAwaitingHash {
|
|
142
|
+
readonly kind: "awaitingHash";
|
|
143
|
+
/** The phase that commits the navigation when `parse()` receives its hash. */
|
|
144
|
+
readonly commit: PhaseCommitting;
|
|
309
145
|
}
|
|
310
146
|
|
|
311
|
-
/**
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
* - `"*"` with object form -> warn, treat enter as global
|
|
320
|
-
* - `"*"` leave -> warn, skip (global leave guards not supported)
|
|
321
|
-
* - Invalid entries -> warn, skip
|
|
322
|
-
*/
|
|
323
|
-
function parseGuardDescriptors(guards: unknown, componentNamespace: string): GuardDescriptor[] {
|
|
324
|
-
if (!isRecord(guards)) {
|
|
325
|
-
Log.warning("guardRouter.guards is not a plain object, skipping", JSON.stringify(guards), LOG_COMPONENT);
|
|
326
|
-
return [];
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
const descriptors: GuardDescriptor[] = [];
|
|
330
|
-
|
|
331
|
-
function pushEntries(entries: unknown[], route: string, type: "enter" | "leave", label: string): void {
|
|
332
|
-
for (const entry of entries) {
|
|
333
|
-
if (typeof entry !== "string" || entry.length === 0) {
|
|
334
|
-
Log.warning(
|
|
335
|
-
`guardRouter.guards${label}: invalid entry, skipping`,
|
|
336
|
-
JSON.stringify(entry),
|
|
337
|
-
LOG_COMPONENT,
|
|
338
|
-
);
|
|
339
|
-
continue;
|
|
340
|
-
}
|
|
341
|
-
const parsed = parseGuardEntry(entry, componentNamespace);
|
|
342
|
-
descriptors.push({ route, type, ...parsed });
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
for (const [key, value] of Object.entries(guards)) {
|
|
347
|
-
if (Array.isArray(value)) {
|
|
348
|
-
pushEntries(value, key, "enter", `["${key}"]`);
|
|
349
|
-
} else if (isRecord(value)) {
|
|
350
|
-
const config = value as ManifestRouteGuardConfig;
|
|
351
|
-
|
|
352
|
-
if (key === "*" && config.leave !== undefined) {
|
|
353
|
-
Log.warning(
|
|
354
|
-
'guardRouter.guards["*"].leave: global leave guards are not supported, skipping',
|
|
355
|
-
undefined,
|
|
356
|
-
LOG_COMPONENT,
|
|
357
|
-
);
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
if (key === "*" && config.enter === undefined && config.leave !== undefined) {
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
if (key === "*" && config.enter !== undefined) {
|
|
365
|
-
Log.info('guardRouter.guards["*"]: object form; treating enter as global', undefined, LOG_COMPONENT);
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
if (Array.isArray(config.enter)) {
|
|
369
|
-
pushEntries(config.enter, key, "enter", `["${key}"].enter`);
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
if (key !== "*" && Array.isArray(config.leave)) {
|
|
373
|
-
pushEntries(config.leave, key, "leave", `["${key}"].leave`);
|
|
374
|
-
}
|
|
375
|
-
} else {
|
|
376
|
-
Log.warning(
|
|
377
|
-
`guardRouter.guards["${key}"]: expected string[] or { enter?, leave? }, skipping`,
|
|
378
|
-
JSON.stringify(value),
|
|
379
|
-
LOG_COMPONENT,
|
|
380
|
-
);
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
return descriptors;
|
|
147
|
+
/** A navigation that did not commit waits for the URL to be back before it settles. */
|
|
148
|
+
interface PhaseRestoring {
|
|
149
|
+
readonly kind: "restoring";
|
|
150
|
+
readonly result: NavigationResult;
|
|
151
|
+
/** Whether the previous hash is written once UI5 has reported the hash change to every router. */
|
|
152
|
+
readonly awaitsReport?: true;
|
|
153
|
+
/** What a redirect to the route that is shown still has to do once the navigation has settled. */
|
|
154
|
+
readonly whenBack?: () => void;
|
|
385
155
|
}
|
|
386
156
|
|
|
387
|
-
|
|
388
|
-
readonly unknownRouteRegistration: UnknownRouteRegistrationPolicy;
|
|
389
|
-
readonly navToPreflight: NavToPreflightMode;
|
|
390
|
-
readonly guardLoading: GuardLoading;
|
|
391
|
-
readonly inheritance: Inheritance;
|
|
392
|
-
}
|
|
157
|
+
type RouterPhase = PhaseIdle | PhaseEvaluating | PhaseCommitting | PhaseAwaitingHash | PhaseRestoring;
|
|
393
158
|
|
|
394
|
-
const
|
|
395
|
-
unknownRouteRegistration: "warn",
|
|
396
|
-
navToPreflight: "guard",
|
|
397
|
-
guardLoading: "lazy",
|
|
398
|
-
inheritance: "none",
|
|
399
|
-
};
|
|
400
|
-
|
|
401
|
-
function applyOption<K extends keyof ResolvedGuardRouterOptions>(
|
|
402
|
-
raw: Record<string, unknown>,
|
|
403
|
-
key: K,
|
|
404
|
-
guard: (v: unknown) => v is ResolvedGuardRouterOptions[K],
|
|
405
|
-
target: { -readonly [P in keyof ResolvedGuardRouterOptions]: ResolvedGuardRouterOptions[P] },
|
|
406
|
-
): void {
|
|
407
|
-
if (raw[key] !== undefined) {
|
|
408
|
-
if (guard(raw[key])) {
|
|
409
|
-
target[key] = raw[key] as ResolvedGuardRouterOptions[K];
|
|
410
|
-
} else {
|
|
411
|
-
Log.warning(`guardRouter.${key} has invalid value, using default`, JSON.stringify(raw[key]), LOG_COMPONENT);
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
function normalizeGuardRouterOptions(raw: unknown): ResolvedGuardRouterOptions {
|
|
417
|
-
if (!isRecord(raw)) {
|
|
418
|
-
if (raw !== undefined) {
|
|
419
|
-
Log.warning("guardRouter config is not a plain object, using defaults", JSON.stringify(raw), LOG_COMPONENT);
|
|
420
|
-
}
|
|
421
|
-
return DEFAULT_OPTIONS;
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
const result = { ...DEFAULT_OPTIONS };
|
|
425
|
-
applyOption(raw, "unknownRouteRegistration", isUnknownRouteRegistrationPolicy, result);
|
|
426
|
-
applyOption(raw, "navToPreflight", isNavToPreflightMode, result);
|
|
427
|
-
applyOption(raw, "guardLoading", isGuardLoading, result);
|
|
428
|
-
applyOption(raw, "inheritance", isInheritance, result);
|
|
429
|
-
return result;
|
|
430
|
-
}
|
|
159
|
+
const IDLE: PhaseIdle = { kind: "idle" };
|
|
431
160
|
|
|
432
161
|
/** Maximum number of hops in a redirect chain before it is treated as a loop. */
|
|
433
162
|
const MAX_REDIRECT_DEPTH = 10;
|
|
@@ -438,12 +167,19 @@ interface RedirectChainContext {
|
|
|
438
167
|
visited: Set<string>;
|
|
439
168
|
/** Hash of the originally attempted navigation (for settlement / hash restore). */
|
|
440
169
|
readonly attemptedHash: string | undefined;
|
|
441
|
-
/** Whether to restore the hash on block (
|
|
170
|
+
/** Whether to restore the hash on block (see {@link NavigationAttempt.restoreHash}). */
|
|
442
171
|
readonly restoreHash: boolean;
|
|
443
172
|
/** Original source route (the route the user occupies). */
|
|
444
173
|
readonly fromRoute: string;
|
|
445
174
|
/** Original source hash (the hash the user occupies). */
|
|
446
175
|
readonly fromHash: string;
|
|
176
|
+
/** Whether the target replaces the current history entry: as the `navTo()` call asked, always after a hash change. */
|
|
177
|
+
readonly replace: boolean | undefined;
|
|
178
|
+
/**
|
|
179
|
+
* How the browser got to the history entry that the target replaces, for the title history
|
|
180
|
+
* of UI5 (see {@link Router._alignTitleHistory}); `undefined` after `navTo()` or `parse()`.
|
|
181
|
+
*/
|
|
182
|
+
readonly direction: Direction | undefined;
|
|
447
183
|
/** Shared AbortSignal from the original navigation. */
|
|
448
184
|
readonly signal: AbortSignal;
|
|
449
185
|
/** Shared generation counter from the original navigation. */
|
|
@@ -460,8 +196,8 @@ interface RedirectChainContext {
|
|
|
460
196
|
* loading, or event firing occurs.
|
|
461
197
|
*
|
|
462
198
|
* Two entry points feed the same pipeline:
|
|
463
|
-
* - `navTo()` runs guards as a preflight check.
|
|
464
|
-
*
|
|
199
|
+
* - `navTo()` runs guards as a preflight check. A blocked navigation
|
|
200
|
+
* never changes the hash; a redirected one only writes its final target.
|
|
465
201
|
* - `parse()` runs guards as a fallback for browser back/forward, URL
|
|
466
202
|
* bar entry, and direct hash changes where the hash has already changed
|
|
467
203
|
* before guards can intercept.
|
|
@@ -477,80 +213,167 @@ interface RedirectChainContext {
|
|
|
477
213
|
* @extends sap.m.routing.Router
|
|
478
214
|
*/
|
|
479
215
|
export default class Router extends MobileRouter implements GuardRouter {
|
|
480
|
-
private _options: ResolvedGuardRouterOptions
|
|
216
|
+
private _options: ResolvedGuardRouterOptions;
|
|
481
217
|
private _pipeline = new GuardPipeline();
|
|
482
218
|
private _currentRoute = "";
|
|
483
219
|
private _currentHash: string | null = null;
|
|
484
220
|
private _phase: RouterPhase = IDLE;
|
|
485
221
|
private _parseGeneration = 0;
|
|
486
222
|
private _suppressedHash: string | null = null;
|
|
223
|
+
/** How to undo the hash change of the pending navigation (see {@link _undoHashChange}). */
|
|
224
|
+
private _undo: HashChangeUndo | null = null;
|
|
225
|
+
/** The hash that the hash changer of this router is reporting, until `parse()` receives it. */
|
|
226
|
+
private _reportedHash: unknown = null;
|
|
227
|
+
/** The hash that the hash changer of this router reported last, reports that are out of date aside. */
|
|
228
|
+
private _lastReport: unknown = null;
|
|
229
|
+
/** Whether the hash changer shows a later hash than the one it is reporting (see {@link _onHashReported}). */
|
|
230
|
+
private _reportOutdated = false;
|
|
231
|
+
/** The global hash changer that {@link _onRootHashChanged} is attached to, behind the listener of UI5 that informs the routers. */
|
|
232
|
+
private _rootHashChanger: HashChanger | null = null;
|
|
233
|
+
/** The route that was current when the router stopped: `initialize(true)` resumes it, as UI5 does. */
|
|
234
|
+
private _stoppedRoute = "";
|
|
487
235
|
private _settlementResolvers: ((result: NavigationResult) => void)[] = [];
|
|
488
236
|
private _lastSettlement: NavigationResult | null = null;
|
|
489
|
-
private _pendingGuardDescriptors: GuardDescriptor[]
|
|
490
|
-
private _sourceDescriptors:
|
|
237
|
+
private _pendingGuardDescriptors: GuardDescriptor[];
|
|
238
|
+
private _sourceDescriptors: ManifestGuardDescriptor[] = [];
|
|
239
|
+
/** The manifest guards registered for a route, by which `addRoute()` places the guards a route inherits then. */
|
|
240
|
+
private _manifestGuards: { descriptor: ManifestGuardDescriptor; fn: GuardFn }[] = [];
|
|
491
241
|
private _destroyed = false;
|
|
492
|
-
|
|
493
|
-
private
|
|
494
|
-
|
|
495
|
-
private
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
242
|
+
/** What UI5 itself wrote to `_bMatchingProcessStarted` (see {@link _mirrorMatchingProcess}). */
|
|
243
|
+
private _nativeMatching = false;
|
|
244
|
+
/** Promises that wait for the `routeMatched` of a match that has not started (see {@link attachRouteMatched}). */
|
|
245
|
+
private _matchWaiters: (() => void)[] = [];
|
|
246
|
+
/**
|
|
247
|
+
* Set while block-mode guard modules load; `start` says whether to initialize once they have,
|
|
248
|
+
* `ignoreInitialHash` is the argument of the `initialize()` call that asked for it.
|
|
249
|
+
*/
|
|
250
|
+
private _blockLoad: { start: boolean; ignoreInitialHash?: boolean } | null = null;
|
|
251
|
+
private _meta: RouteMetaStore;
|
|
252
|
+
/** Recorded by `addRoute()`, which the UI5 constructor calls before field setup; `declare` keeps field setup from resetting it. */
|
|
253
|
+
declare private _routeNames: string[];
|
|
254
|
+
/** Routes that also match when an earlier route has matched the hash (`greedy: true`). */
|
|
255
|
+
declare private _greedyRouteNames: string[];
|
|
256
|
+
private readonly _ownerComponent: UIComponent | undefined;
|
|
257
|
+
|
|
258
|
+
constructor(routes?: object | object[], config?: GuardRouterConfig, owner?: UIComponent, targetsConfig?: object);
|
|
259
|
+
constructor(
|
|
260
|
+
routes?: object | object[],
|
|
261
|
+
config?: GuardRouterConfig,
|
|
262
|
+
owner?: UIComponent,
|
|
263
|
+
...rest: [targetsConfig?: object]
|
|
264
|
+
) {
|
|
265
|
+
const isRecordConfig = isRecord(config);
|
|
266
|
+
const guardRouter = isRecordConfig ? config.guardRouter : undefined;
|
|
267
|
+
// UI5 passes more than its types declare: after the targets config comes the
|
|
268
|
+
// hash changer of a component that is loaded as a routing target.
|
|
269
|
+
super(routes, isRecordConfig ? withoutGuardRouter(config) : config, owner, ...rest);
|
|
270
|
+
this._ownerComponent = owner;
|
|
271
|
+
// A config without routes has made no addRoute() call.
|
|
272
|
+
this._routeNames ??= [];
|
|
273
|
+
this._greedyRouteNames ??= [];
|
|
274
|
+
this._mirrorMatchingProcess();
|
|
275
|
+
let componentNamespace = "";
|
|
276
|
+
const appConfig: unknown = owner?.getManifestEntry("sap.app");
|
|
277
|
+
if (isRecord(appConfig) && typeof appConfig.id === "string") {
|
|
278
|
+
componentNamespace = appConfig.id;
|
|
512
279
|
}
|
|
280
|
+
const parsed = parseGuardRouterConfig(guardRouter, componentNamespace);
|
|
281
|
+
this._options = parsed.options;
|
|
282
|
+
this._meta = new RouteMetaStore(
|
|
283
|
+
parsed.routeMeta,
|
|
284
|
+
this._options.inheritance === "pattern-tree" ? () => this._collectRoutePatterns() : null,
|
|
285
|
+
);
|
|
286
|
+
this._pendingGuardDescriptors = parsed.guards;
|
|
513
287
|
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
JSON.stringify(meta),
|
|
523
|
-
LOG_COMPONENT,
|
|
524
|
-
);
|
|
525
|
-
}
|
|
526
|
-
}
|
|
527
|
-
} else {
|
|
528
|
-
Log.warning(
|
|
529
|
-
"guardRouter.routeMeta: expected object, skipping",
|
|
530
|
-
JSON.stringify(guardRouter.routeMeta),
|
|
531
|
-
LOG_COMPONENT,
|
|
532
|
-
);
|
|
533
|
-
}
|
|
288
|
+
// Fire-and-forget preload hint: a module cached by initialize()
|
|
289
|
+
// needs no async load on navigation (see _registerLazyGuards).
|
|
290
|
+
// Block mode loads modules itself in initialize().
|
|
291
|
+
if (this._options.guardLoading === "lazy") {
|
|
292
|
+
const uniquePaths = [...new Set(this._pendingGuardDescriptors.map((d) => d.modulePath))];
|
|
293
|
+
// A failed preload is reported when the guard runs: its lazy load warns
|
|
294
|
+
// and the navigation settles as Error.
|
|
295
|
+
sap.ui.require(uniquePaths, undefined, () => {});
|
|
534
296
|
}
|
|
297
|
+
}
|
|
535
298
|
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
}
|
|
299
|
+
/**
|
|
300
|
+
* Report a navigation that waits for async guards as a route match in progress, through the
|
|
301
|
+
* UI5-private member `_bMatchingProcessStarted` of `sap.ui.core.routing.Router`. UI5 reads it
|
|
302
|
+
* to tell whether the router of a nested component is still matching; without this, a parent
|
|
303
|
+
* route would count the component as displayed before its first route matched. The router does
|
|
304
|
+
* not write the member: it replaces it with an accessor that keeps what UI5 writes in
|
|
305
|
+
* {@link _nativeMatching} and also reads `true` while a navigation is postponed.
|
|
306
|
+
*
|
|
307
|
+
* See docs/reference/architecture.md ("UI5 Internals the Router Relies On") for the UI5 code this
|
|
308
|
+
* relies on, and docs/reference/upstream-parity.md for the tests that pin it.
|
|
309
|
+
*/
|
|
310
|
+
private _mirrorMatchingProcess(): void {
|
|
311
|
+
Object.defineProperty(this, "_bMatchingProcessStarted", {
|
|
312
|
+
get: () => this._isMatching(),
|
|
313
|
+
set: (matching: boolean) => {
|
|
314
|
+
this._nativeMatching = matching;
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Whether a route match is in progress: in UI5, or postponed until async guards have decided. */
|
|
320
|
+
private _isMatching(): boolean {
|
|
321
|
+
return this._nativeMatching || (this._phase.kind === "evaluating" && this._phase.postponed === true);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Attach an event handler for the `routeMatched` event, as the native router does. In addition,
|
|
326
|
+
* remember a Promise resolve function ({@link isPromiseResolver}) that is subscribed while the
|
|
327
|
+
* router is not initialized or a match is in progress: that is how a UI5 component target
|
|
328
|
+
* waits for this router. UI5 relies on a match always ending in `routeMatched`, which a
|
|
329
|
+
* navigation that guards block, fail or cancel never fires, so {@link _settleMatchWaiters}
|
|
330
|
+
* resolves the Promise then. Application code that subscribes a Promise resolve function under
|
|
331
|
+
* the same condition is treated alike.
|
|
332
|
+
*
|
|
333
|
+
* See docs/reference/architecture.md ("UI5 Internals the Router Relies On") for the UI5 code this
|
|
334
|
+
* relies on, and docs/reference/upstream-parity.md for the tests that pin it.
|
|
335
|
+
*
|
|
336
|
+
* @override sap.ui.core.routing.Router#attachRouteMatched
|
|
337
|
+
* @since 1.7.0
|
|
338
|
+
*/
|
|
339
|
+
override attachRouteMatched(
|
|
340
|
+
oData: object,
|
|
341
|
+
fnFunction: (evt: Router$RouteMatchedEvent) => void,
|
|
342
|
+
oListener?: object,
|
|
343
|
+
): this;
|
|
344
|
+
override attachRouteMatched(fnFunction: (evt: Router$RouteMatchedEvent) => void, oListener?: object): this;
|
|
345
|
+
override attachRouteMatched(
|
|
346
|
+
oData: object,
|
|
347
|
+
fnFunction: (evt: Router$RouteMatchedEvent) => void,
|
|
348
|
+
oListener?: object,
|
|
349
|
+
): this {
|
|
350
|
+
if (isPromiseResolver(oData) && (!this.isInitialized() || this._isMatching())) {
|
|
351
|
+
this._matchWaiters.push(oData);
|
|
553
352
|
}
|
|
353
|
+
// The arguments go on as received: EventProvider#attachEvent tells the two call forms apart.
|
|
354
|
+
return super.attachRouteMatched(oData, fnFunction, oListener);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Decide what becomes of the Promises that wait for a `routeMatched`
|
|
359
|
+
* (see {@link attachRouteMatched}). Runs in a microtask after a settlement, so that a commit
|
|
360
|
+
* has reached `super.parse()` and a navigation that supersedes the settled one has started:
|
|
361
|
+
* - A navigation waits for async guards: the Promises keep waiting, for its settlement.
|
|
362
|
+
* - UI5 is matching a route: the Promises are forgotten, the `routeMatched` of that match
|
|
363
|
+
* resolves them. If UI5 never fires it, because the display of a target fails, they wait
|
|
364
|
+
* forever, as with the native router.
|
|
365
|
+
* - Otherwise no match is coming, and the Promises are resolved.
|
|
366
|
+
*
|
|
367
|
+
* A navigation that starts after this microtask is not waited for. A Promise that is resolved
|
|
368
|
+
* here stays subscribed, and UI5 calls it again with the next `routeMatched`, which has no
|
|
369
|
+
* effect on a Promise.
|
|
370
|
+
*/
|
|
371
|
+
private _settleMatchWaiters(): void {
|
|
372
|
+
if (this._phase.kind === "evaluating" && this._phase.postponed) return;
|
|
373
|
+
const waiters = this._matchWaiters;
|
|
374
|
+
this._matchWaiters = [];
|
|
375
|
+
if (this._nativeMatching) return;
|
|
376
|
+
for (const resolve of waiters) resolve();
|
|
554
377
|
}
|
|
555
378
|
|
|
556
379
|
/**
|
|
@@ -560,127 +383,192 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
560
383
|
* In `"lazy"` mode, lazy wrappers are registered synchronously
|
|
561
384
|
* and `super.initialize()` is called immediately.
|
|
562
385
|
*
|
|
386
|
+
* While block-mode modules load, the router is not initialized yet:
|
|
387
|
+
* calling `initialize()` again changes nothing, and `stop()` cancels
|
|
388
|
+
* the pending start until `initialize()` is called again.
|
|
389
|
+
*
|
|
390
|
+
* @param bIgnoreInitialHash - Whether the current hash is left unparsed, as in the native router (since 1.7.0).
|
|
563
391
|
* @override sap.ui.core.routing.Router#initialize
|
|
564
392
|
* @since 1.0.1
|
|
565
393
|
*/
|
|
566
|
-
override initialize(): this {
|
|
394
|
+
override initialize(bIgnoreInitialHash?: boolean): this {
|
|
395
|
+
if (this._blockLoad) {
|
|
396
|
+
if (!this._blockLoad.start) {
|
|
397
|
+
this._blockLoad.start = true;
|
|
398
|
+
this._blockLoad.ignoreInitialHash = bIgnoreInitialHash;
|
|
399
|
+
}
|
|
400
|
+
return this;
|
|
401
|
+
}
|
|
567
402
|
if (this._pendingGuardDescriptors.length === 0) {
|
|
568
|
-
return
|
|
403
|
+
return this._start(bIgnoreInitialHash);
|
|
569
404
|
}
|
|
570
405
|
|
|
571
|
-
const descriptors = this._pendingGuardDescriptors;
|
|
406
|
+
const descriptors = this._pendingGuardDescriptors.map((source) => ({ ...source, source }));
|
|
572
407
|
this._pendingGuardDescriptors = [];
|
|
573
408
|
this._sourceDescriptors = descriptors;
|
|
574
409
|
|
|
575
410
|
const expandedDescriptors =
|
|
576
|
-
this._options.inheritance === "pattern-tree"
|
|
411
|
+
this._options.inheritance === "pattern-tree"
|
|
412
|
+
? expandToDescendants(descriptors, this._collectRoutePatterns())
|
|
413
|
+
: descriptors;
|
|
577
414
|
|
|
578
415
|
if (this._options.guardLoading === "lazy") {
|
|
579
416
|
this._registerLazyGuards(expandedDescriptors);
|
|
580
|
-
return
|
|
417
|
+
return this._start(bIgnoreInitialHash);
|
|
581
418
|
}
|
|
582
419
|
|
|
583
|
-
// "block" mode: load all modules, then
|
|
584
|
-
//
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
.
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
super.initialize();
|
|
597
|
-
});
|
|
420
|
+
// "block" mode: load all modules, then register their guards in declaration order
|
|
421
|
+
// and initialize. Load and registration failures are logged per module and never
|
|
422
|
+
// reject. A router destroyed while modules load stays destroyed.
|
|
423
|
+
const blockLoad = { start: true, ignoreInitialHash: bIgnoreInitialHash };
|
|
424
|
+
this._blockLoad = blockLoad;
|
|
425
|
+
void loadGuardModules(expandedDescriptors).then((results) => {
|
|
426
|
+
this._blockLoad = null;
|
|
427
|
+
if (this._destroyed) return;
|
|
428
|
+
for (const { descriptor, guards } of results) {
|
|
429
|
+
for (const fn of guards) this._registerManifestGuard(descriptor, fn);
|
|
430
|
+
}
|
|
431
|
+
if (blockLoad.start) this._start(blockLoad.ignoreInitialHash);
|
|
432
|
+
});
|
|
598
433
|
return this;
|
|
599
434
|
}
|
|
600
435
|
|
|
436
|
+
/**
|
|
437
|
+
* Start the native router. With `ignoreInitialHash` it parses nothing and resumes the route
|
|
438
|
+
* that was displayed when the router stopped. That route is the current one again, on the hash
|
|
439
|
+
* that the URL shows now, so that its leave guards run and a blocked hash change returns to it.
|
|
440
|
+
*/
|
|
441
|
+
private _start(ignoreInitialHash?: boolean): this {
|
|
442
|
+
// UI5 only warns about a router that is initialized already.
|
|
443
|
+
const starting = !this.isInitialized();
|
|
444
|
+
if (starting) {
|
|
445
|
+
// Before the listener of UI5 that calls parse(), which initialize() attaches.
|
|
446
|
+
this.getHashChanger().attachEvent("hashChanged", this._onHashReported, this);
|
|
447
|
+
// After the listener of UI5 that informs the routers, which is attached with the hash
|
|
448
|
+
// changer of the first router: UI5 has reported a hash change to every router when
|
|
449
|
+
// this one runs.
|
|
450
|
+
this._rootHashChanger = HashChanger.getInstance();
|
|
451
|
+
this._rootHashChanger.attachEvent("hashChanged", this._onRootHashChanged, this);
|
|
452
|
+
}
|
|
453
|
+
super.initialize(ignoreInitialHash);
|
|
454
|
+
if (starting && ignoreInitialHash) {
|
|
455
|
+
// UI5 has reset the hash of the hash changer if a target was displayed without a route.
|
|
456
|
+
const shownHash: string | undefined = this.getHashChanger().getHash();
|
|
457
|
+
this._currentRoute = this._stoppedRoute;
|
|
458
|
+
this._currentHash = shownHash ?? null;
|
|
459
|
+
}
|
|
460
|
+
return this;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* The hash changer of this router reports a hash change: `parse()` is called with it next.
|
|
465
|
+
*
|
|
466
|
+
* The report is out of date if the hash changer shows a later hash by now, one that it has
|
|
467
|
+
* reported to this router already. That happens to a router that shares its hash changer, as
|
|
468
|
+
* the routers of all components that are not routing targets do: a router that is informed
|
|
469
|
+
* first redirects the hash, UI5 reports the target to every router, and only then the hash
|
|
470
|
+
* that was redirected to the routers that are informed later. A hash changer that reports
|
|
471
|
+
* while a parent router collects the hashes of a navigation shows no hash at all.
|
|
472
|
+
*/
|
|
473
|
+
private _onHashReported(event: HashChangerBase$HashChangedEvent): void {
|
|
474
|
+
// A string, which the UI5 types declare as an object.
|
|
475
|
+
const newHash: unknown = event.getParameter("newHash");
|
|
476
|
+
const shown: unknown = this.getHashChanger().getHash();
|
|
477
|
+
this._reportedHash = newHash;
|
|
478
|
+
this._reportOutdated = shown !== newHash && shown === this._lastReport;
|
|
479
|
+
if (!this._reportOutdated) this._lastReport = newHash;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* UI5 has reported a hash change to every router. The event tells what the URL showed before
|
|
484
|
+
* the change, which is what undoes it. A snapshot of the URL taken at any other time would not
|
|
485
|
+
* do: the URL also changes without an event, as when the Fiori launchpad puts it back after
|
|
486
|
+
* a cross-app navigation that the user cancelled. A navigation that waited for this to put
|
|
487
|
+
* the URL back does so now (see {@link _undoHashChange}).
|
|
488
|
+
*/
|
|
489
|
+
private _onRootHashChanged(event: HashChangerBase$HashChangedEvent): void {
|
|
490
|
+
// A string, which the UI5 types declare as an object.
|
|
491
|
+
const newHash: unknown = event.getParameter("newHash");
|
|
492
|
+
// Only the first hash change that the page reports has no previous hash.
|
|
493
|
+
const oldHash = event.getParameter("oldHash") ?? "";
|
|
494
|
+
const hashChanger = HashChanger.getInstance();
|
|
495
|
+
if (hashChanger === this._rootHashChanger) {
|
|
496
|
+
this._completeUndo(newHash, oldHash);
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
// The global hash changer was replaced (HashChanger.replaceHashChanger(), as the shell of
|
|
500
|
+
// the Fiori launchpad does). UI5 has moved this listener to the new one, in front of its
|
|
501
|
+
// listener that informs the routers. From the next hash change on it runs behind again;
|
|
502
|
+
// for this one, the routers are informed once this listener has returned.
|
|
503
|
+
hashChanger.detachEvent("hashChanged", this._onRootHashChanged, this);
|
|
504
|
+
hashChanger.attachEvent("hashChanged", this._onRootHashChanged, this);
|
|
505
|
+
this._rootHashChanger = hashChanger;
|
|
506
|
+
queueMicrotask(() => this._completeUndo(newHash, oldHash));
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Tell the undo of the pending navigation what the URL showed before the hash change
|
|
511
|
+
* `newHash`, and put the URL back if the navigation waited for that.
|
|
512
|
+
*/
|
|
513
|
+
private _completeUndo(newHash: unknown, oldHash: string): void {
|
|
514
|
+
const undo = this._undo;
|
|
515
|
+
if (!undo || undo.first !== newHash) return;
|
|
516
|
+
undo.fullHash ??= oldHash;
|
|
517
|
+
if (this._phase.kind === "restoring" && this._phase.awaitsReport) this._replaceFullHash(undo.fullHash);
|
|
518
|
+
}
|
|
519
|
+
|
|
601
520
|
/**
|
|
602
521
|
* Add a route dynamically and integrate it into pattern-tree inheritance.
|
|
603
522
|
*
|
|
604
523
|
* Appends the route name to the internal route list so that
|
|
605
524
|
* `_collectRoutePatterns()` includes it in subsequent inheritance
|
|
606
525
|
* lookups, clears the metadata cache, and registers any inherited
|
|
607
|
-
* manifest guards when `inheritance` is `"pattern-tree"
|
|
526
|
+
* manifest guards when `inheritance` is `"pattern-tree"`: on every
|
|
527
|
+
* route, ancestor guards still run before descendant guards.
|
|
608
528
|
*
|
|
609
529
|
* @param oConfig - Route configuration object as defined by `sap.ui.core.routing.Route`.
|
|
610
|
-
* @param
|
|
530
|
+
* @param oParent - Optional parent route, forwarded to the parent `addRoute`.
|
|
611
531
|
* @override sap.ui.core.routing.Router#addRoute
|
|
612
532
|
* @since 1.6.0
|
|
613
533
|
*/
|
|
614
|
-
override addRoute(oConfig: $RouteSettings,
|
|
615
|
-
|
|
616
|
-
super.addRoute(oConfig, ...rest);
|
|
617
|
-
|
|
618
|
-
// Skip when called by the parent constructor before field initializers have run.
|
|
619
|
-
// Routes from the constructor args are captured in _routeNames by the constructor body.
|
|
620
|
-
if (!this._routeNames) return;
|
|
534
|
+
override addRoute(oConfig: $RouteSettings, oParent?: Route): void {
|
|
535
|
+
super.addRoute(oConfig, oParent);
|
|
621
536
|
|
|
622
537
|
const name = oConfig.name;
|
|
623
|
-
|
|
538
|
+
this._routeNames ??= [];
|
|
539
|
+
this._greedyRouteNames ??= [];
|
|
624
540
|
if (this._routeNames.includes(name)) return;
|
|
625
541
|
|
|
626
542
|
this._routeNames.push(name);
|
|
627
|
-
this.
|
|
543
|
+
if (oConfig.greedy) this._greedyRouteNames.push(name);
|
|
544
|
+
// The UI5 constructor adds the routes of the config before this constructor sets up the rest.
|
|
545
|
+
if (!this._meta) return;
|
|
546
|
+
this._meta.invalidate();
|
|
628
547
|
|
|
629
548
|
if (this._options.inheritance !== "pattern-tree") return;
|
|
630
|
-
if (this._sourceDescriptors.length === 0) return;
|
|
631
549
|
|
|
632
|
-
const
|
|
633
|
-
|
|
634
|
-
const
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
const newDescriptors = this._expandGuardDescriptorsForNewRoute(name, newPattern);
|
|
638
|
-
if (newDescriptors.length === 0) return;
|
|
550
|
+
const patterns = this._collectRoutePatterns();
|
|
551
|
+
const declared = byRouteDepth(this._sourceDescriptors, new Map(patterns.map((r) => [r.name, r.pattern])));
|
|
552
|
+
const rankOf = (descriptor: ManifestGuardDescriptor): number =>
|
|
553
|
+
declared.findIndex((entry) => entry.source === descriptor.source);
|
|
639
554
|
|
|
640
555
|
// Always use lazy registration: if the module was loaded during
|
|
641
556
|
// initialize() (block mode), the sync cache probe succeeds immediately.
|
|
642
557
|
// This avoids an async gap between addRoute() and the first navigation.
|
|
643
|
-
this.
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
for (const descriptor of this._sourceDescriptors) {
|
|
658
|
-
if (descriptor.route === "*") continue;
|
|
659
|
-
|
|
660
|
-
if (descriptor.route !== newName) {
|
|
661
|
-
// Check if the source descriptor's route is an ancestor of the new route.
|
|
662
|
-
const ancestorRoute = this.getRoute(descriptor.route);
|
|
663
|
-
const ancestorPattern = ancestorRoute?.getPattern();
|
|
664
|
-
if (ancestorPattern !== undefined && isPatternAncestor(ancestorPattern, newPattern)) {
|
|
665
|
-
result.push({ ...descriptor, route: newName });
|
|
666
|
-
}
|
|
667
|
-
} else {
|
|
668
|
-
// The new route itself has a source descriptor: expand to existing descendants.
|
|
669
|
-
for (const { name, pattern } of this._collectRoutePatterns()) {
|
|
670
|
-
if (name === newName) continue;
|
|
671
|
-
if (isPatternAncestor(newPattern, pattern)) {
|
|
672
|
-
result.push({ ...descriptor, route: name });
|
|
673
|
-
}
|
|
674
|
-
}
|
|
675
|
-
}
|
|
558
|
+
for (const descriptor of expandForNewRoute(this._sourceDescriptors, name, patterns)) {
|
|
559
|
+
// Ancestor guards run first: the new guards go before the manifest guards of the route
|
|
560
|
+
// that stem from an entry of a deeper route, or from a later entry of the same depth.
|
|
561
|
+
const rank = rankOf(descriptor);
|
|
562
|
+
const next = this._manifestGuards
|
|
563
|
+
.filter(
|
|
564
|
+
(guard) =>
|
|
565
|
+
guard.descriptor.route === descriptor.route &&
|
|
566
|
+
guard.descriptor.type === descriptor.type &&
|
|
567
|
+
rankOf(guard.descriptor) > rank,
|
|
568
|
+
)
|
|
569
|
+
.toSorted((a, b) => rankOf(a.descriptor) - rankOf(b.descriptor))[0];
|
|
570
|
+
for (const fn of createLazyGuards(descriptor)) this._registerManifestGuard(descriptor, fn, next?.fn);
|
|
676
571
|
}
|
|
677
|
-
|
|
678
|
-
// Sort by pattern depth (ancestor guards run before descendant guards).
|
|
679
|
-
return result.toSorted((a, b) => {
|
|
680
|
-
const pa = this.getRoute(a.route)?.getPattern() ?? "";
|
|
681
|
-
const pb = this.getRoute(b.route)?.getPattern() ?? "";
|
|
682
|
-
return patternSegments(pa).length - patternSegments(pb).length;
|
|
683
|
-
});
|
|
684
572
|
}
|
|
685
573
|
|
|
686
574
|
/**
|
|
@@ -722,9 +610,7 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
722
610
|
*/
|
|
723
611
|
addRouteGuard(routeName: string, guard: GuardFn | RouteGuardConfig): this {
|
|
724
612
|
if (isRouteGuardConfig(guard)) {
|
|
725
|
-
|
|
726
|
-
return this;
|
|
727
|
-
}
|
|
613
|
+
this._handleUnknownRouteRegistration(routeName, "addRouteGuard");
|
|
728
614
|
let hasHandler = false;
|
|
729
615
|
|
|
730
616
|
if (guard.beforeEnter !== undefined) {
|
|
@@ -742,14 +628,11 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
742
628
|
|
|
743
629
|
if (!hasHandler) {
|
|
744
630
|
Log.info("addRouteGuard: config has no beforeEnter or beforeLeave", routeName, LOG_COMPONENT);
|
|
745
|
-
return this;
|
|
746
631
|
}
|
|
747
632
|
return this;
|
|
748
633
|
}
|
|
749
634
|
if (!this._isFn(guard, "addRouteGuard", routeName)) return this;
|
|
750
|
-
|
|
751
|
-
return this;
|
|
752
|
-
}
|
|
635
|
+
this._handleUnknownRouteRegistration(routeName, "addRouteGuard");
|
|
753
636
|
this._pipeline.addEnterGuard(routeName, guard);
|
|
754
637
|
return this;
|
|
755
638
|
}
|
|
@@ -795,9 +678,7 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
795
678
|
*/
|
|
796
679
|
addLeaveGuard(routeName: string, guard: LeaveGuardFn): this {
|
|
797
680
|
if (!this._isFn(guard, "addLeaveGuard", routeName)) return this;
|
|
798
|
-
|
|
799
|
-
return this;
|
|
800
|
-
}
|
|
681
|
+
this._handleUnknownRouteRegistration(routeName, "addLeaveGuard");
|
|
801
682
|
this._pipeline.addLeaveGuard(routeName, guard);
|
|
802
683
|
return this;
|
|
803
684
|
}
|
|
@@ -808,6 +689,7 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
808
689
|
* UI5's native `navTo` has two signatures where the third parameter is either
|
|
809
690
|
* `componentTargetInfo` (object) or `bReplace` (boolean). This method normalizes
|
|
810
691
|
* both forms so the rest of `navTo` can work with a single set of variables.
|
|
692
|
+
* The options follow `bReplace`, or take its place when it is left out.
|
|
811
693
|
*/
|
|
812
694
|
private _resolveNavToArgs(
|
|
813
695
|
componentTargetInfoOrReplace?: Record<string, ComponentTargetParameters> | boolean,
|
|
@@ -822,15 +704,14 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
822
704
|
// Short form: navTo(name, params, replace, options?)
|
|
823
705
|
return {
|
|
824
706
|
replace: componentTargetInfoOrReplace,
|
|
825
|
-
guardOptions:
|
|
826
|
-
typeof replaceOrOptions === "object" && replaceOrOptions !== null ? replaceOrOptions : undefined,
|
|
707
|
+
guardOptions: typeof replaceOrOptions === "object" ? replaceOrOptions : undefined,
|
|
827
708
|
};
|
|
828
709
|
}
|
|
829
710
|
// Long form: navTo(name, params, componentTargetInfo, replace, options?)
|
|
830
711
|
return {
|
|
831
712
|
componentTargetInfo: componentTargetInfoOrReplace,
|
|
832
713
|
replace: typeof replaceOrOptions === "boolean" ? replaceOrOptions : undefined,
|
|
833
|
-
guardOptions: options,
|
|
714
|
+
guardOptions: typeof replaceOrOptions === "object" ? replaceOrOptions : options,
|
|
834
715
|
};
|
|
835
716
|
}
|
|
836
717
|
|
|
@@ -841,25 +722,20 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
841
722
|
return false;
|
|
842
723
|
}
|
|
843
724
|
|
|
844
|
-
/**
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
*/
|
|
848
|
-
private _handleUnknownRouteRegistration(routeName: string, methodName: string): boolean {
|
|
849
|
-
if (this.getRoute(routeName)) return true;
|
|
725
|
+
/** Apply the `unknownRouteRegistration` policy: warn or throw when the route is unknown. */
|
|
726
|
+
private _handleUnknownRouteRegistration(routeName: string, methodName: string, kept = "guard registered"): void {
|
|
727
|
+
if (this.getRoute(routeName)) return;
|
|
850
728
|
|
|
851
729
|
switch (this._options.unknownRouteRegistration) {
|
|
852
730
|
case "ignore":
|
|
853
|
-
return
|
|
731
|
+
return;
|
|
854
732
|
case "throw":
|
|
855
733
|
throw new Error(
|
|
856
734
|
`${methodName} called for unknown route "${routeName}". ` +
|
|
857
735
|
`Set guardRouter.unknownRouteRegistration to "warn" or "ignore" to allow this.`,
|
|
858
736
|
);
|
|
859
737
|
case "warn":
|
|
860
|
-
|
|
861
|
-
Log.warning(`${methodName}: unknown route, guard registered anyway`, routeName, LOG_COMPONENT);
|
|
862
|
-
return true;
|
|
738
|
+
Log.warning(`${methodName}: unknown route, ${kept} anyway`, routeName, LOG_COMPONENT);
|
|
863
739
|
}
|
|
864
740
|
}
|
|
865
741
|
|
|
@@ -877,8 +753,6 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
877
753
|
return this;
|
|
878
754
|
}
|
|
879
755
|
|
|
880
|
-
private static readonly _EMPTY_META: Readonly<Record<string, unknown>> = Object.freeze({});
|
|
881
|
-
|
|
882
756
|
/**
|
|
883
757
|
* Return the resolved metadata for a route.
|
|
884
758
|
*
|
|
@@ -898,28 +772,9 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
898
772
|
// Empty string is a valid root route name (initial state before first navigation)
|
|
899
773
|
if (routeName !== "" && !this.getRoute(routeName)) {
|
|
900
774
|
Log.warning("getRouteMeta: unknown route, returning empty metadata", routeName, LOG_COMPONENT);
|
|
901
|
-
return
|
|
775
|
+
return EMPTY_META;
|
|
902
776
|
}
|
|
903
|
-
|
|
904
|
-
// Cache hit
|
|
905
|
-
const cached = this._resolvedMetaCache.get(routeName);
|
|
906
|
-
if (cached) return cached;
|
|
907
|
-
|
|
908
|
-
let result: Readonly<Record<string, unknown>>;
|
|
909
|
-
|
|
910
|
-
if (this._options.inheritance === "pattern-tree") {
|
|
911
|
-
result = this._resolveInheritedMeta(routeName);
|
|
912
|
-
} else {
|
|
913
|
-
result = this._resolveFlatMeta(routeName);
|
|
914
|
-
}
|
|
915
|
-
|
|
916
|
-
if (Object.keys(result).length === 0) {
|
|
917
|
-
this._resolvedMetaCache.set(routeName, Router._EMPTY_META);
|
|
918
|
-
return Router._EMPTY_META;
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
this._resolvedMetaCache.set(routeName, result);
|
|
922
|
-
return result;
|
|
777
|
+
return this._meta.get(routeName);
|
|
923
778
|
}
|
|
924
779
|
|
|
925
780
|
/**
|
|
@@ -941,11 +796,8 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
941
796
|
Log.warning("setRouteMeta: expected object, ignoring", routeName, LOG_COMPONENT);
|
|
942
797
|
return this;
|
|
943
798
|
}
|
|
944
|
-
if (routeName !== ""
|
|
945
|
-
|
|
946
|
-
}
|
|
947
|
-
this._runtimeMeta.set(routeName, Object.freeze({ ...meta }));
|
|
948
|
-
this._resolvedMetaCache.clear();
|
|
799
|
+
if (routeName !== "") this._handleUnknownRouteRegistration(routeName, "setRouteMeta", "metadata stored");
|
|
800
|
+
this._meta.set(routeName, meta);
|
|
949
801
|
return this;
|
|
950
802
|
}
|
|
951
803
|
|
|
@@ -957,13 +809,13 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
957
809
|
* settlement result. Before any navigation has settled, it falls back to a
|
|
958
810
|
* synthetic `Committed` result derived from the router's current route/hash
|
|
959
811
|
* state. After `stop()`, that idle fallback reports empty route/hash values
|
|
960
|
-
* until a new navigation settles.
|
|
812
|
+
* until a new navigation settles, or `initialize(true)` resumes the route.
|
|
961
813
|
*
|
|
962
814
|
* @returns Promise that resolves with a {@link NavigationResult} once the pipeline settles.
|
|
963
815
|
* @since 1.2.0
|
|
964
816
|
*/
|
|
965
817
|
navigationSettled(): Promise<NavigationResult> {
|
|
966
|
-
if (this._phase.kind
|
|
818
|
+
if (this._phase.kind === "idle" || this._phase.kind === "committing") {
|
|
967
819
|
return Promise.resolve(
|
|
968
820
|
this._lastSettlement ?? {
|
|
969
821
|
status: NavigationOutcome.Committed,
|
|
@@ -996,14 +848,13 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
996
848
|
oListener?: object,
|
|
997
849
|
): this;
|
|
998
850
|
attachNavigationSettled(fnFunction: (evt: Router$NavigationSettledEvent) => void, oListener?: object): this;
|
|
999
|
-
attachNavigationSettled(
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
);
|
|
1006
|
-
return this;
|
|
851
|
+
attachNavigationSettled(
|
|
852
|
+
oData: object,
|
|
853
|
+
fnFunction: (evt: Router$NavigationSettledEvent) => void,
|
|
854
|
+
oListener?: object,
|
|
855
|
+
): this {
|
|
856
|
+
// The arguments go on as received: EventProvider#attachEvent tells the two call forms apart.
|
|
857
|
+
return this.attachEvent("navigationSettled", oData, fnFunction, oListener);
|
|
1007
858
|
}
|
|
1008
859
|
|
|
1009
860
|
/**
|
|
@@ -1017,7 +868,7 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1017
868
|
* @since 1.3.0
|
|
1018
869
|
*/
|
|
1019
870
|
detachNavigationSettled(fnFunction: (evt: Router$NavigationSettledEvent) => void, oListener?: object): this {
|
|
1020
|
-
this.detachEvent("navigationSettled", fnFunction
|
|
871
|
+
this.detachEvent("navigationSettled", fnFunction, oListener);
|
|
1021
872
|
return this;
|
|
1022
873
|
}
|
|
1023
874
|
|
|
@@ -1027,12 +878,21 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1027
878
|
*/
|
|
1028
879
|
private _flushSettlement(result: NavigationResult): void {
|
|
1029
880
|
this._lastSettlement = result;
|
|
881
|
+
Log.debug(`Navigation settled: ${result.status}`, result.hash, LOG_COMPONENT);
|
|
882
|
+
// After the call that settled: by then a commit has reached super.parse(), and a navigation
|
|
883
|
+
// that supersedes this one has started.
|
|
884
|
+
queueMicrotask(() => this._settleMatchWaiters());
|
|
1030
885
|
const resolvers = this._settlementResolvers;
|
|
1031
886
|
this._settlementResolvers = [];
|
|
1032
887
|
for (const resolve of resolvers) {
|
|
1033
888
|
resolve(result);
|
|
1034
889
|
}
|
|
1035
|
-
|
|
890
|
+
try {
|
|
891
|
+
this.fireEvent("navigationSettled", result);
|
|
892
|
+
} catch (error) {
|
|
893
|
+
// A handler must not keep the router from finishing the navigation it reports.
|
|
894
|
+
Log.error("A navigationSettled handler threw", String(error), LOG_COMPONENT);
|
|
895
|
+
}
|
|
1036
896
|
}
|
|
1037
897
|
|
|
1038
898
|
/**
|
|
@@ -1041,12 +901,13 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1041
901
|
* For programmatic navigation, guards run BEFORE the hash changes.
|
|
1042
902
|
* This prevents history pollution: blocked navigations never push a
|
|
1043
903
|
* history entry, and redirected navigations go directly to the final
|
|
1044
|
-
* target.
|
|
904
|
+
* target, which is written the way this call asked for (`bReplace`).
|
|
1045
905
|
*
|
|
1046
|
-
*
|
|
1047
|
-
*
|
|
1048
|
-
*
|
|
1049
|
-
*
|
|
906
|
+
* A `navTo()` to the committed hash changes no route of this router, so
|
|
907
|
+
* no guard runs: any pending navigation is cancelled and the call goes
|
|
908
|
+
* to the native `navTo()`, which sets or resets the hashes of nested
|
|
909
|
+
* components (`componentTargetInfo`). If the target matches the
|
|
910
|
+
* in-flight attempt's hash, the in-flight preflight continues undisturbed.
|
|
1050
911
|
*
|
|
1051
912
|
* When all guards are synchronous, the decision and the resulting
|
|
1052
913
|
* hash change happen in the same tick. When any guard returns a
|
|
@@ -1055,7 +916,23 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1055
916
|
*
|
|
1056
917
|
* Assumes `super.navTo()` calls `HashChanger.setHash()` which fires
|
|
1057
918
|
* `hashChanged` synchronously, causing `parse()` to re-enter in the
|
|
1058
|
-
* same call stack (validated by test).
|
|
919
|
+
* same call stack (validated by test). If the hash changer refuses the
|
|
920
|
+
* hash change, as the Fiori launchpad's navigation filter does when its
|
|
921
|
+
* dirty-state check stops it, nothing is committed and the navigation
|
|
922
|
+
* settles as `Blocked`.
|
|
923
|
+
*
|
|
924
|
+
* With component targets (`componentTargetInfo`) UI5 writes the hash
|
|
925
|
+
* later, once the nested components are loaded. The navigation commits
|
|
926
|
+
* and settles when `parse()` receives that hash. Until then it is
|
|
927
|
+
* pending: a navigation that supersedes it, `stop()` or `destroy()`
|
|
928
|
+
* settles it as `Cancelled`. That also ends a navigation whose hash UI5
|
|
929
|
+
* never writes, because a nested component failed to load or the router
|
|
930
|
+
* is not async.
|
|
931
|
+
*
|
|
932
|
+
* On a router that is not initialized (before `initialize()`, while
|
|
933
|
+
* block-mode guard modules load, after `stop()`) the call goes straight
|
|
934
|
+
* to the native `navTo()`, which only sets the hash or does nothing when
|
|
935
|
+
* stopped. The guards run when the router starts and parses the hash.
|
|
1059
936
|
*
|
|
1060
937
|
* @override sap.ui.core.routing.Router#navTo
|
|
1061
938
|
* @since 1.0.1
|
|
@@ -1095,74 +972,89 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1095
972
|
return this;
|
|
1096
973
|
}
|
|
1097
974
|
|
|
1098
|
-
//
|
|
1099
|
-
//
|
|
975
|
+
// A router that does not listen to hash changes (not initialized, loading block-mode
|
|
976
|
+
// guards, or stopped) navigates like the native one: the guards run once it parses the hash.
|
|
977
|
+
if (!this.isInitialized()) {
|
|
978
|
+
super.navTo(routeName, parameters, componentTargetInfo, replace);
|
|
979
|
+
return this;
|
|
980
|
+
}
|
|
981
|
+
|
|
1100
982
|
const route = this.getRoute(routeName);
|
|
1101
983
|
if (!route) {
|
|
1102
|
-
// Unknown route -- let parent handle it (
|
|
984
|
+
// Unknown route -- let the parent handle it (it logs a warning).
|
|
1103
985
|
// Cancel any pending async navigation so settlement resolvers drain
|
|
1104
986
|
// and the stale pipeline does not commit a superseded navigation.
|
|
1105
|
-
this._cancelPendingNavigation();
|
|
987
|
+
this._cancelPendingNavigation(true);
|
|
1106
988
|
super.navTo(routeName, parameters, componentTargetInfo, replace);
|
|
1107
989
|
return this;
|
|
1108
990
|
}
|
|
1109
991
|
|
|
1110
992
|
const targetHash = route.getURL(parameters ?? {});
|
|
1111
|
-
const routeInfo = this.
|
|
1112
|
-
const toRoute = routeInfo
|
|
1113
|
-
|
|
1114
|
-
// Same
|
|
1115
|
-
|
|
1116
|
-
|
|
993
|
+
const routeInfo = this._matchRoute(targetHash);
|
|
994
|
+
const toRoute = routeInfo.name;
|
|
995
|
+
|
|
996
|
+
// Same hash: no route of this router changes, so there is nothing to guard. Cancel any
|
|
997
|
+
// pending navigation and navigate natively: UI5 still sets the hashes of nested
|
|
998
|
+
// components (componentTargetInfo), or resets them when none are given.
|
|
999
|
+
if (targetHash === this._currentHash) {
|
|
1000
|
+
this._cancelPendingNavigation(true);
|
|
1001
|
+
// A navigationSettled handler of the cancelled navigation may have navigated on.
|
|
1002
|
+
const shownHash: string | undefined = this.getHashChanger().getHash();
|
|
1003
|
+
if (shownHash === undefined || shownHash === targetHash) {
|
|
1004
|
+
// If UI5 has reset the hash of the hash changer, after a target was displayed without
|
|
1005
|
+
// a route, it reports the hash again, and parse() lets the route match again.
|
|
1006
|
+
super.navTo(routeName, parameters, componentTargetInfo, replace);
|
|
1007
|
+
}
|
|
1117
1008
|
return this;
|
|
1118
1009
|
}
|
|
1119
1010
|
|
|
1011
|
+
const skipGuards = guardOptions?.skipGuards === true || this._options.navToPreflight === "bypass";
|
|
1012
|
+
|
|
1120
1013
|
// Pending-hash dedup: if an async preflight for this exact hash is
|
|
1121
|
-
// already running, don't cancel and restart it.
|
|
1122
|
-
|
|
1014
|
+
// already running, don't cancel and restart it. A navigation that skips
|
|
1015
|
+
// the guards does not wait for them.
|
|
1016
|
+
if (!skipGuards && this._phase.kind === "evaluating" && targetHash === this._phase.attempt.hash) {
|
|
1123
1017
|
return this;
|
|
1124
1018
|
}
|
|
1125
1019
|
|
|
1126
|
-
//
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
const skipGuards = guardOptions?.skipGuards === true;
|
|
1130
|
-
|
|
1131
|
-
// Bypass mode: skip guards for programmatic navTo() -- commit directly.
|
|
1132
|
-
if (skipGuards || this._options.navToPreflight === "bypass") {
|
|
1133
|
-
this._phase = { kind: "committing", hash: targetHash, route: toRoute, origin: "preflight" };
|
|
1020
|
+
// parse() evaluates the guards once the hash has changed. It supersedes a pending
|
|
1021
|
+
// navigation then, and undoes the hash change of that navigation with its own.
|
|
1022
|
+
if (!skipGuards && this._options.navToPreflight === "off") {
|
|
1134
1023
|
super.navTo(routeName, parameters, componentTargetInfo, replace);
|
|
1135
|
-
// Safety: if super.navTo didn't trigger parse (e.g. hash didn't change),
|
|
1136
|
-
// clear the marker to avoid stale state.
|
|
1137
|
-
if (this._phase.kind === "committing" && this._phase.hash === targetHash) {
|
|
1138
|
-
this._commitNavigation(targetHash, toRoute);
|
|
1139
|
-
}
|
|
1140
1024
|
return this;
|
|
1141
1025
|
}
|
|
1142
1026
|
|
|
1143
|
-
//
|
|
1144
|
-
|
|
1145
|
-
|
|
1027
|
+
// Cancel any pending navigation (including previous async preflight).
|
|
1028
|
+
// A superseded hash-change navigation leaves its hash in the URL: restore it
|
|
1029
|
+
// unless this navigation moves the URL.
|
|
1030
|
+
const restoreHash = this._pendingRestoresHash();
|
|
1031
|
+
this._cancelPendingNavigation();
|
|
1032
|
+
|
|
1033
|
+
if (skipGuards) {
|
|
1034
|
+
this._navigateAllowed(
|
|
1035
|
+
routeName,
|
|
1036
|
+
parameters,
|
|
1037
|
+
componentTargetInfo,
|
|
1038
|
+
replace,
|
|
1039
|
+
targetHash,
|
|
1040
|
+
toRoute,
|
|
1041
|
+
restoreHash,
|
|
1042
|
+
);
|
|
1146
1043
|
return this;
|
|
1147
1044
|
}
|
|
1148
1045
|
|
|
1149
|
-
|
|
1150
|
-
const
|
|
1151
|
-
const generation = this._parseGeneration;
|
|
1152
|
-
|
|
1153
|
-
this._phase = {
|
|
1154
|
-
kind: "evaluating",
|
|
1155
|
-
attempt: { hash: targetHash, route: toRoute, controller, generation },
|
|
1156
|
-
};
|
|
1046
|
+
const attempt = this._startAttempt(targetHash, restoreHash);
|
|
1047
|
+
const { generation } = attempt;
|
|
1157
1048
|
|
|
1158
|
-
const context = this._createGuardContext(
|
|
1049
|
+
const context = this._createGuardContext(routeInfo, targetHash, attempt.controller.signal);
|
|
1159
1050
|
|
|
1160
|
-
const decision = this.
|
|
1051
|
+
const decision = this._evaluateGuards(context);
|
|
1161
1052
|
|
|
1162
1053
|
if (isPromiseLike(decision)) {
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1054
|
+
this._applyWhenDecided(
|
|
1055
|
+
decision,
|
|
1056
|
+
(d) => {
|
|
1057
|
+
if (generation !== this._parseGeneration) {
|
|
1166
1058
|
Log.debug(
|
|
1167
1059
|
"Async preflight result discarded (superseded by newer navigation)",
|
|
1168
1060
|
targetHash,
|
|
@@ -1179,24 +1071,15 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1179
1071
|
targetHash,
|
|
1180
1072
|
toRoute,
|
|
1181
1073
|
context.bag,
|
|
1074
|
+
attempt,
|
|
1182
1075
|
);
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
// settlement resolvers via _errorNavigation.
|
|
1188
|
-
if (generation !== this._parseGeneration) return;
|
|
1189
|
-
Log.error(
|
|
1190
|
-
`Async preflight guard failed for route "${routeName}", navigation failed`,
|
|
1191
|
-
String(error),
|
|
1192
|
-
LOG_COMPONENT,
|
|
1193
|
-
);
|
|
1194
|
-
this._errorNavigation(error, targetHash, false);
|
|
1195
|
-
});
|
|
1076
|
+
},
|
|
1077
|
+
targetHash,
|
|
1078
|
+
restoreHash,
|
|
1079
|
+
);
|
|
1196
1080
|
return this;
|
|
1197
1081
|
}
|
|
1198
1082
|
|
|
1199
|
-
// Sync path: apply the decision immediately.
|
|
1200
1083
|
this._applyPreflightDecision(
|
|
1201
1084
|
decision,
|
|
1202
1085
|
routeName,
|
|
@@ -1206,23 +1089,51 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1206
1089
|
targetHash,
|
|
1207
1090
|
toRoute,
|
|
1208
1091
|
context.bag,
|
|
1092
|
+
attempt,
|
|
1209
1093
|
);
|
|
1210
1094
|
return this;
|
|
1211
1095
|
}
|
|
1212
1096
|
|
|
1097
|
+
/**
|
|
1098
|
+
* Navigate to a `navTo()` target that needs no guards (allowed or bypassed) and commit it,
|
|
1099
|
+
* or block it if the hash change was refused (see {@link _commitAfterNavTo}).
|
|
1100
|
+
*/
|
|
1101
|
+
private _navigateAllowed(
|
|
1102
|
+
routeName: string,
|
|
1103
|
+
parameters: object | undefined,
|
|
1104
|
+
componentTargetInfo: Record<string, ComponentTargetParameters> | undefined,
|
|
1105
|
+
bReplace: boolean | undefined,
|
|
1106
|
+
targetHash: string,
|
|
1107
|
+
toRoute: string,
|
|
1108
|
+
restoreHash: boolean,
|
|
1109
|
+
): void {
|
|
1110
|
+
this._phase = {
|
|
1111
|
+
kind: "committing",
|
|
1112
|
+
route: toRoute,
|
|
1113
|
+
hash: targetHash,
|
|
1114
|
+
origin: "preflight",
|
|
1115
|
+
restoreHash,
|
|
1116
|
+
writtenOver: HashChanger.getInstance().getHash(),
|
|
1117
|
+
};
|
|
1118
|
+
try {
|
|
1119
|
+
super.navTo(routeName, parameters, componentTargetInfo, bReplace);
|
|
1120
|
+
if (!this._commitAfterNavTo(componentTargetInfo)) {
|
|
1121
|
+
this._blockNavigation(targetHash, restoreHash);
|
|
1122
|
+
}
|
|
1123
|
+
} finally {
|
|
1124
|
+
// A failed hash change must not leave the next one to be committed without guards.
|
|
1125
|
+
if (this._phase.kind === "committing") {
|
|
1126
|
+
this._phase = IDLE;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1213
1131
|
/**
|
|
1214
1132
|
* Apply a preflight guard decision. For "allow", enter the committing
|
|
1215
|
-
* phase and call super.navTo(). For "block", flush settlement
|
|
1216
|
-
*
|
|
1133
|
+
* phase and call super.navTo(). For "block", flush settlement; the hash is
|
|
1134
|
+
* only touched to restore it after a superseded hash-change navigation.
|
|
1135
|
+
* For "redirect", start a redirect chain.
|
|
1217
1136
|
* For "error", flush Error settlement with the guard's error.
|
|
1218
|
-
*
|
|
1219
|
-
* @param decision - Normalized guard pipeline result.
|
|
1220
|
-
* @param routeName - Original route name passed to navTo().
|
|
1221
|
-
* @param parameters - Original route parameters.
|
|
1222
|
-
* @param componentTargetInfo - Optional component target info from the navTo() overload.
|
|
1223
|
-
* @param bReplace - Whether to replace the current history entry.
|
|
1224
|
-
* @param targetHash - Resolved hash for the target route.
|
|
1225
|
-
* @param toRoute - Resolved route name (may differ from routeName for nested routes).
|
|
1226
1137
|
*/
|
|
1227
1138
|
private _applyPreflightDecision(
|
|
1228
1139
|
decision: GuardDecision,
|
|
@@ -1233,26 +1144,30 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1233
1144
|
targetHash: string,
|
|
1234
1145
|
toRoute: string,
|
|
1235
1146
|
bag: Map<string, unknown>,
|
|
1147
|
+
attempt: NavigationAttempt,
|
|
1236
1148
|
): void {
|
|
1149
|
+
// A guard that navigated itself has superseded the navigation it was guarding.
|
|
1150
|
+
if (attempt.generation !== this._parseGeneration) return;
|
|
1237
1151
|
switch (decision.action) {
|
|
1238
1152
|
case "allow":
|
|
1239
|
-
this.
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1153
|
+
this._navigateAllowed(
|
|
1154
|
+
routeName,
|
|
1155
|
+
parameters,
|
|
1156
|
+
componentTargetInfo,
|
|
1157
|
+
bReplace,
|
|
1158
|
+
targetHash,
|
|
1159
|
+
toRoute,
|
|
1160
|
+
attempt.restoreHash,
|
|
1161
|
+
);
|
|
1247
1162
|
break;
|
|
1248
1163
|
case "block":
|
|
1249
|
-
this._blockNavigation(targetHash,
|
|
1164
|
+
this._blockNavigation(targetHash, attempt.restoreHash);
|
|
1250
1165
|
break;
|
|
1251
1166
|
case "redirect":
|
|
1252
|
-
this._startRedirectChain(decision.target, targetHash,
|
|
1167
|
+
this._startRedirectChain(decision.target, targetHash, bag, attempt, bReplace);
|
|
1253
1168
|
break;
|
|
1254
1169
|
case "error":
|
|
1255
|
-
this._errorNavigation(decision.error, targetHash,
|
|
1170
|
+
this._errorNavigation(decision.error, targetHash, attempt.restoreHash);
|
|
1256
1171
|
break;
|
|
1257
1172
|
}
|
|
1258
1173
|
}
|
|
@@ -1271,48 +1186,82 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1271
1186
|
* @since 1.0.1
|
|
1272
1187
|
*/
|
|
1273
1188
|
override parse(newHash: string): void {
|
|
1274
|
-
if (this.
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1189
|
+
if (this._destroyed) {
|
|
1190
|
+
// The base router only warns about a hash change that reaches a destroyed router.
|
|
1191
|
+
super.parse(newHash);
|
|
1192
|
+
return;
|
|
1193
|
+
}
|
|
1194
|
+
const reported = this._reportedHash === newHash;
|
|
1195
|
+
this._reportedHash = null;
|
|
1196
|
+
// The URL shows a later hash, which this router has parsed.
|
|
1197
|
+
if (reported && this._reportOutdated) return;
|
|
1198
|
+
// The hash that _restoreHash() is writing.
|
|
1199
|
+
if (newHash === this._suppressedHash) return;
|
|
1200
|
+
|
|
1201
|
+
const undo = this._undo;
|
|
1202
|
+
if (undo?.started && undo.fullHash === HashChanger.getInstance().getHash()) {
|
|
1203
|
+
// The URL is back where the router has put it (see _undoHashChange), so nothing is
|
|
1204
|
+
// evaluated. What the hash changer reports now is the hash of the route that is shown.
|
|
1205
|
+
this._undo = null;
|
|
1206
|
+
this._currentHash = newHash;
|
|
1207
|
+
this._finishRestore(newHash);
|
|
1208
|
+
return;
|
|
1280
1209
|
}
|
|
1281
1210
|
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
);
|
|
1211
|
+
const phase = this._phase;
|
|
1212
|
+
const commit = phase.kind === "awaitingHash" ? phase.commit : phase.kind === "committing" ? phase : null;
|
|
1213
|
+
if (commit?.hash === newHash) {
|
|
1214
|
+
this._phase = commit;
|
|
1215
|
+
this._commitNavigation(newHash, commit.route);
|
|
1287
1216
|
return;
|
|
1288
1217
|
}
|
|
1289
1218
|
|
|
1290
|
-
|
|
1291
|
-
|
|
1219
|
+
const currentHash = this._currentHash;
|
|
1220
|
+
if (newHash === currentHash) {
|
|
1221
|
+
if (this._pendingRestoresHash()) {
|
|
1222
|
+
// The URL is back on the committed hash, whose route was never left. That ends the
|
|
1223
|
+
// navigation that had moved it away; one that waits for UI5 to write its hash goes on.
|
|
1224
|
+
if (this._phase.kind === "evaluating") this._cancelPendingNavigation();
|
|
1225
|
+
else this._undo = null;
|
|
1226
|
+
} else {
|
|
1227
|
+
// The committed hash is reported again, and its route matches again as it does
|
|
1228
|
+
// natively: UI5 has written the hash of a navigation with component targets, or has
|
|
1229
|
+
// reset the hash of the hash changer after a target was displayed without a route,
|
|
1230
|
+
// or parse() was called directly.
|
|
1231
|
+
super.parse(newHash);
|
|
1232
|
+
}
|
|
1292
1233
|
return;
|
|
1293
1234
|
}
|
|
1294
1235
|
|
|
1295
|
-
const routeInfo = this.
|
|
1296
|
-
const toRoute = routeInfo
|
|
1236
|
+
const routeInfo = this._matchRoute(newHash);
|
|
1237
|
+
const toRoute = routeInfo.name;
|
|
1297
1238
|
|
|
1239
|
+
// A pending navigation that has moved the URL as well leaves this one to undo both changes.
|
|
1240
|
+
const pendingUndo = this._pendingRestoresHash() ? undo : null;
|
|
1241
|
+
// The router is putting the URL back and gets another hash: that one is not undone as a
|
|
1242
|
+
// whole, so that an undo cannot cause the next one.
|
|
1243
|
+
const undoing = this._phase.kind === "restoring";
|
|
1298
1244
|
this._cancelPendingNavigation();
|
|
1245
|
+
// A navigationSettled handler that navigated on the cancellation has moved the URL on.
|
|
1246
|
+
if (this._currentHash !== currentHash) return;
|
|
1247
|
+
this._undo = undoing ? null : this._describeUndo(pendingUndo, reported);
|
|
1248
|
+
// Another listener of the hash change that navTo() caused has replaced the hash, before
|
|
1249
|
+
// this router received it: undoing this hash change undoes the one of navTo() as well.
|
|
1250
|
+
if (this._undo && commit === phase && !commit.restoreHash) this._undo.fullHash = commit.writtenOver;
|
|
1299
1251
|
|
|
1300
|
-
const
|
|
1301
|
-
const
|
|
1302
|
-
|
|
1303
|
-
this._phase = {
|
|
1304
|
-
kind: "evaluating",
|
|
1305
|
-
attempt: { hash: newHash, route: toRoute, controller, generation },
|
|
1306
|
-
};
|
|
1252
|
+
const direction = reported ? History.getInstance().getDirection() : undefined;
|
|
1253
|
+
const attempt = this._startAttempt(newHash, true, direction);
|
|
1254
|
+
const { generation } = attempt;
|
|
1307
1255
|
|
|
1308
|
-
const context = this._createGuardContext(
|
|
1256
|
+
const context = this._createGuardContext(routeInfo, newHash, attempt.controller.signal);
|
|
1309
1257
|
|
|
1310
|
-
const decision = this.
|
|
1258
|
+
const decision = this._evaluateGuards(context);
|
|
1311
1259
|
|
|
1312
1260
|
if (isPromiseLike(decision)) {
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1261
|
+
this._applyWhenDecided(
|
|
1262
|
+
decision,
|
|
1263
|
+
(d) => {
|
|
1264
|
+
if (generation !== this._parseGeneration) {
|
|
1316
1265
|
Log.debug(
|
|
1317
1266
|
"Async guard result discarded (superseded by newer navigation)",
|
|
1318
1267
|
newHash,
|
|
@@ -1320,24 +1269,15 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1320
1269
|
);
|
|
1321
1270
|
return;
|
|
1322
1271
|
}
|
|
1323
|
-
this._applyDecision(d, newHash, toRoute, context.bag);
|
|
1324
|
-
}
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
// settlement resolvers via _errorNavigation.
|
|
1329
|
-
if (generation !== this._parseGeneration) return;
|
|
1330
|
-
Log.error(
|
|
1331
|
-
`Guard pipeline failed for "${newHash}", navigation failed`,
|
|
1332
|
-
String(error),
|
|
1333
|
-
LOG_COMPONENT,
|
|
1334
|
-
);
|
|
1335
|
-
this._errorNavigation(error, newHash);
|
|
1336
|
-
});
|
|
1272
|
+
this._applyDecision(d, newHash, toRoute, context.bag, attempt);
|
|
1273
|
+
},
|
|
1274
|
+
newHash,
|
|
1275
|
+
true,
|
|
1276
|
+
);
|
|
1337
1277
|
return;
|
|
1338
1278
|
}
|
|
1339
1279
|
|
|
1340
|
-
this._applyDecision(decision, newHash, toRoute, context.bag);
|
|
1280
|
+
this._applyDecision(decision, newHash, toRoute, context.bag, attempt);
|
|
1341
1281
|
}
|
|
1342
1282
|
|
|
1343
1283
|
/**
|
|
@@ -1345,55 +1285,149 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1345
1285
|
*
|
|
1346
1286
|
* Resets `_currentRoute` and `_currentHash` so that a subsequent
|
|
1347
1287
|
* `initialize()` re-parses the current hash and fires `routeMatched`,
|
|
1348
|
-
* matching the native `sap.m.routing.Router` behavior.
|
|
1288
|
+
* matching the native `sap.m.routing.Router` behavior. The route is
|
|
1289
|
+
* kept for `initialize(true)`, which resumes it instead.
|
|
1349
1290
|
*
|
|
1350
1291
|
* @override sap.ui.core.routing.Router#stop
|
|
1351
1292
|
* @since 1.0.1
|
|
1352
1293
|
*/
|
|
1353
1294
|
override stop(): this {
|
|
1295
|
+
if (this._blockLoad) this._blockLoad.start = false;
|
|
1354
1296
|
// Cancel first so in-flight navigationSettled() resolvers receive the
|
|
1355
1297
|
// Cancelled result before _lastSettlement is cleared below.
|
|
1356
1298
|
this._cancelPendingNavigation();
|
|
1357
|
-
|
|
1299
|
+
// A hash change that was to put the URL back does not reach a stopped router.
|
|
1300
|
+
this._undo = null;
|
|
1301
|
+
// Nothing is committed on a router that is stopped already, or stops before its first navigation settles.
|
|
1302
|
+
if (this._currentHash !== null) this._stoppedRoute = this._currentRoute;
|
|
1358
1303
|
this._currentRoute = "";
|
|
1359
1304
|
this._currentHash = null;
|
|
1360
1305
|
this._lastSettlement = null;
|
|
1306
|
+
this._detachHashListeners();
|
|
1361
1307
|
super.stop();
|
|
1362
1308
|
return this;
|
|
1363
1309
|
}
|
|
1364
1310
|
|
|
1311
|
+
/** Detach what {@link _start} has attached. */
|
|
1312
|
+
private _detachHashListeners(): void {
|
|
1313
|
+
this.getHashChanger().detachEvent("hashChanged", this._onHashReported, this);
|
|
1314
|
+
// UI5 moves the listener along when the global hash changer is replaced.
|
|
1315
|
+
HashChanger.getInstance().detachEvent("hashChanged", this._onRootHashChanged, this);
|
|
1316
|
+
this._rootHashChanger = null;
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1365
1319
|
/**
|
|
1366
1320
|
* Invalidate any in-flight async guard work. Bumps the generation counter
|
|
1367
1321
|
* so pending `.then()` callbacks see they are stale, aborts the signal,
|
|
1368
|
-
* and transitions to idle.
|
|
1322
|
+
* and transitions to idle. A navigation that waits for its guards or for
|
|
1323
|
+
* its hash settles as `Cancelled`. With `restoreHash`, a cancelled hash-change
|
|
1324
|
+
* navigation also gets its hash restored: `navTo()` passes it when the
|
|
1325
|
+
* call itself will not move the URL.
|
|
1369
1326
|
*/
|
|
1370
|
-
private _cancelPendingNavigation(): void {
|
|
1327
|
+
private _cancelPendingNavigation(restoreHash = false): void {
|
|
1371
1328
|
++this._parseGeneration;
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
status: NavigationOutcome.Cancelled,
|
|
1376
|
-
route: this._currentRoute,
|
|
1377
|
-
hash: this._currentHash ?? "",
|
|
1378
|
-
});
|
|
1379
|
-
}
|
|
1329
|
+
const phase = this._phase;
|
|
1330
|
+
const pendingRestoresHash = this._pendingRestoresHash();
|
|
1331
|
+
// Idle before the settlement fires, so that a handler can navigate.
|
|
1380
1332
|
this._phase = IDLE;
|
|
1333
|
+
// A navigation that is committing ends with the navigation that supersedes it.
|
|
1334
|
+
if (phase.kind === "idle" || phase.kind === "committing") return;
|
|
1335
|
+
if (phase.kind === "restoring") {
|
|
1336
|
+
// A navigation that waits for the URL to be back has ended already: it settles as it ended.
|
|
1337
|
+
this._flushSettlement(phase.result);
|
|
1338
|
+
return;
|
|
1339
|
+
}
|
|
1340
|
+
if (phase.kind === "evaluating") phase.attempt.controller.abort();
|
|
1341
|
+
this._settleUncommitted(
|
|
1342
|
+
{ status: NavigationOutcome.Cancelled, route: this._currentRoute, hash: this._currentHash ?? "" },
|
|
1343
|
+
phase.kind === "evaluating" ? phase.attempt.hash : phase.commit.hash,
|
|
1344
|
+
restoreHash && pendingRestoresHash,
|
|
1345
|
+
);
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/**
|
|
1349
|
+
* Whether the pending navigation leaves a hash in the URL that never committed, the one of a
|
|
1350
|
+
* hash-change navigation: it must be restored unless a navigation moves the URL.
|
|
1351
|
+
*/
|
|
1352
|
+
private _pendingRestoresHash(): boolean {
|
|
1353
|
+
const phase = this._phase;
|
|
1354
|
+
if (phase.kind === "evaluating") return phase.attempt.restoreHash;
|
|
1355
|
+
if (phase.kind === "committing") return phase.restoreHash;
|
|
1356
|
+
return phase.kind === "awaitingHash" && phase.commit.restoreHash;
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
/**
|
|
1360
|
+
* Start evaluating a navigation. Its generation is its own, so the result of any earlier
|
|
1361
|
+
* attempt is stale: also one that a navigationSettled handler started while this
|
|
1362
|
+
* navigation cancelled its predecessor, which is aborted here without a settlement.
|
|
1363
|
+
*/
|
|
1364
|
+
private _startAttempt(hash: string, restoreHash: boolean, direction?: Direction): NavigationAttempt {
|
|
1365
|
+
if (this._phase.kind === "evaluating") this._phase.attempt.controller.abort();
|
|
1366
|
+
const attempt: NavigationAttempt = {
|
|
1367
|
+
hash,
|
|
1368
|
+
controller: new AbortController(),
|
|
1369
|
+
generation: ++this._parseGeneration,
|
|
1370
|
+
restoreHash,
|
|
1371
|
+
direction,
|
|
1372
|
+
};
|
|
1373
|
+
this._phase = { kind: "evaluating", attempt };
|
|
1374
|
+
return attempt;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
/**
|
|
1378
|
+
* Apply the decision of async guards once it is there. Until then the navigation is postponed,
|
|
1379
|
+
* which UI5 sees as a route match in progress (see {@link _mirrorMatchingProcess}). The pipeline
|
|
1380
|
+
* turns a failing guard into an error decision, so an error thrown here comes from applying the
|
|
1381
|
+
* decision, which has no caller to throw to: it is logged, and fails the navigation unless that
|
|
1382
|
+
* has settled.
|
|
1383
|
+
*/
|
|
1384
|
+
private _applyWhenDecided(
|
|
1385
|
+
decision: PromiseLike<GuardDecision>,
|
|
1386
|
+
apply: (decision: GuardDecision) => void,
|
|
1387
|
+
attemptedHash: string | undefined,
|
|
1388
|
+
restoreHash: boolean,
|
|
1389
|
+
): void {
|
|
1390
|
+
if (this._phase.kind === "evaluating") this._phase = { ...this._phase, postponed: true };
|
|
1391
|
+
decision.then((d) => {
|
|
1392
|
+
const lastSettlement = this._lastSettlement;
|
|
1393
|
+
try {
|
|
1394
|
+
apply(d);
|
|
1395
|
+
} catch (error) {
|
|
1396
|
+
Log.error(
|
|
1397
|
+
"Navigation failed after its guards had settled",
|
|
1398
|
+
error instanceof Error ? error : String(error),
|
|
1399
|
+
LOG_COMPONENT,
|
|
1400
|
+
);
|
|
1401
|
+
if (this._lastSettlement === lastSettlement) {
|
|
1402
|
+
this._errorNavigation(error, attemptedHash, restoreHash);
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
});
|
|
1381
1406
|
}
|
|
1382
1407
|
|
|
1383
1408
|
/**
|
|
1384
1409
|
* Apply a guard decision for the parse() fallback path.
|
|
1385
1410
|
*/
|
|
1386
|
-
private _applyDecision(
|
|
1411
|
+
private _applyDecision(
|
|
1412
|
+
decision: GuardDecision,
|
|
1413
|
+
hash: string,
|
|
1414
|
+
route: string,
|
|
1415
|
+
bag: Map<string, unknown>,
|
|
1416
|
+
attempt: NavigationAttempt,
|
|
1417
|
+
): void {
|
|
1418
|
+
// A guard that navigated itself has superseded the navigation it was guarding.
|
|
1419
|
+
if (attempt.generation !== this._parseGeneration) return;
|
|
1387
1420
|
switch (decision.action) {
|
|
1388
1421
|
case "allow":
|
|
1389
|
-
this._phase = { kind: "committing",
|
|
1422
|
+
this._phase = { kind: "committing", route, hash, origin: "parse", restoreHash: false };
|
|
1390
1423
|
this._commitNavigation(hash, route);
|
|
1391
1424
|
break;
|
|
1392
1425
|
case "block":
|
|
1393
1426
|
this._blockNavigation(hash);
|
|
1394
1427
|
break;
|
|
1395
1428
|
case "redirect":
|
|
1396
|
-
|
|
1429
|
+
// The hash that redirects has reached the browser: the target takes its history entry.
|
|
1430
|
+
this._startRedirectChain(decision.target, hash, bag, attempt, true);
|
|
1397
1431
|
break;
|
|
1398
1432
|
case "error":
|
|
1399
1433
|
this._errorNavigation(decision.error, hash);
|
|
@@ -1401,17 +1435,45 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1401
1435
|
}
|
|
1402
1436
|
}
|
|
1403
1437
|
|
|
1438
|
+
/**
|
|
1439
|
+
* Leave the title history of UI5 (`getTitleHistory()`) as after the native equivalent of a
|
|
1440
|
+
* redirected hash change: the hash change, then `navTo(target, ..., true)`. The route of the
|
|
1441
|
+
* hash change never matched, so UI5 has not handled its title:
|
|
1442
|
+
* - A new entry or a step forward would have added a title, which the title of the target
|
|
1443
|
+
* replaces: UI5 must not remove the title of the route before it.
|
|
1444
|
+
* - A step back would have removed the title of the route that was left, so that the target
|
|
1445
|
+
* replaces the title of the entry the step arrived at: UI5 removes the first for the
|
|
1446
|
+
* replaced hash, the router removes the second, under the condition of UI5 for a step back.
|
|
1447
|
+
*/
|
|
1448
|
+
private _alignTitleHistory(direction: Direction | undefined): void {
|
|
1449
|
+
if (direction === HistoryDirection.NewEntry || direction === HistoryDirection.Forwards) {
|
|
1450
|
+
Reflect.set(this, "_bLastHashReplaced", false);
|
|
1451
|
+
} else if (direction === HistoryDirection.Backwards) {
|
|
1452
|
+
const titles: unknown[] = this.getTitleHistory();
|
|
1453
|
+
const left = titles.at(-1);
|
|
1454
|
+
const replaced = titles.at(-2);
|
|
1455
|
+
if (isRecord(left) && isRecord(replaced) && !left.isHome && left.title !== replaced.title) {
|
|
1456
|
+
titles.splice(-2, 1);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1404
1461
|
/**
|
|
1405
1462
|
* Delegate to the parent router and update internal state.
|
|
1406
1463
|
*
|
|
1407
1464
|
* State is updated BEFORE calling parse to ensure that if event handlers
|
|
1408
1465
|
* (e.g., routeMatched) trigger nested navigation, the leave guards will
|
|
1409
|
-
* run for the correct (new) route rather than the old one.
|
|
1466
|
+
* run for the correct (new) route rather than the old one. The settlement
|
|
1467
|
+
* fires before parse as well, so the settlements of such nested navigations
|
|
1468
|
+
* follow it.
|
|
1410
1469
|
*/
|
|
1411
|
-
private _commitNavigation(hash: string, route
|
|
1470
|
+
private _commitNavigation(hash: string, route: string): void {
|
|
1412
1471
|
const wasRedirect = this._phase.kind === "committing" && this._phase.origin === "redirect";
|
|
1472
|
+
if (this._phase.kind === "committing") this._alignTitleHistory(this._phase.direction);
|
|
1473
|
+
// The URL has moved on: a hash change that was to put it back is not awaited any more.
|
|
1474
|
+
this._undo = null;
|
|
1413
1475
|
this._currentHash = hash;
|
|
1414
|
-
this._currentRoute = route
|
|
1476
|
+
this._currentRoute = route;
|
|
1415
1477
|
// Transition to idle before super.parse so that routeMatched/patternMatched
|
|
1416
1478
|
// handlers that call navTo() go through the full guard pipeline.
|
|
1417
1479
|
this._phase = IDLE;
|
|
@@ -1424,14 +1486,39 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1424
1486
|
route: this._currentRoute,
|
|
1425
1487
|
hash,
|
|
1426
1488
|
});
|
|
1489
|
+
// A navigationSettled handler that navigated on has committed its own hash.
|
|
1490
|
+
if (this._currentHash !== hash) return;
|
|
1427
1491
|
super.parse(hash);
|
|
1428
1492
|
}
|
|
1429
1493
|
|
|
1494
|
+
/**
|
|
1495
|
+
* Commit the navigation of the committing phase after `super.navTo()` unless `parse()` has
|
|
1496
|
+
* committed it. Returns whether the navigation takes place:
|
|
1497
|
+
* - The hash changer shows the target hash: the route matches here.
|
|
1498
|
+
* - UI5 writes the hash later, which it does with component targets, once the nested
|
|
1499
|
+
* components are loaded. The navigation waits for it: it commits, and the route matches,
|
|
1500
|
+
* when `parse()` gets that hash, as the route does natively. Committed here, the router
|
|
1501
|
+
* would be on a route that UI5 does not display if the hash is never written.
|
|
1502
|
+
* - Otherwise the hash changer has refused the hash change, as the Fiori launchpad does while
|
|
1503
|
+
* it asks the user about unsaved data. Nothing changed, so nothing is committed.
|
|
1504
|
+
*/
|
|
1505
|
+
private _commitAfterNavTo(componentTargetInfo: Record<string, ComponentTargetParameters> | undefined): boolean {
|
|
1506
|
+
const phase = this._phase;
|
|
1507
|
+
if (phase.kind !== "committing") return true;
|
|
1508
|
+
if (this.getHashChanger().getHash() === phase.hash) {
|
|
1509
|
+
this._commitNavigation(phase.hash, phase.route);
|
|
1510
|
+
return true;
|
|
1511
|
+
}
|
|
1512
|
+
if (!componentTargetInfo || Object.keys(componentTargetInfo).length === 0) return false;
|
|
1513
|
+
this._phase = { kind: "awaitingHash", commit: phase };
|
|
1514
|
+
return true;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1430
1517
|
/**
|
|
1431
1518
|
* Evaluate guards on a redirect target and apply the resulting decision.
|
|
1432
1519
|
*
|
|
1433
|
-
* Handles loop detection (visited-hash set +
|
|
1434
|
-
*
|
|
1520
|
+
* Handles the unknown-route block, loop detection (visited-hash set +
|
|
1521
|
+
* depth cap), sync/async guard evaluation, and recursive chaining when
|
|
1435
1522
|
* the target's guard itself returns a redirect. All hops in a chain
|
|
1436
1523
|
* share the same AbortSignal and generation counter from the original
|
|
1437
1524
|
* navigation so that a superseding navigation correctly discards
|
|
@@ -1442,19 +1529,30 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1442
1529
|
*/
|
|
1443
1530
|
private _redirect(target: string | GuardRedirect, chain: RedirectChainContext): void {
|
|
1444
1531
|
const targetName = typeof target === "string" ? target : target.route;
|
|
1445
|
-
let targetHash: string | null = null;
|
|
1446
|
-
const targetParameters = typeof target === "string" ? {} : (target.parameters ?? {});
|
|
1447
1532
|
const targetRoute = this.getRoute(targetName);
|
|
1448
|
-
if (targetRoute) {
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1533
|
+
if (!targetRoute) {
|
|
1534
|
+
Log.warning(
|
|
1535
|
+
`Guard redirect target "${targetName}" is not a known route, treating as blocked`,
|
|
1536
|
+
undefined,
|
|
1537
|
+
LOG_COMPONENT,
|
|
1538
|
+
);
|
|
1539
|
+
this._blockNavigation(chain.attemptedHash, chain.restoreHash);
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
let targetHash: string;
|
|
1543
|
+
try {
|
|
1544
|
+
targetHash = targetRoute.getURL(typeof target === "string" ? {} : (target.parameters ?? {}));
|
|
1545
|
+
} catch (error) {
|
|
1546
|
+
Log.error(
|
|
1547
|
+
`Guard redirect target "${targetName}" has no valid hash, navigation failed`,
|
|
1548
|
+
String(error),
|
|
1549
|
+
LOG_COMPONENT,
|
|
1550
|
+
);
|
|
1551
|
+
this._errorNavigation(error, chain.attemptedHash, chain.restoreHash);
|
|
1552
|
+
return;
|
|
1454
1553
|
}
|
|
1455
1554
|
|
|
1456
|
-
|
|
1457
|
-
if (targetHash !== null && chain.visited.has(targetHash)) {
|
|
1555
|
+
if (chain.visited.has(targetHash)) {
|
|
1458
1556
|
Log.error(
|
|
1459
1557
|
`Guard redirect loop detected: ${[...chain.visited, targetHash].join(" -> ")}`,
|
|
1460
1558
|
undefined,
|
|
@@ -1472,130 +1570,101 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1472
1570
|
this._blockNavigation(chain.attemptedHash, chain.restoreHash);
|
|
1473
1571
|
return;
|
|
1474
1572
|
}
|
|
1475
|
-
|
|
1476
|
-
chain.visited.add(targetHash);
|
|
1477
|
-
}
|
|
1478
|
-
|
|
1479
|
-
// If the target route doesn't exist or the hash couldn't be resolved,
|
|
1480
|
-
// attempt navTo (parent may fire bypassed) and fall back to blocked.
|
|
1481
|
-
if (targetHash === null) {
|
|
1482
|
-
const settlementBefore = this._lastSettlement;
|
|
1483
|
-
this._phase = { kind: "committing", hash: "", route: targetName, origin: "redirect" };
|
|
1484
|
-
try {
|
|
1485
|
-
if (typeof target === "string") {
|
|
1486
|
-
this.navTo(target, {}, {}, true);
|
|
1487
|
-
} else {
|
|
1488
|
-
this.navTo(target.route, target.parameters ?? {}, target.componentTargetInfo, true);
|
|
1489
|
-
}
|
|
1490
|
-
} finally {
|
|
1491
|
-
if (this._phase.kind === "committing") {
|
|
1492
|
-
this._phase = IDLE;
|
|
1493
|
-
}
|
|
1494
|
-
}
|
|
1495
|
-
if (this._lastSettlement === settlementBefore) {
|
|
1496
|
-
Log.warning(
|
|
1497
|
-
`Guard redirect target "${targetName}" did not produce a navigation, treating as blocked`,
|
|
1498
|
-
undefined,
|
|
1499
|
-
LOG_COMPONENT,
|
|
1500
|
-
);
|
|
1501
|
-
this._blockNavigation(chain.attemptedHash, chain.restoreHash);
|
|
1502
|
-
}
|
|
1503
|
-
return;
|
|
1504
|
-
}
|
|
1573
|
+
chain.visited.add(targetHash);
|
|
1505
1574
|
|
|
1506
|
-
|
|
1507
|
-
const
|
|
1508
|
-
|
|
1509
|
-
// Build guard context for the redirect target.
|
|
1510
|
-
const routeInfo = this.getRouteInfoByHash(resolvedHash);
|
|
1511
|
-
const context: GuardContext = {
|
|
1512
|
-
toRoute: routeInfo?.name ?? "",
|
|
1513
|
-
toHash: resolvedHash,
|
|
1514
|
-
toArguments: routeInfo?.arguments ?? {},
|
|
1515
|
-
fromRoute: chain.fromRoute,
|
|
1516
|
-
fromHash: chain.fromHash,
|
|
1517
|
-
signal: chain.signal,
|
|
1518
|
-
bag: chain.bag,
|
|
1519
|
-
toMeta: this.getRouteMeta(routeInfo?.name ?? ""),
|
|
1520
|
-
fromMeta: this.getRouteMeta(chain.fromRoute),
|
|
1521
|
-
};
|
|
1575
|
+
const routeInfo = this._matchRoute(targetHash);
|
|
1576
|
+
const toRoute = routeInfo.name;
|
|
1577
|
+
const context = this._createGuardContext(routeInfo, targetHash, chain.signal, chain);
|
|
1522
1578
|
|
|
1523
|
-
const decision = this.
|
|
1579
|
+
const decision = this._evaluateGuards(context, true);
|
|
1524
1580
|
|
|
1525
1581
|
if (isPromiseLike(decision)) {
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
if (chain.generation !== this._parseGeneration) return;
|
|
1533
|
-
Log.error(
|
|
1534
|
-
`Guard pipeline failed during redirect chain for "${targetName}", navigation failed`,
|
|
1535
|
-
String(error),
|
|
1536
|
-
LOG_COMPONENT,
|
|
1537
|
-
);
|
|
1538
|
-
this._errorNavigation(error, chain.attemptedHash, chain.restoreHash);
|
|
1539
|
-
});
|
|
1582
|
+
this._applyWhenDecided(
|
|
1583
|
+
decision,
|
|
1584
|
+
(d) => this._applyRedirectDecision(d, target, targetHash, toRoute, chain),
|
|
1585
|
+
chain.attemptedHash,
|
|
1586
|
+
chain.restoreHash,
|
|
1587
|
+
);
|
|
1540
1588
|
return;
|
|
1541
1589
|
}
|
|
1542
1590
|
|
|
1543
|
-
this._applyRedirectDecision(decision, target,
|
|
1591
|
+
this._applyRedirectDecision(decision, target, targetHash, toRoute, chain);
|
|
1544
1592
|
}
|
|
1545
1593
|
|
|
1546
1594
|
/**
|
|
1547
1595
|
* Apply a guard decision within a redirect chain. For "allow", enter
|
|
1548
|
-
* committing phase and delegate to navTo (which hits the existing bypass)
|
|
1596
|
+
* committing phase and delegate to navTo (which hits the existing bypass);
|
|
1597
|
+
* if that does not reach parse(), commit the target directly. A target that
|
|
1598
|
+
* is displayed already settles the navigation without a commit.
|
|
1549
1599
|
* For "block", block the entire chain. For "redirect", recurse.
|
|
1550
1600
|
*
|
|
1551
1601
|
* @param decision - Normalized guard pipeline result for this hop.
|
|
1552
1602
|
* @param target - The redirect target (route name or {@link GuardRedirect}).
|
|
1553
|
-
* @param targetHash - Resolved hash for the redirect target
|
|
1603
|
+
* @param targetHash - Resolved hash for the redirect target.
|
|
1604
|
+
* @param toRoute - Route that matches the hash, as in the hop's guard context: the route UI5 displays.
|
|
1554
1605
|
* @param chain - Shared redirect chain context with visited set, signals, etc.
|
|
1555
1606
|
*/
|
|
1556
1607
|
private _applyRedirectDecision(
|
|
1557
1608
|
decision: GuardDecision,
|
|
1558
1609
|
target: string | GuardRedirect,
|
|
1559
1610
|
targetHash: string,
|
|
1611
|
+
toRoute: string,
|
|
1560
1612
|
chain: RedirectChainContext,
|
|
1561
1613
|
): void {
|
|
1614
|
+
// Superseded while the hop's guards ran: by a newer navigation, or by a guard that navigated.
|
|
1615
|
+
if (chain.generation !== this._parseGeneration) return;
|
|
1562
1616
|
switch (decision.action) {
|
|
1563
1617
|
case "allow": {
|
|
1564
|
-
const
|
|
1565
|
-
|
|
1566
|
-
|
|
1618
|
+
const componentTargetInfo = typeof target === "string" ? undefined : target.componentTargetInfo;
|
|
1619
|
+
if (targetHash === this._currentHash) {
|
|
1620
|
+
// The target is displayed already, so no route matches again, as for a navTo() to
|
|
1621
|
+
// the committed hash: the URL is put back and UI5 sets the hashes of nested components.
|
|
1622
|
+
this._phase = IDLE;
|
|
1623
|
+
this._settleUncommitted(
|
|
1624
|
+
{ status: NavigationOutcome.Redirected, route: this._currentRoute, hash: targetHash },
|
|
1625
|
+
chain.attemptedHash,
|
|
1626
|
+
chain.restoreHash,
|
|
1627
|
+
typeof target !== "string" && componentTargetInfo
|
|
1628
|
+
? () => {
|
|
1629
|
+
// Unless a settlement handler has moved the URL on.
|
|
1630
|
+
if (this.getHashChanger().getHash() !== targetHash) return;
|
|
1631
|
+
super.navTo(
|
|
1632
|
+
target.route,
|
|
1633
|
+
target.parameters ?? {},
|
|
1634
|
+
componentTargetInfo,
|
|
1635
|
+
chain.replace,
|
|
1636
|
+
);
|
|
1637
|
+
}
|
|
1638
|
+
: undefined,
|
|
1639
|
+
);
|
|
1640
|
+
break;
|
|
1641
|
+
}
|
|
1642
|
+
this._phase = {
|
|
1643
|
+
kind: "committing",
|
|
1644
|
+
route: toRoute,
|
|
1645
|
+
hash: targetHash,
|
|
1646
|
+
origin: "redirect",
|
|
1647
|
+
direction: chain.direction,
|
|
1648
|
+
restoreHash: chain.restoreHash,
|
|
1649
|
+
writtenOver: HashChanger.getInstance().getHash(),
|
|
1650
|
+
};
|
|
1567
1651
|
try {
|
|
1652
|
+
// Writing the hash the URL already shows changes nothing, except that a nested
|
|
1653
|
+
// router would add its prefix for an empty hash (see _restoreHash).
|
|
1654
|
+
const hashShown = this.getHashChanger().getHash() === targetHash;
|
|
1568
1655
|
if (typeof target === "string") {
|
|
1569
|
-
this.navTo(target, {}, {},
|
|
1570
|
-
} else {
|
|
1571
|
-
this.navTo(target.route, target.parameters ?? {},
|
|
1656
|
+
if (!hashShown) this.navTo(target, {}, {}, chain.replace);
|
|
1657
|
+
} else if (!hashShown || componentTargetInfo) {
|
|
1658
|
+
this.navTo(target.route, target.parameters ?? {}, componentTargetInfo, chain.replace);
|
|
1659
|
+
}
|
|
1660
|
+
if (!this._commitAfterNavTo(componentTargetInfo)) {
|
|
1661
|
+
this._blockNavigation(chain.attemptedHash, chain.restoreHash);
|
|
1572
1662
|
}
|
|
1573
1663
|
} finally {
|
|
1574
1664
|
if (this._phase.kind === "committing") {
|
|
1575
1665
|
this._phase = IDLE;
|
|
1576
1666
|
}
|
|
1577
1667
|
}
|
|
1578
|
-
// Safety net: if navTo didn't produce a settlement (e.g. unknown route
|
|
1579
|
-
// or redirect to current hash where HashChanger doesn't fire), handle it.
|
|
1580
|
-
if (this._lastSettlement === settlementBefore) {
|
|
1581
|
-
const redirectsToCurrentHash = targetHash === (this._currentHash ?? "");
|
|
1582
|
-
if (redirectsToCurrentHash) {
|
|
1583
|
-
this._phase = {
|
|
1584
|
-
kind: "committing",
|
|
1585
|
-
hash: this._currentHash ?? "",
|
|
1586
|
-
route: this._currentRoute,
|
|
1587
|
-
origin: "redirect",
|
|
1588
|
-
};
|
|
1589
|
-
this._commitNavigation(this._currentHash ?? "", this._currentRoute);
|
|
1590
|
-
return;
|
|
1591
|
-
}
|
|
1592
|
-
Log.warning(
|
|
1593
|
-
`Guard redirect target "${targetName}" did not produce a navigation, treating as blocked`,
|
|
1594
|
-
undefined,
|
|
1595
|
-
LOG_COMPONENT,
|
|
1596
|
-
);
|
|
1597
|
-
this._blockNavigation(chain.attemptedHash, chain.restoreHash);
|
|
1598
|
-
}
|
|
1599
1668
|
break;
|
|
1600
1669
|
}
|
|
1601
1670
|
case "block":
|
|
@@ -1610,31 +1679,59 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1610
1679
|
}
|
|
1611
1680
|
}
|
|
1612
1681
|
|
|
1682
|
+
/** The route that matches a hash, and its arguments. For a hash that no route matches: no route (`""`), no arguments. */
|
|
1683
|
+
private _matchRoute(hash: string): RouteInfo {
|
|
1684
|
+
const info = this.getRouteInfoByHash(hash);
|
|
1685
|
+
return { name: info?.name ?? "", arguments: info?.arguments ?? {} };
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
/**
|
|
1689
|
+
* The greedy routes that match `hash` in addition to `firstMatch`, the first route that
|
|
1690
|
+
* matches it. UI5 matches them as well and fires their events.
|
|
1691
|
+
*/
|
|
1692
|
+
private _greedyMatches(hash: string, firstMatch: string): string[] {
|
|
1693
|
+
return this._greedyRouteNames.filter((name) => name !== firstMatch && this.getRoute(name)?.match(hash));
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
/**
|
|
1697
|
+
* Evaluate the guards of a navigation: of the routes in its context, and of the greedy routes
|
|
1698
|
+
* that are left and entered with them. A hop of a redirect chain leaves no route.
|
|
1699
|
+
*/
|
|
1700
|
+
private _evaluateGuards(context: GuardContext, redirectHop = false): GuardDecision | Promise<GuardDecision> {
|
|
1701
|
+
return this._pipeline.evaluate(context, {
|
|
1702
|
+
skipLeaveGuards: redirectHop,
|
|
1703
|
+
alsoLeaving: this._greedyMatches(context.fromHash, context.fromRoute),
|
|
1704
|
+
alsoEntering: this._greedyMatches(context.toHash, context.toRoute),
|
|
1705
|
+
});
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1613
1708
|
/**
|
|
1614
|
-
* Build
|
|
1615
|
-
*
|
|
1709
|
+
* Build the guard context of a navigation to `routeInfo`. A hop of a redirect chain passes the
|
|
1710
|
+
* chain, whose source route, source hash and bag are those of the original navigation.
|
|
1616
1711
|
*/
|
|
1617
1712
|
private _createGuardContext(
|
|
1618
|
-
|
|
1713
|
+
routeInfo: RouteInfo,
|
|
1619
1714
|
toHash: string,
|
|
1620
|
-
routeInfo: { arguments: Record<string, string | Record<string, string>> } | undefined,
|
|
1621
1715
|
signal: AbortSignal,
|
|
1716
|
+
chain?: RedirectChainContext,
|
|
1622
1717
|
): GuardContext {
|
|
1718
|
+
const fromRoute = chain ? chain.fromRoute : this._currentRoute;
|
|
1623
1719
|
return {
|
|
1624
|
-
toRoute,
|
|
1720
|
+
toRoute: routeInfo.name,
|
|
1625
1721
|
toHash,
|
|
1626
|
-
toArguments: routeInfo
|
|
1627
|
-
fromRoute
|
|
1628
|
-
fromHash: this._currentHash ?? "",
|
|
1722
|
+
toArguments: routeInfo.arguments,
|
|
1723
|
+
fromRoute,
|
|
1724
|
+
fromHash: chain ? chain.fromHash : (this._currentHash ?? ""),
|
|
1629
1725
|
signal,
|
|
1630
|
-
bag: new Map(),
|
|
1631
|
-
toMeta: this.getRouteMeta(
|
|
1632
|
-
fromMeta: this.getRouteMeta(
|
|
1726
|
+
bag: chain ? chain.bag : new Map<string, unknown>(),
|
|
1727
|
+
toMeta: this.getRouteMeta(routeInfo.name),
|
|
1728
|
+
fromMeta: this.getRouteMeta(fromRoute),
|
|
1729
|
+
ownerComponent: this._ownerComponent,
|
|
1633
1730
|
};
|
|
1634
1731
|
}
|
|
1635
1732
|
|
|
1636
1733
|
/**
|
|
1637
|
-
* Start a new redirect chain
|
|
1734
|
+
* Start a new redirect chain for the given evaluating attempt.
|
|
1638
1735
|
* Called by {@link _applyPreflightDecision} and {@link _applyDecision}
|
|
1639
1736
|
* when a guard returns a redirect. Delegates to {@link _redirect} with
|
|
1640
1737
|
* a fresh {@link RedirectChainContext}.
|
|
@@ -1642,16 +1739,18 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1642
1739
|
private _startRedirectChain(
|
|
1643
1740
|
target: string | GuardRedirect,
|
|
1644
1741
|
hash: string,
|
|
1645
|
-
restoreHash: boolean,
|
|
1646
1742
|
bag: Map<string, unknown>,
|
|
1743
|
+
attempt: NavigationAttempt,
|
|
1744
|
+
replace: boolean | undefined,
|
|
1647
1745
|
): void {
|
|
1648
|
-
const { attempt } = this._phase as PhaseEvaluating;
|
|
1649
1746
|
const visited = new Set<string>();
|
|
1650
1747
|
visited.add(hash);
|
|
1651
1748
|
this._redirect(target, {
|
|
1652
1749
|
visited,
|
|
1653
1750
|
attemptedHash: hash,
|
|
1654
|
-
restoreHash,
|
|
1751
|
+
restoreHash: attempt.restoreHash,
|
|
1752
|
+
replace,
|
|
1753
|
+
direction: attempt.direction,
|
|
1655
1754
|
fromRoute: this._currentRoute,
|
|
1656
1755
|
fromHash: this._currentHash ?? "",
|
|
1657
1756
|
signal: attempt.controller.signal,
|
|
@@ -1661,19 +1760,17 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1661
1760
|
}
|
|
1662
1761
|
|
|
1663
1762
|
/**
|
|
1664
|
-
*
|
|
1665
|
-
*
|
|
1666
|
-
*
|
|
1667
|
-
* never changed.
|
|
1763
|
+
* Settle as Blocked. With `restoreHash` (default), the hash change of the navigation is
|
|
1764
|
+
* undone first (see {@link _settleUncommitted}). Preflight callers pass false unless they
|
|
1765
|
+
* superseded a hash-change navigation: otherwise the hash was never changed.
|
|
1668
1766
|
*/
|
|
1669
1767
|
private _blockNavigation(attemptedHash?: string, restoreHash = true): void {
|
|
1670
1768
|
this._phase = IDLE;
|
|
1671
|
-
this.
|
|
1672
|
-
status: NavigationOutcome.Blocked,
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
this._restoreHashIfNeeded(attemptedHash, restoreHash);
|
|
1769
|
+
this._settleUncommitted(
|
|
1770
|
+
{ status: NavigationOutcome.Blocked, route: this._currentRoute, hash: this._currentHash ?? "" },
|
|
1771
|
+
attemptedHash,
|
|
1772
|
+
restoreHash,
|
|
1773
|
+
);
|
|
1677
1774
|
}
|
|
1678
1775
|
|
|
1679
1776
|
/**
|
|
@@ -1683,337 +1780,199 @@ export default class Router extends MobileRouter implements GuardRouter {
|
|
|
1683
1780
|
*/
|
|
1684
1781
|
private _errorNavigation(error: unknown, attemptedHash?: string, restoreHash = true): void {
|
|
1685
1782
|
this._phase = IDLE;
|
|
1686
|
-
this.
|
|
1687
|
-
status: NavigationOutcome.Error,
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
});
|
|
1692
|
-
this._restoreHashIfNeeded(attemptedHash, restoreHash);
|
|
1693
|
-
}
|
|
1694
|
-
|
|
1695
|
-
/** Conditionally restore the browser hash after a blocked or errored navigation. */
|
|
1696
|
-
private _restoreHashIfNeeded(attemptedHash: string | undefined, restoreHash: boolean): void {
|
|
1697
|
-
if (!restoreHash) return;
|
|
1698
|
-
if (this._currentHash === null && attemptedHash && attemptedHash !== "") {
|
|
1699
|
-
this._restoreHash("", false);
|
|
1700
|
-
return;
|
|
1701
|
-
}
|
|
1702
|
-
this._restoreHash(this._currentHash ?? "");
|
|
1783
|
+
this._settleUncommitted(
|
|
1784
|
+
{ status: NavigationOutcome.Error, route: this._currentRoute, hash: this._currentHash ?? "", error },
|
|
1785
|
+
attemptedHash,
|
|
1786
|
+
restoreHash,
|
|
1787
|
+
);
|
|
1703
1788
|
}
|
|
1704
1789
|
|
|
1705
1790
|
/**
|
|
1706
|
-
*
|
|
1707
|
-
*
|
|
1708
|
-
*
|
|
1709
|
-
*
|
|
1791
|
+
* Settle a navigation that did not commit. With `restoreHash`, the hash it left in the URL
|
|
1792
|
+
* is restored first, so that settlement handlers run on the final URL and a hash they set
|
|
1793
|
+
* is not overwritten. The exception is a first navigation: nothing is committed yet, so the
|
|
1794
|
+
* empty hash is restored after the settlement and parsed as a navigation of its own.
|
|
1795
|
+
* `whenBack` runs after the settlement.
|
|
1710
1796
|
*/
|
|
1711
|
-
private
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1797
|
+
private _settleUncommitted(
|
|
1798
|
+
result: NavigationResult,
|
|
1799
|
+
attemptedHash: string | undefined,
|
|
1800
|
+
restoreHash: boolean,
|
|
1801
|
+
whenBack?: () => void,
|
|
1802
|
+
): void {
|
|
1803
|
+
const loadDefaultRoute = restoreHash && this._currentHash === null && !!attemptedHash;
|
|
1804
|
+
// It settles once the URL is back.
|
|
1805
|
+
if (restoreHash && !loadDefaultRoute && !this._undoHashChange(result, whenBack)) return;
|
|
1806
|
+
this._flushSettlement(result);
|
|
1807
|
+
whenBack?.();
|
|
1808
|
+
// Unless a handler navigated and committed in the meantime.
|
|
1809
|
+
if (loadDefaultRoute && this._currentHash === null) this._restoreHash("", false);
|
|
1720
1810
|
}
|
|
1721
1811
|
|
|
1722
1812
|
/**
|
|
1723
|
-
*
|
|
1724
|
-
*
|
|
1813
|
+
* Describe how to undo the hash change that the navigation starts with. After `pending`, the
|
|
1814
|
+
* undo of a navigation that this one supersedes, it takes back both changes. A `parse()` that
|
|
1815
|
+
* is not `reported` by the hash changer comes with no hash change.
|
|
1725
1816
|
*/
|
|
1726
|
-
private
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1817
|
+
private _describeUndo(pending: HashChangeUndo | null, reported: boolean): HashChangeUndo | null {
|
|
1818
|
+
if (!reported) return pending;
|
|
1819
|
+
const shown = HashChanger.getInstance().getHash();
|
|
1820
|
+
const step = lastStep;
|
|
1821
|
+
if (!pending) return { first: shown, fullHash: undefined, shown, step, started: false };
|
|
1822
|
+
const offset = pending.step && step ? pending.step.offset + step.offset : 0;
|
|
1823
|
+
return {
|
|
1824
|
+
first: pending.first,
|
|
1825
|
+
fullHash: pending.fullHash,
|
|
1826
|
+
shown,
|
|
1827
|
+
step: step && offset ? { offset, href: step.href } : null,
|
|
1828
|
+
started: false,
|
|
1829
|
+
};
|
|
1738
1830
|
}
|
|
1739
1831
|
|
|
1740
1832
|
/**
|
|
1741
|
-
*
|
|
1742
|
-
*
|
|
1743
|
-
*
|
|
1744
|
-
*
|
|
1833
|
+
* Put the URL back after a navigation that did not commit. Returns whether it is back;
|
|
1834
|
+
* otherwise `result` settles when it is.
|
|
1835
|
+
*
|
|
1836
|
+
* While the URL still shows the hash change that started the navigation, that change is undone
|
|
1837
|
+
* as a whole, so that the hashes of nested routers are back as well:
|
|
1838
|
+
* - A step through the browser history is taken back, which leaves the history as it was.
|
|
1839
|
+
* The browser does that asynchronously.
|
|
1840
|
+
* - Any other change (a new entry, or a step the browser does not report) has its entry replaced with
|
|
1841
|
+
* the full previous hash, once UI5 has reported the change to every router. Nested routers
|
|
1842
|
+
* have received their part of the refused hash by then; they receive the previous one next.
|
|
1843
|
+
*
|
|
1844
|
+
* `parse()` ends the wait when the hash change arrives that shows the full previous hash.
|
|
1845
|
+
*
|
|
1846
|
+
* If the URL has moved on since, only the hash of this router is restored. So it is while
|
|
1847
|
+
* no navigation has committed: the URL before the change showed no route of this router either.
|
|
1745
1848
|
*/
|
|
1746
|
-
private
|
|
1747
|
-
const
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
const expanded: GuardDescriptor[] = [];
|
|
1754
|
-
|
|
1755
|
-
for (const descriptor of descriptors) {
|
|
1756
|
-
expanded.push(descriptor);
|
|
1757
|
-
|
|
1758
|
-
// Global guards and routes without a known pattern are not expanded
|
|
1759
|
-
if (descriptor.route === "*") continue;
|
|
1760
|
-
const ancestorPattern = patternByName.get(descriptor.route);
|
|
1761
|
-
if (ancestorPattern === undefined) continue;
|
|
1762
|
-
|
|
1763
|
-
// Find descendant routes whose pattern extends the ancestor's pattern
|
|
1764
|
-
for (const { name, pattern } of allRoutes) {
|
|
1765
|
-
if (name === descriptor.route) continue;
|
|
1766
|
-
if (isPatternAncestor(ancestorPattern, pattern)) {
|
|
1767
|
-
expanded.push({ ...descriptor, route: name });
|
|
1768
|
-
}
|
|
1769
|
-
}
|
|
1849
|
+
private _undoHashChange(result: NavigationResult, whenBack?: () => void): boolean {
|
|
1850
|
+
const undo = this._undo;
|
|
1851
|
+
const hash = this._currentHash;
|
|
1852
|
+
const rootHash = HashChanger.getInstance().getHash();
|
|
1853
|
+
if (undo === null || hash === null || undo.shown !== rootHash || undo.fullHash === rootHash) {
|
|
1854
|
+
this._restoreHash(hash ?? "");
|
|
1855
|
+
return true;
|
|
1770
1856
|
}
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1857
|
+
const href = window.location.href;
|
|
1858
|
+
undo.started = true;
|
|
1859
|
+
this._phase = { kind: "restoring", result, whenBack };
|
|
1860
|
+
if (undoneHref === href) {
|
|
1861
|
+
// Another router is taking the step back.
|
|
1862
|
+
} else if (undo.step) {
|
|
1863
|
+
undoneHref = href;
|
|
1864
|
+
window.history.go(-undo.step.offset);
|
|
1865
|
+
} else if (undo.fullHash === undefined) {
|
|
1866
|
+
// UI5 is still reporting the change to the nested routers.
|
|
1867
|
+
this._phase = { ...this._phase, awaitsReport: true };
|
|
1868
|
+
} else {
|
|
1869
|
+
this._replaceFullHash(undo.fullHash);
|
|
1870
|
+
}
|
|
1871
|
+
return false;
|
|
1781
1872
|
}
|
|
1782
1873
|
|
|
1783
1874
|
/**
|
|
1784
|
-
*
|
|
1785
|
-
*
|
|
1875
|
+
* Replace the hash of the root hash changer with the full previous hash, and settle the
|
|
1876
|
+
* navigation that waits for it unless `parse()` has done so.
|
|
1786
1877
|
*/
|
|
1787
|
-
private
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
if (!manifest && !runtime) return Router._EMPTY_META;
|
|
1791
|
-
if (!runtime) return manifest!;
|
|
1792
|
-
if (!manifest) return runtime;
|
|
1793
|
-
return Object.freeze({ ...manifest, ...runtime });
|
|
1878
|
+
private _replaceFullHash(fullHash: string): void {
|
|
1879
|
+
HashChanger.getInstance().replaceHash(fullHash, HistoryDirection.Unknown);
|
|
1880
|
+
this._finishRestore();
|
|
1794
1881
|
}
|
|
1795
1882
|
|
|
1796
1883
|
/**
|
|
1797
|
-
*
|
|
1798
|
-
*
|
|
1799
|
-
* runtime metadata at each level, then overlays the route's own.
|
|
1884
|
+
* Settle the navigation that waited for the URL to be back: on `hash`, if the hash changer
|
|
1885
|
+
* has reported one with the URL.
|
|
1800
1886
|
*/
|
|
1801
|
-
private
|
|
1802
|
-
const
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
const ancestors = allRoutes.filter(
|
|
1808
|
-
(r) =>
|
|
1809
|
-
r.name !== routeName &&
|
|
1810
|
-
(this._manifestMeta.has(r.name) || this._runtimeMeta.has(r.name)) &&
|
|
1811
|
-
isPatternAncestor(r.pattern, routeEntry.pattern),
|
|
1812
|
-
);
|
|
1813
|
-
// oxlint-disable-next-line unicorn/no-array-sort -- ancestors is a fresh array from filter()
|
|
1814
|
-
ancestors.sort((a, b) => patternSegments(a.pattern).length - patternSegments(b.pattern).length);
|
|
1815
|
-
|
|
1816
|
-
// Merge shallowest-first: root ancestor -> deeper ancestors -> own manifest -> own runtime
|
|
1817
|
-
const merged: Record<string, unknown> = {};
|
|
1818
|
-
|
|
1819
|
-
for (const ancestor of ancestors) {
|
|
1820
|
-
const ancestorManifest = this._manifestMeta.get(ancestor.name);
|
|
1821
|
-
if (ancestorManifest) Object.assign(merged, ancestorManifest);
|
|
1822
|
-
const ancestorRuntime = this._runtimeMeta.get(ancestor.name);
|
|
1823
|
-
if (ancestorRuntime) Object.assign(merged, ancestorRuntime);
|
|
1824
|
-
}
|
|
1825
|
-
|
|
1826
|
-
const ownManifest = this._manifestMeta.get(routeName);
|
|
1827
|
-
if (ownManifest) Object.assign(merged, ownManifest);
|
|
1828
|
-
const ownRuntime = this._runtimeMeta.get(routeName);
|
|
1829
|
-
if (ownRuntime) Object.assign(merged, ownRuntime);
|
|
1830
|
-
|
|
1831
|
-
if (Object.keys(merged).length === 0) return Router._EMPTY_META;
|
|
1832
|
-
return Object.freeze(merged);
|
|
1887
|
+
private _finishRestore(hash?: string): void {
|
|
1888
|
+
const phase = this._phase;
|
|
1889
|
+
if (phase.kind !== "restoring") return;
|
|
1890
|
+
this._phase = IDLE;
|
|
1891
|
+
this._flushSettlement(hash === undefined ? phase.result : { ...phase.result, hash });
|
|
1892
|
+
phase.whenBack?.();
|
|
1833
1893
|
}
|
|
1834
1894
|
|
|
1835
1895
|
/**
|
|
1836
|
-
*
|
|
1837
|
-
*
|
|
1896
|
+
* Restore the previous hash of this router without creating a history entry
|
|
1897
|
+
* (see {@link _undoHashChange} for the hash change of a navigation).
|
|
1898
|
+
* Assumes replaceHash fires hashChanged synchronously (validated by test).
|
|
1899
|
+
* `_currentRoute` stays unchanged because the navigation never
|
|
1900
|
+
* committed. The user remains on the same logical route.
|
|
1838
1901
|
*
|
|
1839
|
-
*
|
|
1840
|
-
*
|
|
1841
|
-
*
|
|
1842
|
-
* register in declaration order. Registration errors (e.g. from
|
|
1843
|
-
* `unknownRouteRegistration: "throw"`) are caught per-module.
|
|
1902
|
+
* A hash that the hash changer already shows is not written again: the navigation never
|
|
1903
|
+
* moved it. For a nested router, writing its empty hash would add its prefix to the browser
|
|
1904
|
+
* hash (`shell` becomes `shell&/child/`).
|
|
1844
1905
|
*/
|
|
1845
|
-
private
|
|
1846
|
-
const
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
resolve({ descriptor, moduleExport });
|
|
1852
|
-
},
|
|
1853
|
-
(err: Error) => {
|
|
1854
|
-
Log.warning(
|
|
1855
|
-
`guardRouter.guards: failed to load module "${descriptor.modulePath}", skipping`,
|
|
1856
|
-
String(err),
|
|
1857
|
-
LOG_COMPONENT,
|
|
1858
|
-
);
|
|
1859
|
-
resolve({ descriptor, moduleExport: null });
|
|
1860
|
-
},
|
|
1861
|
-
);
|
|
1862
|
-
});
|
|
1863
|
-
});
|
|
1864
|
-
return Promise.all(promises).then((results) => {
|
|
1865
|
-
for (const { descriptor, moduleExport } of results) {
|
|
1866
|
-
if (moduleExport === null) continue;
|
|
1867
|
-
const exports = resolveModuleExports(
|
|
1868
|
-
moduleExport,
|
|
1869
|
-
descriptor.modulePath,
|
|
1870
|
-
descriptor.name,
|
|
1871
|
-
descriptor.exportKey,
|
|
1872
|
-
);
|
|
1873
|
-
for (const { fn } of exports) {
|
|
1874
|
-
try {
|
|
1875
|
-
this._registerGuardFromDescriptor(descriptor, fn);
|
|
1876
|
-
} catch (err: unknown) {
|
|
1877
|
-
Log.error(
|
|
1878
|
-
`guardRouter.guards: failed to register "${descriptor.modulePath}"`,
|
|
1879
|
-
String(err),
|
|
1880
|
-
LOG_COMPONENT,
|
|
1881
|
-
);
|
|
1882
|
-
}
|
|
1883
|
-
}
|
|
1884
|
-
}
|
|
1885
|
-
});
|
|
1906
|
+
private _restoreHash(hash: string, suppressParse = true): void {
|
|
1907
|
+
const hashChanger = this.getHashChanger();
|
|
1908
|
+
if (hashChanger.getHash() === hash) return;
|
|
1909
|
+
this._suppressedHash = suppressParse ? hash : null;
|
|
1910
|
+
void hashChanger.replaceHash(hash, HistoryDirection.Unknown);
|
|
1911
|
+
this._suppressedHash = null;
|
|
1886
1912
|
}
|
|
1887
1913
|
|
|
1888
1914
|
/**
|
|
1889
|
-
*
|
|
1915
|
+
* Collect all route names and their patterns from the router.
|
|
1916
|
+
* Skips routes whose pattern is undefined (no pattern configured).
|
|
1890
1917
|
*/
|
|
1891
|
-
private
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
if (
|
|
1896
|
-
this._pipeline.addLeaveGuard(descriptor.route, guardFn);
|
|
1897
|
-
} else {
|
|
1898
|
-
this.addRouteGuard(descriptor.route, guardFn);
|
|
1918
|
+
private _collectRoutePatterns(): RoutePattern[] {
|
|
1919
|
+
const result: RoutePattern[] = [];
|
|
1920
|
+
for (const name of this._routeNames) {
|
|
1921
|
+
const pattern = this.getRoute(name)?.getPattern();
|
|
1922
|
+
if (pattern !== undefined) result.push({ name, pattern });
|
|
1899
1923
|
}
|
|
1924
|
+
return result;
|
|
1900
1925
|
}
|
|
1901
1926
|
|
|
1902
1927
|
/**
|
|
1903
|
-
* Register
|
|
1904
|
-
*
|
|
1905
|
-
*
|
|
1906
|
-
*
|
|
1907
|
-
* cached (preload likely finished), all guards are expanded immediately.
|
|
1908
|
-
* On cache miss, a single "expander" wrapper loads the module on first
|
|
1909
|
-
* navigation, registers remaining guards, and executes the first.
|
|
1928
|
+
* Register one manifest guard: as the last guard of its route, or in front of the guard
|
|
1929
|
+
* `before`. A registration error (`unknownRouteRegistration: "throw"` for an unknown route)
|
|
1930
|
+
* is logged and skips the guard: no caller of the manifest config could catch it, and it
|
|
1931
|
+
* must not keep the router from starting.
|
|
1910
1932
|
*/
|
|
1911
|
-
private
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
// Cherry-picked: one lazy wrapper, resolves to exactly one guard
|
|
1917
|
-
const lazyGuard = (context: GuardContext): GuardResult | PromiseLike<GuardResult> => {
|
|
1918
|
-
const cached = sap.ui.require(modulePath) as unknown;
|
|
1919
|
-
if (cached !== undefined) {
|
|
1920
|
-
const exports = resolveModuleExports(cached, modulePath, name, exportKey);
|
|
1921
|
-
if (exports.length === 0) return true;
|
|
1922
|
-
return exports[0].fn(context);
|
|
1923
|
-
}
|
|
1924
|
-
return new Promise<GuardResult>((resolve, reject) => {
|
|
1925
|
-
sap.ui.require(
|
|
1926
|
-
[modulePath],
|
|
1927
|
-
(mod: unknown) => {
|
|
1928
|
-
const exports = resolveModuleExports(mod, modulePath, name, exportKey);
|
|
1929
|
-
if (exports.length === 0) {
|
|
1930
|
-
resolve(true);
|
|
1931
|
-
return;
|
|
1932
|
-
}
|
|
1933
|
-
resolve(exports[0].fn(context));
|
|
1934
|
-
},
|
|
1935
|
-
(err: Error) => {
|
|
1936
|
-
Log.warning(
|
|
1937
|
-
`guardRouter.guards: lazy load of "${modulePath}" failed`,
|
|
1938
|
-
String(err),
|
|
1939
|
-
LOG_COMPONENT,
|
|
1940
|
-
);
|
|
1941
|
-
reject(err);
|
|
1942
|
-
},
|
|
1943
|
-
);
|
|
1944
|
-
});
|
|
1945
|
-
};
|
|
1946
|
-
this._registerGuardFromDescriptor(descriptor, lazyGuard);
|
|
1947
|
-
continue;
|
|
1933
|
+
private _registerManifestGuard(descriptor: ManifestGuardDescriptor, guardFn: GuardFn, before?: GuardFn): void {
|
|
1934
|
+
try {
|
|
1935
|
+
if (descriptor.route === "*") {
|
|
1936
|
+
this.addGuard(guardFn);
|
|
1937
|
+
return;
|
|
1948
1938
|
}
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
this._registerGuardFromDescriptor(descriptor, exp.fn);
|
|
1956
|
-
}
|
|
1957
|
-
continue;
|
|
1939
|
+
if (descriptor.type === "leave") {
|
|
1940
|
+
this._handleUnknownRouteRegistration(descriptor.route, "addLeaveGuard");
|
|
1941
|
+
this._pipeline.addLeaveGuard(descriptor.route, guardFn, before);
|
|
1942
|
+
} else {
|
|
1943
|
+
this._handleUnknownRouteRegistration(descriptor.route, "addRouteGuard");
|
|
1944
|
+
this._pipeline.addEnterGuard(descriptor.route, guardFn, before);
|
|
1958
1945
|
}
|
|
1946
|
+
this._manifestGuards.push({ descriptor, fn: guardFn });
|
|
1947
|
+
} catch (err: unknown) {
|
|
1948
|
+
Log.error(`guardRouter.guards: failed to register "${descriptor.modulePath}"`, String(err), LOG_COMPONENT);
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1959
1951
|
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
// all guards occupy contiguous positions. In practice this is rare because
|
|
1965
|
-
// the preload hint fires in the constructor and modules are typically cached
|
|
1966
|
-
// by the time initialize() runs.
|
|
1967
|
-
let expanded = false;
|
|
1968
|
-
const lazyExpander = (context: GuardContext): PromiseLike<GuardResult> => {
|
|
1969
|
-
return new Promise<GuardResult>((resolve, reject) => {
|
|
1970
|
-
sap.ui.require(
|
|
1971
|
-
[modulePath],
|
|
1972
|
-
(mod: unknown) => {
|
|
1973
|
-
const exports = resolveModuleExports(mod, modulePath, name);
|
|
1974
|
-
if (exports.length === 0) {
|
|
1975
|
-
resolve(true);
|
|
1976
|
-
return;
|
|
1977
|
-
}
|
|
1978
|
-
if (!expanded) {
|
|
1979
|
-
expanded = true;
|
|
1980
|
-
for (let i = 1; i < exports.length; i++) {
|
|
1981
|
-
this._registerGuardFromDescriptor(descriptor, exports[i].fn);
|
|
1982
|
-
}
|
|
1983
|
-
}
|
|
1984
|
-
resolve(exports[0].fn(context));
|
|
1985
|
-
},
|
|
1986
|
-
(err: Error) => {
|
|
1987
|
-
Log.warning(
|
|
1988
|
-
`guardRouter.guards: lazy load of "${modulePath}" failed`,
|
|
1989
|
-
String(err),
|
|
1990
|
-
LOG_COMPONENT,
|
|
1991
|
-
);
|
|
1992
|
-
reject(err);
|
|
1993
|
-
},
|
|
1994
|
-
);
|
|
1995
|
-
});
|
|
1996
|
-
};
|
|
1997
|
-
this._registerGuardFromDescriptor(descriptor, lazyExpander);
|
|
1952
|
+
/** Register the guards of each descriptor, loading their modules on first use (see `createLazyGuards`). */
|
|
1953
|
+
private _registerLazyGuards(descriptors: ManifestGuardDescriptor[]): void {
|
|
1954
|
+
for (const descriptor of descriptors) {
|
|
1955
|
+
for (const fn of createLazyGuards(descriptor)) this._registerManifestGuard(descriptor, fn);
|
|
1998
1956
|
}
|
|
1999
1957
|
}
|
|
2000
1958
|
|
|
2001
1959
|
/**
|
|
2002
1960
|
* Clean up guards on destroy. Bumps generation to discard pending async results.
|
|
1961
|
+
* A second call does nothing, like `sap.ui.core.routing.Router#destroy`.
|
|
2003
1962
|
*
|
|
2004
1963
|
* @since 1.0.1
|
|
2005
1964
|
*/
|
|
2006
1965
|
override destroy(): this {
|
|
1966
|
+
if (this._destroyed) return this;
|
|
2007
1967
|
this._destroyed = true;
|
|
2008
1968
|
this._pipeline.clear();
|
|
2009
1969
|
this._pendingGuardDescriptors = [];
|
|
2010
1970
|
this._sourceDescriptors = [];
|
|
1971
|
+
this._manifestGuards = [];
|
|
2011
1972
|
this._cancelPendingNavigation();
|
|
2012
|
-
this._suppressedHash = null;
|
|
2013
1973
|
this._lastSettlement = null;
|
|
2014
|
-
this.
|
|
2015
|
-
this.
|
|
2016
|
-
this._resolvedMetaCache.clear();
|
|
1974
|
+
this._detachHashListeners();
|
|
1975
|
+
this._meta.clear();
|
|
2017
1976
|
super.destroy();
|
|
2018
1977
|
return this;
|
|
2019
1978
|
}
|