ui5-lib-guard-router 1.6.2 → 1.7.1
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 +197 -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 +125 -122
- 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 +900 -1033
- package/dist/resources/ui5/guard/router/Router-dbg.js.map +1 -1
- package/dist/resources/ui5/guard/router/Router.d.ts +362 -212
- 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 +158 -129
- package/src/NavigationOutcome.ts +3 -3
- package/src/PatternTree.ts +145 -0
- package/src/RouteMeta.ts +82 -0
- package/src/Router.ts +1110 -1150
- package/src/manifest.json +5 -2
- package/src/types.ts +79 -22
- package/tsconfig.json +0 -11
package/README.md
CHANGED
|
@@ -2,24 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
Drop-in replacement for `sap.m.routing.Router` that intercepts navigation **before** route matching, target loading, or view creation, preventing flashes of unauthorized content and polluted browser history.
|
|
4
4
|
|
|
5
|
-
> Born from [UI5/openui5#3411](https://github.com/UI5/openui5/issues/3411), an open request for native navigation guard support in UI5.
|
|
6
|
-
>
|
|
7
|
-
> **Related resources**:
|
|
8
|
-
>
|
|
9
|
-
> - [Stack Overflow: Preventing router from navigating](https://stackoverflow.com/questions/29165700/preventing-router-from-navigating/29167292#29167292) (native NavContainer `navigate` event, sync-only, fires after route match)
|
|
10
|
-
> - [Research: Native NavContainer navigate event](../../docs/research/native-router-navigate-event.md) (detailed comparison with this library)
|
|
5
|
+
> Born from [UI5/openui5#3411](https://github.com/UI5/openui5/issues/3411), an open request for native navigation guard support in UI5. The native alternative, the `NavContainer` `navigate` event, is sync-only and fires after the route match ([comparison](../../docs/research/native-router-navigate-event.md)).
|
|
11
6
|
|
|
12
7
|
> [!WARNING]
|
|
13
|
-
> This library is **experimental**. It is not battle-tested in production environments, and the API may change without notice.
|
|
8
|
+
> This library is **experimental**. It is not battle-tested in production environments, and the API may change without notice. Pin your version and review changes before upgrading.
|
|
14
9
|
|
|
15
10
|
> [!CAUTION]
|
|
16
|
-
> Navigation guards are a UX layer, not a security boundary. They
|
|
11
|
+
> Navigation guards are a UX layer, not a security boundary. They do **not** replace server-side authorization, backend validation, or service-level access control.
|
|
17
12
|
|
|
18
13
|
## Why
|
|
19
14
|
|
|
20
|
-
UI5's router
|
|
21
|
-
|
|
22
|
-
This library solves all three by intercepting at the router level, before any route matching begins.
|
|
15
|
+
UI5's router cannot block or redirect a navigation before views render. The usual workaround, guard logic in each controller's `attachPatternMatched` callback, flashes unauthorized content, pollutes the browser history and spreads the checks across controllers. This library runs the guards at the router level, before route matching. [Migrating from attachPatternMatched guards](../../docs/guides/migration-from-pattern-matched.md) shows the switch.
|
|
23
16
|
|
|
24
17
|
## Install
|
|
25
18
|
|
|
@@ -28,11 +21,11 @@ npm install ui5-lib-guard-router
|
|
|
28
21
|
```
|
|
29
22
|
|
|
30
23
|
> [!NOTE]
|
|
31
|
-
> The npm package is ~
|
|
24
|
+
> The npm package is ~280 KB compressed (~1.1 MB unpacked) because it ships the pre-built library (`dist/`) with its source maps and type declarations, and the TypeScript sources (`src/`) that the declaration maps point to. At runtime, the browser loads only the `library-preload.js` bundle (~36 KB, ~10 KB gzipped).
|
|
32
25
|
|
|
33
26
|
### TypeScript
|
|
34
27
|
|
|
35
|
-
|
|
28
|
+
If your app does not already depend on UI5 typings, install them (`@sapui5/types` works as well):
|
|
36
29
|
|
|
37
30
|
```bash
|
|
38
31
|
npm install -D @openui5/types
|
|
@@ -48,7 +41,7 @@ Add both packages to `compilerOptions.types`:
|
|
|
48
41
|
}
|
|
49
42
|
```
|
|
50
43
|
|
|
51
|
-
|
|
44
|
+
Import types from the UI5 module path:
|
|
52
45
|
|
|
53
46
|
```typescript
|
|
54
47
|
// Core: router interface and guard function signatures
|
|
@@ -67,57 +60,92 @@ import type { GuardRedirect, RouteGuardConfig } from "ui5/guard/router/types";
|
|
|
67
60
|
|
|
68
61
|
### Serving the library
|
|
69
62
|
|
|
70
|
-
The
|
|
63
|
+
`ui5 serve` (UI5 CLI v4 or later) serves the library from `node_modules` without configuration. The package carries a UI5 build manifest (`.ui5/build-manifest.json`) that tells UI5 Tooling to use the pre-built files in `dist/` as they are. `ui5 tree` lists `ui5.guard.router` among the dependencies. The source maps contain the TypeScript sources, so the browser debugger shows those.
|
|
71
64
|
|
|
72
|
-
|
|
65
|
+
When another middleware answers `/resources` before UI5 Tooling does, serve the files statically ahead of it. `fiori-tools-proxy` in Fiori tools projects, for example, forwards `/resources` to the UI5 CDN. With `fiori-tools-servestatic`, which Fiori tools projects already have:
|
|
73
66
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
67
|
+
```yaml
|
|
68
|
+
# ui5.yaml
|
|
69
|
+
server:
|
|
70
|
+
customMiddleware:
|
|
71
|
+
- name: fiori-tools-servestatic
|
|
72
|
+
beforeMiddleware: fiori-tools-proxy
|
|
73
|
+
configuration:
|
|
74
|
+
paths:
|
|
75
|
+
- path: /resources/ui5/guard/router
|
|
76
|
+
src: node_modules/ui5-lib-guard-router/dist/resources/ui5/guard/router
|
|
79
77
|
```
|
|
80
78
|
|
|
81
|
-
|
|
79
|
+
Outside Fiori tools, [`ui5-middleware-servestatic`](https://github.com/ui5-community/ui5-ecosystem-showcase/tree/main/packages/ui5-middleware-servestatic) does the same with `mountPath: /resources/ui5/guard/router` and `rootPath: node_modules/ui5-lib-guard-router/dist/resources/ui5/guard/router`.
|
|
82
80
|
|
|
83
|
-
|
|
81
|
+
### Building and deploying
|
|
84
82
|
|
|
85
|
-
|
|
83
|
+
`ui5 build` builds the app without its dependencies. Choose where the library lives at runtime:
|
|
86
84
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
85
|
+
| Setup | Library at runtime | Fits |
|
|
86
|
+
| ------------------------------------------------------ | --------------------------------------------- | -------------------------------------------- |
|
|
87
|
+
| [Deployed with the app](#deployed-with-the-app) | `resources/ui5/guard/router/` next to the app | Launchpad, SAP Build Work Zone, standalone |
|
|
88
|
+
| [In the app's preload](#in-the-apps-component-preload) | Inside `Component-preload.js` | The same, with one request less |
|
|
89
|
+
| [Self-contained](#self-contained-app) | Inside `sap-ui-custom.js`, together with UI5 | Standalone apps that ship their own UI5 |
|
|
90
|
+
| [Deployed on its own](#deployed-as-a-reuse-library) | A reuse library that several apps share | One library version for all apps on a system |
|
|
91
|
+
|
|
92
|
+
The first three keep each app on the library version it was built with, so updating the library means redeploying each app. The fourth updates in one place, at the cost of deployment configuration for the library.
|
|
93
|
+
|
|
94
|
+
#### Deployed with the app
|
|
95
|
+
|
|
96
|
+
Include the library in the build, in the `ui5.yaml` the build uses (or `ui5 build --include-dependency=ui5.guard.router`):
|
|
90
97
|
|
|
91
98
|
```yaml
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
afterMiddleware: compression
|
|
97
|
-
configuration:
|
|
98
|
-
transpileDependencies: true
|
|
99
|
+
builder:
|
|
100
|
+
settings:
|
|
101
|
+
includeDependency:
|
|
102
|
+
- ui5.guard.router
|
|
99
103
|
```
|
|
100
104
|
|
|
101
|
-
|
|
105
|
+
The build writes the library, with its `library-preload.js`, to `dist/resources/ui5/guard/router/`. When UI5 itself comes from somewhere else (a CDN, the launchpad), map the namespace to that folder in the app's `manifest.json`:
|
|
106
|
+
|
|
107
|
+
```json
|
|
108
|
+
{
|
|
109
|
+
"sap.ui5": {
|
|
110
|
+
"resourceRoots": {
|
|
111
|
+
"ui5.guard.router": "./resources/ui5/guard/router"
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
```
|
|
102
116
|
|
|
103
|
-
|
|
117
|
+
On SAP BTP, add the library to the archive with `includeDependencies: [ui5.guard.router]` in the `ui5-task-zipper` configuration. If `xs-app.json` routes `/resources` to the UI5 CDN, add a route before it that serves `^/resources/ui5/guard/router/(.*)$` from `html5-apps-repo-rt`. [Simplifying UI5 Library Use on BTP by Bundling Libraries at Build Time](https://community.sap.com/t5/technology-blog-posts-by-members/simplifying-ui5-library-use-on-btp-by-bundling-libraries-at-build-time/ba-p/14304012) walks through the complete setup.
|
|
104
118
|
|
|
105
|
-
|
|
119
|
+
#### In the app's Component-preload
|
|
106
120
|
|
|
107
|
-
|
|
108
|
-
npm install -D ui5-middleware-servestatic
|
|
109
|
-
```
|
|
121
|
+
A custom bundle that replaces `Component-preload.js` takes the library modules in with the app's. The app then needs neither `includeDependency` nor `resourceRoots`:
|
|
110
122
|
|
|
111
123
|
```yaml
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
124
|
+
builder:
|
|
125
|
+
bundles:
|
|
126
|
+
- bundleDefinition:
|
|
127
|
+
name: my/app/Component-preload.js
|
|
128
|
+
sections:
|
|
129
|
+
- mode: preload
|
|
130
|
+
filters:
|
|
131
|
+
- my/app/
|
|
132
|
+
- my/app/**/manifest.json
|
|
133
|
+
- ui5/guard/router/
|
|
134
|
+
resolve: false
|
|
135
|
+
bundleOptions:
|
|
136
|
+
optimize: true
|
|
119
137
|
```
|
|
120
138
|
|
|
139
|
+
Replace `my/app` with the namespace of the app. The filters replace those of the default component preload, so add any the app relied on.
|
|
140
|
+
|
|
141
|
+
#### Self-contained app
|
|
142
|
+
|
|
143
|
+
`ui5 build self-contained --all` bundles UI5, the app and the library into `resources/sap-ui-custom.js`. This is for apps that ship their own UI5, not for the launchpad.
|
|
144
|
+
|
|
145
|
+
#### Deployed as a reuse library
|
|
146
|
+
|
|
147
|
+
Deploy `node_modules/ui5-lib-guard-router/dist/resources/ui5/guard/router` once, as a reuse library: to the SAPUI5 ABAP repository, or to the HTML5 application repository on SAP BTP. Apps keep only the `libs` dependency in their manifest, and the launchpad resolves the library from where it is deployed. On SAP BTP, that takes a destination or a CDM content provider for the library; [the blog above](https://community.sap.com/t5/technology-blog-posts-by-members/simplifying-ui5-library-use-on-btp-by-bundling-libraries-at-build-time/ba-p/14304012) links the guides for both.
|
|
148
|
+
|
|
121
149
|
## Setup
|
|
122
150
|
|
|
123
151
|
**1. Add the library dependency and set the router class in your `manifest.json`:**
|
|
@@ -177,19 +205,120 @@ export default class Component extends UIComponent {
|
|
|
177
205
|
|
|
178
206
|
## How it works
|
|
179
207
|
|
|
180
|
-
The
|
|
208
|
+
The native chain of `sap.m.routing.Router` stays as it is; the library puts its guards in front of it.
|
|
209
|
+
|
|
210
|
+
```mermaid
|
|
211
|
+
---
|
|
212
|
+
config:
|
|
213
|
+
flowchart:
|
|
214
|
+
minNodeWidth: 60
|
|
215
|
+
wrappingWidth: 300
|
|
216
|
+
---
|
|
217
|
+
flowchart TD
|
|
218
|
+
bar["Address bar,<br/>back, forward:<br/>the browser<br/>changes the hash"]
|
|
219
|
+
shell["Fiori launchpad shell:<br/>passes only<br/>in-app hashes on"]
|
|
220
|
+
appCode["Application code<br/>calls navTo()"]
|
|
221
|
+
hash["Hash changer"]
|
|
222
|
+
|
|
223
|
+
subgraph added ["ui5.guard.router.Router (this library)"]
|
|
224
|
+
preflight["Preflight of navTo():<br/>before the hash changes"]
|
|
225
|
+
parse["Override of parse():<br/>after the hash changed"]
|
|
226
|
+
subgraph pipeline ["Guard pipeline"]
|
|
227
|
+
sources["Guards from the manifest<br/>and from addGuard(),<br/>addRouteGuard(),<br/>addLeaveGuard()"]
|
|
228
|
+
leave["1. Leave guards<br/>of the current route"]
|
|
229
|
+
global["2. Global enter guards"]
|
|
230
|
+
enter["3. Enter guards<br/>of the target route"]
|
|
231
|
+
leave --> global --> enter
|
|
232
|
+
end
|
|
233
|
+
commit("✓ All guards<br/>allow:<br/>commit")
|
|
234
|
+
redirect("↪ A guard names<br/>a route:<br/>redirect")
|
|
235
|
+
block("✕ A guard returns<br/>false:<br/>block")
|
|
236
|
+
error("⚠ A guard<br/>throws:<br/>error")
|
|
237
|
+
settled(["Event navigationSettled:<br/>Committed, Bypassed,<br/>Redirected, Blocked<br/>or Error"])
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
subgraph native ["sap.m.routing.Router (native): parse()"]
|
|
241
|
+
match["Route match"] --> target["Target"] --> view["View"]
|
|
242
|
+
nested["Nested component<br/>(target of type Component)"]
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
bar --> hash
|
|
246
|
+
shell -.-> hash
|
|
247
|
+
hash --> parse
|
|
248
|
+
appCode --> preflight
|
|
249
|
+
preflight --> leave
|
|
250
|
+
parse --> leave
|
|
251
|
+
sources -.-> leave
|
|
252
|
+
|
|
253
|
+
enter --> commit
|
|
254
|
+
enter --> redirect
|
|
255
|
+
enter --> block
|
|
256
|
+
enter --> error
|
|
257
|
+
commit ~~~ block
|
|
258
|
+
redirect ~~~ error
|
|
259
|
+
redirect -- "enter guards<br/>of the target" --> global
|
|
260
|
+
|
|
261
|
+
commit --> match
|
|
262
|
+
target -.-> nested
|
|
263
|
+
commit --> settled
|
|
264
|
+
block --> settled
|
|
265
|
+
error --> settled
|
|
266
|
+
|
|
267
|
+
classDef native fill:#6e7781,stroke:#424a53,color:#ffffff
|
|
268
|
+
classDef added fill:#0072B2,stroke:#56B4E9,stroke-width:3px,color:#ffffff
|
|
269
|
+
classDef optional fill:#afb8c1,stroke:#6e7781,stroke-dasharray:5 4,color:#1f2328
|
|
270
|
+
classDef commit fill:#009E73,stroke:#006b4e,stroke-width:3px,color:#000000
|
|
271
|
+
classDef redirect fill:#F0E442,stroke:#8a7f00,stroke-width:3px,color:#000000
|
|
272
|
+
classDef block fill:#D55E00,stroke:#8f3f00,stroke-width:3px,color:#000000
|
|
273
|
+
classDef error fill:#5c1a44,stroke:#CC79A7,stroke-width:3px,stroke-dasharray:6 3,color:#ffffff
|
|
274
|
+
class bar,appCode,hash,match,target,view native
|
|
275
|
+
class preflight,parse,sources,leave,global,enter,settled added
|
|
276
|
+
class shell,nested optional
|
|
277
|
+
class commit commit
|
|
278
|
+
class redirect redirect
|
|
279
|
+
class block block
|
|
280
|
+
class error error
|
|
281
|
+
style added fill:none,stroke:#0072B2,stroke-width:2px
|
|
282
|
+
style pipeline fill:none,stroke:#0072B2
|
|
283
|
+
style native fill:none,stroke:#6e7781,stroke-width:2px
|
|
284
|
+
|
|
285
|
+
subgraph parts ["Parts"]
|
|
286
|
+
direction LR
|
|
287
|
+
lNative["native UI5"] ~~~ lAdded["library"] ~~~ lOptional["optional"]
|
|
288
|
+
end
|
|
289
|
+
subgraph outcomes ["Outcomes"]
|
|
290
|
+
direction LR
|
|
291
|
+
lCommit("✓ commit") ~~~ lRedirect("↪ redirect") ~~~ lBlock("✕ block") ~~~ lError("⚠ error")
|
|
292
|
+
end
|
|
293
|
+
native ~~~ parts ~~~ outcomes
|
|
294
|
+
class lNative native
|
|
295
|
+
class lAdded added
|
|
296
|
+
class lOptional optional
|
|
297
|
+
class lCommit commit
|
|
298
|
+
class lRedirect redirect
|
|
299
|
+
class lBlock block
|
|
300
|
+
class lError error
|
|
301
|
+
style parts fill:none,stroke:none
|
|
302
|
+
style outcomes fill:none,stroke:none
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
A commit lets a `navTo()` write its hash and hands the hash to the native `parse()`. A block or an error undoes a hash that the browser changed. A redirect runs the enter guards of its target, without leave guards, for at most 10 hops. The guards of the manifest are the modules under `guards` in the `guardRouter` block.
|
|
306
|
+
|
|
307
|
+
A navigation that another one supersedes, or that `stop()` or `destroy()` ends, settles as `Cancelled`. For `destroy()` only the `navigationSettled()` promise resolves: no `navigationSettled` handler runs while the router is torn down.
|
|
181
308
|
|
|
182
|
-
|
|
183
|
-
- **`parse()` fallback**: For browser-initiated navigation (back/forward buttons, URL bar entry, direct hash changes), guards run inside the `parse()` override after the browser has already changed the hash. If a guard blocks or redirects, the router restores the previous hash via `replaceHash()`.
|
|
309
|
+
The two entry points run the same guards:
|
|
184
310
|
|
|
185
|
-
|
|
311
|
+
- **`navTo()` preflight**: guards run before the hash changes. A blocked `navTo()` writes no hash; a redirected one writes only its final target.
|
|
312
|
+
- **`parse()` fallback**: for back/forward, URL bar entries and direct hash changes, guards run after the browser has changed the hash. The router undoes a blocked hash change and replaces the entry of a redirected one with the target, see [Browser history](#browser-history).
|
|
186
313
|
|
|
187
|
-
|
|
314
|
+
Where no guard intervenes, `sap.m.routing.Router` behavior (targets, route events, `navTo`, back navigation) is unchanged, see [Compatibility with `sap.m.routing.Router`](#compatibility-with-sapmroutingrouter).
|
|
188
315
|
|
|
189
|
-
The
|
|
316
|
+
The pipeline stays **synchronous while guards return plain values**. From the first guard that returns a Promise, the rest of that navigation runs async; the next navigation starts synchronous again. Results of a superseded navigation are discarded, and each guard gets an `AbortSignal` to cancel async work such as `fetch`. The diagrams of each step are in the [architecture reference](../../docs/reference/architecture.md#two-entry-point-model-navto-preflight--parse-fallback).
|
|
190
317
|
|
|
191
318
|
## API
|
|
192
319
|
|
|
320
|
+
The public modules are `ui5/guard/router/Router`, `types`, `NavigationOutcome` and `library`. The other modules under `ui5/guard/router` are internal and may change in any release.
|
|
321
|
+
|
|
193
322
|
All guard registration and removal methods return `this` for chaining. `navigationSettled()` returns a `Promise<NavigationResult>`.
|
|
194
323
|
|
|
195
324
|
### Guard registration
|
|
@@ -210,7 +339,7 @@ All guard registration and removal methods return `this` for chaining. `navigati
|
|
|
210
339
|
| `removeRouteGuard(routeName, { beforeEnter?, beforeLeave? })` | Remove enter and/or leave guards via object form |
|
|
211
340
|
| `removeLeaveGuard(routeName, fn)` | Remove a leave guard |
|
|
212
341
|
|
|
213
|
-
### Route metadata
|
|
342
|
+
### Route metadata methods
|
|
214
343
|
|
|
215
344
|
| Method | Description |
|
|
216
345
|
| ------------------------------- | --------------------------------------------------------------------- |
|
|
@@ -219,44 +348,49 @@ All guard registration and removal methods return `this` for chaining. `navigati
|
|
|
219
348
|
|
|
220
349
|
### Unknown routes during registration
|
|
221
350
|
|
|
222
|
-
`addRouteGuard()` and `
|
|
351
|
+
With the default `unknownRouteRegistration: "warn"`, `addRouteGuard()`, `addLeaveGuard()` and `setRouteMeta()` warn when the route name is unknown at registration time, but still register, so guards can be attached before a dynamic `addRoute()`. `"ignore"` registers without a warning. `"throw"` makes these calls throw and registers nothing. A manifest guard on an unknown route cannot throw to a caller: with `"throw"` it is skipped and logged as `guardRouter.guards: failed to register "<module path>"`, and the router still starts.
|
|
223
352
|
|
|
224
353
|
### GuardContext
|
|
225
354
|
|
|
226
355
|
Every guard receives a `GuardContext` object:
|
|
227
356
|
|
|
228
|
-
| Property
|
|
229
|
-
|
|
|
230
|
-
| `toRoute`
|
|
231
|
-
| `toHash`
|
|
232
|
-
| `toArguments`
|
|
233
|
-
| `fromRoute`
|
|
234
|
-
| `fromHash`
|
|
235
|
-
| `signal`
|
|
236
|
-
| `bag`
|
|
237
|
-
| `toMeta`
|
|
238
|
-
| `fromMeta`
|
|
357
|
+
| Property | Type | Description |
|
|
358
|
+
| ---------------- | -------------------------------------------------- | ----------------------------------------------------------------------- |
|
|
359
|
+
| `toRoute` | `string` | Target route name (empty if no match) |
|
|
360
|
+
| `toHash` | `string` | Raw hash being navigated to |
|
|
361
|
+
| `toArguments` | `Record<string, string \| Record<string, string>>` | Parsed route parameters |
|
|
362
|
+
| `fromRoute` | `string` | Current route name (empty on first navigation) |
|
|
363
|
+
| `fromHash` | `string` | Current hash |
|
|
364
|
+
| `signal` | `AbortSignal` | Aborted when navigation is superseded, or on `stop()`/`destroy()` |
|
|
365
|
+
| `bag` | `Map<string, unknown>` | Shared mutable store for inter-guard data passing within one navigation |
|
|
366
|
+
| `toMeta` | `Readonly<Record<string, unknown>>` | Resolved metadata for the target route (manifest + runtime, frozen) |
|
|
367
|
+
| `fromMeta` | `Readonly<Record<string, unknown>>` | Resolved metadata for the current route (manifest + runtime, frozen) |
|
|
368
|
+
| `ownerComponent` | `UIComponent \| undefined` | Component that owns the router; `undefined` without owner (since 1.7.0) |
|
|
239
369
|
|
|
240
370
|
### Return values (`GuardResult`)
|
|
241
371
|
|
|
242
|
-
Enter guards return `GuardResult
|
|
372
|
+
Enter guards return a `GuardResult`:
|
|
243
373
|
|
|
244
374
|
```
|
|
245
375
|
GuardResult = boolean | string | GuardRedirect
|
|
246
376
|
```
|
|
247
377
|
|
|
248
|
-
| Return | Type | When to use | Effect
|
|
249
|
-
| ---------------------------------------------- | --------------- | ------------------------------------------------------- |
|
|
250
|
-
| `true` | `boolean` | Guard condition passes | Allow navigation
|
|
251
|
-
| `false` | `boolean` | Guard condition fails, no specific destination | Stay on current route.
|
|
252
|
-
| `"routeName"` | `string` | Redirect to a fixed route (no parameters needed) | Navigate to target route.
|
|
253
|
-
| `{ route, parameters?, componentTargetInfo? }` | `GuardRedirect` | Redirect and pass route parameters or component targets | Same as string redirect, with parameters
|
|
378
|
+
| Return | Type | When to use | Effect |
|
|
379
|
+
| ---------------------------------------------- | --------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
380
|
+
| `true` | `boolean` | Guard condition passes | Allow navigation |
|
|
381
|
+
| `false` | `boolean` | Guard condition fails, no specific destination | Stay on current route. The URL and the history stay as they were, see [Browser history](#browser-history) |
|
|
382
|
+
| `"routeName"` | `string` | Redirect to a fixed route (no parameters needed) | Navigate to target route. The guarded hash does not stay in the history, see [Browser history](#browser-history) |
|
|
383
|
+
| `{ route, parameters?, componentTargetInfo? }` | `GuardRedirect` | Redirect and pass route parameters or component targets | Same as string redirect, with parameters |
|
|
384
|
+
|
|
385
|
+
`toArguments` holds the route's parameters as UI5's `Route#getURL()` expects them back. A query parameter of the pattern (`products{?query}` or `products:?query:`) arrives under the key `"?query"` as an object, `{ "?query": { tab: "notes" } }`; an optional parameter that the hash leaves out is `undefined`. Pass the same shape in `GuardRedirect.parameters`.
|
|
254
386
|
|
|
255
|
-
|
|
387
|
+
Without parameters or component targets, the string form (`return "home"`) is equivalent to `GuardRedirect`.
|
|
256
388
|
|
|
257
|
-
Any other value (`null`, `undefined`, `0`, etc.)
|
|
389
|
+
Any other value (`null`, `undefined`, `0`, etc.) blocks. Only strict `true` allows navigation; there is no truthy coercion.
|
|
258
390
|
|
|
259
|
-
On first load, blocking a non-empty hash restores `""` and continues with the app's default route. Blocking the default route itself
|
|
391
|
+
On first load, blocking a non-empty hash restores `""` and continues with the app's default route. Blocking the default route itself leaves the app without a view. For a specific destination such as `login`, return a redirect instead of `false`.
|
|
392
|
+
|
|
393
|
+
A `navTo()` issued while a browser-initiated navigation is still waiting for an async guard supersedes that navigation. If the `navTo()` is then blocked, fails, or targets the current route, the router also restores the previous hash, so the URL does not stay on a hash that never committed.
|
|
260
394
|
|
|
261
395
|
**Leave guards** (`addLeaveGuard`) return `boolean` only:
|
|
262
396
|
|
|
@@ -265,18 +399,26 @@ On first load, blocking a non-empty hash restores `""` and continues with the ap
|
|
|
265
399
|
| `true` | Allow leaving the current route |
|
|
266
400
|
| `false` (or any non-`true` value) | Block |
|
|
267
401
|
|
|
268
|
-
Leave guards
|
|
402
|
+
Leave guards cannot redirect. Redirect from an enter guard of the target route.
|
|
269
403
|
|
|
270
404
|
### Lifecycle
|
|
271
405
|
|
|
272
|
-
| Method
|
|
273
|
-
|
|
|
274
|
-
| `
|
|
275
|
-
| `
|
|
406
|
+
| Method | Behavior |
|
|
407
|
+
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
408
|
+
| `initialize()` | Starts the router and parses the current hash through the guards, as the native router does |
|
|
409
|
+
| `initialize(true)` | Starts the router without parsing the hash. After `stop()`, it resumes the route that was current, so its leave guards keep working |
|
|
410
|
+
| `stop()` | Cancels a pending navigation (settles as `Cancelled`, aborts the `AbortSignal`) and resets the current route, hash and last settlement; guards are kept |
|
|
411
|
+
| `destroy()` | Clears all guards, cancels a pending navigation without firing `navigationSettled`, then calls `super.destroy()`. A `navTo()` afterwards only logs a warning. A second call does nothing |
|
|
412
|
+
|
|
413
|
+
Before `initialize()`, while `guardLoading: "block"` modules load, and after `stop()`, the router does not listen to hash changes. `navTo()` then behaves like the native router: it only sets the hash, or does nothing on a stopped router. No guard runs and nothing settles; the guards run when the router starts and parses the hash.
|
|
414
|
+
|
|
415
|
+
With `guardLoading: "block"`, the router starts once the manifest guard modules have loaded. Until then `isInitialized()` is `false`, a second `initialize()` changes nothing, and `stop()` cancels the pending start until `initialize()` is called again. Guard modules that finish loading after `destroy()` register nothing.
|
|
416
|
+
|
|
417
|
+
The Fiori launchpad stops the app router when the user leaves the app and calls `initialize(true)` when it puts the app back after the data-loss prompt: the router resumes the route the app was on. For apps the launchpad keeps alive, see [Keep-alive apps](#keep-alive-apps).
|
|
276
418
|
|
|
277
419
|
### Navigation settlement
|
|
278
420
|
|
|
279
|
-
`navigationSettled()` returns a Promise that resolves when the guard pipeline finishes. The
|
|
421
|
+
`navigationSettled()` returns a Promise that resolves when the guard pipeline finishes. The `NavigationResult` holds the outcome (`status`, a `NavigationOutcome` value), the `route` and the `hash`.
|
|
280
422
|
|
|
281
423
|
```typescript
|
|
282
424
|
import type { NavigationResult } from "ui5/guard/router/types";
|
|
@@ -290,19 +432,27 @@ const result: NavigationResult = await router.navigationSettled();
|
|
|
290
432
|
| `NavigationOutcome.Committed` | Guards allowed the navigation; target route is active |
|
|
291
433
|
| `NavigationOutcome.Bypassed` | Guards allowed the navigation, but no route matched; UI5 continued with `bypassed` / not-found handling |
|
|
292
434
|
| `NavigationOutcome.Blocked` | A guard blocked navigation; previous route stays active |
|
|
293
|
-
| `NavigationOutcome.Redirected` | A guard redirected navigation to a different route
|
|
435
|
+
| `NavigationOutcome.Redirected` | A guard redirected navigation to a different route, or to the route that is shown |
|
|
294
436
|
| `NavigationOutcome.Cancelled` | Navigation was cancelled before settling (superseded, stopped, or destroyed) |
|
|
295
437
|
| `NavigationOutcome.Error` | A guard threw or rejected; previous route stays active. `result.error` holds the thrown value |
|
|
296
438
|
|
|
297
|
-
A guard redirect
|
|
439
|
+
A guard redirect to a route that does not exist settles as `Blocked` because no route change commits; the router logs the target name to help diagnose it. A redirect whose target hash cannot be built (a mandatory route parameter is missing) is a guard failure: the navigation settles as `Error` with the error in `result.error`, whether the guard is sync or async and whether the navigation came from `navTo()` or from a hash change. `navTo()` does not throw for it, and a hash change is restored. The router logs the target name.
|
|
298
440
|
|
|
299
|
-
An accepted unmatched hash settles as `Bypassed` with `route === ""` and the attempted hash
|
|
441
|
+
An accepted unmatched hash settles as `Bypassed` with `route === ""` and the attempted hash in `hash`.
|
|
300
442
|
|
|
301
|
-
If no navigation is in flight, `navigationSettled()` resolves immediately with the most recent
|
|
443
|
+
If no navigation is in flight, `navigationSettled()` resolves immediately with the most recent result, so it is safe to call right after `navTo()`, even when guards settle synchronously. On a fresh router this is `Committed` with the current route and hash. After `stop()`, route and hash are empty strings until the next navigation settles or `initialize(true)` resumes the route. All callers waiting on the same navigation receive the same result.
|
|
302
444
|
|
|
303
445
|
**App code: busy indicator during async guards**
|
|
304
446
|
|
|
305
447
|
```typescript
|
|
448
|
+
import MessageBox from "sap/m/MessageBox";
|
|
449
|
+
import MessageToast from "sap/m/MessageToast";
|
|
450
|
+
import type App from "sap/m/App";
|
|
451
|
+
import NavigationOutcome from "ui5/guard/router/NavigationOutcome";
|
|
452
|
+
|
|
453
|
+
// In the root view controller, with an sap.m.App of id "app"
|
|
454
|
+
const app = this.byId("app") as App;
|
|
455
|
+
|
|
306
456
|
router.addRouteGuard("dashboard", async (context) => {
|
|
307
457
|
app.setBusy(true);
|
|
308
458
|
try {
|
|
@@ -313,7 +463,7 @@ router.addRouteGuard("dashboard", async (context) => {
|
|
|
313
463
|
}
|
|
314
464
|
});
|
|
315
465
|
|
|
316
|
-
//
|
|
466
|
+
// React to the outcome once the guards have decided
|
|
317
467
|
router.navTo("dashboard");
|
|
318
468
|
const result = await router.navigationSettled();
|
|
319
469
|
switch (result.status) {
|
|
@@ -347,7 +497,7 @@ assert.strictEqual(result.route, "home", "User stays on home");
|
|
|
347
497
|
|
|
348
498
|
**Event-based: observe every navigation outcome**
|
|
349
499
|
|
|
350
|
-
`
|
|
500
|
+
The `navigationSettled` event fires synchronously after every settlement, except for the navigation that `destroy()` cancels:
|
|
351
501
|
|
|
352
502
|
```typescript
|
|
353
503
|
router.attachNavigationSettled((event) => {
|
|
@@ -358,24 +508,43 @@ router.attachNavigationSettled((event) => {
|
|
|
358
508
|
});
|
|
359
509
|
```
|
|
360
510
|
|
|
361
|
-
|
|
511
|
+
A handler may call `navTo()`: the router is idle when the event fires, also for `Cancelled`, so the call runs its guards like any other. For `Blocked`, `Error` and `Cancelled` the URL is already restored when the event fires (a blocked back or forward step waits for that, see [Browser history](#browser-history)), so the restore does not undo what a handler starts. On first load, a blocked non-empty hash settles before the router falls back to the default route. Navigating inside the handler has two effects:
|
|
512
|
+
|
|
513
|
+
- A `Committed` or `Redirected` navigation that the handler leaves synchronously is not displayed and fires no `routeMatched`; only the handler's target is.
|
|
514
|
+
- For a navigation `Cancelled` by a newer one, the event fires before the newer navigation starts. The newer navigation then supersedes what the handler started: a committed one is navigated away from, a pending one is dropped without a settlement. Only a superseding hash change gives way: it is dropped when the handler's navigation has committed and moved the URL.
|
|
515
|
+
|
|
516
|
+
`detachNavigationSettled(fnFunction, oListener)` removes the listener; pass the same function and listener as to `attachNavigationSettled`. The standard `attachEvent` / `detachEvent` also work. A handler that throws does not stop the navigation: the router logs `A navigationSettled handler threw` and completes it.
|
|
362
517
|
|
|
363
518
|
### Error handling
|
|
364
519
|
|
|
365
|
-
When a guard throws or its Promise rejects, the navigation settles as `Error` with `result.error
|
|
520
|
+
When a guard throws or its Promise rejects, the navigation settles as `Error` with the thrown value in `result.error`, and the previous route stays active. `Blocked` is an intended denial, `Error` an unexpected failure.
|
|
521
|
+
|
|
522
|
+
A guard that calls `navTo()` itself supersedes the navigation it is guarding: that navigation settles as `Cancelled`, and what the guard returns afterwards (`true`, `false` or a redirect) is ignored, for sync and async guards alike. The navigation the guard started decides where the router ends up. To send the user elsewhere from a guard, return a redirect instead.
|
|
523
|
+
|
|
524
|
+
An error thrown while an allowed navigation is carried out, for example by a `beforeRouteMatched` handler, is not a guard failure. With sync guards it reaches the caller of `navTo()`. After async guards there is no caller, so the router logs it (`Navigation failed after its guards had settled`); a navigation that had already settled as `Committed` keeps that result, one that had not settled yet settles as `Error`.
|
|
366
525
|
|
|
367
526
|
### Execution order
|
|
368
527
|
|
|
369
528
|
1. **Leave guards** for the current route (registration order)
|
|
370
529
|
2. **Global enter guards** (registration order)
|
|
371
530
|
3. **Route-specific enter guards** for the target (registration order)
|
|
372
|
-
4. Pipeline **short-circuits** at the first non-`true` result
|
|
373
531
|
|
|
374
|
-
|
|
532
|
+
The pipeline stops at the first non-`true` result: if a leave guard blocks, no enter guard runs; if a global guard redirects, the route-specific guards are skipped.
|
|
533
|
+
|
|
534
|
+
Leave guards run on every hash change, also when only the parameters of the same route change (`employees/1` to `employees/2`); `fromRoute` and `toRoute` are then equal. A leave guard that should only protect leaving the route compares them.
|
|
535
|
+
|
|
536
|
+
**Greedy routes.** UI5 matches a route with `greedy: true` even when an earlier route has matched the hash. The guards of such a route run as well:
|
|
537
|
+
|
|
538
|
+
- The leave guards of every greedy route that matched the current hash run after those of `fromRoute`.
|
|
539
|
+
- The route-specific enter guards of every greedy route that matches the target hash run after those of `toRoute`, in the order the routes are defined. This holds for redirect hops too.
|
|
540
|
+
- A block or redirect from any of them applies to the whole navigation.
|
|
541
|
+
- A greedy route that matches both hashes is left and entered again: its leave guards and its enter guards run, as for a first match whose parameters change. UI5 fires no event for leaving it.
|
|
542
|
+
|
|
543
|
+
Every guard of a navigation gets the same context: `toRoute`, `toArguments` and `fromRoute` are those of the first route that matches. UI5 has no public API for the arguments of a greedy route that is not the first match; a guard that needs them reads `toHash`.
|
|
375
544
|
|
|
376
545
|
## Manifest Configuration
|
|
377
546
|
|
|
378
|
-
Guards can be declared
|
|
547
|
+
Guards, route metadata and router options can be declared in the `guardRouter` block inside `sap.ui5.routing.config` of `manifest.json`.
|
|
379
548
|
|
|
380
549
|
```json
|
|
381
550
|
{
|
|
@@ -408,18 +577,23 @@ Guards can be declared directly in `manifest.json` using the `guardRouter` block
|
|
|
408
577
|
|
|
409
578
|
### Router options
|
|
410
579
|
|
|
411
|
-
| Option | Values
|
|
412
|
-
| -------------------------- |
|
|
413
|
-
| `unknownRouteRegistration` | `"ignore"` \| `"warn"` \| `"throw"`
|
|
414
|
-
| `navToPreflight` | `"guard"` \| `"bypass"` \| `"off"`
|
|
415
|
-
| `guardLoading` | `"block"` \| `"lazy"`
|
|
416
|
-
| `inheritance` | `"none"` \| `"pattern-tree"`
|
|
580
|
+
| Option | Values | Default | Description |
|
|
581
|
+
| -------------------------- | ------------------------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
582
|
+
| `unknownRouteRegistration` | `"ignore"` \| `"warn"` \| `"throw"` | `"warn"` | Policy for guard and metadata registration against unknown route names, see [Unknown routes during registration](#unknown-routes-during-registration) |
|
|
583
|
+
| `navToPreflight` | `"guard"` \| `"bypass"` \| `"off"` | `"guard"` | Whether `navTo()` calls run through the guard pipeline (`"guard"`), skip guards (`"bypass"`), or leave them to `parse()` after the hash has changed (`"off"`), which also supersedes a pending navigation there |
|
|
584
|
+
| `guardLoading` | `"block"` \| `"lazy"` | `"lazy"` | `"lazy"`: `initialize()` starts the router at once; a module that is not loaded yet is loaded on the first navigation that needs it (a failed load settles that navigation as `Error`). `"block"`: the router starts once all modules have loaded; a module that fails to load is skipped with a warning |
|
|
585
|
+
| `inheritance` | `"none"` \| `"pattern-tree"` | `"none"` | `"none"`: guards and metadata apply only to their declared route. `"pattern-tree"`: guards propagate to all routes whose URL pattern extends the declared route's pattern; metadata propagates via shallow merge (child values override ancestor values on conflict). |
|
|
586
|
+
| `logLevel` | `"error"` \| `"warning"` \| `"info"` \| `"debug"` | none | Log level of the router's log component, see [Enabling guard logs](#enabling-guard-logs). Not set: `sap/base/Log` is left as it is |
|
|
417
587
|
|
|
418
588
|
The `guardRouter` block also accepts `guards` (see [Declarative guards](#declarative-guards)) and `routeMeta` (see [Route metadata](#route-metadata)).
|
|
419
589
|
|
|
590
|
+
An invalid value is logged as a warning and the default is used. An invalid `logLevel` is ignored and logged as an error, which shows at the default `ERROR` level.
|
|
591
|
+
|
|
592
|
+
When constructing the router in code rather than from the manifest, the config argument is typed as `GuardRouterConfig` (since 1.7.0): the standard router config plus `guardRouter`, so `new Router(routes, { async: true, guardRouter: { navToPreflight: "bypass" } })` (`import Router from "ui5/guard/router/Router"`) type-checks without casts.
|
|
593
|
+
|
|
420
594
|
### Declarative guards
|
|
421
595
|
|
|
422
|
-
The `guards` map wires guard modules to routes
|
|
596
|
+
The `guards` map wires guard modules to routes.
|
|
423
597
|
|
|
424
598
|
**Global guards** run on every navigation and are declared under the `"*"` key:
|
|
425
599
|
|
|
@@ -437,7 +611,7 @@ The `guards` map wires guard modules to routes without writing code in `Componen
|
|
|
437
611
|
}
|
|
438
612
|
```
|
|
439
613
|
|
|
440
|
-
The
|
|
614
|
+
The object form registers enter and leave guards:
|
|
441
615
|
|
|
442
616
|
```json
|
|
443
617
|
"guards": {
|
|
@@ -448,9 +622,11 @@ The full object form with `enter` and `leave` keys registers both enter and leav
|
|
|
448
622
|
}
|
|
449
623
|
```
|
|
450
624
|
|
|
625
|
+
Keys other than `enter` and `leave`, and an `enter` or `leave` value that is not an array, are logged as warnings and skipped. Under `"*"` only `enter` applies; `leave` is skipped with a warning, because there are no global leave guards.
|
|
626
|
+
|
|
451
627
|
**Module paths** use dot notation and are resolved relative to `sap.app.id`. Given `sap.app.id = "com.example.app"`, the path `"guards.authGuard"` resolves to `"com/example/app/guards/authGuard"`.
|
|
452
628
|
|
|
453
|
-
|
|
629
|
+
For an absolute module path, prefix it with `"module:"`. Slash notation (`module:com/shared/guards/authGuard`) is accepted as well:
|
|
454
630
|
|
|
455
631
|
```json
|
|
456
632
|
"*": ["module:com.shared.guards.authGuard"]
|
|
@@ -489,11 +665,17 @@ export default function authGuard(context: GuardContext): GuardResult {
|
|
|
489
665
|
}
|
|
490
666
|
```
|
|
491
667
|
|
|
492
|
-
|
|
668
|
+
Manifest guards have no closure over the component. Read component state such as models through `context.ownerComponent`, not module-level singletons or `ComponentRegistry` lookups, so each component instance sees its own state:
|
|
669
|
+
|
|
670
|
+
```typescript
|
|
671
|
+
export default function dirtyFormGuard(context: GuardContext): boolean {
|
|
672
|
+
return context.ownerComponent?.getModel("form")?.getProperty("/isDirty") !== true;
|
|
673
|
+
}
|
|
674
|
+
```
|
|
493
675
|
|
|
494
676
|
### Guard module format
|
|
495
677
|
|
|
496
|
-
Each entry in
|
|
678
|
+
Each entry in a guard array is a module. The router uses the value the module returns to UI5's loader, for a transpiled ES module its default export. That value has one of three shapes:
|
|
497
679
|
|
|
498
680
|
**Shape 1: Function (single guard)**
|
|
499
681
|
|
|
@@ -538,14 +720,14 @@ export default {
|
|
|
538
720
|
};
|
|
539
721
|
```
|
|
540
722
|
|
|
541
|
-
|
|
723
|
+
A plain object produces named guards in key order. A module with only named exports (`export function checkAuth`) counts as such an object, with its exports in the order they are written. Named exports next to a default export become properties of the default export, because the UI5 transpiler (`babel-plugin-transform-modules-ui5`) collapses them onto it: next to a default function only `#name` reaches them (see [Cherry-pick syntax](#cherry-pick-syntax)), next to a default object they are further entries of it. Non-function entries in arrays and objects are warned and skipped. Empty arrays and objects are warned and produce no guards.
|
|
542
724
|
|
|
543
725
|
> [!NOTE]
|
|
544
|
-
>
|
|
726
|
+
> A module in a `"leave"` array is a `LeaveGuardFn` and returns `boolean`. A string or `GuardRedirect` from a leave guard is not an error, but like any non-`true` value it blocks.
|
|
545
727
|
|
|
546
728
|
### Cherry-pick syntax
|
|
547
729
|
|
|
548
|
-
|
|
730
|
+
`#` selects one guard of a module by name or index:
|
|
549
731
|
|
|
550
732
|
```json
|
|
551
733
|
{
|
|
@@ -565,18 +747,24 @@ When a module exports multiple guards, you can register a subset using `#` to se
|
|
|
565
747
|
| `"guards.security#1"` | Register by index (array or object key order) |
|
|
566
748
|
| `"module:some.lib.guards#checkAuth"` | `module:` prefix composes with `#` |
|
|
567
749
|
|
|
568
|
-
|
|
750
|
+
Only a plain non-negative integer (`#0`, `#12`) selects by index. Every other key is a name: `#2faGuard` selects the export named `2faGuard` and is skipped with a warning if the module has none.
|
|
751
|
+
|
|
752
|
+
When `#` is used on a single-function module, the key selects a function among the module's own properties, which is what a named export next to the default function becomes. Without such a property the export key is ignored with a debug message and the function is still registered.
|
|
569
753
|
|
|
570
754
|
### Guard context `bag`
|
|
571
755
|
|
|
572
|
-
|
|
756
|
+
`context.bag` is a `Map<string, unknown>` created for each navigation and shared by all its guards, across redirect hops too. Use it to fetch data such as the current user once per navigation:
|
|
573
757
|
|
|
574
758
|
```typescript
|
|
759
|
+
// guards/firstGuard.ts
|
|
575
760
|
export default function firstGuard(context: GuardContext): GuardResult {
|
|
576
761
|
context.bag.set("userId", getCurrentUserId());
|
|
577
762
|
return true;
|
|
578
763
|
}
|
|
764
|
+
```
|
|
579
765
|
|
|
766
|
+
```typescript
|
|
767
|
+
// guards/secondGuard.ts
|
|
580
768
|
export default function secondGuard(context: GuardContext): GuardResult {
|
|
581
769
|
const userId = context.bag.get("userId") as string | undefined;
|
|
582
770
|
if (!userId) return "login";
|
|
@@ -584,13 +772,11 @@ export default function secondGuard(context: GuardContext): GuardResult {
|
|
|
584
772
|
}
|
|
585
773
|
```
|
|
586
774
|
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
This is useful for avoiding repeated work (such as fetching the current user) when multiple guards need the same data in a single navigation.
|
|
775
|
+
Values are `unknown`, so cast on `.get()`.
|
|
590
776
|
|
|
591
777
|
### Route metadata
|
|
592
778
|
|
|
593
|
-
|
|
779
|
+
`guardRouter.routeMeta` maps route names to arbitrary objects. The router stores the metadata and never interprets it. Guards read it from `context.toMeta` and `context.fromMeta`.
|
|
594
780
|
|
|
595
781
|
```json
|
|
596
782
|
"guardRouter": {
|
|
@@ -602,7 +788,7 @@ Per-route metadata can be declared in the manifest under `guardRouter.routeMeta`
|
|
|
602
788
|
}
|
|
603
789
|
```
|
|
604
790
|
|
|
605
|
-
|
|
791
|
+
One global guard can then enforce it:
|
|
606
792
|
|
|
607
793
|
```typescript
|
|
608
794
|
router.addGuard((context) => {
|
|
@@ -612,25 +798,29 @@ router.addGuard((context) => {
|
|
|
612
798
|
});
|
|
613
799
|
```
|
|
614
800
|
|
|
615
|
-
|
|
801
|
+
`setRouteMeta()` sets runtime metadata, which takes precedence over the manifest values:
|
|
616
802
|
|
|
617
803
|
```typescript
|
|
618
804
|
router.setRouteMeta("betaFeature", { enabled: featureToggle.isActive("beta") });
|
|
619
805
|
```
|
|
620
806
|
|
|
621
|
-
`getRouteMeta()` returns a frozen object
|
|
807
|
+
`getRouteMeta()` returns a frozen object: manifest values merged with runtime values, plus inherited metadata with `inheritance: "pattern-tree"` (see [Guard and metadata inheritance](#guard-and-metadata-inheritance)). For a route without metadata it returns an empty frozen object.
|
|
622
808
|
|
|
623
809
|
### `skipGuards` option
|
|
624
810
|
|
|
625
|
-
|
|
811
|
+
`{ skipGuards: true }` as the options argument of `navTo()` bypasses all guards for that call. The options come after `bReplace`; pass `undefined` for `bReplace` to keep its default. With nested components, `componentTargetInfo` (as in the native `navTo()`) comes before `bReplace`:
|
|
626
812
|
|
|
627
813
|
```typescript
|
|
628
814
|
router.navTo("settings", {}, false, { skipGuards: true });
|
|
815
|
+
router.navTo("settings", {}, undefined, { skipGuards: true });
|
|
816
|
+
router.navTo("settings", {}, componentTargetInfo, false, { skipGuards: true });
|
|
629
817
|
```
|
|
630
818
|
|
|
819
|
+
A `skipGuards` navigation does not wait for guards that are still pending for the same target: it cancels that navigation and commits.
|
|
820
|
+
|
|
631
821
|
### Guard and metadata inheritance
|
|
632
822
|
|
|
633
|
-
|
|
823
|
+
With `inheritance: "pattern-tree"`, guards declared on a route apply to all routes whose URL pattern extends that route's pattern:
|
|
634
824
|
|
|
635
825
|
```json
|
|
636
826
|
"guardRouter": {
|
|
@@ -641,9 +831,9 @@ When `inheritance` is set to `"pattern-tree"`, guards declared on a route automa
|
|
|
641
831
|
}
|
|
642
832
|
```
|
|
643
833
|
|
|
644
|
-
With routes `employees`, `employees/{id}`, and `employees/{id}/resume`, the auth guard runs for all three. Ancestor guards run before descendant guards.
|
|
834
|
+
With routes `employees`, `employees/{id}`, and `employees/{id}/resume`, the auth guard runs for all three. Ancestor guards run before descendant guards, in whatever order the routes appear under `guards`; guards of the same route keep their declared order.
|
|
645
835
|
|
|
646
|
-
|
|
836
|
+
Route metadata propagates the same way. With the route-to-pattern mapping `"employees"` -> `employees`, `"employee"` -> `employees/{id}`, `"employeeResume"` -> `employees/{id}/resume`:
|
|
647
837
|
|
|
648
838
|
```json
|
|
649
839
|
"guardRouter": {
|
|
@@ -655,11 +845,9 @@ With the same `inheritance: "pattern-tree"` setting, route metadata also propaga
|
|
|
655
845
|
}
|
|
656
846
|
```
|
|
657
847
|
|
|
658
|
-
`getRouteMeta("employeeResume")` returns `{ section: "hr", requiresAuth: true, clearance: "manager" }` (inherited from both `employees` and `employee`). `getRouteMeta("employee")` returns
|
|
848
|
+
`getRouteMeta("employeeResume")` returns `{ section: "hr", requiresAuth: true, clearance: "manager" }` (inherited from both `employees` and `employee`). `getRouteMeta("employee")` returns the same object (merged, own values win).
|
|
659
849
|
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
**Root-pattern route (`""`) is a universal ancestor.** A route with an empty pattern (typically "home") is considered an ancestor of every other route in the router. With `pattern-tree` inheritance enabled, metadata or guards declared on the root-pattern route propagate to all routes:
|
|
850
|
+
**The root-pattern route (`""`) is an ancestor of every route.** Metadata or guards declared on it, typically on "home", propagate to all routes:
|
|
663
851
|
|
|
664
852
|
```json
|
|
665
853
|
"guardRouter": {
|
|
@@ -670,19 +858,15 @@ Defaults to `"none"` for backward compatibility.
|
|
|
670
858
|
}
|
|
671
859
|
```
|
|
672
860
|
|
|
673
|
-
Every route
|
|
674
|
-
|
|
675
|
-
Metadata is resolved lazily on first access via `getRouteMeta()` and cached until `setRouteMeta()` or `addRoute()` invalidates the cache. Guard inheritance is resolved at `initialize()` time; routes added dynamically via `addRoute()` are integrated into the pattern tree on the fly (inherited guards are registered and the metadata cache is cleared).
|
|
861
|
+
Every route inherits `requiresAuth: true` from "home" unless it overrides it. The reverse holds too: `{ "requiresAuth": false }` on the root route makes every route public unless overridden.
|
|
676
862
|
|
|
677
|
-
|
|
863
|
+
Only manifest guards are inherited; guards added with `addRouteGuard()` or `addLeaveGuard()` apply only to their own route. Guard inheritance is resolved at `initialize()`. A route added later with `addRoute()` joins the pattern tree at once: its inherited guards are registered in front of the manifest guards of deeper routes. Metadata, including runtime metadata from `setRouteMeta()`, is resolved on first access and cached until `setRouteMeta()` or `addRoute()` clears the cache.
|
|
678
864
|
|
|
679
865
|
### Mixing declarative and programmatic guards
|
|
680
866
|
|
|
681
|
-
Manifest
|
|
682
|
-
|
|
683
|
-
**Execution order:** manifest guards run first (in declaration order), then programmatic guards (in registration order). For the same route, both sets execute. They are additive, not exclusive.
|
|
867
|
+
Manifest and programmatic guards of the same route both run. Within each phase, guards run in registration order. Manifest guards are registered in declaration order when `initialize()` runs, so they run after programmatic guards added before `initialize()` and before guards added after it. In `"block"` mode they are registered once all modules have loaded, so a guard added after `initialize()` but before loading finishes runs before them.
|
|
684
868
|
|
|
685
|
-
|
|
869
|
+
Where each kind of guard fits:
|
|
686
870
|
|
|
687
871
|
- **Manifest:** guards that don't need component state (simple blocks, redirects, logging)
|
|
688
872
|
- **Programmatic:** guards that close over models, services, or runtime state
|
|
@@ -690,6 +874,8 @@ A common pattern is to declare static guards in the manifest and add context-dep
|
|
|
690
874
|
|
|
691
875
|
## Examples
|
|
692
876
|
|
|
877
|
+
`router`, `authModel` and `formModel` in the examples stand for the app's router and models.
|
|
878
|
+
|
|
693
879
|
### Async guard with AbortSignal
|
|
694
880
|
|
|
695
881
|
```typescript
|
|
@@ -720,27 +906,22 @@ router.addGuard((context): GuardRedirect | true => {
|
|
|
720
906
|
});
|
|
721
907
|
```
|
|
722
908
|
|
|
723
|
-
|
|
909
|
+
[Guard Integration Patterns](../../docs/guides/integration-patterns.md#redirect-with-parameters) has this guard as a factory for any target route.
|
|
724
910
|
|
|
725
911
|
### Guard factories
|
|
726
912
|
|
|
727
|
-
|
|
913
|
+
A factory closes over what its guard depends on:
|
|
728
914
|
|
|
729
915
|
```typescript
|
|
730
|
-
|
|
731
|
-
import
|
|
732
|
-
import type { GuardFn, LeaveGuardFn, GuardContext, GuardResult } from "ui5/guard/router/types";
|
|
916
|
+
import type JSONModel from "sap/ui/model/json/JSONModel";
|
|
917
|
+
import type { GuardFn, LeaveGuardFn } from "ui5/guard/router/types";
|
|
733
918
|
|
|
734
919
|
export function createAuthGuard(authModel: JSONModel): GuardFn {
|
|
735
|
-
return (
|
|
736
|
-
return authModel.getProperty("/isLoggedIn") ? true : "home";
|
|
737
|
-
};
|
|
920
|
+
return () => (authModel.getProperty("/isLoggedIn") ? true : "home");
|
|
738
921
|
}
|
|
739
922
|
|
|
740
923
|
export function createDirtyFormGuard(formModel: JSONModel): LeaveGuardFn {
|
|
741
|
-
return (
|
|
742
|
-
return !formModel.getProperty("/isDirty");
|
|
743
|
-
};
|
|
924
|
+
return () => !formModel.getProperty("/isDirty");
|
|
744
925
|
}
|
|
745
926
|
```
|
|
746
927
|
|
|
@@ -752,7 +933,7 @@ The object form is useful when registering both enter and leave guards for the s
|
|
|
752
933
|
import type { RouteGuardConfig } from "ui5/guard/router/types";
|
|
753
934
|
|
|
754
935
|
const protectedGuards: RouteGuardConfig = {
|
|
755
|
-
beforeEnter:
|
|
936
|
+
beforeEnter: createAuthGuard(authModel),
|
|
756
937
|
beforeLeave: createDirtyFormGuard(formModel),
|
|
757
938
|
};
|
|
758
939
|
|
|
@@ -760,9 +941,11 @@ router.addRouteGuard("protected", protectedGuards);
|
|
|
760
941
|
// later: router.removeRouteGuard("protected", protectedGuards);
|
|
761
942
|
```
|
|
762
943
|
|
|
944
|
+
More patterns are in [Guard Integration Patterns](../../docs/guides/integration-patterns.md).
|
|
945
|
+
|
|
763
946
|
### Dynamic guard registration
|
|
764
947
|
|
|
765
|
-
Guards can be added
|
|
948
|
+
Guards can be added and removed at any time:
|
|
766
949
|
|
|
767
950
|
```typescript
|
|
768
951
|
const logGuard: GuardFn = (ctx) => {
|
|
@@ -777,304 +960,489 @@ router.removeGuard(logGuard);
|
|
|
777
960
|
|
|
778
961
|
### Leave guard with controller lifecycle
|
|
779
962
|
|
|
780
|
-
|
|
963
|
+
A controller registers its guard in `onInit` and removes the same function in `onExit`:
|
|
781
964
|
|
|
782
965
|
```typescript
|
|
966
|
+
import Controller from "sap/ui/core/mvc/Controller";
|
|
967
|
+
import UIComponent from "sap/ui/core/UIComponent";
|
|
968
|
+
import type JSONModel from "sap/ui/model/json/JSONModel";
|
|
783
969
|
import type { GuardRouter, LeaveGuardFn } from "ui5/guard/router/types";
|
|
784
|
-
import BaseController from "./BaseController";
|
|
785
|
-
import { createHomeLeaveLogger } from "../guards";
|
|
786
970
|
|
|
787
|
-
export default class
|
|
788
|
-
private _leaveGuard
|
|
971
|
+
export default class EditController extends Controller {
|
|
972
|
+
private _leaveGuard?: LeaveGuardFn;
|
|
789
973
|
|
|
790
|
-
onInit(): void {
|
|
791
|
-
const
|
|
792
|
-
this._leaveGuard =
|
|
793
|
-
|
|
974
|
+
override onInit(): void {
|
|
975
|
+
const form = this.getOwnerComponent()?.getModel("form") as JSONModel;
|
|
976
|
+
this._leaveGuard = () => form.getProperty("/isDirty") !== true;
|
|
977
|
+
(UIComponent.getRouterFor(this) as GuardRouter).addLeaveGuard("edit", this._leaveGuard);
|
|
794
978
|
}
|
|
795
979
|
|
|
796
|
-
onExit(): void {
|
|
980
|
+
override onExit(): void {
|
|
797
981
|
if (this._leaveGuard) {
|
|
798
|
-
|
|
799
|
-
router.removeLeaveGuard("home", this._leaveGuard);
|
|
800
|
-
this._leaveGuard = null;
|
|
982
|
+
(UIComponent.getRouterFor(this) as GuardRouter).removeLeaveGuard("edit", this._leaveGuard);
|
|
801
983
|
}
|
|
802
984
|
}
|
|
803
985
|
}
|
|
804
986
|
```
|
|
805
987
|
|
|
806
988
|
> [!TIP]
|
|
807
|
-
> **User feedback on blocked navigation**:
|
|
989
|
+
> **User feedback on blocked navigation**: A blocked navigation gives the user no feedback, and there is no built-in confirmation dialog. Show a `sap.m.MessageBox.confirm()` in the leave guard and return the user's choice as a `Promise<boolean>`.
|
|
808
990
|
|
|
809
991
|
> [!NOTE]
|
|
810
992
|
> **Guard cleanup and lifecycle**
|
|
811
993
|
>
|
|
812
|
-
> **Component level**: The router's `destroy()`
|
|
994
|
+
> **Component level**: The router's `destroy()` clears all guards when the component is destroyed, also during FLP navigation.
|
|
813
995
|
>
|
|
814
|
-
> **Controller level**: UI5's routing caches views indefinitely, so `onExit` is called only when the component is destroyed, not on every navigation away.
|
|
996
|
+
> **Controller level**: UI5's routing [caches views indefinitely](../../docs/research/view-caching-controller-lifecycle.md), so `onExit` is called only when the component is destroyed, not on every navigation away. Guards registered by a controller therefore stay across in-app navigations.
|
|
815
997
|
>
|
|
816
|
-
> In FLP apps with `sap-keep-alive
|
|
817
|
-
|
|
818
|
-
### Metadata-driven guards via manifest (legacy alternative)
|
|
819
|
-
|
|
820
|
-
> [!NOTE]
|
|
821
|
-
> The native `guardRouter.routeMeta` configuration (see [Route metadata](#route-metadata)) is the recommended way to declare per-route metadata. The custom-namespace approach below predates native support and is shown for historical reference only.
|
|
822
|
-
|
|
823
|
-
For common patterns like "this route requires authentication", you can store per-route metadata in a custom manifest section and use a single global guard instead of writing repetitive per-route guards:
|
|
824
|
-
|
|
825
|
-
```json
|
|
826
|
-
{
|
|
827
|
-
"ui5.guard.router": {
|
|
828
|
-
"routeMeta": {
|
|
829
|
-
"admin": { "requiresAuth": true, "roles": ["admin"] },
|
|
830
|
-
"profile": { "requiresAuth": true },
|
|
831
|
-
"home": { "public": true }
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
```
|
|
836
|
-
|
|
837
|
-
```typescript
|
|
838
|
-
// Component.ts: read the custom section via getManifestEntry (typed path lookup)
|
|
839
|
-
type RouteMeta = Record<string, Record<string, unknown>>;
|
|
840
|
-
const routeMeta = (this.getManifestEntry("/ui5.guard.router/routeMeta") ?? {}) as RouteMeta;
|
|
841
|
-
|
|
842
|
-
router.addGuard((context) => {
|
|
843
|
-
const meta = routeMeta[context.toRoute] ?? {};
|
|
844
|
-
if (meta.requiresAuth && !authModel.getProperty("/isLoggedIn")) return "login";
|
|
845
|
-
if (meta.roles && !hasAnyRole(meta.roles as string[])) return "forbidden";
|
|
846
|
-
return true;
|
|
847
|
-
});
|
|
848
|
-
```
|
|
998
|
+
> In FLP apps with `sap-keep-alive`, the component and its guards stay while the app is hidden, see [Keep-alive apps](#keep-alive-apps).
|
|
849
999
|
|
|
850
|
-
|
|
1000
|
+
## Fiori Launchpad
|
|
851
1001
|
|
|
852
|
-
|
|
1002
|
+
The examples in this section import `sap/ushell` modules, whose typings come with `@sapui5/types`, not `@openui5/types`.
|
|
853
1003
|
|
|
854
|
-
###
|
|
1004
|
+
### Data loss prevention of the launchpad
|
|
855
1005
|
|
|
856
|
-
|
|
1006
|
+
Inside SAP Fiori Launchpad (FLP), the shell has its own data loss protection on `sap.ushell.Container`:
|
|
857
1007
|
|
|
858
|
-
**`setDirtyFlag(bDirty)`** (since 1.27.0):
|
|
1008
|
+
- **`setDirtyFlag(bDirty)`** (since 1.27.0): while `true`, FLP shows a browser `confirm()` dialog on every hash change, in-app ones included, and the leave-page dialog on refresh or close. An in-app `navTo()` that the shell holds back for the dialog settles as `Blocked`; if the user confirms, the shell sets the hash again and the guards run for it.
|
|
1009
|
+
- **`registerDirtyStateProvider(fn)`** (since 1.31.0, `deregisterDirtyStateProvider` since 1.67.0): FLP calls the provider on each navigation with a `NavigationContext` (`isCrossAppNavigation`, `innerAppRoute`), so it can tell cross-app from in-app navigation.
|
|
1010
|
+
- Since 1.146, `setDirtyFlag` and the provider functions are on `sap/ushell/navigation/DirtyState`, and the `Container` methods are deprecated.
|
|
859
1011
|
|
|
860
1012
|
```typescript
|
|
861
|
-
sap
|
|
862
|
-
sap.ushell.Container.setDirtyFlag(false); // clear after save
|
|
863
|
-
```
|
|
1013
|
+
import Container from "sap/ushell/Container"; // 1.146 and later: the same functions on sap/ushell/navigation/DirtyState
|
|
864
1014
|
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
```typescript
|
|
868
|
-
const dirtyProvider = (navigationContext) => {
|
|
1015
|
+
const dirtyProvider = (navigationContext?: { isCrossAppNavigation?: boolean }) => {
|
|
869
1016
|
if (navigationContext?.isCrossAppNavigation === false) {
|
|
870
|
-
return false; //
|
|
1017
|
+
return false; // in-app navigation: the leave guards handle it
|
|
871
1018
|
}
|
|
872
1019
|
return formModel.getProperty("/isDirty") === true;
|
|
873
1020
|
};
|
|
874
|
-
|
|
1021
|
+
Container.registerDirtyStateProvider(dirtyProvider);
|
|
875
1022
|
|
|
876
|
-
//
|
|
877
|
-
|
|
1023
|
+
// When the form or the app goes away
|
|
1024
|
+
Container.deregisterDirtyStateProvider(dirtyProvider);
|
|
878
1025
|
```
|
|
879
1026
|
|
|
880
|
-
|
|
1027
|
+
`getDirtyFlag()` is deprecated since UI5 1.120. The APIs and the shell internals are in [FLP Dirty State Research](../../docs/research/flp-dirty-state.md).
|
|
881
1028
|
|
|
882
|
-
|
|
1029
|
+
### Combining leave guards with FLP dirty-state protection
|
|
883
1030
|
|
|
884
|
-
|
|
1031
|
+
A leave guard and a dirty-state provider cover separate scopes and need no coordination:
|
|
885
1032
|
|
|
886
|
-
- **
|
|
887
|
-
- **
|
|
1033
|
+
- The **leave guard** protects **in-app** navigation (route to route within your app).
|
|
1034
|
+
- The **dirty-state provider** protects **cross-app** navigation (shell home, other tiles, browser close).
|
|
888
1035
|
|
|
889
|
-
|
|
1036
|
+
`ShellNavigationHashChanger` never passes a cross-app hash to the app router, so the leave guard never runs for it. The provider returns `false` for in-app navigation, so the shell does not prompt for it:
|
|
890
1037
|
|
|
891
1038
|
```typescript
|
|
1039
|
+
import Container from "sap/ushell/Container";
|
|
1040
|
+
|
|
892
1041
|
// 1. Leave guard: blocks in-app navigation when dirty
|
|
893
1042
|
router.addRouteGuard("editOrder", {
|
|
894
1043
|
beforeLeave: () => formModel.getProperty("/isDirty") !== true,
|
|
895
1044
|
});
|
|
896
1045
|
|
|
897
1046
|
// 2. Dirty-state provider: tells FLP about unsaved changes for cross-app
|
|
898
|
-
const dirtyProvider = (navigationContext) => {
|
|
1047
|
+
const dirtyProvider = (navigationContext?: { isCrossAppNavigation?: boolean }) => {
|
|
899
1048
|
if (navigationContext?.isCrossAppNavigation === false) {
|
|
900
1049
|
return false; // in-app navigation handled by leave guard
|
|
901
1050
|
}
|
|
902
1051
|
return formModel.getProperty("/isDirty") === true;
|
|
903
1052
|
};
|
|
904
|
-
|
|
1053
|
+
Container.registerDirtyStateProvider(dirtyProvider);
|
|
905
1054
|
```
|
|
906
1055
|
|
|
907
|
-
|
|
1056
|
+
The leave guard needs no `toRoute` check or FLP detection: the shell handles cross-app navigation in production and in the FLP sandbox. In an app the launchpad keeps alive, deregister the provider while the app is hidden ([Keep-alive apps](#keep-alive-apps)).
|
|
908
1057
|
|
|
909
1058
|
> [!TIP]
|
|
910
|
-
>
|
|
1059
|
+
> To test a dirty-state provider in the FLP preview, set `useNewSandbox: true` on the `fiori-tools-preview` middleware (SAPUI5 1.151 and later; before that, `enhancedHomePage: true` from 1.123.0). Both start a CDM launchpad, whose `ShellNavigationHashChanger` and `Navigation` service behave like a production FLP.
|
|
1060
|
+
|
|
1061
|
+
### Keep-alive apps
|
|
1062
|
+
|
|
1063
|
+
With `sap-keep-alive=true` the launchpad hides an app that the user leaves for another app and shows it again when the user returns. With `sap-keep-alive=restricted` it also destroys kept apps when the user reaches the launchpad home; returning from there through a hash with an inner route (browser back, bookmark) creates a new component.
|
|
1064
|
+
|
|
1065
|
+
What happens to the router depends on whether the manifest declares keep-alive support:
|
|
1066
|
+
|
|
1067
|
+
```json
|
|
1068
|
+
{
|
|
1069
|
+
"sap.ui5": {
|
|
1070
|
+
"keepAlive": { "supported": true }
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
```
|
|
1074
|
+
|
|
1075
|
+
| | Hidden | Shown again |
|
|
1076
|
+
| ------------ | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1077
|
+
| Declared | UI5's `Component#deactivate()` stops the router, then calls `onDeactivate()` | `Component#activate()` calls `initialize()`, which runs the guards for the hash the URL shows, then `onActivate()`. No leave guard runs. Returning through an intent without an inner route starts on the default route |
|
|
1078
|
+
| Not declared | The launchpad calls `stop()` | The launchpad calls `initialize(true)`: the router resumes the route the app was on, and its leave guards keep working |
|
|
1079
|
+
|
|
1080
|
+
Declared: the launchpad goes through the component.
|
|
1081
|
+
|
|
1082
|
+
```mermaid
|
|
1083
|
+
sequenceDiagram
|
|
1084
|
+
box rgba(110, 119, 129, 0.2) Fiori launchpad
|
|
1085
|
+
participant Shell as Launchpad
|
|
1086
|
+
end
|
|
1087
|
+
participant Comp as App component
|
|
1088
|
+
box rgba(0, 114, 178, 0.15) This library
|
|
1089
|
+
participant Router as Guard router
|
|
1090
|
+
end
|
|
1091
|
+
Shell->>Comp: deactivate()
|
|
1092
|
+
Comp->>Router: stop()
|
|
1093
|
+
Comp->>Comp: onDeactivate()
|
|
1094
|
+
Note over Shell,Router: app hidden
|
|
1095
|
+
Shell->>Comp: activate()
|
|
1096
|
+
Comp->>Router: initialize()
|
|
1097
|
+
Note over Router: guards run<br/>for the hash
|
|
1098
|
+
Comp->>Comp: onActivate()
|
|
1099
|
+
```
|
|
1100
|
+
|
|
1101
|
+
Not declared: the launchpad calls the router itself.
|
|
1102
|
+
|
|
1103
|
+
```mermaid
|
|
1104
|
+
sequenceDiagram
|
|
1105
|
+
box rgba(110, 119, 129, 0.2) Fiori launchpad
|
|
1106
|
+
participant Shell as Launchpad
|
|
1107
|
+
end
|
|
1108
|
+
box rgba(0, 114, 178, 0.15) This library
|
|
1109
|
+
participant Router as Guard router
|
|
1110
|
+
end
|
|
1111
|
+
Shell->>Router: stop()
|
|
1112
|
+
Note over Shell,Router: app hidden
|
|
1113
|
+
Shell->>Router: initialize(true)
|
|
1114
|
+
Note over Router: resumes the route
|
|
1115
|
+
```
|
|
1116
|
+
|
|
1117
|
+
Guards and dirty-state providers stay registered while the app is hidden. The launchpad asks every registered provider on each navigation, also the provider of a hidden app embedded in the launchpad page, so the user is asked about unsaved data of an app they are not in. Deregister the provider in `onDeactivate()` and register it again in `onActivate()`; UI5 calls both only when the manifest declares keep-alive support (the Declared row):
|
|
1118
|
+
|
|
1119
|
+
```typescript
|
|
1120
|
+
import UIComponent from "sap/ui/core/UIComponent";
|
|
1121
|
+
import Container from "sap/ushell/Container";
|
|
1122
|
+
import type JSONModel from "sap/ui/model/json/JSONModel";
|
|
911
1123
|
|
|
912
|
-
|
|
1124
|
+
type DirtyStateProvider = (context?: { isCrossAppNavigation?: boolean }) => boolean;
|
|
1125
|
+
|
|
1126
|
+
export default class Component extends UIComponent {
|
|
1127
|
+
public static metadata = { manifest: "json" };
|
|
1128
|
+
|
|
1129
|
+
// No initializer: it would run after init(), which the UIComponent constructor calls.
|
|
1130
|
+
private _dirtyProvider?: DirtyStateProvider;
|
|
1131
|
+
|
|
1132
|
+
override init(): void {
|
|
1133
|
+
super.init();
|
|
1134
|
+
const form = this.getModel("form") as JSONModel;
|
|
1135
|
+
this._dirtyProvider = (context) =>
|
|
1136
|
+
context?.isCrossAppNavigation !== false && form.getProperty("/isDirty") === true;
|
|
1137
|
+
this.onActivate();
|
|
1138
|
+
this.getRouter().initialize();
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
// Hidden: the launchpad would still ask the provider when the user navigates between other apps.
|
|
1142
|
+
override onDeactivate(): void {
|
|
1143
|
+
if (this._dirtyProvider) Container.deregisterDirtyStateProvider(this._dirtyProvider);
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
override onActivate(): void {
|
|
1147
|
+
if (this._dirtyProvider) Container.registerDirtyStateProvider(this._dirtyProvider);
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
override exit(): void {
|
|
1151
|
+
this.onDeactivate();
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
```
|
|
1155
|
+
|
|
1156
|
+
> [!WARNING]
|
|
1157
|
+
> `UIComponent` calls `init()` from its constructor. TypeScript class field initializers run after that constructor and overwrite what `init()` stored: with `private _dirtyProvider: DirtyStateProvider | null = null`, `onDeactivate()` and `exit()` find nothing to deregister. The same applies to guards that `init()` registers and `exit()` removes. Declare such fields without an initializer: `ui5-tooling-transpile` (Babel 7, `allowDeclareFields: false`) emits nothing for them. tsc with `useDefineForClassFields` (the default from target ES2022) and Babel with `allowDeclareFields: true` still emit them as `undefined`; there, write `declare private _dirtyProvider: DirtyStateProvider | undefined;`, which Babel 7 with its default options rejects.
|
|
1158
|
+
|
|
1159
|
+
An app that the launchpad runs in an iframe is hidden and shown the same way, but the app runtime inside the iframe asks its provider, see [Keep-alive apps: dirty-state provider](../../docs/guides/flp-keep-alive.md).
|
|
913
1160
|
|
|
914
1161
|
## Redirect chains
|
|
915
1162
|
|
|
916
|
-
When a guard redirects
|
|
1163
|
+
When a guard redirects from route A to route B, the global and route-specific enter guards of B run before anything commits. If B redirects too, the chain continues. Leave guards run only for the first navigation, not on redirect hops.
|
|
917
1164
|
|
|
918
1165
|
```
|
|
919
1166
|
User navigates to "dashboard"
|
|
920
|
-
→ dashboard guard
|
|
921
|
-
→ profile guard
|
|
1167
|
+
→ dashboard guard returns "profile"
|
|
1168
|
+
→ profile guard returns "onboarding"
|
|
922
1169
|
→ onboarding guard allows → onboarding view renders
|
|
923
1170
|
```
|
|
924
1171
|
|
|
925
|
-
Two safeguards
|
|
1172
|
+
Two safeguards stop redirect loops. Each logs an error and settles the navigation as `Blocked`:
|
|
926
1173
|
|
|
927
|
-
- **Visited
|
|
928
|
-
- **Depth cap
|
|
1174
|
+
- **Visited set**: a chain that reaches a hash it has evaluated before is a loop.
|
|
1175
|
+
- **Depth cap**: a chain longer than 10 hops is blocked, even if every hash is unique.
|
|
929
1176
|
|
|
930
|
-
|
|
1177
|
+
## Browser history
|
|
931
1178
|
|
|
932
|
-
|
|
1179
|
+
A hash that a guard refused does not stay in the history, and Back returns to the page the navigation started from.
|
|
933
1180
|
|
|
934
|
-
|
|
1181
|
+
| Navigation | Blocked (or `Error`) | Redirected |
|
|
1182
|
+
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
1183
|
+
| `navTo()` | No hash is written | Only the final target is written, the way the call asked: a new entry, or with `bReplace` the current entry replaced. Back returns to the page it started on |
|
|
1184
|
+
| Back or forward (a step through the history) | The router takes the step back with `history.go()`. The history is as it was, forward entries included | The entry the step arrived at is replaced with the target |
|
|
1185
|
+
| Any other hash change (URL bar, link, `HashChanger.setHash()`) | The new entry is replaced with the previous hash | The new entry is replaced with the target |
|
|
935
1186
|
|
|
936
|
-
|
|
1187
|
+
A redirect chain writes once, its final target. A redirect to the route that is shown settles as `Redirected` without matching that route again (no `routeMatched`) and writes no hash: after a `navTo()` the URL stays as it is, a hash change is undone as if it were blocked. A `parse()` call with the current hash still matches the route again, as it does with the native router.
|
|
937
1188
|
|
|
938
|
-
|
|
1189
|
+
The history in three cases, starting on `home` (the current entry in bold):
|
|
939
1190
|
|
|
940
|
-
|
|
1191
|
+
| Case | Before | While the guards run | After |
|
|
1192
|
+
| -------------------------------------------------------- | -------------------- | -------------------- | --------------------- |
|
|
1193
|
+
| `navTo("admin")`, redirected to `profile` | **`home`** | **`home`** | `home`, **`profile`** |
|
|
1194
|
+
| `#admin` typed into the URL bar, redirected to `profile` | **`home`** | `home`, **`admin`** | `home`, **`profile`** |
|
|
1195
|
+
| Back from `detail` to `home`, blocked by a leave guard | `home`, **`detail`** | **`home`**, `detail` | `home`, **`detail`** |
|
|
941
1196
|
|
|
942
|
-
|
|
1197
|
+
`navTo()` runs the guards before any hash is written:
|
|
943
1198
|
|
|
944
|
-
|
|
1199
|
+
Allowed: the hash is written once the guards have passed.
|
|
945
1200
|
|
|
1201
|
+
```mermaid
|
|
1202
|
+
sequenceDiagram
|
|
1203
|
+
participant App
|
|
1204
|
+
box rgba(0, 114, 178, 0.15) This library
|
|
1205
|
+
participant Router as Guard router
|
|
1206
|
+
end
|
|
1207
|
+
participant History as Browser history
|
|
1208
|
+
rect rgba(0, 158, 115, 0.15)
|
|
1209
|
+
App->>Router: navTo("admin")
|
|
1210
|
+
Router->>Router: leave, global and<br/>route guards allow
|
|
1211
|
+
Router->>History: new entry<br/>#35;admin
|
|
1212
|
+
Router-->>App: settles Committed
|
|
1213
|
+
Router-->>App: routeMatched "admin"
|
|
1214
|
+
end
|
|
946
1215
|
```
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
┌────┴────┐
|
|
964
|
-
allowed blocked
|
|
965
|
-
↓ ↓
|
|
966
|
-
super.navTo() return
|
|
967
|
-
hash changes (no hash change)
|
|
1216
|
+
|
|
1217
|
+
Blocked: nothing is written.
|
|
1218
|
+
|
|
1219
|
+
```mermaid
|
|
1220
|
+
sequenceDiagram
|
|
1221
|
+
participant App
|
|
1222
|
+
box rgba(0, 114, 178, 0.15) This library
|
|
1223
|
+
participant Router as Guard router
|
|
1224
|
+
end
|
|
1225
|
+
participant History as Browser history
|
|
1226
|
+
rect rgba(213, 94, 0, 0.15)
|
|
1227
|
+
App->>Router: navTo("admin")
|
|
1228
|
+
Router->>Router: a guard blocks
|
|
1229
|
+
Router-->>App: settles Blocked
|
|
1230
|
+
Note over History: no entry written
|
|
1231
|
+
end
|
|
968
1232
|
```
|
|
969
1233
|
|
|
970
|
-
|
|
1234
|
+
Redirected to `profile`: only the final target is written.
|
|
1235
|
+
|
|
1236
|
+
```mermaid
|
|
1237
|
+
sequenceDiagram
|
|
1238
|
+
participant App
|
|
1239
|
+
box rgba(0, 114, 178, 0.15) This library
|
|
1240
|
+
participant Router as Guard router
|
|
1241
|
+
end
|
|
1242
|
+
participant History as Browser history
|
|
1243
|
+
rect rgba(240, 228, 66, 0.15)
|
|
1244
|
+
App->>Router: navTo("admin")
|
|
1245
|
+
Router->>Router: an enter guard<br/>redirects to "profile"
|
|
1246
|
+
Router->>Router: global and route guards<br/>of "profile" allow
|
|
1247
|
+
Router->>History: new entry<br/>#35;profile
|
|
1248
|
+
Router-->>App: settles Redirected
|
|
1249
|
+
Router-->>App: routeMatched "profile"
|
|
1250
|
+
end
|
|
1251
|
+
```
|
|
971
1252
|
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
1253
|
+
A hash change from the browser arrives after the URL has changed, so the router puts it back or replaces it:
|
|
1254
|
+
|
|
1255
|
+
Back, blocked by a leave guard: the router takes the step back.
|
|
1256
|
+
|
|
1257
|
+
```mermaid
|
|
1258
|
+
sequenceDiagram
|
|
1259
|
+
actor User
|
|
1260
|
+
participant Browser
|
|
1261
|
+
box rgba(0, 114, 178, 0.15) This library
|
|
1262
|
+
participant Router as Guard router
|
|
1263
|
+
end
|
|
1264
|
+
rect rgba(213, 94, 0, 0.15)
|
|
1265
|
+
User->>Browser: Back
|
|
1266
|
+
Browser->>Router: hashChanged "home"
|
|
1267
|
+
Router->>Router: leave guard of<br/>"detail" blocks
|
|
1268
|
+
Router->>Browser: history.go(1)
|
|
1269
|
+
Browser->>Router: hashChanged "detail"
|
|
1270
|
+
Note over Router: taken without guards
|
|
1271
|
+
Router-->>User: settles Blocked, history as before
|
|
1272
|
+
end
|
|
986
1273
|
```
|
|
987
1274
|
|
|
988
|
-
|
|
1275
|
+
`#admin` typed into the URL bar, redirected: the target replaces the new entry.
|
|
1276
|
+
|
|
1277
|
+
```mermaid
|
|
1278
|
+
sequenceDiagram
|
|
1279
|
+
actor User
|
|
1280
|
+
participant Browser
|
|
1281
|
+
box rgba(0, 114, 178, 0.15) This library
|
|
1282
|
+
participant Router as Guard router
|
|
1283
|
+
end
|
|
1284
|
+
rect rgba(240, 228, 66, 0.15)
|
|
1285
|
+
User->>Browser: types #35;admin
|
|
1286
|
+
Note over Browser: new entry #35;admin
|
|
1287
|
+
Browser->>Router: hashChanged "admin"
|
|
1288
|
+
Router->>Router: an enter guard<br/>redirects to "profile"
|
|
1289
|
+
Router->>Router: global and route guards<br/>of "profile" allow
|
|
1290
|
+
Router->>Browser: replaces the entry<br/>with #35;profile
|
|
1291
|
+
Browser->>Router: hashChanged "profile"
|
|
1292
|
+
Note over Router: commits without guards
|
|
1293
|
+
Router-->>User: settles Redirected
|
|
1294
|
+
end
|
|
1295
|
+
```
|
|
989
1296
|
|
|
990
|
-
|
|
1297
|
+
**Settlement of a blocked step.** The browser takes a step asynchronously. A navigation that the router undoes with a step settles once the URL is back, after the `hashChanged` event that started it has returned.
|
|
1298
|
+
|
|
1299
|
+
**How a step is recognized.** The router reads the length and direction of a step from the browser's [Navigation API](https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API) (Chrome and Edge 102+, Firefox 147+, Safari 26.2+). Without it, a blocked back or forward step is handled like any other hash change: its entry is replaced with the previous hash, the page the step went to is gone from the history, and the current page has two entries.
|
|
1300
|
+
|
|
1301
|
+
The cases that leave the history different from before are listed under [Limitations](#browser-history-after-a-refused-hash-change).
|
|
1302
|
+
|
|
1303
|
+
## Nested components
|
|
1304
|
+
|
|
1305
|
+
A component that a parent router displays through a routing target of type `Component` can have its own guard router: set `routerClass` to `ui5.guard.router.Router` in the nested component's manifest and declare its guards there or in its `Component.ts`. Each router guards only its own routes:
|
|
1306
|
+
|
|
1307
|
+
- The nested router's guards see the nested part of the hash. `context.ownerComponent` is the nested component, so manifest guards read its models, not the parent's.
|
|
1308
|
+
- A redirect names a route of the same router. To leave the nested component, navigate with the parent's router (`Component.getOwnerComponentFor(component).getRouter()`), not from a guard.
|
|
1309
|
+
- On the first display, the parent route waits until the nested router's first navigation has passed its guards and matched, as with the native router. If a nested guard blocks that navigation, the parent route is still displayed and the nested component shows no view. If it redirects, the parent waits for the redirect target.
|
|
1310
|
+
- When the parent leaves the route, UI5 stops the nested router and removes its part of the hash. To keep the user in the nested component, register a leave guard on the parent's route.
|
|
1311
|
+
- A `navTo()` of the parent, or a guard redirect, with `componentTargetInfo` commits and settles when UI5 has loaded the nested components and written the hash, not within the call. Until then the navigation is pending, and a navigation that supersedes it, `stop()` or `destroy()` settles it as `Cancelled`. That is also how a navigation ends whose hash UI5 never writes, because a nested component failed to load or the router is not async.
|
|
1312
|
+
- Navigate with `navTo()` of the respective router or with the router's own hash changer (`router.getHashChanger()`). The global `HashChanger.getInstance()` replaces the whole browser hash, including the part of the other router ([Enabling Routing in Nested Components](https://sdk.openui5.org/#/topic/fb19f501b16e4e4991eb6a017770945b)).
|
|
1313
|
+
|
|
1314
|
+
When the parent refuses a hash change, it puts the whole URL back, the nested part included. UI5 reports every hash change to the nested router whatever the parent decides, so the nested router first matches its part of the refused hash and then its previous route, and fires the events of both:
|
|
1315
|
+
|
|
1316
|
+
```mermaid
|
|
1317
|
+
sequenceDiagram
|
|
1318
|
+
participant Browser
|
|
1319
|
+
box rgba(0, 114, 178, 0.15) This library
|
|
1320
|
+
participant Parent as Parent router
|
|
1321
|
+
participant Child as Nested router
|
|
1322
|
+
end
|
|
1323
|
+
rect rgba(213, 94, 0, 0.15)
|
|
1324
|
+
Note over Browser: #35;shell&/child/detail/1,<br/>Back to #35;home
|
|
1325
|
+
Browser->>Parent: hashChanged "home"
|
|
1326
|
+
Parent->>Parent: leave guard of<br/>"shell" blocks
|
|
1327
|
+
Parent->>Browser: history.go(1)
|
|
1328
|
+
Browser->>Child: hashChanged "", its part of #35;home
|
|
1329
|
+
Note over Child: matches "list"
|
|
1330
|
+
Browser->>Parent: hashChanged "shell"
|
|
1331
|
+
Note over Parent: taken without guards,<br/>settles Blocked
|
|
1332
|
+
Browser->>Child: hashChanged "detail/1"
|
|
1333
|
+
Note over Child: matches "detail"<br/>again
|
|
1334
|
+
end
|
|
1335
|
+
```
|
|
991
1336
|
|
|
992
|
-
|
|
1337
|
+
With `propagateTitle` set on the component target or in the routing config, titles propagate from the nested router to the parent as with the native router. `titleChanged` fires only for navigations that commit; while a navigation waits for async guards, UI5 defers it to the next `routeMatched`.
|
|
993
1338
|
|
|
994
|
-
The router
|
|
1339
|
+
The router relies on two UI5 internals for this, see [Compatibility](#compatibility).
|
|
995
1340
|
|
|
996
|
-
|
|
1341
|
+
## Compatibility with `sap.m.routing.Router`
|
|
997
1342
|
|
|
998
|
-
|
|
999
|
-
import Log from "sap/base/Log";
|
|
1000
|
-
Log.setLevel(Log.Level.DEBUG, "ui5.guard.router.Router");
|
|
1001
|
-
```
|
|
1343
|
+
The router is a `sap.m.routing.Router` with the guard API added. Without guards it behaves like the native router in every row below. With guards it differs only where a guard blocks, redirects or makes a navigation wait. Differential tests run the same steps on both routers and compare hashes, history entries, routing events, titles, displayed views and log lines. The test behind each row is listed in [Compatibility evidence](../../docs/guides/native-router-compatibility.md); how the comparison works is in [Upstream Parity](../../docs/reference/upstream-parity.md).
|
|
1002
1344
|
|
|
1003
|
-
|
|
1345
|
+
| Behavior | Native router | Guard router with guards |
|
|
1346
|
+
| -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1347
|
+
| Route matching, `getRouteInfoByHash()`, `getURL()` | The first route whose pattern matches | Same; guards get the first match as `toRoute` |
|
|
1348
|
+
| Events: `beforeRouteMatched`, `routeMatched`, `routePatternMatched`, `bypassed`, the events of a `Route` | Fire for every hash | Fire once the guards allow; none for a blocked navigation; only those of the target for a redirect |
|
|
1349
|
+
| Titles: `titleChanged`, `propagateTitle` | Change with every route match | Change only for navigations that commit. The target of a redirected hash change gets the title entry that the redirected hash would have got |
|
|
1350
|
+
| Views and `NavContainer` transitions | Targets display views, view levels choose the animation direction | Same, once the guards allow |
|
|
1351
|
+
| `navTo()` with and without `bReplace` | Writes the hash: a new entry, or the current one replaced | Blocked: writes nothing. Redirected: writes only the final target, the way the call asked |
|
|
1352
|
+
| `navTo()` to the route that is shown, `componentTargetInfo` | Sets or resets the hashes of nested components; with `componentTargetInfo` the route matches once UI5 has written the combined hash | Same, no guard runs. A redirect to the route that is shown changes nothing, with `componentTargetInfo` it sets the nested hashes |
|
|
1353
|
+
| `parse()` with the current hash | The route matches again | Same, without guards |
|
|
1354
|
+
| `Targets#display()` without a route | Displays the target, no hash change; the route shown before matches again when its hash is reported | Same; no guard runs for the display |
|
|
1355
|
+
| Back, forward and the address bar | Every hash that matches a route is displayed | A blocked step is taken back with `history.go()`, the history is as it was. A redirected hash change has its entry replaced with the target. See [Browser history](#browser-history) |
|
|
1356
|
+
| Nested components (routing target of type `Component`) | Each nested router has a hash changer of its own and matches its part of the hash | Same with guards that allow. A parent that blocks puts the whole URL back; the nested router matches the refused part first. The parent route waits for a nested first navigation that waits for async guards. See [Nested components](#nested-components) |
|
|
1357
|
+
| `stop()`, `initialize()`, `initialize(true)` | `initialize()` parses the hash, `initialize(true)` keeps the current route; a stopped router ignores hash changes and `navTo()` | `initialize()` runs the guards for the hash. After `stop()`, `initialize(true)` resumes the route, so its leave guards run on the next navigation |
|
|
1358
|
+
| Greedy routes (`greedy: true`) | Match in addition to the first match | Same with guards that allow. Their guards run too; a greedy route that still matches is left and entered again |
|
|
1359
|
+
| Two routers on one hash changer | Each parses every hash it is told about, also a redirected hash that UI5 reports after the target | A guard router drops the stale report. A native router next to it still parses it. See [Limitations](#routers-that-share-a-hash-changer) |
|
|
1360
|
+
| Fiori launchpad: shell stops and restarts the router, keep-alive | Stopped on a cross-app change, `initialize(true)` or `initialize()` on return | Same calls; a blocked hash change after a cancelled cross-app navigation returns to the URL the browser showed. See [Keep-alive apps](#keep-alive-apps) |
|
|
1004
1361
|
|
|
1005
|
-
|
|
1006
|
-
?sap-ui-log-level=DEBUG
|
|
1007
|
-
```
|
|
1362
|
+
## Limitations
|
|
1008
1363
|
|
|
1009
|
-
|
|
1364
|
+
### Routers that share a hash changer
|
|
1010
1365
|
|
|
1011
|
-
|
|
1366
|
+
A component's router gets a hash changer of its own only when the component is displayed by a routing target of type `Component`. The routers of all other components with routing (in a `ComponentContainer`, or created with `Component.create()` outside routing) share the root one, as the root routers of all apps in the Fiori launchpad do. When one router redirects a hash change, UI5 reports the redirected hash to the routers after it only after the target. A guard router ignores that stale report. A native `sap.m.routing.Router` displays its route, although the URL shows the target, as it does next to another native router. Use the guard router for every router on a shared hash changer, or display the component through a routing target.
|
|
1012
1367
|
|
|
1013
|
-
|
|
1368
|
+
### Targets displayed without a route
|
|
1014
1369
|
|
|
1015
|
-
|
|
1370
|
+
`getTargets().display()` displays a target without a hash change and without route matching, so no guard runs. Guard the code path that calls it instead.
|
|
1016
1371
|
|
|
1017
|
-
|
|
1372
|
+
### `sap.f.routing.Router` is not supported
|
|
1018
1373
|
|
|
1019
|
-
|
|
1374
|
+
The router extends `sap.m.routing.Router`. Apps whose root control is `sap.f.FlexibleColumnLayout` and that need `sap.f.routing.Router` (route `layout` property) cannot use it.
|
|
1020
1375
|
|
|
1021
|
-
|
|
1376
|
+
### Optional and query segments in pattern-tree inheritance
|
|
1022
1377
|
|
|
1023
|
-
|
|
1378
|
+
With `inheritance: "pattern-tree"`, ancestry is decided by the mandatory segments of a pattern. Optional (`:id:`), rest (`:all*:`) and query segments are ignored, so a route whose pattern has only such segments is an ancestor of no route.
|
|
1024
1379
|
|
|
1025
|
-
|
|
1380
|
+
### Browser history after a refused hash change
|
|
1026
1381
|
|
|
1027
|
-
|
|
1382
|
+
The router puts the URL back after every hash change it refuses, see [Browser history](#browser-history). In these cases the history still differs from what it was:
|
|
1028
1383
|
|
|
1029
|
-
The
|
|
1384
|
+
- **A hash change that is not a step through the history** (URL bar, link, `HashChanger.setHash()`) has added an entry and dropped the forward entries. The router replaces the new entry with the previous hash, so the current page has two entries, and the dropped forward entries are not recovered.
|
|
1385
|
+
- **Browsers without the Navigation API** (Firefox before 147, Safari before 26.2) handle a blocked back or forward step the same way.
|
|
1386
|
+
- **`navTo()` while a blocked step is taken back.** The blocked navigation settles first, then the `navTo()` runs. Its new entry drops the entry that the browser was stepping back to.
|
|
1387
|
+
- **Nested components.** When the parent router blocks a hash change, or redirects it to the route it shows, the nested router matches its part of the refused hash before it returns to its previous route, and fires the events of both ([Nested components](#nested-components)).
|
|
1030
1388
|
|
|
1031
|
-
|
|
1032
|
-
# All suites (Router, RouterGuards, RouterAsync, RouterNavigation, RouterSettlement, RouterOptions, GuardPipeline, NativeRouterCompat, UpstreamParity)
|
|
1033
|
-
npm run test:qunit
|
|
1389
|
+
### URL bar shows target hash during async guards (browser-initiated only)
|
|
1034
1390
|
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1391
|
+
For back/forward, URL bar entries and direct hash changes, the URL bar shows the target hash while an async guard resolves. UI5's `HashChanger` changes the URL and fires `hashChanged` before `parse()` runs, so the router can only react. If the guard blocks or redirects, the router puts the URL back or replaces it with the target (see [Browser history](#browser-history)).
|
|
1392
|
+
|
|
1393
|
+
This does not apply to `navTo()`, which changes the hash only after the guards allow, nor to sync guards, which decide in the same tick as the hash change. Show a busy indicator while async guards run, as in the [busy indicator example](#navigation-settlement).
|
|
1394
|
+
|
|
1395
|
+
## Debugging and Troubleshooting
|
|
1038
1396
|
|
|
1039
|
-
###
|
|
1397
|
+
### Enabling guard logs
|
|
1398
|
+
|
|
1399
|
+
The router logs configuration and registration problems, invalid guard results, guard errors, redirect loops, and discarded async results through UI5's `Log` API under the component name `ui5.guard.router.Router`. Plain allow and block decisions are not logged; at debug level each settled navigation logs its outcome (`Navigation settled: blocked`). When a manifest guard throws, the error log names it, e.g. `Enter guard [1] "checks#1" on route "admin" threw, navigation failed`.
|
|
1400
|
+
|
|
1401
|
+
Optimized UI5 builds log at `ERROR` by default, which hides the router's warnings. Raise the level for the router only in the manifest (since 1.7.0):
|
|
1402
|
+
|
|
1403
|
+
```json
|
|
1404
|
+
"guardRouter": { "logLevel": "warning" }
|
|
1405
|
+
```
|
|
1040
1406
|
|
|
1041
|
-
|
|
1407
|
+
Or in code:
|
|
1042
1408
|
|
|
1043
1409
|
```typescript
|
|
1044
|
-
|
|
1045
|
-
|
|
1410
|
+
import Log from "sap/base/Log";
|
|
1411
|
+
Log.setLevel(Log.Level.DEBUG, "ui5.guard.router.Router");
|
|
1046
1412
|
```
|
|
1047
1413
|
|
|
1048
|
-
|
|
1414
|
+
The URL parameter `?sap-ui-log-level=DEBUG` sets the level for all components.
|
|
1049
1415
|
|
|
1050
|
-
|
|
1051
|
-
| -------------------------------- | ----------------------------------- | ---------------------------------------------------------- |
|
|
1052
|
-
| Enforcement | Compile-time only | Runtime (engine-level) |
|
|
1053
|
-
| `Reflect.get` access | Works | Returns `undefined` |
|
|
1054
|
-
| Bracket notation (`obj["prop"]`) | Works | Returns `undefined` |
|
|
1055
|
-
| Test inspection | Straightforward | Requires dedicated accessors |
|
|
1056
|
-
| UI5 compatibility | Full (prototype-based class system) | Limited (UI5 metadata introspection cannot see `#` fields) |
|
|
1416
|
+
How they combine:
|
|
1057
1417
|
|
|
1058
|
-
|
|
1418
|
+
1. **URL parameter**: sets the global level, which the router's component uses until a level of its own is set.
|
|
1419
|
+
2. **JS API** (`Log.setLevel(level, "ui5.guard.router.Router")`): sets the component's level; the last call wins, also over `logLevel`.
|
|
1420
|
+
3. **Manifest `logLevel`**: applied once, when the router is constructed, to the router's component only, and only if it is more verbose than the level in effect then (from 1. or an earlier call of 2.). It never lowers a level, but once set, the component no longer follows later changes of the global level; change it with 2.
|
|
1059
1421
|
|
|
1060
|
-
|
|
1422
|
+
The level belongs to the component name, so it applies to the whole page: with several guard routers (e.g. nested components) the most verbose `logLevel` wins, and `destroy()` does not reset it.
|
|
1061
1423
|
|
|
1062
|
-
|
|
1063
|
-
> **Shipped UI5 baseline: 1.144.0**
|
|
1064
|
-
>
|
|
1065
|
-
> The published package declares `minUI5Version: 1.144.0`, and the full CI suite runs on that shipped baseline. In addition, CI runs the library QUnit suite against OpenUI5 `1.120.0` as a compatibility lane for the core router implementation. The compatibility baseline is 1.120 because `DataType.registerEnum` (used for the `NavigationOutcome` enum) requires that version. The shipped baseline also carries a vendored OpenUI5 router parity lane for inherited `sap.m.routing.Router` behavior when no guards are active.
|
|
1424
|
+
### Common issues
|
|
1066
1425
|
|
|
1067
|
-
|
|
1426
|
+
**Guards not running**: The name passed to `addRouteGuard()` must be the route name in `manifest.json`, not the pattern or target name. If loop detection blocked a redirect chain, the error log says so, see [Redirect chains](#redirect-chains).
|
|
1068
1427
|
|
|
1069
|
-
|
|
1070
|
-
npm run test:qunit:compat:120
|
|
1071
|
-
```
|
|
1428
|
+
**Navigation blocked unexpectedly**: Only a strict `true` allows navigation. Returning `undefined` or `null`, or no return statement, blocks and logs `Guard returned invalid value, treating as block`. A plain `false` is not logged.
|
|
1072
1429
|
|
|
1073
|
-
The
|
|
1430
|
+
**Redirect treated as blocked**: The redirect target route does not exist. The router logs `Guard redirect target "<name>" is not a known route, treating as blocked`. A redirect to the route that is shown is not a block; it settles as `Redirected` and the route does not match again.
|
|
1074
1431
|
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1432
|
+
**Async guard hangs indefinitely**: `context.signal` aborts only when the navigation is superseded or the router stops or is destroyed, not on a timeout. A `fetch` to a dead endpoint keeps the navigation pending. Set a deadline with `signal: AbortSignal.any([context.signal, AbortSignal.timeout(10_000)])`, see the [async guard timeout pattern](../../docs/guides/integration-patterns.md#async-guard-timeout), which includes a fallback for older browsers.
|
|
1433
|
+
|
|
1434
|
+
**Async guard result discarded**: A newer navigation started before the async guard resolved, so its result is stale. The debug log records it.
|
|
1435
|
+
|
|
1436
|
+
**URL bar shows target hash, then reverts**: Expected for async guards on back/forward and URL changes, see [URL bar shows target hash during async guards](#url-bar-shows-target-hash-during-async-guards-browser-initiated-only).
|
|
1437
|
+
|
|
1438
|
+
## Compatibility
|
|
1439
|
+
|
|
1440
|
+
> [!IMPORTANT]
|
|
1441
|
+
> **Supported UI5 versions: 1.136 and later**
|
|
1442
|
+
>
|
|
1443
|
+
> The package declares `minUI5Version: 1.136.0`, the version that manifest version 2 (`_version` 2.0.0) requires. CI runs the full suite on OpenUI5 1.144.0 and the launchpad tests on SAPUI5 1.151.0 and 1.154.0. It also runs the library QUnit suite with the parity tests on OpenUI5 1.120.0, the oldest version with `DataType.registerEnum` (used for the `NavigationOutcome` enum); that lane catches regressions on older versions, but 1.120 to 1.135 are not supported. How the router compares with the native one: [Compatibility with `sap.m.routing.Router`](#compatibility-with-sapmroutingrouter).
|
|
1444
|
+
|
|
1445
|
+
The router uses public and protected API of `sap.m.routing.Router`, with four exceptions: two UI5 internals for [nested components](#nested-components) (`_bMatchingProcessStarted` and the component target's wait for the nested `routeMatched`), and two for the title history after a redirected hash change (`_bLastHashReplaced` and the array of `getTitleHistory()`). Tests on OpenUI5 1.144.0 and 1.120.0 fail if a UI5 upgrade changes them. Details: [UI5 Internals the Router Relies On](../../docs/reference/architecture.md#ui5-internals-the-router-relies-on).
|
|
1078
1446
|
|
|
1079
1447
|
## License
|
|
1080
1448
|
|