import * as ts from 'typescript'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { strings } from '@angular-devkit/core'; import { apply, applyTemplates, chain, mergeWith, move, noop, Rule, SchematicsException, Tree, url } from '@angular-devkit/schematics'; import { addDeclarationToModule, addEntryComponentToModule, addExportToModule, insertImport } from '../utility/ast-utils'; import { InsertChange } from '../utility/change'; import { createComment } from '../utility/comment'; import { buildRelativePath, findModuleFromOptions } from '../utility/find-module'; import { applyLintFix } from '../utility/lint-fix'; import { parseName } from '../utility/parse-name'; import { buildDefaultPath, getDefaultProjectName, getProject } from '../utility/project'; import { validateHtmlSelector, validateName } from '../utility/validation'; import { ChangeDetection, Schema as ComponentOptions, Style, ViewEncapsulation } from './schema'; function readIntoSourceFile(host: Tree, modulePath: string): ts.SourceFile { const text = host.read(modulePath); if (text === null) { throw new SchematicsException(`File ${modulePath} does not exist.`); } const sourceText = text.toString('utf-8'); return ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true); } function addComponentToRouteModule(options: ComponentOptions): Rule{ return (host: Tree) => { if (options.skipImport || !options.module) { return host; } const modulePath = options.module.replace('.module.ts', '-routing.module.ts'); const source = readIntoSourceFile(host, modulePath); let routes: ts.VariableStatement; ts.forEachChild(source, node => { if(ts.isVariableStatement(node)){ const name = node.declarationList.declarations[0].name.getText(); if(name === 'routes'){ routes = node; } } }) const classifiedName = strings.classify(`${options.name}Component`); const route = `{path: '${options.name}', component: ${classifiedName} }`; const elements = (routes.declarationList.declarations[0].initializer as ts.ArrayLiteralExpression).elements; const position = elements.length === 0 ? routes.getEnd() - 2 : elements[elements.length - 1].getEnd(); const toInsert = (elements.length === 0 ? '' : ',') + `\n\t${route}\n`; const componentPath = `/${options.path}/` + (options.flat ? '' : strings.dasherize(options.name) + '/') + strings.dasherize(options.name) + '.component'; const relativePath = buildRelativePath(modulePath, componentPath); const importChanges = [ insertImport(source, modulePath, classifiedName, relativePath ), new InsertChange(modulePath, position, toInsert) ] const declarationRecorder = host.beginUpdate(modulePath); for (const change of importChanges) { if (change instanceof InsertChange) { declarationRecorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(declarationRecorder); if (options.export) { // Need to refresh the AST because we overwrote the file in the host. const source = readIntoSourceFile(host, modulePath); const exportRecorder = host.beginUpdate(modulePath); const exportChanges = addExportToModule(source, modulePath, strings.classify(`${options.name}Component`), relativePath); for (const change of exportChanges) { if (change instanceof InsertChange) { exportRecorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(exportRecorder); } if (options.entryComponent) { // Need to refresh the AST because we overwrote the file in the host. const source = readIntoSourceFile(host, modulePath); const entryComponentRecorder = host.beginUpdate(modulePath); const entryComponentChanges = addEntryComponentToModule( source, modulePath, strings.classify(`${options.name}Component`), relativePath); for (const change of entryComponentChanges) { if (change instanceof InsertChange) { entryComponentRecorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(entryComponentRecorder); } return host; } } function addDeclarationToNgModule(options: ComponentOptions): Rule { return (host: Tree) => { if (options.skipImport || !options.module) { return host; } const modulePath = options.module; const source = readIntoSourceFile(host, modulePath); const componentPath = `/${options.path}/` + (options.flat ? '' : strings.dasherize(options.name) + '/') + strings.dasherize(options.name) + '.component'; const relativePath = buildRelativePath(modulePath, componentPath); const classifiedName = strings.classify(`${options.name}Component`); const declarationChanges = addDeclarationToModule(source, modulePath, classifiedName, relativePath); const declarationRecorder = host.beginUpdate(modulePath); for (const change of declarationChanges) { if (change instanceof InsertChange) { declarationRecorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(declarationRecorder); if (options.export) { // Need to refresh the AST because we overwrote the file in the host. const source = readIntoSourceFile(host, modulePath); const exportRecorder = host.beginUpdate(modulePath); const exportChanges = addExportToModule(source, modulePath, strings.classify(`${options.name}Component`), relativePath); for (const change of exportChanges) { if (change instanceof InsertChange) { exportRecorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(exportRecorder); } if (options.entryComponent) { // Need to refresh the AST because we overwrote the file in the host. const source = readIntoSourceFile(host, modulePath); const entryComponentRecorder = host.beginUpdate(modulePath); const entryComponentChanges = addEntryComponentToModule( source, modulePath, strings.classify(`${options.name}Component`), relativePath); for (const change of entryComponentChanges) { if (change instanceof InsertChange) { entryComponentRecorder.insertLeft(change.pos, change.toAdd); } } host.commitUpdate(entryComponentRecorder); } return host; }; } function buildSelector(options: ComponentOptions, projectPrefix: string) { let selector = strings.dasherize(options.name); if (options.prefix) { selector = `${options.prefix}-${selector}`; } else if (options.prefix === undefined && projectPrefix) { selector = `${projectPrefix}-${selector}`; } return selector; } export function component(options: ComponentOptions): Rule { return (host: Tree) => { if (!options.project) { options.project = getDefaultProjectName(host, options).projectName as string; } const project = getProject(host, options.project); options.viewEncapsulation = ViewEncapsulation.ShadowDom; options.style = Style.Less; options.skipTests = true; options.changeDetection = ChangeDetection.Default; options.inlineTemplate = false; options.inlineStyle = false; if (options.path === undefined) { options.path = buildDefaultPath(project); } options.module = findModuleFromOptions(host, options); let moduleName = (options.module as string).split('.')[0].split('/').reverse()[0]; const parsedPath = parseName(options.path, options.name); options.name = parsedPath.name; options.path = parsedPath.path; options.selector = options.selector || buildSelector(options, project.prefix); validateName(options.name); validateHtmlSelector(options.selector); const templateSource = apply(url('./files'), [ applyTemplates({ ...strings, ...options, 'if-flat': (s: string) => options.flat ? '' : s, moduleName, comment: createComment() }), move(parsedPath.path), ]); return chain([ addDeclarationToNgModule(options), addComponentToRouteModule(options), mergeWith(templateSource), options.lintFix ? applyLintFix(options.path) : noop(), ]); }; }