UNPKG

@jsverse/transloco-keys-manager

Version:

Extract translatable keys from projects that uses Transloco

82 lines 2.96 kB
import { ASTWithSource, ParenthesizedExpression, } from '@angular/compiler'; import { addKey } from '../add-key.js'; import { resolveAliasAndKey } from '../utils/resolvers.utils.js'; import { isBlockNode, isBoundAttribute, isElement, isInterpolation, isSupportedNode, isTemplate, isTextAttribute, parseTemplate, resolveBlockChildNodes, resolveKeysFromLiteralMap, } from './utils.js'; import { coerceArray } from '../../utils/collection.utils.js'; import { isConditionalExpression, isLiteralExpression, isLiteralMap } from '@jsverse/angular-utils'; export function directiveExtractor(config) { const ast = parseTemplate(config); traverse(ast.nodes, config); } function traverse(nodes, config) { for (const node of nodes) { if (isBlockNode(node)) { traverse(resolveBlockChildNodes(node), config); continue; } if (!isSupportedNode(node, [isTemplate, isElement])) { continue; } const params = node.inputs .filter(isTranslocoParams) .map((ast) => { const value = ast.value; if (value instanceof ASTWithSource && isLiteralMap(value.ast)) { return resolveKeysFromLiteralMap(value.ast); } return []; }) .flat(); const keys = [...node.inputs, ...node.attributes] .filter(isTranslocoDirective) .map((ast) => { let value = ast.value; if (value instanceof ASTWithSource) { value = value.ast; } return isInterpolation(value) ? value.expressions : value; }) .flat() .map(resolveKey) .flat(); addKeys(keys, params, config); traverse(node.children, config); } } function isTranslocoDirective(ast) { return ((isBoundAttribute(ast) || isTextAttribute(ast)) && ast.name === 'transloco'); } function isTranslocoParams(ast) { return isBoundAttribute(ast) && ast.name === 'translocoParams'; } function resolveKey(ast) { return coerceArray(ast) .map((expression) => { if (typeof expression === 'string') { return expression; } else if (isConditionalExpression(expression)) { return resolveKey([expression.trueExp, expression.falseExp]); } else if (isLiteralExpression(expression)) { return expression.value; } else if (expression instanceof ParenthesizedExpression) { return resolveKey(expression.expression); } }) .filter(Boolean) .flat(); } function addKeys(keys, params, config) { for (const rawKey of keys) { const [key, scopeAlias] = resolveAliasAndKey(rawKey, config.scopes); addKey({ ...config, keyWithoutScope: key, scopeAlias, params, }); } } //# sourceMappingURL=directive.extractor.js.map