UNPKG

17.4 kBJavaScriptView Raw
1import * as i1 from '@ngrx/store';
2import { createAction, props, isNgrxMockEnvironment, select, ACTIVE_RUNTIME_CHECKS, createFeatureSelector, createSelector } from '@ngrx/store';
3import * as i0 from '@angular/core';
4import { InjectionToken, isDevMode, NgModule, Inject } from '@angular/core';
5import * as i2 from '@angular/router';
6import { NavigationStart, RoutesRecognized, NavigationCancel, NavigationError, NavigationEnd } from '@angular/router';
7import { withLatestFrom } from 'rxjs/operators';
8
9/**
10 * An action dispatched when a router navigation request is fired.
11 */
12const ROUTER_REQUEST = '@ngrx/router-store/request';
13const routerRequestAction = createAction(ROUTER_REQUEST, props());
14/**
15 * An action dispatched when the router navigates.
16 */
17const ROUTER_NAVIGATION = '@ngrx/router-store/navigation';
18const routerNavigationAction = createAction(ROUTER_NAVIGATION, props());
19/**
20 * An action dispatched when the router cancels navigation.
21 */
22const ROUTER_CANCEL = '@ngrx/router-store/cancel';
23const routerCancelAction = createAction(ROUTER_CANCEL, props());
24/**
25 * An action dispatched when the router errors.
26 */
27const ROUTER_ERROR = '@ngrx/router-store/error';
28const routerErrorAction = createAction(ROUTER_ERROR, props());
29/**
30 * An action dispatched after navigation has ended and new route is active.
31 */
32const ROUTER_NAVIGATED = '@ngrx/router-store/navigated';
33const routerNavigatedAction = createAction(ROUTER_NAVIGATED, props());
34
35function routerReducer(state, action) {
36 // Allow compilation with strictFunctionTypes - ref: #1344
37 const routerAction = action;
38 switch (routerAction.type) {
39 case ROUTER_NAVIGATION:
40 case ROUTER_ERROR:
41 case ROUTER_CANCEL:
42 return {
43 state: routerAction.payload.routerState,
44 navigationId: routerAction.payload.event.id,
45 };
46 default:
47 return state;
48 }
49}
50
51class RouterStateSerializer {
52}
53
54class FullRouterStateSerializer {
55 serialize(routerState) {
56 return {
57 root: this.serializeRoute(routerState.root),
58 url: routerState.url,
59 };
60 }
61 serializeRoute(route) {
62 const children = route.children.map((c) => this.serializeRoute(c));
63 return {
64 params: route.params,
65 paramMap: route.paramMap,
66 data: route.data,
67 url: route.url,
68 outlet: route.outlet,
69 routeConfig: route.routeConfig
70 ? {
71 component: route.routeConfig.component,
72 path: route.routeConfig.path,
73 pathMatch: route.routeConfig.pathMatch,
74 redirectTo: route.routeConfig.redirectTo,
75 outlet: route.routeConfig.outlet,
76 title: route.routeConfig.title,
77 }
78 : null,
79 queryParams: route.queryParams,
80 queryParamMap: route.queryParamMap,
81 fragment: route.fragment,
82 component: (route.routeConfig
83 ? route.routeConfig.component
84 : undefined),
85 root: undefined,
86 parent: undefined,
87 firstChild: children[0],
88 pathFromRoot: undefined,
89 children,
90 };
91 }
92}
93
94class MinimalRouterStateSerializer {
95 serialize(routerState) {
96 return {
97 root: this.serializeRoute(routerState.root),
98 url: routerState.url,
99 };
100 }
101 serializeRoute(route) {
102 const children = route.children.map((c) => this.serializeRoute(c));
103 return {
104 params: route.params,
105 data: route.data,
106 url: route.url,
107 outlet: route.outlet,
108 routeConfig: route.routeConfig
109 ? {
110 path: route.routeConfig.path,
111 pathMatch: route.routeConfig.pathMatch,
112 redirectTo: route.routeConfig.redirectTo,
113 outlet: route.routeConfig.outlet,
114 title: route.routeConfig.title,
115 }
116 : null,
117 queryParams: route.queryParams,
118 fragment: route.fragment,
119 firstChild: children[0],
120 children,
121 };
122 }
123}
124
125var NavigationActionTiming;
126(function (NavigationActionTiming) {
127 NavigationActionTiming[NavigationActionTiming["PreActivation"] = 1] = "PreActivation";
128 NavigationActionTiming[NavigationActionTiming["PostActivation"] = 2] = "PostActivation";
129})(NavigationActionTiming || (NavigationActionTiming = {}));
130const _ROUTER_CONFIG = new InjectionToken('@ngrx/router-store Internal Configuration');
131const ROUTER_CONFIG = new InjectionToken('@ngrx/router-store Configuration');
132const DEFAULT_ROUTER_FEATURENAME = 'router';
133function _createRouterConfig(config) {
134 return {
135 stateKey: DEFAULT_ROUTER_FEATURENAME,
136 serializer: MinimalRouterStateSerializer,
137 navigationActionTiming: NavigationActionTiming.PreActivation,
138 ...config,
139 };
140}
141var RouterTrigger;
142(function (RouterTrigger) {
143 RouterTrigger[RouterTrigger["NONE"] = 1] = "NONE";
144 RouterTrigger[RouterTrigger["ROUTER"] = 2] = "ROUTER";
145 RouterTrigger[RouterTrigger["STORE"] = 3] = "STORE";
146})(RouterTrigger || (RouterTrigger = {}));
147/**
148 * Connects RouterModule with StoreModule.
149 *
150 * During the navigation, before any guards or resolvers run, the router will dispatch
151 * a ROUTER_NAVIGATION action, which has the following signature:
152 *
153 * ```
154 * export type RouterNavigationPayload = {
155 * routerState: SerializedRouterStateSnapshot,
156 * event: RoutesRecognized
157 * }
158 * ```
159 *
160 * Either a reducer or an effect can be invoked in response to this action.
161 * If the invoked reducer throws, the navigation will be canceled.
162 *
163 * If navigation gets canceled because of a guard, a ROUTER_CANCEL action will be
164 * dispatched. If navigation results in an error, a ROUTER_ERROR action will be dispatched.
165 *
166 * Both ROUTER_CANCEL and ROUTER_ERROR contain the store state before the navigation
167 * which can be used to restore the consistency of the store.
168 *
169 * Usage:
170 *
171 * ```typescript
172 * @NgModule({
173 * declarations: [AppCmp, SimpleCmp],
174 * imports: [
175 * BrowserModule,
176 * StoreModule.forRoot(mapOfReducers),
177 * RouterModule.forRoot([
178 * { path: '', component: SimpleCmp },
179 * { path: 'next', component: SimpleCmp }
180 * ]),
181 * StoreRouterConnectingModule.forRoot()
182 * ],
183 * bootstrap: [AppCmp]
184 * })
185 * export class AppModule {
186 * }
187 * ```
188 */
189class StoreRouterConnectingModule {
190 constructor(store, router, serializer, errorHandler, config, activeRuntimeChecks) {
191 this.store = store;
192 this.router = router;
193 this.serializer = serializer;
194 this.errorHandler = errorHandler;
195 this.config = config;
196 this.activeRuntimeChecks = activeRuntimeChecks;
197 this.lastEvent = null;
198 this.routerState = null;
199 this.trigger = RouterTrigger.NONE;
200 this.stateKey = this.config.stateKey;
201 if (!isNgrxMockEnvironment() &&
202 isDevMode() &&
203 (activeRuntimeChecks?.strictActionSerializability ||
204 activeRuntimeChecks?.strictStateSerializability) &&
205 this.serializer instanceof FullRouterStateSerializer) {
206 console.warn('@ngrx/router-store: The serializability runtime checks cannot be enabled ' +
207 'with the FullRouterStateSerializer. The FullRouterStateSerializer ' +
208 'has an unserializable router state and actions that are not serializable. ' +
209 'To use the serializability runtime checks either use ' +
210 'the MinimalRouterStateSerializer or implement a custom router state serializer.');
211 }
212 this.setUpStoreStateListener();
213 this.setUpRouterEventsListener();
214 }
215 static forRoot(config = {}) {
216 return {
217 ngModule: StoreRouterConnectingModule,
218 providers: [
219 { provide: _ROUTER_CONFIG, useValue: config },
220 {
221 provide: ROUTER_CONFIG,
222 useFactory: _createRouterConfig,
223 deps: [_ROUTER_CONFIG],
224 },
225 {
226 provide: RouterStateSerializer,
227 useClass: config.serializer
228 ? config.serializer
229 : config.routerState === 0 /* Full */
230 ? FullRouterStateSerializer
231 : MinimalRouterStateSerializer,
232 },
233 ],
234 };
235 }
236 setUpStoreStateListener() {
237 this.store
238 .pipe(select(this.stateKey), withLatestFrom(this.store))
239 .subscribe(([routerStoreState, storeState]) => {
240 this.navigateIfNeeded(routerStoreState, storeState);
241 });
242 }
243 navigateIfNeeded(routerStoreState, storeState) {
244 if (!routerStoreState || !routerStoreState.state) {
245 return;
246 }
247 if (this.trigger === RouterTrigger.ROUTER) {
248 return;
249 }
250 if (this.lastEvent instanceof NavigationStart) {
251 return;
252 }
253 const url = routerStoreState.state.url;
254 if (!isSameUrl(this.router.url, url)) {
255 this.storeState = storeState;
256 this.trigger = RouterTrigger.STORE;
257 this.router.navigateByUrl(url).catch((error) => {
258 this.errorHandler.handleError(error);
259 });
260 }
261 }
262 setUpRouterEventsListener() {
263 const dispatchNavLate = this.config.navigationActionTiming ===
264 NavigationActionTiming.PostActivation;
265 let routesRecognized;
266 this.router.events
267 .pipe(withLatestFrom(this.store))
268 .subscribe(([event, storeState]) => {
269 this.lastEvent = event;
270 if (event instanceof NavigationStart) {
271 this.routerState = this.serializer.serialize(this.router.routerState.snapshot);
272 if (this.trigger !== RouterTrigger.STORE) {
273 this.storeState = storeState;
274 this.dispatchRouterRequest(event);
275 }
276 }
277 else if (event instanceof RoutesRecognized) {
278 routesRecognized = event;
279 if (!dispatchNavLate && this.trigger !== RouterTrigger.STORE) {
280 this.dispatchRouterNavigation(event);
281 }
282 }
283 else if (event instanceof NavigationCancel) {
284 this.dispatchRouterCancel(event);
285 this.reset();
286 }
287 else if (event instanceof NavigationError) {
288 this.dispatchRouterError(event);
289 this.reset();
290 }
291 else if (event instanceof NavigationEnd) {
292 if (this.trigger !== RouterTrigger.STORE) {
293 if (dispatchNavLate) {
294 this.dispatchRouterNavigation(routesRecognized);
295 }
296 this.dispatchRouterNavigated(event);
297 }
298 this.reset();
299 }
300 });
301 }
302 dispatchRouterRequest(event) {
303 this.dispatchRouterAction(ROUTER_REQUEST, { event });
304 }
305 dispatchRouterNavigation(lastRoutesRecognized) {
306 const nextRouterState = this.serializer.serialize(lastRoutesRecognized.state);
307 this.dispatchRouterAction(ROUTER_NAVIGATION, {
308 routerState: nextRouterState,
309 event: new RoutesRecognized(lastRoutesRecognized.id, lastRoutesRecognized.url, lastRoutesRecognized.urlAfterRedirects, nextRouterState),
310 });
311 }
312 dispatchRouterCancel(event) {
313 this.dispatchRouterAction(ROUTER_CANCEL, {
314 storeState: this.storeState,
315 event,
316 });
317 }
318 dispatchRouterError(event) {
319 this.dispatchRouterAction(ROUTER_ERROR, {
320 storeState: this.storeState,
321 event: new NavigationError(event.id, event.url, `${event}`),
322 });
323 }
324 dispatchRouterNavigated(event) {
325 const routerState = this.serializer.serialize(this.router.routerState.snapshot);
326 this.dispatchRouterAction(ROUTER_NAVIGATED, { event, routerState });
327 }
328 dispatchRouterAction(type, payload) {
329 this.trigger = RouterTrigger.ROUTER;
330 try {
331 this.store.dispatch({
332 type,
333 payload: {
334 routerState: this.routerState,
335 ...payload,
336 event: this.config.routerState === 0 /* Full */
337 ? payload.event
338 : {
339 id: payload.event.id,
340 url: payload.event.url,
341 // safe, as it will just be `undefined` for non-NavigationEnd router events
342 urlAfterRedirects: payload.event
343 .urlAfterRedirects,
344 },
345 },
346 });
347 }
348 finally {
349 this.trigger = RouterTrigger.NONE;
350 }
351 }
352 reset() {
353 this.trigger = RouterTrigger.NONE;
354 this.storeState = null;
355 this.routerState = null;
356 }
357}
358/** @nocollapse */ StoreRouterConnectingModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.0.0-rc.1", ngImport: i0, type: StoreRouterConnectingModule, deps: [{ token: i1.Store }, { token: i2.Router }, { token: RouterStateSerializer }, { token: i0.ErrorHandler }, { token: ROUTER_CONFIG }, { token: ACTIVE_RUNTIME_CHECKS }], target: i0.ɵɵFactoryTarget.NgModule });
359/** @nocollapse */ StoreRouterConnectingModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "14.0.0-rc.1", ngImport: i0, type: StoreRouterConnectingModule });
360/** @nocollapse */ StoreRouterConnectingModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "14.0.0-rc.1", ngImport: i0, type: StoreRouterConnectingModule });
361i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.0.0-rc.1", ngImport: i0, type: StoreRouterConnectingModule, decorators: [{
362 type: NgModule,
363 args: [{}]
364 }], ctorParameters: function () { return [{ type: i1.Store }, { type: i2.Router }, { type: RouterStateSerializer }, { type: i0.ErrorHandler }, { type: undefined, decorators: [{
365 type: Inject,
366 args: [ROUTER_CONFIG]
367 }] }, { type: undefined, decorators: [{
368 type: Inject,
369 args: [ACTIVE_RUNTIME_CHECKS]
370 }] }]; } });
371/**
372 * Check if the URLs are matching. Accounts for the possibility of trailing "/" in url.
373 */
374function isSameUrl(first, second) {
375 return stripTrailingSlash(first) === stripTrailingSlash(second);
376}
377function stripTrailingSlash(text) {
378 if (text?.length > 0 && text[text.length - 1] === '/') {
379 return text.substring(0, text.length - 1);
380 }
381 return text;
382}
383
384function createRouterSelector() {
385 return createFeatureSelector(DEFAULT_ROUTER_FEATURENAME);
386}
387function getSelectors(selectState = createRouterSelector()) {
388 const selectRouterState = createSelector(selectState, (router) => router && router.state);
389 const selectRootRoute = createSelector(selectRouterState, (routerState) => routerState && routerState.root);
390 const selectCurrentRoute = createSelector(selectRootRoute, (rootRoute) => {
391 if (!rootRoute) {
392 return undefined;
393 }
394 let route = rootRoute;
395 while (route.firstChild) {
396 route = route.firstChild;
397 }
398 return route;
399 });
400 const selectFragment = createSelector(selectRootRoute, (route) => route && route.fragment);
401 const selectQueryParams = createSelector(selectRootRoute, (route) => route && route.queryParams);
402 const selectQueryParam = (param) => createSelector(selectQueryParams, (params) => params && params[param]);
403 const selectRouteParams = createSelector(selectCurrentRoute, (route) => route && route.params);
404 const selectRouteParam = (param) => createSelector(selectRouteParams, (params) => params && params[param]);
405 const selectRouteData = createSelector(selectCurrentRoute, (route) => route && route.data);
406 const selectUrl = createSelector(selectRouterState, (routerState) => routerState && routerState.url);
407 const selectTitle = createSelector(selectCurrentRoute, (route) => route && route.routeConfig?.title);
408 return {
409 selectCurrentRoute,
410 selectFragment,
411 selectQueryParams,
412 selectQueryParam,
413 selectRouteParams,
414 selectRouteParam,
415 selectRouteData,
416 selectUrl,
417 selectTitle,
418 };
419}
420
421/**
422 * DO NOT EDIT
423 *
424 * This file is automatically generated at build
425 */
426
427/**
428 * Generated bundle index. Do not edit.
429 */
430
431export { DEFAULT_ROUTER_FEATURENAME, FullRouterStateSerializer, MinimalRouterStateSerializer, NavigationActionTiming, ROUTER_CANCEL, ROUTER_CONFIG, ROUTER_ERROR, ROUTER_NAVIGATED, ROUTER_NAVIGATION, ROUTER_REQUEST, RouterStateSerializer, StoreRouterConnectingModule, createRouterSelector, getSelectors, routerCancelAction, routerErrorAction, routerNavigatedAction, routerNavigationAction, routerReducer, routerRequestAction };
432//# sourceMappingURL=ngrx-router-store.mjs.map