-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
routing.ts
393 lines (332 loc) · 14.7 KB
/
routing.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/**
* @license
* Copyright Akveo. All Rights Reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
import * as ts from 'typescript';
import { basename, dirname, join, normalize, NormalizedSep, Path } from '@angular-devkit/core';
import { SchematicsException, Tree } from '@angular-devkit/schematics';
import { getSourceFile } from '@angular/cdk/schematics';
import { getDecoratorMetadata, insertImport } from '@schematics/angular/utility/ast-utils';
import {
addArrayElement,
addObjectProperty,
applyInsertChange,
findDeclarationByIdentifier,
importPath,
isBasePlaygroundModule,
isLayoutPath,
isRootPlaygroundModule,
LAYOUT_COMPONENT_CLASS,
LAYOUT_MODULE_CLASS,
LAYOUT_MODULE_PATH,
LAYOUT_ROUTING_MODULE_PATH,
NO_LAYOUT_COMPONENT_CLASS,
NO_LAYOUT_MODULE_CLASS,
NO_LAYOUT_MODULE_PATH,
NO_LAYOUT_ROUTING_MODULE_PATH,
PLAYGROUND_ROUTING_MODULE_PATH,
} from '../utils';
export function findRoutesArray(tree: Tree, modulePath: Path): ts.ArrayLiteralExpression {
const source = getSourceFile(tree, modulePath);
const decoratorNode = getDecoratorMetadata(source, 'NgModule', '@angular/core')[0] as ts.ObjectLiteralExpression;
if (decoratorNode == null) {
throw new SchematicsException(`Error in ${modulePath}. Can't find NgModule decorator.`);
}
try {
const imports = getImports(decoratorNode);
const routerModuleCall = getRouterModuleCall(imports);
const routesArgument = routerModuleCall.arguments[0];
if (routesArgument.kind === ts.SyntaxKind.ArrayLiteralExpression) {
return routesArgument as ts.ArrayLiteralExpression;
}
if (routesArgument.kind === ts.SyntaxKind.Identifier) {
const declaration = getRoutesVariableDeclaration(source, (routesArgument as ts.Identifier));
return declaration.initializer as ts.ArrayLiteralExpression;
}
throw new SchematicsException(`Expecting RouterModule.forChild parameter to be an array or variable identifier.`);
} catch (e) {
throw new SchematicsException(`Error in ${modulePath}. ${e.message}`);
}
}
function getImports(moduleDecorator: ts.ObjectLiteralExpression): ts.PropertyAssignment {
const imports = moduleDecorator.properties
.filter(p => p.kind === ts.SyntaxKind.PropertyAssignment)
.find((p: ts.PropertyAssignment) => p.name.getText() === 'imports') as ts.PropertyAssignment;
if (imports == null) {
throw new SchematicsException(`Can't find imports in module.`);
}
if (imports.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
throw new SchematicsException(`'imports' property should be initialized with array.`);
}
return imports;
}
function getRouterModuleCall(importsNode: ts.PropertyAssignment): ts.CallExpression {
const routerModuleCall = (importsNode.initializer as ts.ArrayLiteralExpression)
.elements
.filter(el => el.kind === ts.SyntaxKind.CallExpression)
.find((el: ts.CallExpression) => el.expression.getText() === 'RouterModule.forChild') as ts.CallExpression;
if (routerModuleCall == null) {
throw new SchematicsException(`Can't find RouterModule.forChild call in module imports.`);
}
if (routerModuleCall.arguments.length === 0) {
throw new SchematicsException(`RouterModule.forChild should be called with arguments.`);
}
return routerModuleCall;
}
function getRoutesVariableDeclaration(source: ts.SourceFile, identifier: ts.Identifier): ts.VariableDeclaration {
const declaration = findDeclarationByIdentifier(source, (identifier as ts.Identifier).getText());
if (declaration == null) {
throw new SchematicsException(`Can't find declaration of '${identifier.getText()}'.`);
}
if (declaration.initializer == null) {
throw new SchematicsException(`Routes variable should be initialized during declaration.`);
}
if (declaration.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
throw new SchematicsException(`Routes variable should be initialized with array.`);
}
return declaration;
}
export function generateComponentRoute(path: string, component: string, ...routeFields: string[]): string {
return generatePathRoute(path, `component: ${component}`, ...routeFields);
}
export function generatePathRoute(path: string, ...routeFields: string[]): string {
return generateRoute(`path: '${path}'`, ...routeFields);
}
export function generateRoute(...routeFields: string[]) {
return `{
${routeFields.join(',\n ')},
}`;
}
export type RoutePredicate = (route: ts.ObjectLiteralExpression) => boolean;
export function generateLazyModuleImport(from: Path, to: Path, moduleClassName: string): string {
const path = normalize(importPath(from, to));
return `() => import('./${dirname(path)}/${basename(path)}').then(m => m.${moduleClassName})`;
}
/**
* @param routingModulePath full path to routing module
* @param targetFile full path to file containing component or module for the route
*/
export function addMissingChildRoutes(tree: Tree, routingModulePath: Path, targetFile: Path): void {
const routingModuleDir = dirname(routingModulePath);
if (isRootPlaygroundModule(routingModuleDir)) {
return addRootRoute(tree, targetFile);
}
if (isBasePlaygroundModule(routingModuleDir)) {
addBaseRoute(tree, targetFile);
}
addMissingPaths(tree, routingModulePath, targetFile);
}
function addMissingPaths(tree: Tree, routingModulePath: Path, targetFile: Path): void {
const targetDir = dirname(targetFile);
const relativePath = targetDir.replace(dirname(routingModulePath), '');
const existingPathEnd = targetDir.indexOf(relativePath);
let existingPath = normalize(targetDir.slice(0, existingPathEnd));
const pathsToCheck = dirsToRoutePaths(relativePath);
for (let i = 0; i < pathsToCheck.length; i++) {
const routePathToCheck = pathsToCheck[i];
const fullPathToCheck = join(existingPath, routePathToCheck);
const pathPredicates = routePredicatesFromPath(routingModulePath, fullPathToCheck);
let routesArray = findRoutesArray(tree, routingModulePath);
let route = findRouteWithPath(routesArray, pathPredicates);
if (!route) {
const routesArrayToAddTo = getParentRouteChildren(routesArray, routingModulePath, fullPathToCheck);
addRoute(tree, routingModulePath, routesArrayToAddTo, generatePathRoute(routePathToCheck));
routesArray = findRoutesArray(tree, routingModulePath);
route = findRouteWithPath(routesArray, pathPredicates) as ts.ObjectLiteralExpression;
}
const allChecked = i === pathsToCheck.length - 1;
if (allChecked) {
return;
}
existingPath = fullPathToCheck;
if (!getRouteChildren(route)) {
addObjectProperty(tree, getSourceFile(tree, routingModulePath), route, 'children: []');
}
}
}
function getParentRouteChildren(
routesArray: ts.ArrayLiteralExpression,
routingModulePath: Path,
targetDir: Path,
): ts.ArrayLiteralExpression {
const predicates = routePredicatesFromPath(routingModulePath, dirname(targetDir));
const route = findRouteWithPath(routesArray, predicates) as ts.ObjectLiteralExpression;
return getRouteChildren(route) as ts.ArrayLiteralExpression;
}
export function addRootRoute(tree: Tree, targetFile: Path): void {
const routesArray = findRoutesArray(tree, PLAYGROUND_ROUTING_MODULE_PATH);
if (findRouteWithPath(routesArray, [rootRoutePredicate(targetFile)])) {
return;
}
const isLayout = isLayoutPath(targetFile);
const baseModulePath = isLayout ? LAYOUT_MODULE_PATH : NO_LAYOUT_MODULE_PATH ;
const baseModuleClass = isLayout ? LAYOUT_MODULE_CLASS : NO_LAYOUT_MODULE_CLASS ;
const lazyModuleImport = generateLazyModuleImport(PLAYGROUND_ROUTING_MODULE_PATH, baseModulePath, baseModuleClass);
const routeString = generatePathRoute('', `loadChildren: ${lazyModuleImport}`);
addRoute(tree, PLAYGROUND_ROUTING_MODULE_PATH, routesArray, routeString);
}
export function addBaseRoute(tree: Tree, targetFile: Path): void {
const isLayout = isLayoutPath(targetFile);
const baseModulePath = isLayout ? LAYOUT_ROUTING_MODULE_PATH : NO_LAYOUT_ROUTING_MODULE_PATH;
const routesArray = findRoutesArray(tree, baseModulePath);
const baseRoute = findRouteWithPath(routesArray, [baseComponentPredicate(targetFile)]);
if (baseRoute) {
if (!getRouteChildren(baseRoute)) {
addObjectProperty(tree, getSourceFile(tree, baseModulePath), baseRoute, 'children: []');
}
return;
}
const baseModuleComponent = isLayout ? LAYOUT_COMPONENT_CLASS : NO_LAYOUT_COMPONENT_CLASS;
const routeString = generateComponentRoute('', baseModuleComponent, `children: []`);
addRoute(tree, baseModulePath, routesArray, routeString);
}
export function addRoute(
tree: Tree,
routingModulePath: Path,
routes: ts.ArrayLiteralExpression,
route: string,
componentClass?: string,
fileImportPath?: string,
): void {
const source = getSourceFile(tree, routingModulePath);
const alreadyInRoutes = routes.getFullText().includes(route);
if (alreadyInRoutes) {
return;
}
addArrayElement(tree, source, routes, route);
if (componentClass && fileImportPath) {
const importChange = insertImport(source, source.fileName, componentClass, fileImportPath);
applyInsertChange(tree, normalize(source.fileName), importChange);
}
}
export function findRoute(
routesArray: ts.ArrayLiteralExpression,
predicate: RoutePredicate,
): ts.ObjectLiteralExpression | undefined {
const queue: ts.ObjectLiteralExpression[] = getRoutesFromArray(routesArray);
while (queue.length > 0) {
const route = queue.shift() as ts.ObjectLiteralExpression;
if (predicate(route)) {
return route;
}
const routeChildren = getRouteChildren(route);
if (routeChildren) {
queue.push(...getRoutesFromArray(routeChildren));
}
}
return undefined;
}
/**
* @param routesArray array to search in
* @param predicates predicate for each level
*/
export function findRouteWithPath(
routesArray: ts.ArrayLiteralExpression,
predicates: RoutePredicate[],
): ts.ObjectLiteralExpression | undefined {
const routes = getRoutesFromArray(routesArray);
for (const route of routes) {
const isMatch = predicates[0](route);
const isLastMatch = isMatch && predicates.length === 1;
if (!isMatch) {
continue;
}
if (isLastMatch) {
return route;
}
const children = getRouteChildren(route);
const foundRoute = children && findRouteWithPath(children, predicates.slice(1));
if (foundRoute) {
return foundRoute;
}
}
return undefined;
}
export function getRoutesFromArray(routesArray: ts.ArrayLiteralExpression): ts.ObjectLiteralExpression[] {
return routesArray.elements
.filter(node => node.kind === ts.SyntaxKind.ObjectLiteralExpression) as ts.ObjectLiteralExpression[];
}
export function getRouteChildren(route: ts.ObjectLiteralExpression): ts.ArrayLiteralExpression | undefined {
const children = findRouteProp(route, 'children');
if (children == null) {
return undefined;
}
if (children.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
throw new SchematicsException(`Expecting children to be an array.`);
}
return children.initializer as ts.ArrayLiteralExpression;
}
export function getRouteProps(route: ts.ObjectLiteralExpression): ts.PropertyAssignment[] {
return route.properties
.filter(prop => prop.kind === ts.SyntaxKind.PropertyAssignment) as ts.PropertyAssignment[];
}
export function findRouteProp(route: ts.ObjectLiteralExpression, propName: string): ts.PropertyAssignment | undefined {
return getRouteProps(route).find(prop => prop.name.getText() === propName);
}
export function getRouteLazyModule(route: ts.ObjectLiteralExpression): ts.PropertyAssignment | undefined {
return findRouteProp(route, 'loadChildren');
}
export function getRouteComponent(route: ts.ObjectLiteralExpression): ts.PropertyAssignment | undefined {
return findRouteProp(route, 'component');
}
export function getRoutePath(route: ts.ObjectLiteralExpression): ts.PropertyAssignment | undefined {
return findRouteProp(route, 'path');
}
/**
* Returns array of route paths relative to playground.
*/
export function dirsToRoutePaths(dirPath: string): string[] {
return dirPath.split(NormalizedSep).filter(dir => dir);
}
/**
* Returns predicate bound to array of predicates which will check route and it's children to conform routing path
* for a given file path.
* @param routingModulePath full path to routing module
* @param targetDirPath full path to directory containing component or module file for the route
*/
export function routePredicatesFromPath(routingModulePath: Path, targetDirPath: Path): RoutePredicate[] {
const routingModuleDir = dirname(routingModulePath);
if (isRootPlaygroundModule(routingModuleDir)) {
return [rootRoutePredicate(targetDirPath)];
}
const predicates: RoutePredicate[] = [];
if (isBasePlaygroundModule(routingModuleDir)) {
predicates.push(baseComponentPredicate(targetDirPath));
}
const relativeToRoutingModule = targetDirPath.replace(dirname(routingModulePath), '');
const routePaths = dirsToRoutePaths(relativeToRoutingModule);
for (const path of routePaths) {
predicates.push((route: ts.ObjectLiteralExpression) => pathRoutePredicate(path, route));
}
return predicates;
}
export function pathRoutePredicate(routePath: string, route: ts.ObjectLiteralExpression): boolean {
const path = getRoutePath(route);
return !!path && path.initializer.getText() === `'${routePath}'`;
}
export function componentRoutePredicate(componentClass: string, route: ts.ObjectLiteralExpression): boolean {
const component = getRouteComponent(route);
return !!component && component.initializer.getText() === componentClass;
}
export function lazyModulePredicate(lazyModuleImport: string, route: ts.ObjectLiteralExpression): boolean {
const loadChildren = getRouteLazyModule(route);
return !!loadChildren && loadChildren.initializer.getText() === lazyModuleImport;
}
export function baseComponentPredicate(modulePath: Path): RoutePredicate {
const rootComponentClass = isLayoutPath(modulePath) ? LAYOUT_COMPONENT_CLASS : NO_LAYOUT_COMPONENT_CLASS;
return (route: ts.ObjectLiteralExpression) => componentRoutePredicate(rootComponentClass, route);
}
export function rootRoutePredicate(modulePath: Path): RoutePredicate {
const isLayout = isLayoutPath(modulePath);
const baseModulePath = isLayout ? LAYOUT_MODULE_PATH : NO_LAYOUT_MODULE_PATH;
const baseModuleClass = isLayout ? LAYOUT_MODULE_CLASS : NO_LAYOUT_MODULE_CLASS;
const lazyModuleImport = generateLazyModuleImport(PLAYGROUND_ROUTING_MODULE_PATH, baseModulePath, baseModuleClass);
return (route: ts.ObjectLiteralExpression) => lazyModulePredicate(lazyModuleImport, route);
}
export function isLazyRoute(route: ts.ObjectLiteralExpression): boolean {
return !!getRouteLazyModule(route);
}
export function isComponentRoute(route: ts.ObjectLiteralExpression): boolean {
return !!getRouteComponent(route);
}