refactor(directive parser) remove cheerio in favor of angular's own compiler

This commit is contained in:
Kim Biesbjerg
2019-06-18 15:54:58 +02:00
parent c8ba1312b5
commit 9a8abb3248
9 changed files with 174 additions and 130 deletions

View File

@@ -2,69 +2,78 @@ import { ParserInterface } from './parser.interface';
import { TranslationCollection } from '../utils/translation.collection';
import { isPathAngularComponent, extractComponentInlineTemplate } from '../utils/utils';
import * as cheerio from 'cheerio';
const $ = cheerio.load('', { xmlMode: true });
import { parseTemplate, TmplAstNode, TmplAstElement, TmplAstTextAttribute } from '@angular/compiler';
export class DirectiveParser implements ParserInterface {
public extract(contents: string, path?: string): TranslationCollection {
public extract(template: string, path: string): TranslationCollection {
if (path && isPathAngularComponent(path)) {
contents = extractComponentInlineTemplate(contents);
template = extractComponentInlineTemplate(template);
}
return this.parseTemplate(contents);
}
protected parseTemplate(template: string): TranslationCollection {
let collection: TranslationCollection = new TranslationCollection();
const selector = '[translate], [ng2-translate]';
template = this.prepareTemplate(template);
$(template)
.find(selector)
.addBack(selector)
.each((i: number, element: CheerioElement) => {
const $element = $(element);
const attr = $element.attr('translate') || $element.attr('ng2-translate');
if (attr) {
collection = collection.add(attr);
} else {
$element
.contents()
.toArray()
.filter(node => node.type === 'text')
.map(node => node.nodeValue.trim())
.filter(text => text.length > 0)
.forEach(text => collection = collection.add(text));
}
});
const nodes: TmplAstNode[] = this.parseTemplate(template, path);
this.getTranslatableElements(nodes).forEach(element => {
const translateAttr = this.getTranslateAttribute(element);
const key = translateAttr.value || this.getContents(element);
collection = collection.add(key);
});
return collection;
}
protected prepareTemplate(template: string): string {
return this.wrapTemplate(
this.normalizeTemplateAttributes(template)
);
protected getTranslatableElements(nodes: TmplAstNode[]): TmplAstElement[] {
return nodes
.filter(element => this.isElement(element))
.reduce((result: TmplAstElement[], element: TmplAstElement) => {
return result.concat(this.findChildrenElements(element));
}, [])
.filter(element => this.hasTranslateAttribute(element));
}
/**
* Angular's `[attr]="'val'"` syntax is not valid HTML,
* so it can't be parsed by standard HTML parsers.
* This method replaces `[attr]="'val'""` with `attr="val"`
*/
protected normalizeTemplateAttributes(template: string): string {
return template.replace(/\[([^\]]+)\]="'([^']*)'"/g, '$1="$2"');
protected findChildrenElements(node: TmplAstNode): TmplAstElement[] {
// Safe guard, since only elements have children
if (!this.isElement(node)) {
return [];
}
// If element has translate attribute it means all of its contents
// is translatable, so we don't need to go any deeper
if (this.hasTranslateAttribute(node)) {
return [node];
}
return node.children.reduce((result: TmplAstElement[], childNode: TmplAstNode) => {
if (this.isElement(childNode)) {
const children = this.findChildrenElements(childNode);
return result.concat(children);
}
return result;
}, [node]);
}
/**
* Wraps template in tag
*/
protected wrapTemplate(template: string, tag: string = 'div'): string {
return `<${tag}>${template}</${tag}>`;
protected parseTemplate(template: string, path: string): TmplAstNode[] {
return parseTemplate(template, path).nodes;
}
protected isElement(node: any): node is TmplAstElement {
return node
&& node.attributes !== undefined
&& node.children !== undefined;
}
protected getContents(element: TmplAstElement): string {
const start = element.startSourceSpan.end.offset;
const end = element.endSourceSpan.start.offset;
return element.sourceSpan.start.file.content.substring(start, end).trim();
}
protected hasTranslateAttribute(element: TmplAstElement): boolean {
return !!this.getTranslateAttribute(element);
}
protected getTranslateAttribute(element: TmplAstElement): TmplAstTextAttribute {
return element.attributes.find(attribute => attribute.name === 'translate');
}
}