Skip to content

refactor(schematics): cleanup attribute selector rules #12507

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/lib/schematics/update/material/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const colorFns = {

export function color(message: string): string {
// 'r{{text}}' with red 'text', 'g{{text}}' with green 'text', and 'b{{text}}' with bold 'text'.
return message.replace(/(.)\{\{(.*?)\}\}/g, (_m, fnName, text) => {
return message.replace(/(.){{(.*?)}}/g, (_m, fnName, text) => {
const fn = colorFns[fnName];
return fn ? fn(text) : text;
});
Expand Down
9 changes: 0 additions & 9 deletions src/lib/schematics/update/material/extra-stylsheets.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably in another PR, but we should also make these filenames consistent with the rest of the project (dashes instead of camelCase)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That does unfortunately not work because TSLint expects the files to the be camel-cased in order to load them.

* @license
* Copyright Google LLC 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 {green, red} from 'chalk';
import {Replacement, RuleFailure, Rules, RuleWalker} from 'tslint';
import {
attributeSelectors,
MaterialAttributeSelectorData,
} from '../../material/data/attribute-selectors';
import {findAllSubstringIndices} from '../../typescript/literal';
import * as ts from 'typescript';

/**
* Rule that walks through every string literal that is part of a call expression and
* switches deprecated attribute selectors to the updated selector.
*/
export class Rule extends Rules.AbstractRule {
apply(sourceFile: ts.SourceFile): RuleFailure[] {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
}
}

class Walker extends RuleWalker {

visitStringLiteral(literal: ts.StringLiteral) {
if (literal.parent && literal.parent.kind !== ts.SyntaxKind.CallExpression) {
return;
}

const literalText = literal.getFullText();

attributeSelectors.forEach(selector => {
findAllSubstringIndices(literalText, selector.replace)
.map(offset => literal.getStart() + offset)
.map(start => new Replacement(start, selector.replace.length, selector.replaceWith))
.forEach(replacement => this._addFailureWithReplacement(literal, replacement, selector));
});
}

/** Adds an attribute selector failure with the given replacement at the specified node. */
private _addFailureWithReplacement(node: ts.Node, replacement: Replacement,
selector: MaterialAttributeSelectorData) {

this.addFailureAtNode(
node,
`Found deprecated attribute selector "${red('[' + selector.replace + ']')}" which ` +
`has been renamed to "${green('[' + selector.replaceWith + ']')}"`,
replacement);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* @license
* Copyright Google LLC 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 {green, red} from 'chalk';
import {sync as globSync} from 'glob';
import {IOptions, Replacement, RuleFailure, Rules} from 'tslint';
import {attributeSelectors} from '../../material/data/attribute-selectors';
import {ExternalResource} from '../../tslint/component-file';
import {ComponentWalker} from '../../tslint/component-walker';
import {
addFailureAtReplacement,
createExternalReplacementFailure,
} from '../../tslint/rule-failures';
import {findAllSubstringIndices} from '../../typescript/literal';
import * as ts from 'typescript';

/**
* Rule that walks through every stylesheet in the application and updates outdated
* attribute selectors to the updated selector.
*/
export class Rule extends Rules.AbstractRule {

apply(sourceFile: ts.SourceFile): RuleFailure[] {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
}
}

export class Walker extends ComponentWalker {

constructor(sourceFile: ts.SourceFile, options: IOptions) {
// In some applications, developers will have global stylesheets that are not specified in any
// Angular component. Therefore we glob up all css and scss files outside of node_modules and
// dist and check them as well.
const extraFiles = globSync('!(node_modules|dist)/**/*.+(css|scss)');
super(sourceFile, options, extraFiles);
extraFiles.forEach(styleUrl => this._reportExternalStyle(styleUrl));
}

visitInlineStylesheet(literal: ts.StringLiteral) {
this._createReplacementsForContent(literal, literal.getText())
.forEach(data => addFailureAtReplacement(this, data.failureMessage, data.replacement));
}

visitExternalStylesheet(node: ExternalResource) {
this._createReplacementsForContent(node, node.getFullText())
.map(data => createExternalReplacementFailure(node, data.failureMessage,
this.getRuleName(), data.replacement))
.forEach(failure => this.addFailure(failure));
}

/**
* Searches for outdated attribute selectors in the specified content and creates replacements
* with the according messages that can be added to a rule failure.
*/
private _createReplacementsForContent(node: ts.Node, stylesheetContent: string) {
const replacements: {failureMessage: string, replacement: Replacement}[] = [];

attributeSelectors.forEach(selector => {
const currentSelector = `[${selector.replace}]`;
const updatedSelector = `[${selector.replaceWith}]`;

const failureMessage = `Found deprecated attribute selector "${red(currentSelector)}"` +
` which has been renamed to "${green(updatedSelector)}"`;

findAllSubstringIndices(stylesheetContent, currentSelector)
.map(offset => node.getStart() + offset)
.map(start => new Replacement(start, currentSelector.length, updatedSelector))
.forEach(replacement => replacements.push({replacement, failureMessage}));
});

return replacements;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* @license
* Copyright Google LLC 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 {green, red} from 'chalk';
import {Replacement, RuleFailure, Rules} from 'tslint';
import * as ts from 'typescript';
import {attributeSelectors} from '../../material/data/attribute-selectors';
import {ExternalResource} from '../../tslint/component-file';
import {ComponentWalker} from '../../tslint/component-walker';
import {
addFailureAtReplacement,
createExternalReplacementFailure,
} from '../../tslint/rule-failures';
import {findAllSubstringIndices} from '../../typescript/literal';

/**
* Rule that walks through every component template and switches outdated attribute
* selectors to the updated selector.
*/
export class Rule extends Rules.AbstractRule {
apply(sourceFile: ts.SourceFile): RuleFailure[] {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions()));
}
}

export class Walker extends ComponentWalker {

visitInlineTemplate(template: ts.StringLiteral) {
this._createReplacementsForContent(template, template.getText())
.forEach(data => addFailureAtReplacement(this, data.failureMessage, data.replacement));
}

visitExternalTemplate(template: ExternalResource) {
this._createReplacementsForContent(template, template.getFullText())
.map(data => createExternalReplacementFailure(template, data.failureMessage,
this.getRuleName(), data.replacement))
.forEach(failure => this.addFailure(failure));
}

/**
* Searches for outdated attribute selectors in the specified content and creates replacements
* with the according messages that can be added to a rule failure.
*/
private _createReplacementsForContent(node: ts.Node, templateContent: string) {
const replacements: {failureMessage: string, replacement: Replacement}[] = [];

attributeSelectors.forEach(selector => {
const failureMessage = `Found deprecated attribute selector "[${red(selector.replace)}]"` +
` which has been renamed to "[${green(selector.replaceWith)}]"`;

findAllSubstringIndices(templateContent, selector.replace)
.map(offset => node.getStart() + offset)
.map(start => new Replacement(start, selector.replace.length, selector.replaceWith))
.forEach(replacement => replacements.push({replacement, failureMessage}));
});

return replacements;
}
}
16 changes: 9 additions & 7 deletions src/lib/schematics/update/rules/checkTemplateMiscRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import * as ts from 'typescript';
import {findInputsOnElementWithTag, findOutputsOnElementWithTag} from '../html/angular';
import {ExternalResource} from '../tslint/component-file';
import {ComponentWalker} from '../tslint/component-walker';
import {findAll} from '../typescript/literal';
import {findAllSubstringIndices} from '../typescript/literal';

/**
* Rule that walks through every component decorator and updates their inline or external
Expand Down Expand Up @@ -48,12 +48,14 @@ export class CheckTemplateMiscWalker extends ComponentWalker {
{start: number, end: number, message: string}[] {
let failures: {message: string, start: number, end: number}[] = [];

failures = failures.concat(findAll(templateContent, 'cdk-focus-trap').map(offset => ({
start: offset,
end: offset + 'cdk-focus-trap'.length,
message: `Found deprecated element selector "${red('cdk-focus-trap')}" which has been` +
` changed to an attribute selector "${green('[cdkTrapFocus]')}"`
})));
failures = failures.concat(
findAllSubstringIndices(templateContent, 'cdk-focus-trap').map(offset => ({
start: offset,
end: offset + 'cdk-focus-trap'.length,
message: `Found deprecated element selector "${red('cdk-focus-trap')}" which has been` +
` changed to an attribute selector "${green('[cdkTrapFocus]')}"`
}))
);

failures = failures.concat(
findOutputsOnElementWithTag(templateContent, 'selectionChange', ['mat-list-option'])
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {green, red} from 'chalk';
import {Replacement, RuleFailure, Rules, RuleWalker} from 'tslint';
import * as ts from 'typescript';
import {cssNames} from '../material/data/css-names';
import {findAll} from '../typescript/literal';
import {findAllSubstringIndices} from '../typescript/literal';

/**
* Rule that walks through every string literal, which includes the outdated Material name and
Expand All @@ -34,7 +34,7 @@ export class SwitchStringLiteralCssNamesWalker extends RuleWalker {
cssNames.forEach(name => {
if (!name.whitelist || name.whitelist.strings) {
this.createReplacementsForOffsets(stringLiteral, name,
findAll(stringLiteralText, name.replace)).forEach(replacement => {
findAllSubstringIndices(stringLiteralText, name.replace)).forEach(replacement => {
this.addFailureAtNode(
stringLiteral,
`Found deprecated CSS class "${red(name.replace)}" which has been renamed to` +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {green, red} from 'chalk';
import {Replacement, RuleFailure, Rules, RuleWalker} from 'tslint';
import * as ts from 'typescript';
import {elementSelectors} from '../material/data/element-selectors';
import {findAll} from '../typescript/literal';
import {findAllSubstringIndices} from '../typescript/literal';

/**
* Rule that walks through every string literal, which includes the outdated Material name and
Expand All @@ -33,7 +33,7 @@ export class SwitchStringLiteralElementSelectorsWalker extends RuleWalker {

elementSelectors.forEach(selector => {
this.createReplacementsForOffsets(stringLiteral, selector,
findAll(stringLiteralText, selector.replace)).forEach(replacement => {
findAllSubstringIndices(stringLiteralText, selector.replace)).forEach(replacement => {
this.addFailureAtNode(
stringLiteral,
`Found deprecated element selector "${red(selector.replace)}" which has been` +
Expand Down
Loading