UNPKG

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