refactor: migrate router to prettier formatting (#54318)

Migrate formatting to prettier for router from clang-format

PR Close #54318
This commit is contained in:
Joey Perrott
2024-02-08 19:17:14 +00:00
committed by Jessica Janiuk
parent d02fcb1ab4
commit b857aafcb9
79 changed files with 13550 additions and 10967 deletions
+3 -1
View File
@@ -20,6 +20,7 @@ export const format: FormatConfig = {
'packages/examples/**/*.{js,ts}',
'packages/misc/**/*.{js,ts}',
'packages/private/**/*.{js,ts}',
'packages/router/**/*.{js,ts}',
'packages/service-worker/**/*.{js,ts}',
'packages/upgrade/**/*.{js,ts}',
@@ -33,7 +34,7 @@ export const format: FormatConfig = {
},
'clang-format': {
'matchers': [
//'**/*.{js,ts}',
'**/*.{js,ts}',
// TODO: burn down format failures and remove aio and integration exceptions.
'!aio/**',
'!integration/**',
@@ -70,6 +71,7 @@ export const format: FormatConfig = {
'!packages/examples/**/*.{js,ts}',
'!packages/misc/**/*.{js,ts}',
'!packages/private/**/*.{js,ts}',
'!packages/router/**/*.{js,ts}',
'!packages/service-worker/**/*.{js,ts}',
'!packages/upgrade/**/*.{js,ts}',
],
+1
View File
@@ -2,6 +2,7 @@
"printWidth": 100,
"tabWidth": 2,
"tabs": false,
"embeddedLanguageFormatting": "off",
"singleQuote": true,
"semicolon": true,
"quoteProps": "preserve",
+57 -28
View File
@@ -16,9 +16,8 @@ import {navigationCancelingError} from './navigation_canceling_error';
import {Params, PRIMARY_OUTLET} from './shared';
import {UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree} from './url_tree';
export class NoMatch {
public segmentGroup: UrlSegmentGroup|null;
public segmentGroup: UrlSegmentGroup | null;
constructor(segmentGroup?: UrlSegmentGroup) {
this.segmentGroup = segmentGroup || null;
@@ -40,23 +39,30 @@ export function absoluteRedirect(newTree: UrlTree): Observable<any> {
}
export function namedOutletsRedirect(redirectTo: string): Observable<any> {
return throwError(new RuntimeError(
return throwError(
new RuntimeError(
RuntimeErrorCode.NAMED_OUTLET_REDIRECT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`));
`Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`,
),
);
}
export function canLoadFails(route: Route): Observable<LoadedRouterConfig> {
return throwError(navigationCancelingError(
return throwError(
navigationCancelingError(
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`Cannot load children because the guard of the route "path: '${
route.path}'" returned false`,
NavigationCancellationCode.GuardRejected));
`Cannot load children because the guard of the route "path: '${route.path}'" returned false`,
NavigationCancellationCode.GuardRejected,
),
);
}
export class ApplyRedirects {
constructor(private urlSerializer: UrlSerializer, private urlTree: UrlTree) {}
constructor(
private urlSerializer: UrlSerializer,
private urlTree: UrlTree,
) {}
lineralizeSegments(route: Route, urlTree: UrlTree): Observable<UrlSegment[]> {
let res: UrlSegment[] = [];
@@ -76,9 +82,16 @@ export class ApplyRedirects {
}
applyRedirectCommands(
segments: UrlSegment[], redirectTo: string, posParams: {[k: string]: UrlSegment}): UrlTree {
segments: UrlSegment[],
redirectTo: string,
posParams: {[k: string]: UrlSegment},
): UrlTree {
const newTree = this.applyRedirectCreateUrlTree(
redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
redirectTo,
this.urlSerializer.parse(redirectTo),
segments,
posParams,
);
if (redirectTo.startsWith('/')) {
throw new AbsoluteRedirect(newTree);
}
@@ -86,12 +99,17 @@ export class ApplyRedirects {
}
applyRedirectCreateUrlTree(
redirectTo: string, urlTree: UrlTree, segments: UrlSegment[],
posParams: {[k: string]: UrlSegment}): UrlTree {
redirectTo: string,
urlTree: UrlTree,
segments: UrlSegment[],
posParams: {[k: string]: UrlSegment},
): UrlTree {
const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
return new UrlTree(
newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams),
urlTree.fragment);
newRoot,
this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams),
urlTree.fragment,
);
}
createQueryParams(redirectToParams: Params, actualParams: Params): Params {
@@ -109,8 +127,11 @@ export class ApplyRedirects {
}
createSegmentGroup(
redirectTo: string, group: UrlSegmentGroup, segments: UrlSegment[],
posParams: {[k: string]: UrlSegment}): UrlSegmentGroup {
redirectTo: string,
group: UrlSegmentGroup,
segments: UrlSegment[],
posParams: {[k: string]: UrlSegment},
): UrlSegmentGroup {
const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
let children: {[n: string]: UrlSegmentGroup} = {};
@@ -122,22 +143,30 @@ export class ApplyRedirects {
}
createSegments(
redirectTo: string, redirectToSegments: UrlSegment[], actualSegments: UrlSegment[],
posParams: {[k: string]: UrlSegment}): UrlSegment[] {
return redirectToSegments.map(
s => s.path.startsWith(':') ? this.findPosParam(redirectTo, s, posParams) :
this.findOrReturn(s, actualSegments));
redirectTo: string,
redirectToSegments: UrlSegment[],
actualSegments: UrlSegment[],
posParams: {[k: string]: UrlSegment},
): UrlSegment[] {
return redirectToSegments.map((s) =>
s.path.startsWith(':')
? this.findPosParam(redirectTo, s, posParams)
: this.findOrReturn(s, actualSegments),
);
}
findPosParam(
redirectTo: string, redirectToUrlSegment: UrlSegment,
posParams: {[k: string]: UrlSegment}): UrlSegment {
redirectTo: string,
redirectToUrlSegment: UrlSegment,
posParams: {[k: string]: UrlSegment},
): UrlSegment {
const pos = posParams[redirectToUrlSegment.path.substring(1)];
if (!pos)
throw new RuntimeError(
RuntimeErrorCode.MISSING_REDIRECT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`);
RuntimeErrorCode.MISSING_REDIRECT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`,
);
return pos;
}
@@ -24,7 +24,6 @@ import {RouterOutlet} from '../directives/router_outlet';
imports: [RouterOutlet],
standalone: true,
})
export class ɵEmptyOutletComponent {
}
export class ɵEmptyOutletComponent {}
export {ɵEmptyOutletComponent as EmptyOutletComponent};
+30 -12
View File
@@ -9,19 +9,28 @@
import {BehaviorSubject} from 'rxjs';
import {DetachedRouteHandleInternal, RouteReuseStrategy} from './route_reuse_strategy';
import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot} from './router_state';
import {
ActivatedRoute,
ActivatedRouteSnapshot,
RouterState,
RouterStateSnapshot,
} from './router_state';
import {TreeNode} from './utils/tree';
export function createRouterState(
routeReuseStrategy: RouteReuseStrategy, curr: RouterStateSnapshot,
prevState: RouterState): RouterState {
routeReuseStrategy: RouteReuseStrategy,
curr: RouterStateSnapshot,
prevState: RouterState,
): RouterState {
const root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
return new RouterState(root, curr);
}
function createNode(
routeReuseStrategy: RouteReuseStrategy, curr: TreeNode<ActivatedRouteSnapshot>,
prevState?: TreeNode<ActivatedRoute>): TreeNode<ActivatedRoute> {
routeReuseStrategy: RouteReuseStrategy,
curr: TreeNode<ActivatedRouteSnapshot>,
prevState?: TreeNode<ActivatedRoute>,
): TreeNode<ActivatedRoute> {
// reuse an activated route that is currently displayed on the screen
if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
const value = prevState.value;
@@ -35,21 +44,23 @@ function createNode(
if (detachedRouteHandle !== null) {
const tree = (detachedRouteHandle as DetachedRouteHandleInternal).route;
tree.value._futureSnapshot = curr.value;
tree.children = curr.children.map(c => createNode(routeReuseStrategy, c));
tree.children = curr.children.map((c) => createNode(routeReuseStrategy, c));
return tree;
}
}
const value = createActivatedRoute(curr.value);
const children = curr.children.map(c => createNode(routeReuseStrategy, c));
const children = curr.children.map((c) => createNode(routeReuseStrategy, c));
return new TreeNode<ActivatedRoute>(value, children);
}
}
function createOrReuseChildren(
routeReuseStrategy: RouteReuseStrategy, curr: TreeNode<ActivatedRouteSnapshot>,
prevState: TreeNode<ActivatedRoute>) {
return curr.children.map(child => {
routeReuseStrategy: RouteReuseStrategy,
curr: TreeNode<ActivatedRouteSnapshot>,
prevState: TreeNode<ActivatedRoute>,
) {
return curr.children.map((child) => {
for (const p of prevState.children) {
if (routeReuseStrategy.shouldReuseRoute(child.value, p.value.snapshot)) {
return createNode(routeReuseStrategy, child, p);
@@ -61,6 +72,13 @@ function createOrReuseChildren(
function createActivatedRoute(c: ActivatedRouteSnapshot) {
return new ActivatedRoute(
new BehaviorSubject(c.url), new BehaviorSubject(c.params), new BehaviorSubject(c.queryParams),
new BehaviorSubject(c.fragment), new BehaviorSubject(c.data), c.outlet, c.component, c);
new BehaviorSubject(c.url),
new BehaviorSubject(c.params),
new BehaviorSubject(c.queryParams),
new BehaviorSubject(c.fragment),
new BehaviorSubject(c.data),
c.outlet,
c.component,
c,
);
}
+94 -48
View File
@@ -14,7 +14,6 @@ import {Params, PRIMARY_OUTLET} from './shared';
import {createRoot, squashSegmentGroup, UrlSegment, UrlSegmentGroup, UrlTree} from './url_tree';
import {last, shallowEqual} from './utils/collection';
/**
* Creates a `UrlTree` relative to an `ActivatedRouteSnapshot`.
*
@@ -67,17 +66,21 @@ import {last, shallowEqual} from './utils/collection';
* ```
*/
export function createUrlTreeFromSnapshot(
relativeTo: ActivatedRouteSnapshot, commands: any[], queryParams: Params|null = null,
fragment: string|null = null): UrlTree {
relativeTo: ActivatedRouteSnapshot,
commands: any[],
queryParams: Params | null = null,
fragment: string | null = null,
): UrlTree {
const relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeTo);
return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, queryParams, fragment);
}
export function createSegmentGroupFromRoute(route: ActivatedRouteSnapshot): UrlSegmentGroup {
let targetGroup: UrlSegmentGroup|undefined;
let targetGroup: UrlSegmentGroup | undefined;
function createSegmentGroupFromRouteRecursive(currentRoute: ActivatedRouteSnapshot):
UrlSegmentGroup {
function createSegmentGroupFromRouteRecursive(
currentRoute: ActivatedRouteSnapshot,
): UrlSegmentGroup {
const childOutlets: {[outlet: string]: UrlSegmentGroup} = {};
for (const childSnapshot of currentRoute.children) {
const root = createSegmentGroupFromRouteRecursive(childSnapshot);
@@ -96,8 +99,11 @@ export function createSegmentGroupFromRoute(route: ActivatedRouteSnapshot): UrlS
}
export function createUrlTreeFromSegmentGroup(
relativeTo: UrlSegmentGroup, commands: any[], queryParams: Params|null,
fragment: string|null): UrlTree {
relativeTo: UrlSegmentGroup,
commands: any[],
queryParams: Params | null,
fragment: string | null,
): UrlTree {
let root = relativeTo;
while (root.parent) {
root = root.parent;
@@ -116,9 +122,9 @@ export function createUrlTreeFromSegmentGroup(
}
const position = findStartingPositionForTargetGroup(nav, root, relativeTo);
const newSegmentGroup = position.processChildren ?
updateSegmentGroupChildren(position.segmentGroup, position.index, nav.commands) :
updateSegmentGroup(position.segmentGroup, position.index, nav.commands);
const newSegmentGroup = position.processChildren
? updateSegmentGroupChildren(position.segmentGroup, position.index, nav.commands)
: updateSegmentGroup(position.segmentGroup, position.index, nav.commands);
return tree(root, position.segmentGroup, newSegmentGroup, queryParams, fragment);
}
@@ -135,8 +141,12 @@ function isCommandWithOutlets(command: any): command is {outlets: {[key: string]
}
function tree(
oldRoot: UrlSegmentGroup, oldSegmentGroup: UrlSegmentGroup, newSegmentGroup: UrlSegmentGroup,
queryParams: Params|null, fragment: string|null): UrlTree {
oldRoot: UrlSegmentGroup,
oldSegmentGroup: UrlSegmentGroup,
newSegmentGroup: UrlSegmentGroup,
queryParams: Params | null,
fragment: string | null,
): UrlTree {
let qp: any = {};
if (queryParams) {
Object.entries(queryParams).forEach(([name, value]) => {
@@ -163,8 +173,10 @@ function tree(
* value.
*/
function replaceSegment(
current: UrlSegmentGroup, oldSegment: UrlSegmentGroup,
newSegment: UrlSegmentGroup): UrlSegmentGroup {
current: UrlSegmentGroup,
oldSegment: UrlSegmentGroup,
newSegment: UrlSegmentGroup,
): UrlSegmentGroup {
const children: {[key: string]: UrlSegmentGroup} = {};
Object.entries(current.children).forEach(([outletName, c]) => {
if (c === oldSegment) {
@@ -178,20 +190,25 @@ function replaceSegment(
class Navigation {
constructor(
public isAbsolute: boolean, public numberOfDoubleDots: number, public commands: any[]) {
public isAbsolute: boolean,
public numberOfDoubleDots: number,
public commands: any[],
) {
if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
throw new RuntimeError(
RuntimeErrorCode.ROOT_SEGMENT_MATRIX_PARAMS,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'Root segment cannot have matrix parameters');
RuntimeErrorCode.ROOT_SEGMENT_MATRIX_PARAMS,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'Root segment cannot have matrix parameters',
);
}
const cmdWithOutlet = commands.find(isCommandWithOutlets);
if (cmdWithOutlet && cmdWithOutlet !== last(commands)) {
throw new RuntimeError(
RuntimeErrorCode.MISPLACED_OUTLETS_COMMAND,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'{outlets:{}} has to be the last command');
RuntimeErrorCode.MISPLACED_OUTLETS_COMMAND,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'{outlets:{}} has to be the last command',
);
}
}
@@ -202,7 +219,7 @@ class Navigation {
/** Transforms commands to a normalized `Navigation` */
function computeNavigation(commands: any[]): Navigation {
if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') {
if (typeof commands[0] === 'string' && commands.length === 1 && commands[0] === '/') {
return new Navigation(true, 0, commands);
}
@@ -232,9 +249,11 @@ function computeNavigation(commands: any[]): Navigation {
cmd.split('/').forEach((urlPart, partIndex) => {
if (partIndex == 0 && urlPart === '.') {
// skip './a'
} else if (partIndex == 0 && urlPart === '') { // '/a'
} else if (partIndex == 0 && urlPart === '') {
// '/a'
isAbsolute = true;
} else if (urlPart === '..') { // '../a'
} else if (urlPart === '..') {
// '../a'
numberOfDoubleDots++;
} else if (urlPart != '') {
res.push(urlPart);
@@ -252,12 +271,17 @@ function computeNavigation(commands: any[]): Navigation {
class Position {
constructor(
public segmentGroup: UrlSegmentGroup, public processChildren: boolean, public index: number) {
}
public segmentGroup: UrlSegmentGroup,
public processChildren: boolean,
public index: number,
) {}
}
function findStartingPositionForTargetGroup(
nav: Navigation, root: UrlSegmentGroup, target: UrlSegmentGroup): Position {
nav: Navigation,
root: UrlSegmentGroup,
target: UrlSegmentGroup,
): Position {
if (nav.isAbsolute) {
return new Position(root, true, 0);
}
@@ -279,7 +303,10 @@ function findStartingPositionForTargetGroup(
}
function createPositionApplyingDoubleDots(
group: UrlSegmentGroup, index: number, numberOfDoubleDots: number): Position {
group: UrlSegmentGroup,
index: number,
numberOfDoubleDots: number,
): Position {
let g = group;
let ci = index;
let dd = numberOfDoubleDots;
@@ -288,15 +315,16 @@ function createPositionApplyingDoubleDots(
g = g.parent!;
if (!g) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_DOUBLE_DOTS,
(typeof ngDevMode === 'undefined' || ngDevMode) && 'Invalid number of \'../\'');
RuntimeErrorCode.INVALID_DOUBLE_DOTS,
(typeof ngDevMode === 'undefined' || ngDevMode) && "Invalid number of '../'",
);
}
ci = g.segments.length;
}
return new Position(g, false, ci - dd);
}
function getOutlets(commands: unknown[]): {[k: string]: unknown[]|string} {
function getOutlets(commands: unknown[]): {[k: string]: unknown[] | string} {
if (isCommandWithOutlets(commands[0])) {
return commands[0].outlets;
}
@@ -305,7 +333,10 @@ function getOutlets(commands: unknown[]): {[k: string]: unknown[]|string} {
}
function updateSegmentGroup(
segmentGroup: UrlSegmentGroup|undefined, startIndex: number, commands: any[]): UrlSegmentGroup {
segmentGroup: UrlSegmentGroup | undefined,
startIndex: number,
commands: any[],
): UrlSegmentGroup {
segmentGroup ??= new UrlSegmentGroup([], {});
if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
@@ -315,8 +346,10 @@ function updateSegmentGroup(
const slicedCommands = commands.slice(m.commandIndex);
if (m.match && m.pathIndex < segmentGroup.segments.length) {
const g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
g.children[PRIMARY_OUTLET] =
new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
g.children[PRIMARY_OUTLET] = new UrlSegmentGroup(
segmentGroup.segments.slice(m.pathIndex),
segmentGroup.children,
);
return updateSegmentGroupChildren(g, 0, slicedCommands);
} else if (m.match && slicedCommands.length === 0) {
return new UrlSegmentGroup(segmentGroup.segments, {});
@@ -330,7 +363,10 @@ function updateSegmentGroup(
}
function updateSegmentGroupChildren(
segmentGroup: UrlSegmentGroup, startIndex: number, commands: any[]): UrlSegmentGroup {
segmentGroup: UrlSegmentGroup,
startIndex: number,
commands: any[],
): UrlSegmentGroup {
if (commands.length === 0) {
return new UrlSegmentGroup(segmentGroup.segments, {});
} else {
@@ -357,11 +393,17 @@ function updateSegmentGroupChildren(
// `UrlSegmentGroup` that is created from an "unsquashed"/expanded `ActivatedRoute` tree.
// This code effectively "squashes" empty path primary routes when they have no siblings on
// the same level of the tree.
if (Object.keys(outlets).some(o => o !== PRIMARY_OUTLET) &&
segmentGroup.children[PRIMARY_OUTLET] && segmentGroup.numberOfChildren === 1 &&
segmentGroup.children[PRIMARY_OUTLET].segments.length === 0) {
const childrenOfEmptyChild =
updateSegmentGroupChildren(segmentGroup.children[PRIMARY_OUTLET], startIndex, commands);
if (
Object.keys(outlets).some((o) => o !== PRIMARY_OUTLET) &&
segmentGroup.children[PRIMARY_OUTLET] &&
segmentGroup.numberOfChildren === 1 &&
segmentGroup.children[PRIMARY_OUTLET].segments.length === 0
) {
const childrenOfEmptyChild = updateSegmentGroupChildren(
segmentGroup.children[PRIMARY_OUTLET],
startIndex,
commands,
);
return new UrlSegmentGroup(segmentGroup.segments, childrenOfEmptyChild.children);
}
@@ -400,11 +442,11 @@ function prefixedWith(segmentGroup: UrlSegmentGroup, startIndex: number, command
}
const curr = `${command}`;
const next =
currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
if (currentPathIndex > 0 && curr === undefined) break;
if (curr && next && (typeof next === 'object') && next.outlets === undefined) {
if (curr && next && typeof next === 'object' && next.outlets === undefined) {
if (!compare(curr, next, path)) return noMatch;
currentCommandIndex += 2;
} else {
@@ -418,7 +460,10 @@ function prefixedWith(segmentGroup: UrlSegmentGroup, startIndex: number, command
}
function createNewSegmentGroup(
segmentGroup: UrlSegmentGroup, startIndex: number, commands: any[]): UrlSegmentGroup {
segmentGroup: UrlSegmentGroup,
startIndex: number,
commands: any[],
): UrlSegmentGroup {
const paths = segmentGroup.segments.slice(0, startIndex);
let i = 0;
@@ -438,7 +483,7 @@ function createNewSegmentGroup(
}
const curr = isCommandWithOutlets(command) ? command.outlets[PRIMARY_OUTLET] : `${command}`;
const next = (i < commands.length - 1) ? commands[i + 1] : null;
const next = i < commands.length - 1 ? commands[i + 1] : null;
if (curr && next && isMatrixParams(next)) {
paths.push(new UrlSegment(curr, stringify(next)));
i += 2;
@@ -450,8 +495,9 @@ function createNewSegmentGroup(
return new UrlSegmentGroup(paths, {});
}
function createNewSegmentChildren(outlets: {[name: string]: unknown[]|string}):
{[outlet: string]: UrlSegmentGroup} {
function createNewSegmentChildren(outlets: {[name: string]: unknown[] | string}): {
[outlet: string]: UrlSegmentGroup;
} {
const children: {[outlet: string]: UrlSegmentGroup} = {};
Object.entries(outlets).forEach(([outlet, commands]) => {
if (typeof commands === 'string') {
@@ -466,7 +512,7 @@ function createNewSegmentChildren(outlets: {[name: string]: unknown[]|string}):
function stringify(params: {[key: string]: any}): {[key: string]: string} {
const res: {[key: string]: string} = {};
Object.entries(params).forEach(([k, v]) => res[k] = `${v}`);
Object.entries(params).forEach(([k, v]) => (res[k] = `${v}`));
return res;
}
+67 -37
View File
@@ -7,7 +7,20 @@
*/
import {LocationStrategy} from '@angular/common';
import {Attribute, booleanAttribute, Directive, ElementRef, HostBinding, HostListener, Input, OnChanges, OnDestroy, Renderer2, SimpleChanges, ɵɵsanitizeUrlOrResourceUrl} from '@angular/core';
import {
Attribute,
booleanAttribute,
Directive,
ElementRef,
HostBinding,
HostListener,
Input,
OnChanges,
OnDestroy,
Renderer2,
SimpleChanges,
ɵɵsanitizeUrlOrResourceUrl,
} from '@angular/core';
import {Subject, Subscription} from 'rxjs';
import {Event, NavigationEnd} from '../events';
@@ -17,7 +30,6 @@ import {ActivatedRoute} from '../router_state';
import {Params} from '../shared';
import {UrlTree} from '../url_tree';
/**
* @description
*
@@ -124,7 +136,7 @@ export class RouterLink implements OnChanges, OnDestroy {
* Represents an `href` attribute value applied to a host element,
* when a host element is `<a>`. For other tags, the value is `null`.
*/
href: string|null = null;
href: string | null = null;
/**
* Represents the `target` attribute on a host element.
@@ -138,7 +150,7 @@ export class RouterLink implements OnChanges, OnDestroy {
* @see {@link UrlCreationOptions#queryParams}
* @see {@link Router#createUrlTree}
*/
@Input() queryParams?: Params|null;
@Input() queryParams?: Params | null;
/**
* Passed to {@link Router#createUrlTree} as part of the
* `UrlCreationOptions`.
@@ -152,7 +164,7 @@ export class RouterLink implements OnChanges, OnDestroy {
* @see {@link UrlCreationOptions#queryParamsHandling}
* @see {@link Router#createUrlTree}
*/
@Input() queryParamsHandling?: QueryParamsHandling|null;
@Input() queryParamsHandling?: QueryParamsHandling | null;
/**
* Passed to {@link Router#navigateByUrl} as part of the
* `NavigationBehaviorOptions`.
@@ -176,9 +188,9 @@ export class RouterLink implements OnChanges, OnDestroy {
* @see {@link UrlCreationOptions#relativeTo}
* @see {@link Router#createUrlTree}
*/
@Input() relativeTo?: ActivatedRoute|null;
@Input() relativeTo?: ActivatedRoute | null;
private commands: any[]|null = null;
private commands: any[] | null = null;
/** Whether a host element is an `<a>` tag. */
private isAnchorElement: boolean;
@@ -189,10 +201,13 @@ export class RouterLink implements OnChanges, OnDestroy {
onChanges = new Subject<RouterLink>();
constructor(
private router: Router, private route: ActivatedRoute,
@Attribute('tabindex') private readonly tabIndexAttribute: string|null|undefined,
private readonly renderer: Renderer2, private readonly el: ElementRef,
private locationStrategy?: LocationStrategy) {
private router: Router,
private route: ActivatedRoute,
@Attribute('tabindex') private readonly tabIndexAttribute: string | null | undefined,
private readonly renderer: Renderer2,
private readonly el: ElementRef,
private locationStrategy?: LocationStrategy,
) {
const tagName = el.nativeElement.tagName?.toLowerCase();
this.isAnchorElement = tagName === 'a' || tagName === 'area';
@@ -235,7 +250,7 @@ export class RouterLink implements OnChanges, OnDestroy {
* Modifies the tab index if there was not a tabindex attribute on the element during
* instantiation.
*/
private setTabIndexIfNotOnNativeEl(newTabIndex: string|null) {
private setTabIndexIfNotOnNativeEl(newTabIndex: string | null) {
if (this.tabIndexAttribute != null /* both `null` and `undefined` */ || this.isAnchorElement) {
return;
}
@@ -260,7 +275,7 @@ export class RouterLink implements OnChanges, OnDestroy {
* @see {@link Router#createUrlTree}
*/
@Input()
set routerLink(commands: any[]|string|null|undefined) {
set routerLink(commands: any[] | string | null | undefined) {
if (commands != null) {
this.commands = Array.isArray(commands) ? commands : [commands];
this.setTabIndexIfNotOnNativeEl('0');
@@ -271,13 +286,22 @@ export class RouterLink implements OnChanges, OnDestroy {
}
/** @nodoc */
@HostListener(
'click',
['$event.button', '$event.ctrlKey', '$event.shiftKey', '$event.altKey', '$event.metaKey'])
onClick(button: number, ctrlKey: boolean, shiftKey: boolean, altKey: boolean, metaKey: boolean):
boolean {
@HostListener('click', [
'$event.button',
'$event.ctrlKey',
'$event.shiftKey',
'$event.altKey',
'$event.metaKey',
])
onClick(
button: number,
ctrlKey: boolean,
shiftKey: boolean,
altKey: boolean,
metaKey: boolean,
): boolean {
const urlTree = this.urlTree;
if (urlTree === null) {
return true;
}
@@ -313,27 +337,33 @@ export class RouterLink implements OnChanges, OnDestroy {
private updateHref(): void {
const urlTree = this.urlTree;
this.href = urlTree !== null && this.locationStrategy ?
this.locationStrategy?.prepareExternalUrl(this.router.serializeUrl(urlTree)) :
null;
this.href =
urlTree !== null && this.locationStrategy
? this.locationStrategy?.prepareExternalUrl(this.router.serializeUrl(urlTree))
: null;
const sanitizedValue = this.href === null ?
null :
// This class represents a directive that can be added to both `<a>` elements,
// as well as other elements. As a result, we can't define security context at
// compile time. So the security context is deferred to runtime.
// The `ɵɵsanitizeUrlOrResourceUrl` selects the necessary sanitizer function
// based on the tag and property names. The logic mimics the one from
// `packages/compiler/src/schema/dom_security_schema.ts`, which is used at compile time.
//
// Note: we should investigate whether we can switch to using `@HostBinding('attr.href')`
// instead of applying a value via a renderer, after a final merge of the
// `RouterLinkWithHref` directive.
ɵɵsanitizeUrlOrResourceUrl(this.href, this.el.nativeElement.tagName.toLowerCase(), 'href');
const sanitizedValue =
this.href === null
? null
: // This class represents a directive that can be added to both `<a>` elements,
// as well as other elements. As a result, we can't define security context at
// compile time. So the security context is deferred to runtime.
// The `ɵɵsanitizeUrlOrResourceUrl` selects the necessary sanitizer function
// based on the tag and property names. The logic mimics the one from
// `packages/compiler/src/schema/dom_security_schema.ts`, which is used at compile time.
//
// Note: we should investigate whether we can switch to using `@HostBinding('attr.href')`
// instead of applying a value via a renderer, after a final merge of the
// `RouterLinkWithHref` directive.
ɵɵsanitizeUrlOrResourceUrl(
this.href,
this.el.nativeElement.tagName.toLowerCase(),
'href',
);
this.applyAttributeValue('href', sanitizedValue);
}
private applyAttributeValue(attrName: string, attrValue: string|null) {
private applyAttributeValue(attrName: string, attrValue: string | null) {
const renderer = this.renderer;
const nativeElement = this.el.nativeElement;
if (attrValue !== null) {
@@ -343,7 +373,7 @@ export class RouterLink implements OnChanges, OnDestroy {
}
}
get urlTree(): UrlTree|null {
get urlTree(): UrlTree | null {
if (this.commands === null) {
return null;
}
@@ -6,7 +6,22 @@
* found in the LICENSE file at https://angular.io/license
*/
import {AfterContentInit, ChangeDetectorRef, ContentChildren, Directive, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Optional, Output, QueryList, Renderer2, SimpleChanges} from '@angular/core';
import {
AfterContentInit,
ChangeDetectorRef,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
SimpleChanges,
} from '@angular/core';
import {from, of, Subscription} from 'rxjs';
import {mergeAll} from 'rxjs/operators';
@@ -16,7 +31,6 @@ import {IsActiveMatchOptions} from '../url_tree';
import {RouterLink} from './router_link';
/**
*
* @description
@@ -110,8 +124,7 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
*
* @see {@link Router#isActive}
*/
@Input() routerLinkActiveOptions: {exact: boolean}|IsActiveMatchOptions = {exact: false};
@Input() routerLinkActiveOptions: {exact: boolean} | IsActiveMatchOptions = {exact: false};
/**
* Aria-current attribute to apply when the router link is active.
@@ -120,7 +133,7 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current}
*/
@Input() ariaCurrentWhenActive?: 'page'|'step'|'location'|'date'|'time'|true|false;
@Input() ariaCurrentWhenActive?: 'page' | 'step' | 'location' | 'date' | 'time' | true | false;
/**
*
@@ -141,8 +154,12 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
@Output() readonly isActiveChange: EventEmitter<boolean> = new EventEmitter();
constructor(
private router: Router, private element: ElementRef, private renderer: Renderer2,
private readonly cdr: ChangeDetectorRef, @Optional() private link?: RouterLink) {
private router: Router,
private element: ElementRef,
private renderer: Renderer2,
private readonly cdr: ChangeDetectorRef,
@Optional() private link?: RouterLink,
) {
this.routerEventsSubscription = router.events.subscribe((s: Event) => {
if (s instanceof NavigationEnd) {
this.update();
@@ -153,28 +170,32 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
/** @nodoc */
ngAfterContentInit(): void {
// `of(null)` is used to force subscribe body to execute once immediately (like `startWith`).
of(this.links.changes, of(null)).pipe(mergeAll()).subscribe(_ => {
this.update();
this.subscribeToEachLinkOnChanges();
});
of(this.links.changes, of(null))
.pipe(mergeAll())
.subscribe((_) => {
this.update();
this.subscribeToEachLinkOnChanges();
});
}
private subscribeToEachLinkOnChanges() {
this.linkInputChangesSubscription?.unsubscribe();
const allLinkChanges = [...this.links.toArray(), this.link]
.filter((link): link is RouterLink => !!link)
.map(link => link.onChanges);
this.linkInputChangesSubscription = from(allLinkChanges).pipe(mergeAll()).subscribe(link => {
if (this._isActive !== this.isLinkActive(this.router)(link)) {
this.update();
}
});
.filter((link): link is RouterLink => !!link)
.map((link) => link.onChanges);
this.linkInputChangesSubscription = from(allLinkChanges)
.pipe(mergeAll())
.subscribe((link) => {
if (this._isActive !== this.isLinkActive(this.router)(link)) {
this.update();
}
});
}
@Input()
set routerLinkActive(data: string[]|string) {
set routerLinkActive(data: string[] | string) {
const classes = Array.isArray(data) ? data : data.split(' ');
this.classes = classes.filter(c => !!c);
this.classes = classes.filter((c) => !!c);
}
/** @nodoc */
@@ -203,7 +224,10 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
});
if (hasActiveLinks && this.ariaCurrentWhenActive !== undefined) {
this.renderer.setAttribute(
this.element.nativeElement, 'aria-current', this.ariaCurrentWhenActive.toString());
this.element.nativeElement,
'aria-current',
this.ariaCurrentWhenActive.toString(),
);
} else {
this.renderer.removeAttribute(this.element.nativeElement, 'aria-current');
}
@@ -215,11 +239,12 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
}
private isLinkActive(router: Router): (link: RouterLink) => boolean {
const options: boolean|IsActiveMatchOptions =
isActiveMatchOptions(this.routerLinkActiveOptions) ?
this.routerLinkActiveOptions :
// While the types should disallow `undefined` here, it's possible without strict inputs
(this.routerLinkActiveOptions.exact || false);
const options: boolean | IsActiveMatchOptions = isActiveMatchOptions(
this.routerLinkActiveOptions,
)
? this.routerLinkActiveOptions
: // While the types should disallow `undefined` here, it's possible without strict inputs
this.routerLinkActiveOptions.exact || false;
return (link: RouterLink) => {
const urlTree = link.urlTree;
return urlTree ? router.isActive(urlTree, options) : false;
@@ -228,14 +253,15 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
private hasActiveLinks(): boolean {
const isActiveCheckFn = this.isLinkActive(this.router);
return this.link && isActiveCheckFn(this.link) || this.links.some(isActiveCheckFn);
return (this.link && isActiveCheckFn(this.link)) || this.links.some(isActiveCheckFn);
}
}
/**
* Use instead of `'paths' in options` to be compatible with property renaming
*/
function isActiveMatchOptions(options: {exact: boolean}|
IsActiveMatchOptions): options is IsActiveMatchOptions {
function isActiveMatchOptions(
options: {exact: boolean} | IsActiveMatchOptions,
): options is IsActiveMatchOptions {
return !!(options as IsActiveMatchOptions).paths;
}
+88 -57
View File
@@ -6,7 +6,25 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ChangeDetectorRef, ComponentRef, Directive, EnvironmentInjector, EventEmitter, inject, Injectable, InjectionToken, Injector, Input, OnDestroy, OnInit, Output, reflectComponentType, SimpleChanges, ViewContainerRef, ɵRuntimeError as RuntimeError,} from '@angular/core';
import {
ChangeDetectorRef,
ComponentRef,
Directive,
EnvironmentInjector,
EventEmitter,
inject,
Injectable,
InjectionToken,
Injector,
Input,
OnDestroy,
OnInit,
Output,
reflectComponentType,
SimpleChanges,
ViewContainerRef,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {combineLatest, of, Subscription} from 'rxjs';
import {switchMap} from 'rxjs/operators';
@@ -16,7 +34,6 @@ import {ChildrenOutletContexts} from '../router_outlet_context';
import {ActivatedRoute} from '../router_state';
import {PRIMARY_OUTLET} from '../shared';
/**
* An interface that defines the contract for developing a component outlet for the `Router`.
*
@@ -39,7 +56,7 @@ export interface RouterOutletContract {
isActivated: boolean;
/** The instance of the activated component or `null` if the outlet is not activated. */
component: Object|null;
component: Object | null;
/**
* The `Data` of the `ActivatedRoute` snapshot.
@@ -49,12 +66,15 @@ export interface RouterOutletContract {
/**
* The `ActivatedRoute` for the outlet or `null` if the outlet is not activated.
*/
activatedRoute: ActivatedRoute|null;
activatedRoute: ActivatedRoute | null;
/**
* Called by the `Router` when the outlet should activate (create a component).
*/
activateWith(activatedRoute: ActivatedRoute, environmentInjector: EnvironmentInjector|null): void;
activateWith(
activatedRoute: ActivatedRoute,
environmentInjector: EnvironmentInjector | null,
): void;
/**
* A request to destroy the currently activated component.
@@ -167,12 +187,12 @@ export interface RouterOutletContract {
standalone: true,
})
export class RouterOutlet implements OnDestroy, OnInit, RouterOutletContract {
private activated: ComponentRef<any>|null = null;
private activated: ComponentRef<any> | null = null;
/** @internal */
get activatedComponentRef(): ComponentRef<any>|null {
get activatedComponentRef(): ComponentRef<any> | null {
return this.activated;
}
private _activatedRoute: ActivatedRoute|null = null;
private _activatedRoute: ActivatedRoute | null = null;
/**
* The name of the outlet
*
@@ -270,16 +290,18 @@ export class RouterOutlet implements OnDestroy, OnInit, RouterOutletContract {
get component(): Object {
if (!this.activated)
throw new RuntimeError(
RuntimeErrorCode.OUTLET_NOT_ACTIVATED,
(typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
RuntimeErrorCode.OUTLET_NOT_ACTIVATED,
(typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated',
);
return this.activated.instance;
}
get activatedRoute(): ActivatedRoute {
if (!this.activated)
throw new RuntimeError(
RuntimeErrorCode.OUTLET_NOT_ACTIVATED,
(typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
RuntimeErrorCode.OUTLET_NOT_ACTIVATED,
(typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated',
);
return this._activatedRoute as ActivatedRoute;
}
@@ -296,8 +318,9 @@ export class RouterOutlet implements OnDestroy, OnInit, RouterOutletContract {
detach(): ComponentRef<any> {
if (!this.activated)
throw new RuntimeError(
RuntimeErrorCode.OUTLET_NOT_ACTIVATED,
(typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
RuntimeErrorCode.OUTLET_NOT_ACTIVATED,
(typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated',
);
this.location.detach();
const cmp = this.activated;
this.activated = null;
@@ -327,12 +350,13 @@ export class RouterOutlet implements OnDestroy, OnInit, RouterOutletContract {
}
}
activateWith(activatedRoute: ActivatedRoute, environmentInjector?: EnvironmentInjector|null) {
activateWith(activatedRoute: ActivatedRoute, environmentInjector?: EnvironmentInjector | null) {
if (this.isActivated) {
throw new RuntimeError(
RuntimeErrorCode.OUTLET_ALREADY_ACTIVATED,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'Cannot activate an already activated outlet');
RuntimeErrorCode.OUTLET_ALREADY_ACTIVATED,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'Cannot activate an already activated outlet',
);
}
this._activatedRoute = activatedRoute;
const location = this.location;
@@ -344,7 +368,7 @@ export class RouterOutlet implements OnDestroy, OnInit, RouterOutletContract {
this.activated = location.createComponent(component, {
index: location.length,
injector,
environmentInjector: environmentInjector ?? this.environmentInjector
environmentInjector: environmentInjector ?? this.environmentInjector,
});
// Calling `markForCheck` to make sure we will run the change detection when the
// `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
@@ -356,8 +380,10 @@ export class RouterOutlet implements OnDestroy, OnInit, RouterOutletContract {
class OutletInjector implements Injector {
constructor(
private route: ActivatedRoute, private childContexts: ChildrenOutletContexts,
private parent: Injector) {}
private route: ActivatedRoute,
private childContexts: ChildrenOutletContexts,
private parent: Injector,
) {}
get(token: any, notFoundValue?: any): any {
if (token === ActivatedRoute) {
@@ -390,7 +416,7 @@ export const INPUT_BINDER = new InjectionToken<RoutedComponentInputBinder>('');
*/
@Injectable()
export class RoutedComponentInputBinder {
private outletDataSubscriptions = new Map<RouterOutlet, Subscription>;
private outletDataSubscriptions = new Map<RouterOutlet, Subscription>();
bindActivatedRouteToOutletComponent(outlet: RouterOutlet) {
this.unsubscribeFromRouteData(outlet);
@@ -404,43 +430,48 @@ export class RoutedComponentInputBinder {
private subscribeToRouteData(outlet: RouterOutlet) {
const {activatedRoute} = outlet;
const dataSubscription =
combineLatest([
activatedRoute.queryParams,
activatedRoute.params,
activatedRoute.data,
])
.pipe(switchMap(([queryParams, params, data], index) => {
data = {...queryParams, ...params, ...data};
// Get the first result from the data subscription synchronously so it's available to
// the component as soon as possible (and doesn't require a second change detection).
if (index === 0) {
return of(data);
}
// Promise.resolve is used to avoid synchronously writing the wrong data when
// two of the Observables in the `combineLatest` stream emit one after
// another.
return Promise.resolve(data);
}))
.subscribe(data => {
// Outlet may have been deactivated or changed names to be associated with a different
// route
if (!outlet.isActivated || !outlet.activatedComponentRef ||
outlet.activatedRoute !== activatedRoute || activatedRoute.component === null) {
this.unsubscribeFromRouteData(outlet);
return;
}
const dataSubscription = combineLatest([
activatedRoute.queryParams,
activatedRoute.params,
activatedRoute.data,
])
.pipe(
switchMap(([queryParams, params, data], index) => {
data = {...queryParams, ...params, ...data};
// Get the first result from the data subscription synchronously so it's available to
// the component as soon as possible (and doesn't require a second change detection).
if (index === 0) {
return of(data);
}
// Promise.resolve is used to avoid synchronously writing the wrong data when
// two of the Observables in the `combineLatest` stream emit one after
// another.
return Promise.resolve(data);
}),
)
.subscribe((data) => {
// Outlet may have been deactivated or changed names to be associated with a different
// route
if (
!outlet.isActivated ||
!outlet.activatedComponentRef ||
outlet.activatedRoute !== activatedRoute ||
activatedRoute.component === null
) {
this.unsubscribeFromRouteData(outlet);
return;
}
const mirror = reflectComponentType(activatedRoute.component);
if (!mirror) {
this.unsubscribeFromRouteData(outlet);
return;
}
const mirror = reflectComponentType(activatedRoute.component);
if (!mirror) {
this.unsubscribeFromRouteData(outlet);
return;
}
for (const {templateName} of mirror.inputs) {
outlet.activatedComponentRef.setInput(templateName, data[templateName]);
}
});
for (const {templateName} of mirror.inputs) {
outlet.activatedComponentRef.setInput(templateName, data[templateName]);
}
});
this.outletDataSubscriptions.set(outlet, dataSubscription);
}
File diff suppressed because it is too large Load Diff
+110 -10
View File
@@ -6,31 +6,131 @@
* found in the LICENSE file at https://angular.io/license
*/
export {createUrlTreeFromSnapshot} from './create_url_tree';
export {RouterLink, RouterLinkWithHref} from './directives/router_link';
export {RouterLinkActive} from './directives/router_link_active';
export {RouterOutlet, RouterOutletContract} from './directives/router_outlet';
export {ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, Event, EventType, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationCancellationCode as NavigationCancellationCode, NavigationEnd, NavigationError, NavigationSkipped, NavigationSkippedCode, NavigationStart, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouterEvent, RoutesRecognized, Scroll} from './events';
export {CanActivateChildFn, CanActivateFn, CanDeactivateFn, CanLoadFn, CanMatchFn, Data, DefaultExport, LoadChildren, LoadChildrenCallback, NavigationBehaviorOptions, OnSameUrlNavigation, QueryParamsHandling, ResolveData, ResolveFn, Route, Routes, RunGuardsAndResolvers, UrlMatcher, UrlMatchResult} from './models';
export {
ActivationEnd,
ActivationStart,
ChildActivationEnd,
ChildActivationStart,
Event,
EventType,
GuardsCheckEnd,
GuardsCheckStart,
NavigationCancel,
NavigationCancellationCode as NavigationCancellationCode,
NavigationEnd,
NavigationError,
NavigationSkipped,
NavigationSkippedCode,
NavigationStart,
ResolveEnd,
ResolveStart,
RouteConfigLoadEnd,
RouteConfigLoadStart,
RouterEvent,
RoutesRecognized,
Scroll,
} from './events';
export {
CanActivateChildFn,
CanActivateFn,
CanDeactivateFn,
CanLoadFn,
CanMatchFn,
Data,
DefaultExport,
LoadChildren,
LoadChildrenCallback,
NavigationBehaviorOptions,
OnSameUrlNavigation,
QueryParamsHandling,
ResolveData,
ResolveFn,
Route,
Routes,
RunGuardsAndResolvers,
UrlMatcher,
UrlMatchResult,
} from './models';
export {ViewTransitionInfo, ViewTransitionsFeatureOptions} from './utils/view_transition';
export * from './models_deprecated';
export {Navigation, NavigationExtras, UrlCreationOptions} from './navigation_transition';
export {DefaultTitleStrategy, TitleStrategy} from './page_title_strategy';
export {DebugTracingFeature, DisabledInitialNavigationFeature, withViewTransitions, ViewTransitionsFeature, EnabledBlockingInitialNavigationFeature, InitialNavigationFeature, InMemoryScrollingFeature, NavigationErrorHandlerFeature, PreloadingFeature, provideRouter, provideRoutes, RouterConfigurationFeature, RouterFeature, RouterFeatures, RouterHashLocationFeature, withComponentInputBinding, withDebugTracing, withDisabledInitialNavigation, withEnabledBlockingInitialNavigation, withHashLocation, withInMemoryScrolling, withNavigationErrorHandler, withPreloading, withRouterConfig} from './provide_router';
export {BaseRouteReuseStrategy, DetachedRouteHandle, RouteReuseStrategy} from './route_reuse_strategy';
export {
DebugTracingFeature,
DisabledInitialNavigationFeature,
withViewTransitions,
ViewTransitionsFeature,
EnabledBlockingInitialNavigationFeature,
InitialNavigationFeature,
InMemoryScrollingFeature,
NavigationErrorHandlerFeature,
PreloadingFeature,
provideRouter,
provideRoutes,
RouterConfigurationFeature,
RouterFeature,
RouterFeatures,
RouterHashLocationFeature,
withComponentInputBinding,
withDebugTracing,
withDisabledInitialNavigation,
withEnabledBlockingInitialNavigation,
withHashLocation,
withInMemoryScrolling,
withNavigationErrorHandler,
withPreloading,
withRouterConfig,
} from './provide_router';
export {
BaseRouteReuseStrategy,
DetachedRouteHandle,
RouteReuseStrategy,
} from './route_reuse_strategy';
export {Router} from './router';
export {ExtraOptions, InitialNavigation, InMemoryScrollingOptions, ROUTER_CONFIGURATION, RouterConfigOptions} from './router_config';
export {
ExtraOptions,
InitialNavigation,
InMemoryScrollingOptions,
ROUTER_CONFIGURATION,
RouterConfigOptions,
} from './router_config';
export {ROUTES} from './router_config_loader';
export {ROUTER_INITIALIZER, RouterModule} from './router_module';
export {ChildrenOutletContexts, OutletContext} from './router_outlet_context';
export {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader';
export {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot} from './router_state';
export {
NoPreloading,
PreloadAllModules,
PreloadingStrategy,
RouterPreloader,
} from './router_preloader';
export {
ActivatedRoute,
ActivatedRouteSnapshot,
RouterState,
RouterStateSnapshot,
} from './router_state';
export {convertToParamMap, defaultUrlMatcher, ParamMap, Params, PRIMARY_OUTLET} from './shared';
export {UrlHandlingStrategy} from './url_handling_strategy';
export {DefaultUrlSerializer, IsActiveMatchOptions, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree} from './url_tree';
export {mapToCanActivate, mapToCanActivateChild, mapToCanDeactivate, mapToCanMatch, mapToResolve} from './utils/functional_guards';
export {
DefaultUrlSerializer,
IsActiveMatchOptions,
UrlSegment,
UrlSegmentGroup,
UrlSerializer,
UrlTree,
} from './url_tree';
export {
mapToCanActivate,
mapToCanActivateChild,
mapToCanDeactivate,
mapToCanMatch,
mapToResolve,
} from './utils/functional_guards';
export {VERSION} from './version';
export * from './private_export';
File diff suppressed because it is too large Load Diff
+9 -1
View File
@@ -10,4 +10,12 @@
// The public API re-exports everything from this file, which can be patched
// locally in g3 to prevent regressions after cleanups complete.
export {CanActivate, CanActivateChild, CanDeactivate, CanLoad, CanMatch, DeprecatedGuard, Resolve} from './models';
export {
CanActivate,
CanActivateChild,
CanDeactivate,
CanLoad,
CanMatch,
DeprecatedGuard,
Resolve,
} from './models';
@@ -12,28 +12,36 @@ import {isUrlTree, UrlSerializer, UrlTree} from './url_tree';
export const NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
export type NavigationCancelingError =
Error&{[NAVIGATION_CANCELING_ERROR]: true, cancellationCode: NavigationCancellationCode};
export type RedirectingNavigationCancelingError = NavigationCancelingError&{
export type NavigationCancelingError = Error & {
[NAVIGATION_CANCELING_ERROR]: true;
cancellationCode: NavigationCancellationCode;
};
export type RedirectingNavigationCancelingError = NavigationCancelingError & {
url: UrlTree;
navigationBehaviorOptions?: NavigationBehaviorOptions;
cancellationCode: NavigationCancellationCode.Redirect;
};
export function redirectingNavigationError(
urlSerializer: UrlSerializer, redirect: UrlTree): RedirectingNavigationCancelingError {
const {redirectTo, navigationBehaviorOptions} =
isUrlTree(redirect) ? {redirectTo: redirect, navigationBehaviorOptions: undefined} : redirect;
urlSerializer: UrlSerializer,
redirect: UrlTree,
): RedirectingNavigationCancelingError {
const {redirectTo, navigationBehaviorOptions} = isUrlTree(redirect)
? {redirectTo: redirect, navigationBehaviorOptions: undefined}
: redirect;
const error = navigationCancelingError(
ngDevMode && `Redirecting to "${urlSerializer.serialize(redirectTo)}"`,
NavigationCancellationCode.Redirect) as RedirectingNavigationCancelingError;
ngDevMode && `Redirecting to "${urlSerializer.serialize(redirectTo)}"`,
NavigationCancellationCode.Redirect,
) as RedirectingNavigationCancelingError;
error.url = redirectTo;
error.navigationBehaviorOptions = navigationBehaviorOptions;
return error;
}
export function navigationCancelingError(
message: string|null|false, code: NavigationCancellationCode) {
message: string | null | false,
code: NavigationCancellationCode,
) {
const error = new Error(`NavigationCancelingError: ${message || ''}`) as NavigationCancelingError;
error[NAVIGATION_CANCELING_ERROR] = true;
error.cancellationCode = code;
@@ -41,10 +49,12 @@ export function navigationCancelingError(
}
export function isRedirectingNavigationCancelingError(
error: unknown|
RedirectingNavigationCancelingError): error is RedirectingNavigationCancelingError {
return isNavigationCancelingError(error) &&
isUrlTree((error as RedirectingNavigationCancelingError).url);
error: unknown | RedirectingNavigationCancelingError,
): error is RedirectingNavigationCancelingError {
return (
isNavigationCancelingError(error) &&
isUrlTree((error as RedirectingNavigationCancelingError).url)
);
}
export function isNavigationCancelingError(error: unknown): error is NavigationCancelingError {
File diff suppressed because it is too large Load Diff
@@ -19,22 +19,31 @@ import {nodeChildrenAsMap, TreeNode} from '../utils/tree';
let warnedAboutUnsupportedInputBinding = false;
export const activateRoutes =
(rootContexts: ChildrenOutletContexts, routeReuseStrategy: RouteReuseStrategy,
forwardEvent: (evt: Event) => void,
inputBindingEnabled: boolean): MonoTypeOperatorFunction<NavigationTransition> => map(t => {
new ActivateRoutes(
routeReuseStrategy, t.targetRouterState!, t.currentRouterState, forwardEvent,
inputBindingEnabled)
.activate(rootContexts);
return t;
});
export const activateRoutes = (
rootContexts: ChildrenOutletContexts,
routeReuseStrategy: RouteReuseStrategy,
forwardEvent: (evt: Event) => void,
inputBindingEnabled: boolean,
): MonoTypeOperatorFunction<NavigationTransition> =>
map((t) => {
new ActivateRoutes(
routeReuseStrategy,
t.targetRouterState!,
t.currentRouterState,
forwardEvent,
inputBindingEnabled,
).activate(rootContexts);
return t;
});
export class ActivateRoutes {
constructor(
private routeReuseStrategy: RouteReuseStrategy, private futureState: RouterState,
private currState: RouterState, private forwardEvent: (evt: Event) => void,
private inputBindingEnabled: boolean) {}
private routeReuseStrategy: RouteReuseStrategy,
private futureState: RouterState,
private currState: RouterState,
private forwardEvent: (evt: Event) => void,
private inputBindingEnabled: boolean,
) {}
activate(parentContexts: ChildrenOutletContexts): void {
const futureRoot = this.futureState._root;
@@ -47,12 +56,14 @@ export class ActivateRoutes {
// De-activate the child route that are not re-used for the future state
private deactivateChildRoutes(
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>|null,
contexts: ChildrenOutletContexts): void {
futureNode: TreeNode<ActivatedRoute>,
currNode: TreeNode<ActivatedRoute> | null,
contexts: ChildrenOutletContexts,
): void {
const children: {[outletName: string]: TreeNode<ActivatedRoute>} = nodeChildrenAsMap(currNode);
// Recurse on the routes active in the future state to de-activate deeper children
futureNode.children.forEach(futureChild => {
futureNode.children.forEach((futureChild) => {
const childOutletName = futureChild.value.outlet;
this.deactivateRoutes(futureChild, children[childOutletName], contexts);
delete children[childOutletName];
@@ -65,8 +76,10 @@ export class ActivateRoutes {
}
private deactivateRoutes(
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>,
parentContext: ChildrenOutletContexts): void {
futureNode: TreeNode<ActivatedRoute>,
currNode: TreeNode<ActivatedRoute>,
parentContext: ChildrenOutletContexts,
): void {
const future = futureNode.value;
const curr = currNode ? currNode.value : null;
@@ -91,7 +104,9 @@ export class ActivateRoutes {
}
private deactivateRouteAndItsChildren(
route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts): void {
route: TreeNode<ActivatedRoute>,
parentContexts: ChildrenOutletContexts,
): void {
// If there is no component, the Route is never attached to an outlet (because there is no
// component to attach).
if (route.value.component && this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
@@ -102,7 +117,9 @@ export class ActivateRoutes {
}
private detachAndStoreRouteSubtree(
route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts): void {
route: TreeNode<ActivatedRoute>,
parentContexts: ChildrenOutletContexts,
): void {
const context = parentContexts.getContext(route.value.outlet);
const contexts = context && route.value.component ? context.children : parentContexts;
const children: {[outletName: string]: TreeNode<ActivatedRoute>} = nodeChildrenAsMap(route);
@@ -119,7 +136,9 @@ export class ActivateRoutes {
}
private deactivateRouteAndOutlet(
route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts): void {
route: TreeNode<ActivatedRoute>,
parentContexts: ChildrenOutletContexts,
): void {
const context = parentContexts.getContext(route.value.outlet);
// The context could be `null` if we are on a componentless route but there may still be
// children that need deactivating.
@@ -146,10 +165,12 @@ export class ActivateRoutes {
}
private activateChildRoutes(
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>|null,
contexts: ChildrenOutletContexts): void {
futureNode: TreeNode<ActivatedRoute>,
currNode: TreeNode<ActivatedRoute> | null,
contexts: ChildrenOutletContexts,
): void {
const children: {[outlet: string]: TreeNode<ActivatedRoute>} = nodeChildrenAsMap(currNode);
futureNode.children.forEach(c => {
futureNode.children.forEach((c) => {
this.activateRoutes(c, children[c.value.outlet], contexts);
this.forwardEvent(new ActivationEnd(c.value.snapshot));
});
@@ -159,8 +180,10 @@ export class ActivateRoutes {
}
private activateRoutes(
futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>,
parentContexts: ChildrenOutletContexts): void {
futureNode: TreeNode<ActivatedRoute>,
currNode: TreeNode<ActivatedRoute>,
parentContexts: ChildrenOutletContexts,
): void {
const future = futureNode.value;
const curr = currNode ? currNode.value : null;
@@ -182,8 +205,9 @@ export class ActivateRoutes {
const context = parentContexts.getOrCreateContext(future.outlet);
if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
const stored =
(<DetachedRouteHandleInternal>this.routeReuseStrategy.retrieve(future.snapshot));
const stored = <DetachedRouteHandleInternal>(
this.routeReuseStrategy.retrieve(future.snapshot)
);
this.routeReuseStrategy.store(future.snapshot, null);
context.children.onOutletReAttached(stored.contexts);
context.attachRef = stored.componentRef;
@@ -214,14 +238,19 @@ export class ActivateRoutes {
this.activateChildRoutes(futureNode, null, parentContexts);
}
}
if ((typeof ngDevMode === 'undefined' || ngDevMode)) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
const context = parentContexts.getOrCreateContext(future.outlet);
const outlet = context.outlet;
if (outlet && this.inputBindingEnabled && !outlet.supportsBindingToComponentInputs &&
!warnedAboutUnsupportedInputBinding) {
if (
outlet &&
this.inputBindingEnabled &&
!outlet.supportsBindingToComponentInputs &&
!warnedAboutUnsupportedInputBinding
) {
console.warn(
`'withComponentInputBinding' feature is enabled but ` +
`this application is using an outlet that may not support binding to component inputs.`);
`'withComponentInputBinding' feature is enabled but ` +
`this application is using an outlet that may not support binding to component inputs.`,
);
warnedAboutUnsupportedInputBinding = true;
}
}
File diff suppressed because it is too large Load Diff
@@ -14,31 +14,34 @@ import {UrlTree} from '../url_tree';
const INITIAL_VALUE = /* @__PURE__ */ Symbol('INITIAL_VALUE');
declare type INTERIM_VALUES = typeof INITIAL_VALUE | boolean | UrlTree;
export function prioritizedGuardValue():
OperatorFunction<Observable<boolean|UrlTree>[], boolean|UrlTree> {
return switchMap(obs => {
return combineLatest(obs.map(o => o.pipe(take(1), startWith(INITIAL_VALUE as INTERIM_VALUES))))
.pipe(
map((results: INTERIM_VALUES[]) => {
for (const result of results) {
if (result === true) {
// If result is true, check the next one
continue;
} else if (result === INITIAL_VALUE) {
// If guard has not finished, we need to stop processing.
return INITIAL_VALUE;
} else if (result === false || result instanceof UrlTree) {
// Result finished and was not true. Return the result.
// Note that we only allow false/UrlTree. Other values are considered invalid and
// ignored.
return result;
}
}
// Everything resolved to true. Return true.
return true;
}),
filter((item): item is boolean|UrlTree => item !== INITIAL_VALUE),
take(1),
);
export function prioritizedGuardValue(): OperatorFunction<
Observable<boolean | UrlTree>[],
boolean | UrlTree
> {
return switchMap((obs) => {
return combineLatest(
obs.map((o) => o.pipe(take(1), startWith(INITIAL_VALUE as INTERIM_VALUES))),
).pipe(
map((results: INTERIM_VALUES[]) => {
for (const result of results) {
if (result === true) {
// If result is true, check the next one
continue;
} else if (result === INITIAL_VALUE) {
// If guard has not finished, we need to stop processing.
return INITIAL_VALUE;
} else if (result === false || result instanceof UrlTree) {
// Result finished and was not true. Return the result.
// Note that we only allow false/UrlTree. Other values are considered invalid and
// ignored.
return result;
}
}
// Everything resolved to true. Return true.
return true;
}),
filter((item): item is boolean | UrlTree => item !== INITIAL_VALUE),
take(1),
);
});
}
+22 -11
View File
@@ -17,15 +17,26 @@ import {RouterConfigLoader} from '../router_config_loader';
import {UrlSerializer} from '../url_tree';
export function recognize(
injector: EnvironmentInjector, configLoader: RouterConfigLoader,
rootComponentType: Type<any>|null, config: Route[], serializer: UrlSerializer,
paramsInheritanceStrategy: 'emptyOnly'|
'always'): MonoTypeOperatorFunction<NavigationTransition> {
return mergeMap(
t => recognizeFn(
injector, configLoader, rootComponentType, config, t.extractedUrl, serializer,
paramsInheritanceStrategy)
.pipe(map(({state: targetSnapshot, tree: urlAfterRedirects}) => {
return {...t, targetSnapshot, urlAfterRedirects};
})));
injector: EnvironmentInjector,
configLoader: RouterConfigLoader,
rootComponentType: Type<any> | null,
config: Route[],
serializer: UrlSerializer,
paramsInheritanceStrategy: 'emptyOnly' | 'always',
): MonoTypeOperatorFunction<NavigationTransition> {
return mergeMap((t) =>
recognizeFn(
injector,
configLoader,
rootComponentType,
config,
t.extractedUrl,
serializer,
paramsInheritanceStrategy,
).pipe(
map(({state: targetSnapshot, tree: urlAfterRedirects}) => {
return {...t, targetSnapshot, urlAfterRedirects};
}),
),
);
}
+66 -44
View File
@@ -12,7 +12,12 @@ import {catchError, concatMap, first, map, mapTo, mergeMap, takeLast, tap} from
import {ResolveData} from '../models';
import {NavigationTransition} from '../navigation_transition';
import {ActivatedRouteSnapshot, getInherited, hasStaticTitle, RouterStateSnapshot} from '../router_state';
import {
ActivatedRouteSnapshot,
getInherited,
hasStaticTitle,
RouterStateSnapshot,
} from '../router_state';
import {RouteTitleKey} from '../shared';
import {getDataKeys, wrapIntoObservable} from '../utils/collection';
import {getClosestRouteInjector} from '../utils/config';
@@ -20,10 +25,14 @@ import {getTokenOrFunctionIdentity} from '../utils/preactivation';
import {isEmptyError} from '../utils/type_guards';
export function resolveData(
paramsInheritanceStrategy: 'emptyOnly'|'always',
injector: EnvironmentInjector): MonoTypeOperatorFunction<NavigationTransition> {
return mergeMap(t => {
const {targetSnapshot, guards: {canActivateChecks}} = t;
paramsInheritanceStrategy: 'emptyOnly' | 'always',
injector: EnvironmentInjector,
): MonoTypeOperatorFunction<NavigationTransition> {
return mergeMap((t) => {
const {
targetSnapshot,
guards: {canActivateChecks},
} = t;
if (!canActivateChecks.length) {
return of(t);
@@ -31,7 +40,7 @@ export function resolveData(
// Iterating a Set in javascript happens in insertion order so it is safe to use a `Set` to
// preserve the correct order that the resolvers should run in.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#description
const routesWithResolversToRun = new Set(canActivateChecks.map(check => check.route));
const routesWithResolversToRun = new Set(canActivateChecks.map((check) => check.route));
const routesNeedingDataUpdates = new Set<ActivatedRouteSnapshot>();
for (const route of routesWithResolversToRun) {
if (routesNeedingDataUpdates.has(route)) {
@@ -43,20 +52,19 @@ export function resolveData(
}
}
let routesProcessed = 0;
return from(routesNeedingDataUpdates)
.pipe(
concatMap(route => {
if (routesWithResolversToRun.has(route)) {
return runResolve(route, targetSnapshot!, paramsInheritanceStrategy, injector);
} else {
route.data = getInherited(route, route.parent, paramsInheritanceStrategy).resolve;
return of(void 0);
}
}),
tap(() => routesProcessed++),
takeLast(1),
mergeMap(_ => routesProcessed === routesNeedingDataUpdates.size ? of(t) : EMPTY),
);
return from(routesNeedingDataUpdates).pipe(
concatMap((route) => {
if (routesWithResolversToRun.has(route)) {
return runResolve(route, targetSnapshot!, paramsInheritanceStrategy, injector);
} else {
route.data = getInherited(route, route.parent, paramsInheritanceStrategy).resolve;
return of(void 0);
}
}),
tap(() => routesProcessed++),
takeLast(1),
mergeMap((_) => (routesProcessed === routesNeedingDataUpdates.size ? of(t) : EMPTY)),
);
});
}
@@ -64,52 +72,66 @@ export function resolveData(
* Returns the `ActivatedRouteSnapshot` tree as an array, using DFS to traverse the route tree.
*/
function flattenRouteTree(route: ActivatedRouteSnapshot): ActivatedRouteSnapshot[] {
const descendants = route.children.map(child => flattenRouteTree(child)).flat();
const descendants = route.children.map((child) => flattenRouteTree(child)).flat();
return [route, ...descendants];
}
function runResolve(
futureARS: ActivatedRouteSnapshot, futureRSS: RouterStateSnapshot,
paramsInheritanceStrategy: 'emptyOnly'|'always', injector: EnvironmentInjector) {
futureARS: ActivatedRouteSnapshot,
futureRSS: RouterStateSnapshot,
paramsInheritanceStrategy: 'emptyOnly' | 'always',
injector: EnvironmentInjector,
) {
const config = futureARS.routeConfig;
const resolve = futureARS._resolve;
if (config?.title !== undefined && !hasStaticTitle(config)) {
resolve[RouteTitleKey] = config.title;
}
return resolveNode(resolve, futureARS, futureRSS, injector).pipe(map((resolvedData: any) => {
futureARS._resolvedData = resolvedData;
futureARS.data = getInherited(futureARS, futureARS.parent, paramsInheritanceStrategy).resolve;
return null;
}));
return resolveNode(resolve, futureARS, futureRSS, injector).pipe(
map((resolvedData: any) => {
futureARS._resolvedData = resolvedData;
futureARS.data = getInherited(futureARS, futureARS.parent, paramsInheritanceStrategy).resolve;
return null;
}),
);
}
function resolveNode(
resolve: ResolveData, futureARS: ActivatedRouteSnapshot, futureRSS: RouterStateSnapshot,
injector: EnvironmentInjector): Observable<any> {
resolve: ResolveData,
futureARS: ActivatedRouteSnapshot,
futureRSS: RouterStateSnapshot,
injector: EnvironmentInjector,
): Observable<any> {
const keys = getDataKeys(resolve);
if (keys.length === 0) {
return of({});
}
const data: {[k: string|symbol]: any} = {};
const data: {[k: string | symbol]: any} = {};
return from(keys).pipe(
mergeMap(
key => getResolver(resolve[key], futureARS, futureRSS, injector)
.pipe(first(), tap((value: any) => {
data[key] = value;
}))),
takeLast(1),
mapTo(data),
catchError((e: unknown) => isEmptyError(e as Error) ? EMPTY : throwError(e)),
mergeMap((key) =>
getResolver(resolve[key], futureARS, futureRSS, injector).pipe(
first(),
tap((value: any) => {
data[key] = value;
}),
),
),
takeLast(1),
mapTo(data),
catchError((e: unknown) => (isEmptyError(e as Error) ? EMPTY : throwError(e))),
);
}
function getResolver(
injectionToken: ProviderToken<any>|Function, futureARS: ActivatedRouteSnapshot,
futureRSS: RouterStateSnapshot, injector: EnvironmentInjector): Observable<any> {
injectionToken: ProviderToken<any> | Function,
futureARS: ActivatedRouteSnapshot,
futureRSS: RouterStateSnapshot,
injector: EnvironmentInjector,
): Observable<any> {
const closestInjector = getClosestRouteInjector(futureARS) ?? injector;
const resolver = getTokenOrFunctionIdentity(injectionToken, closestInjector);
const resolverValue = resolver.resolve ?
resolver.resolve(futureARS, futureRSS) :
runInInjectionContext(closestInjector, () => resolver(futureARS, futureRSS));
const resolverValue = resolver.resolve
? resolver.resolve(futureARS, futureRSS)
: runInInjectionContext(closestInjector, () => resolver(futureARS, futureRSS));
return wrapIntoObservable(resolverValue);
}
+4 -3
View File
@@ -15,9 +15,10 @@ import {map, switchMap} from 'rxjs/operators';
* the `tap` operator, but if the side effectful `next` function returns an ObservableInput,
* it will wait before continuing with the original value.
*/
export function switchTap<T>(next: (x: T) => void|ObservableInput<any>):
MonoTypeOperatorFunction<T> {
return switchMap(v => {
export function switchTap<T>(
next: (x: T) => void | ObservableInput<any>,
): MonoTypeOperatorFunction<T> {
return switchMap((v) => {
const nextResult = next(v);
if (nextResult) {
return from(nextResult).pipe(map(() => v));
+4 -4
View File
@@ -43,12 +43,12 @@ export abstract class TitleStrategy {
/**
* @returns The `title` of the deepest primary route.
*/
buildTitle(snapshot: RouterStateSnapshot): string|undefined {
let pageTitle: string|undefined;
let route: ActivatedRouteSnapshot|undefined = snapshot.root;
buildTitle(snapshot: RouterStateSnapshot): string | undefined {
let pageTitle: string | undefined;
let route: ActivatedRouteSnapshot | undefined = snapshot.root;
while (route !== undefined) {
pageTitle = this.getResolvedTitleForRoute(route) ?? pageTitle;
route = route.children.find(child => child.outlet === PRIMARY_OUTLET);
route = route.children.find((child) => child.outlet === PRIMARY_OUTLET);
}
return pageTitle;
}
-1
View File
@@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
export {ɵEmptyOutletComponent} from './components/empty_outlet';
export {RestoredState as ɵRestoredState} from './navigation_transition';
export {loadChildren as ɵloadChildren} from './router_config_loader';
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+7 -8
View File
@@ -26,9 +26,9 @@ export type DetachedRouteHandle = {};
/** @internal */
export type DetachedRouteHandleInternal = {
contexts: Map<string, OutletContext>,
componentRef: ComponentRef<any>,
route: TreeNode<ActivatedRoute>,
contexts: Map<string, OutletContext>;
componentRef: ComponentRef<any>;
route: TreeNode<ActivatedRoute>;
};
/**
@@ -48,13 +48,13 @@ export abstract class RouteReuseStrategy {
*
* Storing a `null` value should erase the previously stored value.
*/
abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle|null): void;
abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void;
/** Determines if this route (and its subtree) should be reattached */
abstract shouldAttach(route: ActivatedRouteSnapshot): boolean;
/** Retrieves the previously stored route */
abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null;
abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;
/** Determines if a route should be reused */
abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
@@ -97,7 +97,7 @@ export abstract class BaseRouteReuseStrategy implements RouteReuseStrategy {
}
/** Returns `null` because this strategy does not store routes for later re-use. */
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null {
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
return null;
}
@@ -112,5 +112,4 @@ export abstract class BaseRouteReuseStrategy implements RouteReuseStrategy {
}
@Injectable({providedIn: 'root'})
export class DefaultRouteReuseStrategy extends BaseRouteReuseStrategy {
}
export class DefaultRouteReuseStrategy extends BaseRouteReuseStrategy {}
File diff suppressed because it is too large Load Diff
+13 -12
View File
@@ -10,7 +10,6 @@ import {InjectionToken} from '@angular/core';
import {OnSameUrlNavigation} from './models';
/**
* Error handler that is invoked when a navigation error occurs.
*
@@ -46,7 +45,7 @@ export type ErrorHandler = (error: any) => any;
*
* @publicApi
*/
export type InitialNavigation = 'disabled'|'enabledBlocking'|'enabledNonBlocking';
export type InitialNavigation = 'disabled' | 'enabledBlocking' | 'enabledNonBlocking';
/**
* Extra configuration options that can be used with the `withRouterConfig` function.
@@ -75,7 +74,7 @@ export interface RouterConfigOptions {
*
* The default value is `replace` when not set.
*/
canceledNavigationResolution?: 'replace'|'computed';
canceledNavigationResolution?: 'replace' | 'computed';
/**
* Configures the default for handling a navigation request to the current URL.
@@ -103,7 +102,7 @@ export interface RouterConfigOptions {
* `a;foo=bar/b`.
*
*/
paramsInheritanceStrategy?: 'emptyOnly'|'always';
paramsInheritanceStrategy?: 'emptyOnly' | 'always';
/**
* Defines when the router updates the browser URL. By default ('deferred'),
@@ -112,7 +111,7 @@ export interface RouterConfigOptions {
* Updating the URL early allows you to handle a failure of navigation by
* showing an error message with the URL that failed.
*/
urlUpdateStrategy?: 'deferred'|'eager';
urlUpdateStrategy?: 'deferred' | 'eager';
/**
* When `true`, the `Promise` will instead resolve with `false`, as it does with other failed
@@ -138,7 +137,7 @@ export interface InMemoryScrollingOptions {
* Anchor scrolling does not happen on 'popstate'. Instead, we restore the position
* that we stored or scroll to the top.
*/
anchorScrolling?: 'disabled'|'enabled';
anchorScrolling?: 'disabled' | 'enabled';
/**
* Configures if the scroll position needs to be restored when navigating back.
@@ -174,7 +173,7 @@ export interface InMemoryScrollingOptions {
* }
* ```
*/
scrollPositionRestoration?: 'disabled'|'enabled'|'top';
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top';
}
/**
@@ -255,7 +254,7 @@ export interface ExtraOptions extends InMemoryScrollingOptions, RouterConfigOpti
* When given a function, the router invokes the function every time
* it restores scroll position.
*/
scrollOffset?: [number, number]|(() => [number, number]);
scrollOffset?: [number, number] | (() => [number, number]);
}
/**
@@ -264,7 +263,9 @@ export interface ExtraOptions extends InMemoryScrollingOptions, RouterConfigOpti
* @publicApi
*/
export const ROUTER_CONFIGURATION = new InjectionToken<ExtraOptions>(
(typeof ngDevMode === 'undefined' || ngDevMode) ? 'router config' : '', {
providedIn: 'root',
factory: () => ({}),
});
typeof ngDevMode === 'undefined' || ngDevMode ? 'router config' : '',
{
providedIn: 'root',
factory: () => ({}),
},
);
+82 -67
View File
@@ -6,7 +6,16 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Compiler, EnvironmentInjector, inject, Injectable, InjectionToken, Injector, NgModuleFactory, Type} from '@angular/core';
import {
Compiler,
EnvironmentInjector,
inject,
Injectable,
InjectionToken,
Injector,
NgModuleFactory,
Type,
} from '@angular/core';
import {ConnectableObservable, from, Observable, of, Subject} from 'rxjs';
import {finalize, map, mergeMap, refCount, tap} from 'rxjs/operators';
@@ -14,8 +23,6 @@ import {DefaultExport, LoadedRouterConfig, Route, Routes} from './models';
import {wrapIntoObservable} from './utils/collection';
import {assertStandalone, standardizeConfig, validateConfig} from './utils/config';
/**
* The [DI token](guide/glossary/#di-token) for a router configuration.
*
@@ -48,24 +55,24 @@ export class RouterConfigLoader {
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
const loadRunner = wrapIntoObservable(route.loadComponent!())
.pipe(
map(maybeUnwrapDefaultExport),
tap(component => {
if (this.onLoadEndListener) {
this.onLoadEndListener(route);
}
(typeof ngDevMode === 'undefined' || ngDevMode) &&
assertStandalone(route.path ?? '', component);
route._loadedComponent = component;
}),
finalize(() => {
this.componentLoaders.delete(route);
}),
);
const loadRunner = wrapIntoObservable(route.loadComponent!()).pipe(
map(maybeUnwrapDefaultExport),
tap((component) => {
if (this.onLoadEndListener) {
this.onLoadEndListener(route);
}
(typeof ngDevMode === 'undefined' || ngDevMode) &&
assertStandalone(route.path ?? '', component);
route._loadedComponent = component;
}),
finalize(() => {
this.componentLoaders.delete(route);
}),
);
// Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
const loader =
new ConnectableObservable(loadRunner, () => new Subject<Type<unknown>>()).pipe(refCount());
const loader = new ConnectableObservable(loadRunner, () => new Subject<Type<unknown>>()).pipe(
refCount(),
);
this.componentLoaders.set(route, loader);
return loader;
}
@@ -80,16 +87,22 @@ export class RouterConfigLoader {
if (this.onLoadStartListener) {
this.onLoadStartListener(route);
}
const moduleFactoryOrRoutes$ =
loadChildren(route, this.compiler, parentInjector, this.onLoadEndListener);
const moduleFactoryOrRoutes$ = loadChildren(
route,
this.compiler,
parentInjector,
this.onLoadEndListener,
);
const loadRunner = moduleFactoryOrRoutes$.pipe(
finalize(() => {
this.childrenLoaders.delete(route);
}),
finalize(() => {
this.childrenLoaders.delete(route);
}),
);
// Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
const loader = new ConnectableObservable(loadRunner, () => new Subject<LoadedRouterConfig>())
.pipe(refCount());
const loader = new ConnectableObservable(
loadRunner,
() => new Subject<LoadedRouterConfig>(),
).pipe(refCount());
this.childrenLoaders.set(route, loader);
return loader;
}
@@ -104,54 +117,56 @@ export class RouterConfigLoader {
* an update to the extractor.
*/
export function loadChildren(
route: Route, compiler: Compiler, parentInjector: Injector,
onLoadEndListener?: (r: Route) => void): Observable<LoadedRouterConfig> {
return wrapIntoObservable(route.loadChildren!())
.pipe(
map(maybeUnwrapDefaultExport),
mergeMap((t) => {
if (t instanceof NgModuleFactory || Array.isArray(t)) {
return of(t);
} else {
return from(compiler.compileModuleAsync(t));
}
}),
map((factoryOrRoutes: NgModuleFactory<any>|Routes) => {
if (onLoadEndListener) {
onLoadEndListener(route);
}
// This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is
// no injector associated with lazy loading a `Route` array.
let injector: EnvironmentInjector|undefined;
let rawRoutes: Route[];
let requireStandaloneComponents = false;
if (Array.isArray(factoryOrRoutes)) {
rawRoutes = factoryOrRoutes;
requireStandaloneComponents = true;
} else {
injector = factoryOrRoutes.create(parentInjector).injector;
// When loading a module that doesn't provide `RouterModule.forChild()` preloader
// will get stuck in an infinite loop. The child module's Injector will look to
// its parent `Injector` when it doesn't find any ROUTES so it will return routes
// for it's parent module instead.
rawRoutes = injector.get(ROUTES, [], {optional: true, self: true}).flat();
}
const routes = rawRoutes.map(standardizeConfig);
(typeof ngDevMode === 'undefined' || ngDevMode) &&
validateConfig(routes, route.path, requireStandaloneComponents);
return {routes, injector};
}),
);
route: Route,
compiler: Compiler,
parentInjector: Injector,
onLoadEndListener?: (r: Route) => void,
): Observable<LoadedRouterConfig> {
return wrapIntoObservable(route.loadChildren!()).pipe(
map(maybeUnwrapDefaultExport),
mergeMap((t) => {
if (t instanceof NgModuleFactory || Array.isArray(t)) {
return of(t);
} else {
return from(compiler.compileModuleAsync(t));
}
}),
map((factoryOrRoutes: NgModuleFactory<any> | Routes) => {
if (onLoadEndListener) {
onLoadEndListener(route);
}
// This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is
// no injector associated with lazy loading a `Route` array.
let injector: EnvironmentInjector | undefined;
let rawRoutes: Route[];
let requireStandaloneComponents = false;
if (Array.isArray(factoryOrRoutes)) {
rawRoutes = factoryOrRoutes;
requireStandaloneComponents = true;
} else {
injector = factoryOrRoutes.create(parentInjector).injector;
// When loading a module that doesn't provide `RouterModule.forChild()` preloader
// will get stuck in an infinite loop. The child module's Injector will look to
// its parent `Injector` when it doesn't find any ROUTES so it will return routes
// for it's parent module instead.
rawRoutes = injector.get(ROUTES, [], {optional: true, self: true}).flat();
}
const routes = rawRoutes.map(standardizeConfig);
(typeof ngDevMode === 'undefined' || ngDevMode) &&
validateConfig(routes, route.path, requireStandaloneComponents);
return {routes, injector};
}),
);
}
function isWrappedDefaultExport<T>(value: T|DefaultExport<T>): value is DefaultExport<T> {
function isWrappedDefaultExport<T>(value: T | DefaultExport<T>): value is DefaultExport<T> {
// We use `in` here with a string key `'default'`, because we expect `DefaultExport` objects to be
// dynamically imported ES modules with a spec-mandated `default` key. Thus we don't expect that
// `default` will be a renamed property.
return value && typeof value === 'object' && 'default' in value;
}
function maybeUnwrapDefaultExport<T>(input: T|DefaultExport<T>): T {
function maybeUnwrapDefaultExport<T>(input: T | DefaultExport<T>): T {
// As per `isWrappedDefaultExport`, the `default` key here is generated by the browser and not
// subject to property renaming, so we reference it with bracket access.
return isWrappedDefaultExport(input) ? input['default'] : input;
+54 -19
View File
@@ -6,8 +6,27 @@
* found in the LICENSE file at https://angular.io/license
*/
import {HashLocationStrategy, Location, LocationStrategy, PathLocationStrategy, ViewportScroller} from '@angular/common';
import {APP_BOOTSTRAP_LISTENER, ComponentRef, inject, Inject, InjectionToken, ModuleWithProviders, NgModule, NgZone, Optional, Provider, SkipSelf, ɵRuntimeError as RuntimeError} from '@angular/core';
import {
HashLocationStrategy,
Location,
LocationStrategy,
PathLocationStrategy,
ViewportScroller,
} from '@angular/common';
import {
APP_BOOTSTRAP_LISTENER,
ComponentRef,
inject,
Inject,
InjectionToken,
ModuleWithProviders,
NgModule,
NgZone,
Optional,
Provider,
SkipSelf,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {EmptyOutletComponent} from './components/empty_outlet';
import {RouterLink} from './directives/router_link';
@@ -16,7 +35,17 @@ import {RouterOutlet} from './directives/router_outlet';
import {RuntimeErrorCode} from './errors';
import {Routes} from './models';
import {NavigationTransitions} from './navigation_transition';
import {getBootstrapListener, rootRoute, ROUTER_IS_PROVIDED, withComponentInputBinding, withDebugTracing, withDisabledInitialNavigation, withEnabledBlockingInitialNavigation, withPreloading, withViewTransitions} from './provide_router';
import {
getBootstrapListener,
rootRoute,
ROUTER_IS_PROVIDED,
withComponentInputBinding,
withDebugTracing,
withDisabledInitialNavigation,
withEnabledBlockingInitialNavigation,
withPreloading,
withViewTransitions,
} from './provide_router';
import {Router} from './router';
import {ExtraOptions, ROUTER_CONFIGURATION} from './router_config';
import {RouterConfigLoader, ROUTES} from './router_config_loader';
@@ -25,7 +54,6 @@ import {ROUTER_SCROLLER, RouterScroller} from './router_scroller';
import {ActivatedRoute} from './router_state';
import {DefaultUrlSerializer, UrlSerializer} from './url_tree';
/**
* The directives defined in the `RouterModule`.
*/
@@ -35,8 +63,10 @@ const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkActive, EmptyOutl
* @docsNotRequired
*/
export const ROUTER_FORROOT_GUARD = new InjectionToken<void>(
(typeof ngDevMode === 'undefined' || ngDevMode) ? 'router duplicate forRoot guard' :
'ROUTER_FORROOT_GUARD');
typeof ngDevMode === 'undefined' || ngDevMode
? 'router duplicate forRoot guard'
: 'ROUTER_FORROOT_GUARD',
);
// TODO(atscott): All of these except `ActivatedRoute` are `providedIn: 'root'`. They are only kept
// here to avoid a breaking change whereby the provider order matters based on where the
@@ -51,8 +81,9 @@ export const ROUTER_PROVIDERS: Provider[] = [
RouterConfigLoader,
// Only used to warn when `provideRoutes` is used without `RouterModule` or `provideRouter`. Can
// be removed when `provideRoutes` is removed.
(typeof ngDevMode === 'undefined' || ngDevMode) ? {provide: ROUTER_IS_PROVIDED, useValue: true} :
[],
typeof ngDevMode === 'undefined' || ngDevMode
? {provide: ROUTER_IS_PROVIDED, useValue: true}
: [],
];
/**
@@ -106,14 +137,16 @@ export class RouterModule {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
(typeof ngDevMode === 'undefined' || ngDevMode) ?
(config?.enableTracing ? withDebugTracing().ɵproviders : []) :
[],
typeof ngDevMode === 'undefined' || ngDevMode
? config?.enableTracing
? withDebugTracing().ɵproviders
: []
: [],
{provide: ROUTES, multi: true, useValue: routes},
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new Optional(), new SkipSelf()]]
deps: [[Router, new Optional(), new SkipSelf()]],
},
{provide: ROUTER_CONFIGURATION, useValue: config ? config : {}},
config?.useHash ? provideHashLocationStrategy() : providePathLocationStrategy(),
@@ -187,9 +220,10 @@ function providePathLocationStrategy(): Provider {
export function provideForRootGuard(router: Router): any {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && router) {
throw new RuntimeError(
RuntimeErrorCode.FOR_ROOT_CALLED_TWICE,
`The Router was provided more than once. This can happen if 'forRoot' is used outside of the root injector.` +
` Lazy loaded modules should use RouterModule.forChild() instead.`);
RuntimeErrorCode.FOR_ROOT_CALLED_TWICE,
`The Router was provided more than once. This can happen if 'forRoot' is used outside of the root injector.` +
` Lazy loaded modules should use RouterModule.forChild() instead.`,
);
}
return 'guarded';
}
@@ -199,9 +233,9 @@ export function provideForRootGuard(router: Router): any {
function provideInitialNavigation(config: Pick<ExtraOptions, 'initialNavigation'>): Provider[] {
return [
config.initialNavigation === 'disabled' ? withDisabledInitialNavigation().ɵproviders : [],
config.initialNavigation === 'enabledBlocking' ?
withEnabledBlockingInitialNavigation().ɵproviders :
[],
config.initialNavigation === 'enabledBlocking'
? withEnabledBlockingInitialNavigation().ɵproviders
: [],
];
}
@@ -213,7 +247,8 @@ function provideInitialNavigation(config: Pick<ExtraOptions, 'initialNavigation'
* @publicApi
*/
export const ROUTER_INITIALIZER = new InjectionToken<(compRef: ComponentRef<any>) => void>(
(typeof ngDevMode === 'undefined' || ngDevMode) ? 'Router Initializer' : '');
typeof ngDevMode === 'undefined' || ngDevMode ? 'Router Initializer' : '',
);
function provideRouterInitializer(): Provider[] {
return [

Some files were not shown because too many files have changed in this diff Show More