From 64df0efcca238e2ebb2ba1e246e9820c01df0fbf Mon Sep 17 00:00:00 2001 From: Alex Rickabaugh Date: Thu, 22 Dec 2022 11:57:20 -0500 Subject: [PATCH] refactor(compiler): pipeline phase to lift element attributes into const arrays (#48580) This commit serializes the attributes on element-like structures in the template and converts them to constant arrays, which it lifts into the `consts` array for the entire component compilation. PR Close #48580 --- .../pipeline/src/phases/const_collection.ts | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 packages/compiler/src/template/pipeline/src/phases/const_collection.ts diff --git a/packages/compiler/src/template/pipeline/src/phases/const_collection.ts b/packages/compiler/src/template/pipeline/src/phases/const_collection.ts new file mode 100644 index 00000000000..b7430ad6564 --- /dev/null +++ b/packages/compiler/src/template/pipeline/src/phases/const_collection.ts @@ -0,0 +1,62 @@ +/** + * @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 * as core from '../../../../core'; +import * as o from '../../../../output/output_ast'; +import * as ir from '../../ir'; +import {ElementAttributes} from '../../ir/src/element'; +import {ComponentCompilation} from '../compilation'; + +/** + * Converts the semantic attributes of element-like operations (elements, templates) into constant + * array expressions, and lifts them into the overall component `consts`. + */ +export function phaseConstCollection(cpl: ComponentCompilation): void { + for (const [_, view] of cpl.views) { + for (const op of view.create) { + if (op.kind !== ir.OpKind.ElementStart && op.kind !== ir.OpKind.Element && + op.kind !== ir.OpKind.Template) { + continue; + } else if (!(op.attributes instanceof ElementAttributes)) { + continue; + } + + const attrArray = serializeAttributes(op.attributes); + if (attrArray.entries.length > 0) { + op.attributes = cpl.addConst(attrArray); + } else { + op.attributes = null; + } + } + } +} + +function serializeAttributes({attributes, bindings, classes, i18n, projectAs, styles, template}: + ElementAttributes): o.LiteralArrayExpr { + const attrArray = [...attributes]; + + if (projectAs !== null) { + attrArray.push(o.literal(core.AttributeMarker.ProjectAs), o.literal(projectAs)); + } + if (classes.length > 0) { + attrArray.push(o.literal(core.AttributeMarker.Classes), ...classes); + } + if (styles.length > 0) { + attrArray.push(o.literal(core.AttributeMarker.Styles), ...styles); + } + if (bindings.length > 0) { + attrArray.push(o.literal(core.AttributeMarker.Bindings), ...bindings); + } + if (template.length > 0) { + attrArray.push(o.literal(core.AttributeMarker.Template), ...template); + } + if (i18n.length > 0) { + attrArray.push(o.literal(core.AttributeMarker.I18n), ...i18n); + } + return o.literalArr(attrArray); +}