import * as t from "@babel/types";
import {
escapeStringForTemplate,
getConfig,
getNumberedId,
getRendererConfig,
getSetupStatement,
isLockedDOMProperty,
isStatementVariableInitializer,
isStatefulDOMProperty,
registerImportMethod,
wrapForEffect
} from "../shared/utils";
import { setAttr } from "./element";
import { namesBindings } from "../config";
import { bindingOptions } from "../shared/location";
import type { NodePath } from "@babel/traverse";
import type { DynamicBinding, ProgramScopeData, TemplateRecord, TransformResult } from "../types";
export function createTemplate(
path: NodePath,
result: TransformResult,
wrap: boolean
): t.Expression {
const config = getConfig(path);
if (result.id) {
// Claim targets with dynamic bindings are claimed at the tail of the
// binding effect's first run, under the owner the template is created
// with: the effect's callback runs ownerless when a held mount lands, so
// the owner is captured here, at creation, and handed to the claim.
let ownerId: t.Identifier | undefined;
if (result.claims?.length) {
ownerId = path.scope.generateUidIdentifier("o$");
result.declarations.push(
t.variableDeclarator(
ownerId,
t.callExpression(
registerImportMethod(path, "getOwner", getRendererConfig(path, "dom").moduleName),
[]
)
)
);
}
registerTemplate(path, result);
const decl = result.decl!;
const dynamicsStmt = wrapDynamics(path, result.dynamics, result.claims, ownerId);
pruneUnusedWalks(decl, [
...result.exprs,
...(dynamicsStmt ? [dynamicsStmt] : []),
...(result.postExprs || [])
]);
if (
!(result.exprs.length || dynamicsStmt || result.postExprs?.length) &&
decl.declarations.length === 1
) {
return decl.declarations[0].init as t.Expression;
} else {
const stmts = [
decl,
...result.exprs,
...(dynamicsStmt ? [dynamicsStmt] : []),
...(result.postExprs || [])
];
// In statement position (`return ;`, `const x = ;`),
// emit flat statements before the parent instead of wrapping in an
// IIFE — saves one closure allocation + one function-call frame
// per render. The DOM emission interleaves variable declarations
// with side-effecting statements (insert / effect / postExprs), so
// each `var` stays in place; `var` is function-scoped + hoisted,
// so the bindings remain visible throughout the surrounding
// function.
const isReturnArg = t.isReturnStatement(path.parent) && path.parent.argument === path.node;
const isVarInit = isStatementVariableInitializer(path);
if (isReturnArg || isVarInit) {
getSetupStatement(path)?.insertBefore(stmts as t.Statement[]);
return result.id;
}
// Fallback: JSX is in a ternary branch / array element / function arg
// / logical expression — keep the IIFE. Flattening to a sequence
// expression here is doable but harder to read for the DOM shape
// (mixed variable declarations + side-effecting expression statements
// would need to be linearized into commas), and the perf delta in
// these rarer positions is negligible.
return t.callExpression(
t.arrowFunctionExpression(
[],
t.blockStatement([...(stmts as t.Statement[]), t.returnStatement(result.id)])
),
[]
);
}
}
if (wrap && result.dynamic && config.memoWrapper) {
return t.callExpression(registerImportMethod(path, config.memoWrapper, undefined), [
result.exprs[0] as t.Expression
]);
}
return result.exprs[0] as t.Expression;
}
/** Drops `_el$N = _el$M.firstChild` / `.nextSibling` walks whose node is never
* read. Positional ids are handed out before it is known whether a child's
* insert needs a marker, so a text node ahead of an appended expression keeps
* a walk nothing reads. A minifier keeps the property read (it could be a
* getter), so it would ship as `_el$M.firstChild;`.
*
* Runs from the last declarator back, so a walk that only feeds a dropped walk
* is dropped too. Other declarators always stay. */
function pruneUnusedWalks(decl: t.VariableDeclaration, after: t.Node[]) {
const read = new Set();
const collect = (node: t.Node) =>
t.traverseFast(node, n => {
if (t.isIdentifier(n)) read.add(n.name);
});
// Names read by the statements that run after the walks
for (const node of after) collect(node);
// Keep a walk only when something kept after it reads its node
const kept: t.VariableDeclarator[] = [];
for (let i = decl.declarations.length - 1; i >= 0; i--) {
const declarator = decl.declarations[i];
const init = declarator.init;
const isWalk =
t.isIdentifier(declarator.id) &&
t.isMemberExpression(init) &&
!init.computed &&
t.isIdentifier(init.object) &&
t.isIdentifier(init.property) &&
(init.property.name === "firstChild" || init.property.name === "nextSibling");
if (isWalk && !read.has((declarator.id as t.Identifier).name)) continue;
collect(declarator);
kept.push(declarator);
}
decl.declarations = kept.reverse();
}
export function appendTemplates(path: NodePath, templates: TemplateRecord[]) {
const declarators = templates.map(template => {
const templateText = template.template as string;
const tmpl = {
cooked: templateText,
raw: escapeStringForTemplate(templateText)
};
const flag = template.isWrapped ? 2 : template.isImportNode ? 1 : null;
return t.variableDeclarator(
template.id,
t.addComment(
t.callExpression(
registerImportMethod(path, "template", getRendererConfig(path, "dom").moduleName),
[
t.templateLiteral([t.templateElement(tmpl, true)], []),
...(flag ? [t.numericLiteral(flag)] : [])
]
),
"leading",
"#__PURE__"
)
);
});
path.node.body.unshift(t.variableDeclaration("var", declarators));
}
function registerTemplate(path: NodePath, results: TransformResult) {
const { hydratable } = getConfig(path);
let decl;
if (typeof results.template === "string" && results.template.length) {
let templateDef, templateId;
if (!results.skipTemplate) {
const data = path.scope.getProgramParent().data as ProgramScopeData;
const templates = data.templates || (data.templates = []);
if ((templateDef = templates.find(t => t.template === results.template))) {
templateId = templateDef.id;
} else {
templateId = path.scope.generateUidIdentifier("tmpl$");
templates.push({
id: templateId,
template: results.template as string,
templateWithClosingTags: results.templateWithClosingTags as string,
isImportNode: results.isImportNode,
isWrapped: results.isWrapped,
renderer: "dom",
// templates dedupe on markup, so the FIRST site carries the blame
// for a validate failure (#3099) — good enough: every site with
// this markup has the same problem
node: path.node
});
}
}
const id = results.id!;
decl = t.variableDeclarator(
id,
hydratable
? t.callExpression(
registerImportMethod(path, "getNextElement", getRendererConfig(path, "dom").moduleName),
templateId ? [templateId] : []
)
: t.callExpression(templateId!, [])
);
}
if (decl) results.declarations.unshift(decl);
results.decl = t.variableDeclaration("var", results.declarations as t.VariableDeclarator[]);
}
/** A non-inline object-valued `style` / `class` binding is read in the TRACKED
* half of its effect through `readShallow()`: `style()`/`className()` enumerate
* their object in the untracked commit phase, so a proxy value (a store
* sub-object, merged props) would be identity-reactive only. Skipped when the
* expression is provably a string or a fresh literal (`readShallow` would pass
* those through anyway; the call is what's saved). */
function wrapReadShallow(path: NodePath, key: string, value: t.Expression): t.Expression {
if (key !== "class" && key !== "style") return value;
if (
t.isStringLiteral(value) ||
t.isTemplateLiteral(value) ||
t.isBinaryExpression(value) ||
t.isObjectExpression(value) ||
// a class array of literals cannot hold a proxy either
(t.isArrayExpression(value) &&
value.elements.every(
e => t.isStringLiteral(e) || t.isTemplateLiteral(e) || t.isObjectExpression(e)
))
)
return value;
return t.callExpression(
registerImportMethod(path, "readShallow", getRendererConfig(path, "dom").moduleName),
[value]
);
}
function wrapDynamics(
path: NodePath,
dynamics: DynamicBinding[],
claims: t.Identifier[] = [],
ownerId?: t.Identifier
) {
if (!dynamics.length) return;
const config = getConfig(path);
// dynamics are only queued when effectWrapper is configured (element.ts
// guards every push), so the name is always a string here
const effectWrapperId = registerImportMethod(path, config.effectWrapper as string, undefined);
// The claim contract's mount claims for this root's claim targets with
// dynamic bindings (element.ts): the tail of the effect body, so the first
// run claims after it applied the initial attributes; `claimElement` is
// once-per-element, so reruns cost one check. `ownerId` is the owner
// captured at creation (createTemplate) the handlers run under.
const claimStatements = claims.map(id =>
t.expressionStatement(
t.callExpression(
registerImportMethod(path, "claimElement", getRendererConfig(path, "dom").moduleName),
[id, ownerId!]
)
)
);
// `sourceNames.bindings`: the effect is named by what it writes — each
// binding's `.` as written (undoing the `prop:` the locked
// DOM property pre-pass added to `value`, `checked`, …), the merged effect
// listing all of its bindings — as a trailing `{ name }` options argument.
// `sourceNames.locations` adds `loc` after it: the first binding's
// attribute start (a merged effect points at the first attribute it lists).
const label = namesBindings(config)
? [
bindingOptions(
dynamics
.map(
d =>
`${d.tagName}.${isLockedDOMProperty(d.tagName, d.key) ? d.key.replace(/^prop:/, "") : d.key}`
)
.join(", "),
dynamics.find(d => d.loc !== undefined)?.loc
)
]
: [];
if (dynamics.length === 1) {
const prevValue =
dynamics[0].key === "class" || dynamics[0].key === "style" ? t.identifier("_$p") : undefined;
if (
dynamics[0].classProperty &&
!t.isBooleanLiteral(dynamics[0].value) &&
!t.isUnaryExpression(dynamics[0].value)
) {
dynamics[0].value = t.unaryExpression("!", t.unaryExpression("!", dynamics[0].value));
}
const newValue = t.identifier("_v$");
return t.expressionStatement(
t.callExpression(effectWrapperId, [
wrapForEffect(wrapReadShallow(path, dynamics[0].key, dynamics[0].value)),
t.arrowFunctionExpression(
prevValue ? [newValue, prevValue] : [newValue],
t.blockStatement([
t.expressionStatement(
setAttr(path, dynamics[0].elem, dynamics[0].key, newValue, {
tagName: dynamics[0].tagName,
checkableInput: dynamics[0].checkableInput,
dynamic: true,
prevId: prevValue,
styleProperty: dynamics[0].styleProperty,
classProperty: dynamics[0].classProperty
})
),
...claimStatements
])
),
...label
])
);
}
const prevId = t.identifier("_p$");
const values: t.ObjectProperty[] = [];
const statements: t.ExpressionStatement[] = [];
const properties: t.Identifier[] = [];
let heldId: t.Identifier | undefined;
dynamics.forEach((binding, index) => {
const { elem, key, tagName, styleProperty, classProperty, checkableInput } = binding;
let value = binding.value;
const propIdent = t.identifier(getNumberedId(index));
const propMember = t.memberExpression(prevId, propIdent);
const optionalPropMember = t.optionalMemberExpression(prevId, propIdent, false, true);
if (classProperty && !t.isBooleanLiteral(value) && !t.isUnaryExpression(value)) {
value = t.unaryExpression("!", t.unaryExpression("!", value));
}
properties.push(propIdent);
values.push(t.objectProperty(propIdent, wrapReadShallow(path, key, value)));
if (isStatefulDOMProperty(tagName, key)) {
// #4872: a stateful prop is written on every run (#2016, #4186) but
// one: an unchanged value while the effect is a stale reader of an
// open hold (`heldRead`, read after every value). A sibling's re-run
// would put the held write's committed value back over the field; the
// hold's landing re-runs the effect and writes the bound value.
heldId ||= t.identifier(getNumberedId(dynamics.length));
statements.push(
t.expressionStatement(
t.logicalExpression(
"&&",
t.logicalExpression(
"||",
t.binaryExpression("!==", propIdent, optionalPropMember),
t.unaryExpression("!", heldId)
),
setAttr(path, elem, key, propIdent, {
tagName,
dynamic: true,
prevId: optionalPropMember,
checkableInput
})
)
)
);
} else if (key === "class" || key === "style") {
statements.push(
t.expressionStatement(
setAttr(path, elem, key, propIdent, {
tagName,
dynamic: true,
prevId: optionalPropMember,
checkableInput
})
)
);
} else {
statements.push(
t.expressionStatement(
t.logicalExpression(
"&&",
key === "textContent"
? t.logicalExpression(
"||",
t.unaryExpression("!", prevId),
t.binaryExpression("!==", propIdent, propMember)
)
: t.binaryExpression("!==", propIdent, optionalPropMember),
setAttr(path, elem, key, propIdent, {
tagName,
dynamic: true,
styleProperty,
classProperty,
checkableInput
})
)
)
);
}
});
if (heldId) {
properties.push(heldId);
values.push(
t.objectProperty(
heldId,
t.callExpression(
registerImportMethod(path, "heldRead", getRendererConfig(path, "dom").moduleName),
[]
)
)
);
}
return t.expressionStatement(
t.callExpression(effectWrapperId, [
t.arrowFunctionExpression([], t.objectExpression(values)),
t.arrowFunctionExpression(
[t.objectPattern(properties.map(id => t.objectProperty(id, id, false, true))), prevId],
t.blockStatement([...statements, ...claimStatements])
),
...label
])
);
}