@unframework.dev/target-angular 0.3.0 → 0.4.1

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,283 @@
1
+ import { ELEMENT_INTERFACES } from "./elements.js";
2
+ import { angularDialect, candidateAttributes } from "@unframework.dev/codegen";
3
+ import { walk } from "@unframework.dev/ir";
4
+ /** The input that takes the consumer's attributes, each by its name. */
5
+ const ATTRIBUTES_INPUT = "ufAttributes";
6
+ /** The input that takes the consumer's native listeners, each by its event's name. */
7
+ const LISTENERS_INPUT = "ufListeners";
8
+ /** The member that holds the element a ref on the component holds, where it exposes nothing. */
9
+ const ELEMENT_MEMBER = "ufElement";
10
+ /** The template ref the root carries for {@link ELEMENT_MEMBER}'s query. */
11
+ const ELEMENT_REF = "ufElement";
12
+ /** The attribute of the directive that puts the records on their element. */
13
+ const FALLTHROUGH_ATTRIBUTE = "ufFallthrough";
14
+ /**
15
+ * The names a component that takes fallthrough declares beside its own (ADR-0056, ADR-0118):
16
+ * a prop, an event or an exposed function of one of them is UF2003, and a setup binding of one
17
+ * is renamed.
18
+ */
19
+ const FALLTHROUGH_MEMBERS = [
20
+ "class",
21
+ "style",
22
+ ATTRIBUTES_INPUT,
23
+ LISTENERS_INPUT,
24
+ ELEMENT_MEMBER
25
+ ];
26
+ /**
27
+ * The component's root (an element, or a fragment of one element, one component or one
28
+ * `<component is>` over tags, ADR-0119), which what a consumer passes falls through to
29
+ * (ADR-0054, ADR-0118), or none. A `<component is>` takes only `class` and `style`, in each
30
+ * `@case`.
31
+ */
32
+ function fallthroughRoot(render) {
33
+ if (render.kind === "Element") return render;
34
+ const [only] = render.children;
35
+ if (render.children.length !== 1) return;
36
+ if (only?.kind === "Element" || only?.kind === "Component") return only;
37
+ return only?.kind === "Dynamic" && only.candidates.every((each) => each.kind === "Tag") ? only : void 0;
38
+ }
39
+ /**
40
+ * The API of the component a template renders by its local name: from its import, or from the
41
+ * module's own component, read as the analyser reads it (`fillRootComponents`).
42
+ */
43
+ function childApi(module, local, seen = /* @__PURE__ */ new Set()) {
44
+ for (const entry of module.imports ?? []) {
45
+ const imported = entry.names.find((name) => name.kind === "Component" && name.local === local);
46
+ if (!imported) continue;
47
+ const api = entry.api.components.find((each) => imported.imported === "default" ? each.export === "default" : each.export === "named" && each.name === imported.imported);
48
+ if (!api) return;
49
+ const refTag = api.refTag ?? api.refTags?.[0];
50
+ const takes = api.fallthroughTag ?? (api.inheritAttrs ? api.rootTags?.[0] : void 0);
51
+ const literal = takes === void 0 ? void 0 : api.fallthroughOwn?.attributes.find(({ name, value }) => name !== "class" && name !== "style" && typeof value === "string" && value.includes("{{"))?.name;
52
+ const fallthroughTag = literal === void 0 ? takes : void 0;
53
+ return {
54
+ exposes: api.exposes.length > 0,
55
+ ...refTag === void 0 ? {} : { refTag },
56
+ ...fallthroughTag === void 0 ? {} : { fallthroughTag },
57
+ ...literal === void 0 ? {} : { literal }
58
+ };
59
+ }
60
+ const own = module.components.find((each) => each.name === local);
61
+ if (!own || seen.has(local)) return;
62
+ const next = /* @__PURE__ */ new Set([...seen, local]);
63
+ const exposes = (own.exposes?.functions.length ?? 0) > 0;
64
+ const root = fallthroughRoot(own.render);
65
+ const rootChild = root?.kind === "Component" ? childApi(module, root.component, next) : void 0;
66
+ const rootTag = root?.kind === "Element" ? root.tag : root?.kind === "Dynamic" && root.candidates[0]?.kind === "Tag" ? root.candidates[0].tag : void 0;
67
+ const refTag = exposes ? void 0 : rootTag ?? (rootChild && !rootChild.exposes ? rootChild.refTag : void 0);
68
+ const rest = own.inheritAttrs === false ? restElement(own.render)?.element : void 0;
69
+ const takes = own.inheritAttrs === false ? rest?.tag : rootTag ?? rootChild?.fallthroughTag;
70
+ const literal = takes === void 0 ? rootChild?.literal : literalAttribute(rest ? [rest] : root?.kind === "Dynamic" ? tagElements(root) : root?.kind === "Element" ? [root] : []);
71
+ const fallthroughTag = literal === void 0 ? takes : void 0;
72
+ return {
73
+ exposes,
74
+ ...refTag === void 0 ? {} : { refTag },
75
+ ...fallthroughTag === void 0 ? {} : { fallthroughTag },
76
+ ...literal === void 0 ? {} : { literal }
77
+ };
78
+ }
79
+ /** Each tag of a `<component is>` over tags as the element its `@case` writes. */
80
+ function tagElements(root) {
81
+ return root.candidates.flatMap((candidate) => candidate.kind === "Tag" ? [{
82
+ kind: "Element",
83
+ tag: candidate.tag,
84
+ attributes: candidateAttributes(root, candidate.tag),
85
+ children: root.children,
86
+ span: root.span
87
+ }] : []);
88
+ }
89
+ /** The static attribute holding `{{` that puts one of `elements` in a literal region (ADR-0037). */
90
+ function literalAttribute(elements) {
91
+ for (const element of elements) {
92
+ if (angularDialect.literalRegion?.(element) === void 0) continue;
93
+ const found = element.attributes.find((attribute) => attribute.kind === "Static" && attribute.value !== true && attribute.value.includes("{{"));
94
+ if (found?.kind === "Static") return found.name;
95
+ }
96
+ }
97
+ /**
98
+ * How the component takes what its consumer passes (ADR-0056, ADR-0118), or `undefined` where it
99
+ * takes nothing: its root, one element or one component, unless it sets `inheritAttrs: false`,
100
+ * when the element that spreads the props' rest takes it, if one does. An element Angular binds
101
+ * nothing on (`{{` in an attribute, ADR-0037) takes nothing.
102
+ */
103
+ function planFallthrough(component, module) {
104
+ if (component.inheritAttrs === false) {
105
+ const found = restElement(component.render);
106
+ if (!found || angularDialect.literalRegion?.(found.element) !== void 0) return;
107
+ return {
108
+ target: found.element,
109
+ rest: true,
110
+ passes: true,
111
+ events: found.svg ? "SVGElementEventMap" : "HTMLElementEventMap"
112
+ };
113
+ }
114
+ const root = fallthroughRoot(component.render);
115
+ if (!root) return;
116
+ if (root.kind === "Element") {
117
+ if (angularDialect.literalRegion?.(root) !== void 0) return;
118
+ return {
119
+ target: root,
120
+ rest: false,
121
+ passes: true,
122
+ events: eventsOf(root.tag)
123
+ };
124
+ }
125
+ if (root.kind === "Dynamic") {
126
+ if (!root.candidates.every((candidate) => candidate.kind === "Tag" && angularDialect.literalRegion?.({
127
+ kind: "Element",
128
+ tag: candidate.tag,
129
+ attributes: candidateAttributes(root, candidate.tag),
130
+ children: root.children,
131
+ span: root.span
132
+ }) === void 0)) return;
133
+ return {
134
+ target: root,
135
+ rest: false,
136
+ passes: true,
137
+ events: "HTMLElementEventMap"
138
+ };
139
+ }
140
+ const tag = childApi(module, root.component)?.fallthroughTag;
141
+ return {
142
+ target: root,
143
+ rest: false,
144
+ passes: tag !== void 0,
145
+ events: eventsOf(tag)
146
+ };
147
+ }
148
+ /** The event map of the element a tag names. */
149
+ function eventsOf(tag) {
150
+ return tag === "svg" ? "SVGElementEventMap" : "HTMLElementEventMap";
151
+ }
152
+ /**
153
+ * The element a ref on the component holds (ADR-0118), where it exposes nothing: its root
154
+ * element, or its root component's own, which that component declares. `undefined` where a ref
155
+ * holds no element.
156
+ */
157
+ function planRootElement(component, module) {
158
+ if (component.exposes?.functions.length) return;
159
+ const root = fallthroughRoot(component.render);
160
+ if (!root) return;
161
+ if (root.kind === "Dynamic") {
162
+ const types = root.candidates.map((candidate) => candidate.kind === "Tag" ? ELEMENT_INTERFACES.get(candidate.tag) : void 0);
163
+ if (types.some((type) => type === void 0)) return;
164
+ return {
165
+ root,
166
+ type: [...new Set(types)].join(" | ")
167
+ };
168
+ }
169
+ if (root.kind === "Element") {
170
+ const type = ELEMENT_INTERFACES.get(root.tag);
171
+ if (type === void 0 || angularDialect.literalRegion?.(root) !== void 0) return;
172
+ return {
173
+ root,
174
+ type
175
+ };
176
+ }
177
+ const child = childApi(module, root.component, /* @__PURE__ */ new Set([component.name]));
178
+ return child && !child.exposes && child.refTag !== void 0 ? { root } : void 0;
179
+ }
180
+ /** The element that spreads the props' rest, which the analyser allows on one element. */
181
+ function restElement(render) {
182
+ let found;
183
+ const svg = [];
184
+ walk(render, {
185
+ enter(node) {
186
+ if (found || node.kind !== "Element") return;
187
+ svg.push(node.tag === "svg" || svg.at(-1) === true);
188
+ if (node.attributes.some((attribute) => attribute.kind === "Rest")) found = {
189
+ element: node,
190
+ svg: svg.at(-1)
191
+ };
192
+ },
193
+ leave(node) {
194
+ if (node.kind === "Element") svg.pop();
195
+ }
196
+ });
197
+ return found;
198
+ }
199
+ /**
200
+ * The directive that puts what a consumer passes on the element that takes it (ADR-0118), and
201
+ * the type of the listeners' record. Angular has no attribute spread, so it emulates Vue's
202
+ * `$attrs`: as the record changes it sets each attribute through `Renderer2`, removes one that
203
+ * is `null` or `undefined` as `[attr.name]` does, and so overrides the element's own attribute
204
+ * of the name, the consumer's winning, on the server and in the browser. It writes only as the
205
+ * record changes, so an attribute the element binds itself binds the consumer's value where the
206
+ * record has its name (`consumerFirst` in ./template.ts), or Angular would write the element's
207
+ * own over it each time that binding changes. In the browser it listens to each event with
208
+ * `Renderer2.listen`, again on a new handler, and stops with the element. Its inputs are set
209
+ * after the element's own listeners are added, so those run first.
210
+ */
211
+ function fallthroughDirectiveCode(names, events, core, common) {
212
+ const { directive: className, listeners } = names;
213
+ const type = listenersTypeCode(listeners, events);
214
+ if (className === void 0) return type;
215
+ return `${type}\n${fallthroughClassCode(className, listeners, core, common)}`;
216
+ }
217
+ /**
218
+ * The directive's class (see {@link fallthroughDirectiveCode}), whose records' listeners are of
219
+ * the type `listeners` names: one type, inline, or the union of both event maps' types, where the
220
+ * directive is shared in `_unframework/` (ADR-0121) and so takes either.
221
+ */
222
+ function fallthroughClassCode(className, listeners, core, common) {
223
+ return [
224
+ "/**",
225
+ " * Puts what a consumer passes the component, and the component does not declare, on the element",
226
+ " * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and",
227
+ " * the native listeners, which run after the element's own.",
228
+ " */",
229
+ `@${core("Directive")}({ selector: "[${FALLTHROUGH_ATTRIBUTE}]" })`,
230
+ `export class ${className} implements ${core("OnChanges", true)}, ${core("OnDestroy", true)} {`,
231
+ ` readonly ${FALLTHROUGH_ATTRIBUTE} = ${core("input")}.required<{`,
232
+ " attributes: Record<string, unknown> | undefined;",
233
+ ` listeners: ${listeners} | undefined;`,
234
+ " }>();",
235
+ ` private readonly element = ${core("inject")}<${core("ElementRef")}<Element>>(${core("ElementRef")});`,
236
+ ` private readonly renderer = ${core("inject")}(${core("Renderer2")});`,
237
+ ` private readonly browser = ${common("isPlatformBrowser")}(${core("inject")}(${core("PLATFORM_ID")}));`,
238
+ " private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();",
239
+ " private written: Record<string, unknown> = {};",
240
+ "",
241
+ " ngOnChanges(): void {",
242
+ " const element = this.element.nativeElement;",
243
+ ` const { attributes = {}, listeners = {} } = this.${FALLTHROUGH_ATTRIBUTE}();`,
244
+ " for (const name of Object.keys(this.written)) {",
245
+ " if (!(name in attributes)) this.renderer.removeAttribute(element, name);",
246
+ " }",
247
+ " for (const [name, value] of Object.entries(attributes)) {",
248
+ " if (value === null || value === undefined) this.renderer.removeAttribute(element, name);",
249
+ " else this.renderer.setAttribute(element, name, String(value));",
250
+ " }",
251
+ " this.written = attributes;",
252
+ " if (!this.browser) return;",
253
+ " const handlers = new Map(Object.entries(listeners));",
254
+ " for (const [event, { handler, stop }] of this.listening) {",
255
+ " if (handlers.get(event) === handler) continue;",
256
+ " stop();",
257
+ " this.listening.delete(event);",
258
+ " }",
259
+ " for (const [event, handler] of handlers) {",
260
+ " if (handler === undefined || this.listening.has(event)) continue;",
261
+ " this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });",
262
+ " }",
263
+ " }",
264
+ "",
265
+ " ngOnDestroy(): void {",
266
+ " for (const { stop } of this.listening.values()) stop();",
267
+ " }",
268
+ "}",
269
+ ""
270
+ ].join("\n");
271
+ }
272
+ /**
273
+ * The type of the listeners' record: a handler of each event, typed by its event. `exported`
274
+ * exports it, from the module where it is shared (ADR-0121).
275
+ */
276
+ function listenersTypeCode(name, events, exported = false) {
277
+ return [
278
+ events === "SVGElementEventMap" ? "/** A native listener of each event a consumer passes an SVG element, by name (ADR-0118). */" : "/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */",
279
+ `${exported ? "export " : ""}type ${name} = { [K in keyof ${events}]?: (event: ${events}[K]) => void };`,
280
+ ""
281
+ ].join("\n");
282
+ }
283
+ export { ATTRIBUTES_INPUT, ELEMENT_MEMBER, ELEMENT_REF, FALLTHROUGH_ATTRIBUTE, FALLTHROUGH_MEMBERS, LISTENERS_INPUT, childApi, fallthroughClassCode, fallthroughDirectiveCode, fallthroughRoot, listenersTypeCode, planFallthrough, planRootElement };