@unframework.dev/target-angular 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,239 @@
1
+ import { assertedSetup, narrowedWhole } from "./narrowing.js";
2
+ import { ANGULAR_IMPORTS, unreachable } from "./plan.js";
3
+ import { annotation, arrow, defaulted, parameterBinding } from "./effects.js";
4
+ import { moduleReads } from "./modules.js";
5
+ import { ImportSet, NameScope, addTypeImports, codeKind, codeNames, componentTypes, functionBodyText, functionText, js, kebabCase, pascalCase, printProgram, rewriteCode, sourceNames, typeDeclarationCode, typeNames, typeSpecifier, writtenValue } from "@unframework.dev/codegen";
6
+ /**
7
+ * A composable as the setup owner the codegen helpers read: its bindings, its setup and the
8
+ * types it declares, with no props and nothing to render.
9
+ */
10
+ function setupOwner(composable) {
11
+ return {
12
+ name: composable.name,
13
+ span: composable.span,
14
+ ...composable.typeParameters ? { typeParameters: composable.typeParameters } : {},
15
+ props: [],
16
+ types: composable.types,
17
+ bindings: composable.bindings,
18
+ setup: composable.setup,
19
+ render: {
20
+ kind: "Fragment",
21
+ children: [],
22
+ span: composable.span
23
+ }
24
+ };
25
+ }
26
+ /**
27
+ * `use-toggle.ts`: `export function useToggle(initial: boolean) { …; return { on:
28
+ * on.asReadonly(), toggle }; }`, its setup in source order, its parameters as written.
29
+ */
30
+ function emitComposable(composable, context) {
31
+ const { module } = context;
32
+ const owner = assertedSetup(setupOwner(composable));
33
+ const source = sourceNames(owner, module);
34
+ const imports = new ImportSet(new NameScope([...source]));
35
+ const core = (name) => imports.add("@angular/core", name);
36
+ const kinds = new Map(owner.bindings.map((binding) => [binding.id, binding.kind]));
37
+ const head = [];
38
+ let nextTick;
39
+ let browser;
40
+ const taken = [
41
+ ...source,
42
+ ...ANGULAR_IMPORTS,
43
+ "Object"
44
+ ];
45
+ const scope = new NameScope(taken);
46
+ const locals = { claim: (name) => {
47
+ const local = scope.claim(name);
48
+ taken.push(local);
49
+ return local;
50
+ } };
51
+ const code = {
52
+ owner,
53
+ imports,
54
+ rules: {
55
+ binding: (reference, binding, written) => {
56
+ const kind = kinds.get(binding.id);
57
+ if ((kind === "state" || kind === "derived") && written.endsWith(".value")) return `${binding.name}()${narrowedWhole(reference) ? "!" : ""}`;
58
+ return binding.name;
59
+ },
60
+ write: (write, binding, parts) => kinds.get(binding.id) === "state" ? `${binding.name}.set(${writtenValue(write, parts)})` : void 0,
61
+ api: () => {
62
+ if (nextTick === void 0) {
63
+ nextTick = locals.claim("nextTick");
64
+ const appRef = locals.claim("appRef");
65
+ head.push(`const ${appRef} = ${core("inject")}(${core("ApplicationRef")});`, `async function ${nextTick}(): Promise<void> {\n await Promise.resolve();\n ${appRef}.tick();\n}`);
66
+ }
67
+ return nextTick;
68
+ }
69
+ },
70
+ locals,
71
+ taken,
72
+ browser: () => {
73
+ if (browser === void 0) {
74
+ browser = locals.claim("browser");
75
+ const check = imports.add("@angular/common", "isPlatformBrowser");
76
+ head.push(`const ${browser} = ${check}(${core("inject")}(${core("PLATFORM_ID")}));`);
77
+ }
78
+ return browser;
79
+ }
80
+ };
81
+ const statements = owner.setup.map((item) => itemCode(item, code));
82
+ const returned = composable.returns.map(({ name, binding }) => kinds.get(binding) === "state" ? `${name}: ${name}.asReadonly()` : name);
83
+ const parameters = composable.parameters.map(({ name, optional, type }) => `${name}${optional ? "?" : ""}: ${type.code}`);
84
+ const typeParameters = composable.typeParameters?.length ? `<${composable.typeParameters.map(({ name, constraint, default: fallback }) => `${name}${constraint ? ` extends ${constraint.code}` : ""}${fallback ? ` = ${fallback.code}` : ""}`).join(", ")}>` : "";
85
+ const body = [
86
+ ...head,
87
+ ...statements,
88
+ `return { ${returned.join(", ")} };`
89
+ ].join("\n\n");
90
+ const reads = moduleReads(owner.bindings, module, imports, kebabCase);
91
+ addTypeImports(owner, module, imports, kebabCase);
92
+ addParameterTypeImports(composable, imports, module);
93
+ const declared = componentTypes(owner, module);
94
+ const names = new Set(declared.map(({ name }) => name));
95
+ const types = [...declared, ...reads.types.filter(({ name }) => !names.has(name))].toSorted((a, b) => a.span.start - b.span.start);
96
+ const contents = [
97
+ printProgram(js.program(imports.toDeclarations())).trim(),
98
+ ...types.map(typeDeclarationCode),
99
+ ...reads.constants.length ? [reads.constants.join("\n")] : [],
100
+ `export function ${composable.name}${typeParameters}(${parameters.join(", ")}) {\n${body}\n}`
101
+ ].filter(Boolean).join("\n\n");
102
+ return [{
103
+ path: `${kebabCase(composable.name)}.ts`,
104
+ contents: `${contents}\n`
105
+ }];
106
+ }
107
+ /** The types its parameters and type parameters name, imported as the source imports them. */
108
+ function addParameterTypeImports(composable, imports, module) {
109
+ const texts = [...composable.parameters.map(({ type }) => type), ...(composable.typeParameters ?? []).flatMap(({ constraint, default: fallback }) => [constraint, fallback].filter((type) => type !== void 0))];
110
+ const read = new Set(texts.flatMap((type) => [...typeNames(type)]));
111
+ for (const entry of module.typeImports ?? []) for (const name of entry.names) {
112
+ if (!read.has(name.local)) continue;
113
+ imports.add(typeSpecifier(entry.specifier, module, kebabCase), name.imported, {
114
+ type: true,
115
+ local: name.local,
116
+ exact: true
117
+ });
118
+ }
119
+ }
120
+ /** A setup item's statement. */
121
+ function itemCode(item, context) {
122
+ const { owner, rules, imports } = context;
123
+ const core = (name) => imports.add("@angular/core", name);
124
+ const name = (id) => bindingOf(owner, id).name;
125
+ const pure = (code) => rewriteCode(code, owner, rules, "pure");
126
+ switch (item.kind) {
127
+ case "State": {
128
+ const type = item.type ? `<${item.initial ? item.type.code : `${item.type.code} | undefined`}>` : "";
129
+ return `const ${name(item.binding)} = ${core("signal")}${type}(${item.initial ? pure(item.initial) : "undefined"});`;
130
+ }
131
+ case "Derived": {
132
+ const type = item.type ? `<${item.type.code}>` : "";
133
+ return `const ${name(item.binding)} = ${core("computed")}${type}(${functionText(item.getter, owner, rules, "pure")});`;
134
+ }
135
+ case "Const": return `const ${name(item.binding)}${item.type ? `: ${item.type.code}` : ""} = ${pure(item.value)};`;
136
+ case "Variable": return `let ${name(item.binding)}${item.type ? `: ${item.type.code}` : ""}${item.initial ? ` = ${pure(item.initial)}` : ""};`;
137
+ case "Function": return functionText(item.function, owner, rules, "client", { name: name(item.binding) });
138
+ case "Watch": return watcherCode(item, context);
139
+ case "WatchEffect": {
140
+ const [cleanup] = item.effect.parameters;
141
+ const statements = hookBody(item.effect, context);
142
+ const body = item.effect.async ? `void (async () => {\n${statements}\n})();` : statements;
143
+ return `${core("afterRenderEffect")}((${cleanup?.name ?? ""}) => {\n${body}\n});`;
144
+ }
145
+ case "Lifecycle": {
146
+ const body = hookBody(item.callback, context);
147
+ switch (item.hook) {
148
+ case "mounted": return `${core("afterNextRender")}(${item.callback.async ? "async " : ""}() => {\n${body}\n});`;
149
+ case "unmounted": return `if (${context.browser()}) {\n${core("inject")}(${core("DestroyRef")}).onDestroy(${item.callback.async ? "async " : ""}() => {\n${body}\n});\n}`;
150
+ default: return unreachable(item.hook);
151
+ }
152
+ }
153
+ case "TemplateRef":
154
+ case "Id":
155
+ case "Model":
156
+ case "Provide":
157
+ case "Inject":
158
+ case "Use": throw new Error(`A composable holds a \`${item.kind}\` item, which the analyser rejects.`);
159
+ default: return unreachable(item);
160
+ }
161
+ }
162
+ /** A hook's or an effect's body as statements, its value dropped. */
163
+ function hookBody(fn, context) {
164
+ return functionBodyText(fn, context.owner, context.rules, "client", { discard: true });
165
+ }
166
+ /**
167
+ * `watch(source, callback)` as an `effect()` over a `computed` of the source, whose value changes
168
+ * only when it differs. Its first run records the value; an immediate watcher's runs the callback
169
+ * too, in the browser only (ADR-0048).
170
+ */
171
+ function watcherCode(item, context) {
172
+ const { owner, rules, imports, locals } = context;
173
+ const core = (name) => imports.add("@angular/core", name);
174
+ const [valueParameter, previousParameter, cleanupParameter] = item.callback.parameters;
175
+ const read = (binding) => `${binding.name}()`;
176
+ const sources = item.sources.map((source) => {
177
+ switch (source.kind) {
178
+ case "Ref": return {
179
+ hint: bindingOf(owner, source.binding).name,
180
+ value: read(bindingOf(owner, source.binding))
181
+ };
182
+ case "Getter": {
183
+ const body = rewriteCode(source.getter.body, owner, rules, "pure");
184
+ return {
185
+ hint: valueParameter?.name ?? "value",
186
+ value: source.getter.expression ? body : `(() => ${body})()`
187
+ };
188
+ }
189
+ default: return unreachable(source);
190
+ }
191
+ });
192
+ const lines = [];
193
+ const hint = item.array ? "values" : sources[0].hint;
194
+ const signal = locals.claim(`current${pascalCase(hint)}`);
195
+ if (item.array) {
196
+ const tuple = sources.map(() => "unknown").join(", ");
197
+ lines.push(`const ${signal} = ${core("computed")}(() => [${sources.map(({ value }) => value).join(", ")}] satisfies [${tuple}], { equal: (next, last) => next.every((value, index) => Object.is(value, last[index])) });`);
198
+ } else lines.push(`const ${signal} = ${core("computed")}(${arrow(sources[0].value)});`);
199
+ const reads = codeNames(item.callback.body.code, codeKind(item.callback.body, owner));
200
+ const readsPrevious = previousParameter !== void 0 && (previousParameter.name === void 0 ? (previousParameter.pattern?.names ?? []).some((each) => reads.has(each)) : reads.has(previousParameter.name));
201
+ const last = readsPrevious ? locals.claim(`last${pascalCase(hint)}`) : void 0;
202
+ const watching = !item.immediate || readsPrevious ? locals.claim("watching") : void 0;
203
+ if (last !== void 0) lines.push(`let ${last}!: ReturnType<typeof ${signal}>;`);
204
+ if (watching !== void 0) lines.push(`let ${watching} = false;`);
205
+ const value = new NameScope([...context.taken, ...callbackNames(item.callback, owner)]).claim(item.array ? "current" : "value");
206
+ const body = [valueParameter || last ? `const ${value} = ${signal}();` : `${signal}();`];
207
+ if (!item.immediate) {
208
+ const record = last === void 0 ? "" : `${last} = ${value};\n`;
209
+ body.push(`if (!${watching}) {\n${watching} = true;\n${record}return;\n}`);
210
+ }
211
+ if (valueParameter) body.push(`const ${parameterBinding(valueParameter)}${annotation(valueParameter)} = ${value};`);
212
+ if (previousParameter && readsPrevious) {
213
+ const previous = item.immediate ? item.array ? `(${watching} ? ${last} : []) as [${sources.map((_, index) => `(typeof ${last})[${index}] | undefined`).join(", ")}]` : `${watching} ? ${last} : undefined` : last;
214
+ body.push(`const ${parameterBinding(previousParameter)}${annotation(previousParameter)} = ${defaulted(previousParameter, previous)};`);
215
+ }
216
+ if (item.immediate && watching !== void 0) body.push(`${watching} = true;`);
217
+ if (last !== void 0) body.push(`${last} = ${value};`);
218
+ if (item.immediate) body.push(`if (!${context.browser()}) return;`);
219
+ const callback = item.callback.expression ? `${item.callback.async ? "async " : ""}() => ${arrowBody(rewriteCode(item.callback.body, owner, rules, "client"))}` : `${item.callback.async ? "async " : ""}() => {\n${functionBodyText(item.callback, owner, rules, "client")}\n}`;
220
+ body.push(`${core("untracked")}(${callback});`);
221
+ const effect = core(item.post ? "afterRenderEffect" : "effect");
222
+ lines.push(`${effect}((${cleanupParameter?.name ?? ""}) => {\n${body.join("\n")}\n});`);
223
+ return lines.join("\n");
224
+ }
225
+ /** An arrow's expression body, an object literal in parentheses. */
226
+ function arrowBody(code) {
227
+ return /^\s*\{/.test(code) ? `(${code})` : code;
228
+ }
229
+ /** The names a callback declares and reads, which the effect's own locals leave alone. */
230
+ function callbackNames(fn, owner) {
231
+ return [...codeNames(fn.body.code, codeKind(fn.body, owner)), ...fn.parameters.flatMap((parameter) => parameter.name === void 0 ? parameter.pattern?.names ?? [] : [parameter.name])];
232
+ }
233
+ /** The binding a composable declares under `id`. */
234
+ function bindingOf(owner, id) {
235
+ const binding = owner.bindings.find((each) => each.id === id);
236
+ if (!binding) throw new Error(`Composable ${owner.name} declares no binding ${id}.`);
237
+ return binding;
238
+ }
239
+ export { emitComposable };
@@ -0,0 +1,214 @@
1
+ import { atConstraints } from "./types.js";
2
+ import { childImports, kebabCase, keyImports, keyOwner, pascalCase } from "@unframework.dev/codegen";
3
+ import { walk } from "@unframework.dev/ir";
4
+ /** The output file a component's output is named by, without `./` (ADR-0053). */
5
+ const outputFile = (name) => kebabCase(name);
6
+ /** The selector a component is written with: `uf-` and its name in kebab case (ADR-0010). */
7
+ function selectorOf(name) {
8
+ return `uf-${kebabCase(name)}`;
9
+ }
10
+ /**
11
+ * The attribute a slot's directive selects, as `angularDialect` writes a fill: the component's
12
+ * selector in camel case and the slot's name (`ufCardTitle`).
13
+ */
14
+ function slotAttribute(name, slot) {
15
+ return `${selectorOf(name).replace(/-(\w)/g, (_, next) => next.toUpperCase())}${pascalCase(slot)}`;
16
+ }
17
+ /** Whether a slot is written through a directive: any but the default slot without props. */
18
+ function usesDirective(slot, scoped) {
19
+ return slot !== "default" || scoped;
20
+ }
21
+ /** Where the template first renders a child, by its local name: the component's span if nowhere. */
22
+ function firstUse(component, local) {
23
+ let found;
24
+ walk(component.render, { enter(node) {
25
+ if (found) return;
26
+ if ((node.kind === "Component" ? [node.component] : node.kind === "Dynamic" ? node.candidates.flatMap((each) => each.kind === "Component" ? [each.component] : []) : []).includes(local)) found = node.span;
27
+ } });
28
+ return found ?? component.span;
29
+ }
30
+ /** Plans the component's composition: its children, its slots and its keys. */
31
+ function planComposition(plan) {
32
+ const { component, module, imports } = plan;
33
+ const keys = module.keys?.length && keyOwner(module.components, module.exports) === component.name ? module.keys : [];
34
+ imports.reserve(...keys.map(({ name }) => name));
35
+ const tags = /* @__PURE__ */ new Map();
36
+ const classes = [];
37
+ const specifiers = /* @__PURE__ */ new Map();
38
+ const clashes = /* @__PURE__ */ new Map();
39
+ const selectors = /* @__PURE__ */ new Set([selectorOf(component.name)]);
40
+ for (const child of childImports(component, module, outputFile)) {
41
+ const selector = selectorOf(child.name);
42
+ if (!child.self && selectors.has(selector)) clashes.set(child.local, selector);
43
+ selectors.add(selector);
44
+ tags.set(child.local, selector);
45
+ specifiers.set(child.local, child);
46
+ if (child.self) continue;
47
+ const local = child.export === "default" ? imports.addDefault(child.specifier, child.local, { exact: true }) : imports.add(child.specifier, child.name, {
48
+ local: child.local,
49
+ exact: true
50
+ });
51
+ if (!classes.includes(local)) classes.push(local);
52
+ }
53
+ const keyNames = /* @__PURE__ */ new Map();
54
+ for (const key of keyImports(component, module, outputFile)) keyNames.set(key.local, key.specifier ? imports.add(key.specifier, key.name, {
55
+ local: key.local,
56
+ exact: true
57
+ }) : key.local);
58
+ const slots = (component.slots?.slots ?? []).filter((slot) => usesDirective(slot.name, slot.props !== void 0)).map((slot) => {
59
+ const exported = `${component.name}${pascalCase(slot.name)}`;
60
+ return {
61
+ slot,
62
+ className: imports.claim(exported),
63
+ exported,
64
+ attribute: slotAttribute(component.name, slot.name)
65
+ };
66
+ });
67
+ for (const directive of slots) if (directive.slot.props) directive.context = imports.claim(`${directive.exported}Context`);
68
+ const attributes = /* @__PURE__ */ new Map();
69
+ const slotClashes = [];
70
+ let outlet = false;
71
+ const fillDirectives = (local, fills) => {
72
+ const child = specifiers.get(local);
73
+ for (const fill of fills) {
74
+ if (fill.forward !== void 0 && fill.slot !== "default") outlet = true;
75
+ if (!usesDirective(fill.slot, fill.parameter !== void 0)) continue;
76
+ const name = `${child.name}${pascalCase(fill.slot)}`;
77
+ const attribute = slotAttribute(child.name, fill.slot);
78
+ const filled = `\`<${child.name}>\`'s \`${fill.slot}\` slot`;
79
+ const other = attributes.get(attribute) ?? filled;
80
+ attributes.set(attribute, other);
81
+ if (other !== filled) slotClashes.push({
82
+ fill,
83
+ child: filled,
84
+ attribute,
85
+ other
86
+ });
87
+ const directive = child.self ? slots.find((slot) => slot.slot.name === fill.slot).className : imports.add(child.specifier, name);
88
+ if (!classes.includes(directive)) classes.push(directive);
89
+ }
90
+ };
91
+ walk(component.render, { enter(node) {
92
+ if (node.kind === "Component") fillDirectives(node.component, node.fills);
93
+ if (node.kind === "Dynamic") {
94
+ for (const candidate of node.candidates) if (candidate.kind === "Component") fillDirectives(candidate.component, node.fills ?? []);
95
+ }
96
+ if (node.kind === "SlotOutlet" && usesDirective(node.slot, node.props !== void 0)) outlet = true;
97
+ } });
98
+ if (outlet) classes.push(imports.add("@angular/common", "NgTemplateOutlet"));
99
+ return {
100
+ tags,
101
+ imports: classes,
102
+ slots,
103
+ outlet,
104
+ keys,
105
+ keyNames,
106
+ clashes,
107
+ slotClashes
108
+ };
109
+ }
110
+ /**
111
+ * A key's declaration or its API, by the local name a component's setup gives it: the module's
112
+ * own, or the one an import names.
113
+ */
114
+ function keyOf(plan, local) {
115
+ const { module } = plan;
116
+ const own = module.keys?.find((key) => key.name === local);
117
+ if (own) return own;
118
+ for (const entry of module.imports ?? []) {
119
+ const name = entry.names.find((each) => each.kind === "Key" && each.local === local);
120
+ const key = name && entry.api.keys.find((each) => each.name === name.imported);
121
+ if (key) return key;
122
+ }
123
+ throw new Error(`No injection key is named ${local}.`);
124
+ }
125
+ /**
126
+ * The type an injection token holds: the key's, or for a key of a ref (`Ref<number>`) an object
127
+ * with a `value` getter of the ref's type, which `refObject` makes (ADR-0054).
128
+ */
129
+ function tokenType(key) {
130
+ const type = typeof key.type === "string" ? key.type : key.type.code;
131
+ if (!key.ref) return type;
132
+ return `{ readonly value: ${type.slice(type.indexOf("<") + 1, type.lastIndexOf(">")).trim()} }`;
133
+ }
134
+ /**
135
+ * The event a child declares under a name: from its module's API, or from the module's own
136
+ * component, as `ApiEvent`.
137
+ */
138
+ function childEvent(plan, local, event) {
139
+ const { module } = plan;
140
+ for (const entry of module.imports ?? []) {
141
+ const imported = entry.names.find((name) => name.kind === "Component" && name.local === local);
142
+ if (!imported) continue;
143
+ const found = entry.api.components.find((each) => imported.imported === "default" ? each.export === "default" : each.export === "named" && each.name === imported.imported)?.events.find((each) => each.name === event);
144
+ if (found) return found;
145
+ }
146
+ const declared = module.components.find((each) => each.name === local)?.emits?.events.find((each) => each.name === event);
147
+ if (!declared) throw new Error(`${local} declares no event ${event}.`);
148
+ return {
149
+ name: declared.name,
150
+ parameters: declared.parameters.map((parameter) => ({
151
+ name: parameter.name,
152
+ type: parameter.type.code,
153
+ ...parameter.optional ? { optional: true } : {}
154
+ }))
155
+ };
156
+ }
157
+ /**
158
+ * A slot directive's code (ADR-0056): the selector its consumers' `<ng-template>` names and, for
159
+ * a scoped slot, the context guard that types their `let-` variables as the slot's props, by
160
+ * name and whole (`$implicit`). A directive cannot infer its component's type parameters, so
161
+ * the props read each one as its constraint (`generic-slot-props`, UF4004, ADR-0068).
162
+ */
163
+ function slotDirectiveCode(component, directive, decorator, typeParameters = []) {
164
+ const { slot, className, exported, attribute, context } = directive;
165
+ const selector = `@${decorator}({ selector: "ng-template[${attribute}]" })`;
166
+ const type = context ? `${context} & { $implicit: ${context} }` : "Record<never, never>";
167
+ return [
168
+ ...context ? [
169
+ `/** What a template of \`${component}\`'s \`${slot.name}\` slot reads: the slot's props. */`,
170
+ `export type ${context} = ${atConstraints(`${slot.props.code}${aliases(slot.props.code)}`, typeParameters)};`,
171
+ ""
172
+ ] : [],
173
+ `/** A template of \`${component}\`'s \`${slot.name}\` slot, ${context ? "its `let-` variables typed" : "which takes no `let-` variable"} (ADR-0056). */`,
174
+ selector,
175
+ `${className === exported ? "export " : ""}class ${className} {`,
176
+ ` static ngTemplateContextGuard(`,
177
+ ` _directive: ${className},`,
178
+ ` _context: unknown,`,
179
+ ` ): _context is ${type} {`,
180
+ ` return true;`,
181
+ ` }`,
182
+ `}`,
183
+ ...className === exported ? [] : ["", `export { ${className} as ${exported} };`],
184
+ ""
185
+ ].join("\n");
186
+ }
187
+ /** `refObject`'s code: a ref's value through a getter, as a descendant reads a provided ref. */
188
+ function refObjectCode(name) {
189
+ return `/** A ref as a descendant injects it (ADR-0054): its value through a getter, read as it changes. */
190
+ function ${name}<T>(ref: () => T): { readonly value: T } {
191
+ return {
192
+ get value() {
193
+ return ref();
194
+ },
195
+ };
196
+ }
197
+ `;
198
+ }
199
+ /**
200
+ * The context's names for the slot's props whose names no template variable can read
201
+ * (`"data-id"`, which a `let-` value would read as `data - id`): each in camel case, of the
202
+ * prop's type (` & { dataId: string }`), as `angularDialect` writes the outlet's context and
203
+ * the fill's `let-` values.
204
+ */
205
+ function aliases(props) {
206
+ const found = [...props.matchAll(/["']([^"']+)["']\??\s*:\s*([^;,}]+)/g)].filter(([, key]) => !/^[A-Za-z_$][\w$]*$/.test(key));
207
+ if (!found.length) return "";
208
+ return ` & { ${found.map(([, key, type]) => `${contextAlias(key)}: ${type.trim()}`).join("; ")} }`;
209
+ }
210
+ /** A prop's name as a context key a template variable can read: `data-id` → `dataId`. */
211
+ function contextAlias(key) {
212
+ return key.replace(/[^A-Za-z0-9_$]+(.)?/g, (_, next) => next?.toUpperCase() ?? "").replace(/^(?=\d)/, "_");
213
+ }
214
+ export { childEvent, firstUse, keyOf, outputFile, planComposition, refObjectCode, selectorOf, slotDirectiveCode, tokenType, usesDirective };
@@ -0,0 +1,82 @@
1
+ import { exportDeclaration, js, printExpression } from "@unframework.dev/codegen";
2
+ /**
3
+ * A directive's declaration, its decorator apart (printed before the class, see ./index.ts):
4
+ *
5
+ * ```ts
6
+ * @Directive({ selector: "[ufClickCapture]" })
7
+ * class ClickCapture {
8
+ * readonly ufClickCapture = output<PointerEvent>();
9
+ *
10
+ * constructor() {
11
+ * const element: HTMLElement = inject(ElementRef).nativeElement;
12
+ * const stop = inject(Renderer2).listen(element, "click", (event: PointerEvent) => this.ufClickCapture.emit(event), { capture: true });
13
+ * inject(DestroyRef).onDestroy(stop);
14
+ * }
15
+ * }
16
+ * ```
17
+ */
18
+ function directiveCode(spec, imports, placeholders) {
19
+ const core = (name) => imports.add("@angular/core", name);
20
+ const decorator = `@${printExpression(js.callExpression(js.identifier(core("Directive")), [js.objectExpression([["selector", js.stringLiteral(`[${spec.output}]`)]])]))}`;
21
+ const output = js.propertyDefinition(spec.output, js.callExpression(js.identifier(core("output")), [], [placeholders.type(spec.eventType)]), { readonly: true });
22
+ const body = [
23
+ `const element: HTMLElement = ${core("inject")}(${core("ElementRef")}).nativeElement;`,
24
+ `const stop = ${core("inject")}(${core("Renderer2")}).listen(element, ${JSON.stringify(spec.event)}, (event: ${spec.eventType}) => this.${spec.output}.emit(event), { ${spec.option}: true });`,
25
+ `${core("inject")}(${core("DestroyRef")}).onDestroy(stop);`
26
+ ].join("\n");
27
+ const constructor = js.methodDefinition("constructor", [], [placeholders.statements(body)], { kind: "constructor" });
28
+ const declaration = js.classDeclaration(spec.className, [], [output, constructor]);
29
+ return {
30
+ decorator,
31
+ statements: exportDeclaration(spec.className, declaration, [{
32
+ kind: "named",
33
+ name: spec.className,
34
+ local: spec.className,
35
+ span: {
36
+ start: 0,
37
+ end: 0
38
+ }
39
+ }])
40
+ };
41
+ }
42
+ /**
43
+ * `child-root-scope` (ADR-0063): the directive each of a component's root nodes binds to the
44
+ * component's host, `<button [ufScope]="this.host">`. A styled parent writes its scope attribute
45
+ * on the child's tag, which is the host here; the attribute's name is the parent's id, which the
46
+ * child cannot know, so the directive reads the host's `data-uf-*` attributes as its root renders,
47
+ * after the parent's own root directive has set them, and takes them off the host, which then
48
+ * keeps only `display: contents` and is unwrapped (ADR-0056). A root that renders later (another
49
+ * branch) reads them from the module's map.
50
+ */
51
+ function scopeDirectiveCode(names, imports) {
52
+ const core = (name, type = false) => imports.add("@angular/core", name, { type });
53
+ const { className, scopes } = names;
54
+ return [
55
+ "/** The scope attributes taken off each host, for the roots its component renders later. */",
56
+ `const ${scopes} = new WeakMap<Element, string[]>();`,
57
+ "",
58
+ "/**",
59
+ " * Gives a root node of its component the scope attributes the component's styled parents put on",
60
+ " * its host (ADR-0063), and takes them off the host, which keeps only `display: contents`.",
61
+ " */",
62
+ `@${core("Directive")}({ selector: "[ufScope]" })`,
63
+ `export class ${className} implements ${core("OnInit", true)} {`,
64
+ ` readonly ufScope = ${core("input")}.required<HTMLElement>();`,
65
+ ` private readonly element = ${core("inject")}<${core("ElementRef")}<Element>>(${core("ElementRef")});`,
66
+ ` private readonly renderer = ${core("inject")}(${core("Renderer2")});`,
67
+ "",
68
+ " ngOnInit(): void {",
69
+ " const host = this.ufScope();",
70
+ ` let names = ${scopes}.get(host);`,
71
+ " if (!names) {",
72
+ " names = host.getAttributeNames().filter((name) => name.startsWith(\"data-uf-\"));",
73
+ " for (const name of names) this.renderer.removeAttribute(host, name);",
74
+ ` ${scopes}.set(host, names);`,
75
+ " }",
76
+ " for (const name of names) this.renderer.setAttribute(this.element.nativeElement, name, \"\");",
77
+ " }",
78
+ "}",
79
+ ""
80
+ ].join("\n");
81
+ }
82
+ export { directiveCode, scopeDirectiveCode };