@unframework.dev/target-angular 0.0.0-stage → 0.0.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.
package/dist/models.js ADDED
@@ -0,0 +1,308 @@
1
+ import { bindingById } from "./plan.js";
2
+ import { templateRules } from "./rules.js";
3
+ import { angularCode, bindingForms, mergesWholeStyle, rewriteExpression, typeNames } from "@unframework.dev/codegen";
4
+ /** The helpers' code, by their base names. */
5
+ const HELPERS = {
6
+ classNames: (name) => `/**
7
+ * Class names as Vue's \`normalizeClass\` reads them (ADR-0065): a string as it is, an array's
8
+ * entries and an object's keys whose values are truthy, Angular's \`[class]\` taking the string.
9
+ */
10
+ function ${name}(value: unknown): string {
11
+ if (typeof value === "string") return value;
12
+ if (Array.isArray(value)) return value.map(${name}).filter(Boolean).join(" ");
13
+ if (!value || typeof value !== "object") return "";
14
+ return Object.entries(value)
15
+ .flatMap(([key, on]) => (on ? [key] : []))
16
+ .join(" ");
17
+ }`,
18
+ styleObject: (name) => String.raw`/**
19
+ * A style bound to a value as an object of CSS properties (ADR-0065), which a merge spreads: a
20
+ * declaration list splits as Vue's parseStringStyle splits it, and an object's camel-case keys
21
+ * are written in kebab case, as the template writes its declarations.
22
+ */
23
+ function ${name}(style: object | string | null | undefined): Record<string, string | null | undefined> {
24
+ const properties: Record<string, string | null | undefined> = {};
25
+ if (typeof style === "string") {
26
+ for (const declaration of style.replace(/\/\*[^]*?\*\//g, "").split(/;(?![^(]*\))/g)) {
27
+ const [property, value] = declaration.split(/:([^]+)/);
28
+ const key = property!.trim();
29
+ // A property is a custom property or a CSS identifier: anything else would reach the markup.
30
+ if (value !== undefined && /^(?:--[^\s"'<>&;:]+|-?[A-Za-z_][\w-]*)$/.test(key)) properties[key.startsWith("--") ? key : key.toLowerCase()] = value.trim();
31
+ }
32
+ return properties;
33
+ }
34
+ for (const [key, value] of Object.entries(style ?? {})) {
35
+ const kebab = key.replace(/[A-Z]/g, (letter) => "-" + letter.toLowerCase());
36
+ properties[key.startsWith("--") ? key : kebab] = value === null || value === undefined ? value : String(value);
37
+ }
38
+ return properties;
39
+ }`,
40
+ modelText: (name) => `/**
41
+ * Vue's \`vModelText\` (ADR-0054): the text a field shows for its model's value. It keeps the
42
+ * field's own text where that text already means the value (\`12.5kg\` for \`12.5\` with a number
43
+ * cast), or where the person is editing a trimmed field whose trimmed text is the value.
44
+ */
45
+ function ${name}(
46
+ field: HTMLInputElement | HTMLTextAreaElement,
47
+ value: unknown,
48
+ modifiers: { trim?: boolean; number?: boolean },
49
+ ): string {
50
+ const text = field.value;
51
+ const current = modifiers.number && !/^0\\d/.test(text) ? looseToNumber(text) : text;
52
+ const next = value ?? "";
53
+ if (current === next) return text;
54
+ const editing = field.ownerDocument.activeElement === field && field.type !== "range";
55
+ if (editing && modifiers.trim && text.trim() === next) return text;
56
+ return String(next);
57
+ }`,
58
+ writeModelText: (name) => `/** What a field's text writes to its model, as Vue's \`vModelText\` reads it (ADR-0054). */
59
+ function ${name}<T>(
60
+ model: WritableSignal<T>,
61
+ field: HTMLInputElement | HTMLTextAreaElement,
62
+ modifiers: { trim?: boolean; number?: boolean },
63
+ ): void {
64
+ const text = modifiers.trim ? field.value.trim() : field.value;
65
+ model.set((modifiers.number ? looseToNumber(text) : text) as T);
66
+ }`,
67
+ looseToNumber: (name) => `/** Vue's \`looseToNumber\`: the text's leading number, or the text when it has none. */
68
+ function ${name}(text: string): string | number {
69
+ const number = Number.parseFloat(text);
70
+ return Number.isNaN(number) ? text : number;
71
+ }`,
72
+ toggle: (name) => `/**
73
+ * A checkbox group's array once a box is checked or unchecked, as Vue's \`vModelCheckbox\`
74
+ * writes it (ADR-0054): a new array with the box's value added or removed.
75
+ */
76
+ function ${name}<T>(values: readonly T[], value: T, checked: boolean): T[] {
77
+ const index = values.indexOf(value);
78
+ if (checked) return index === -1 ? [...values, value] : [...values];
79
+ return values.filter((_, at) => at !== index);
80
+ }`,
81
+ optionText: (name) => `/**
82
+ * An option's value from its text, as the browser reads it without a \`value\`: its ASCII
83
+ * whitespace stripped and collapsed (ADR-0054). A no-break space is no ASCII whitespace, so it
84
+ * stays.
85
+ */
86
+ function ${name}(text: string): string {
87
+ return text.replace(/^[\\t\\n\\f\\r ]+|[\\t\\n\\f\\r ]+$/g, "").replace(/[\\t\\n\\f\\r ]+/g, " ");
88
+ }`,
89
+ selectedValues: (name) => `/** A multiple select's selected values, as Vue's \`vModelSelect\` writes them (ADR-0054). */
90
+ function ${name}(select: HTMLSelectElement): string[] {
91
+ return Array.from(select.selectedOptions, (option) => option.value);
92
+ }`
93
+ };
94
+ /** Plans every native control's `v-model` of the component's template. */
95
+ function planModels(plan) {
96
+ const attributes = /* @__PURE__ */ new Map();
97
+ const writes = /* @__PURE__ */ new Map();
98
+ const options = /* @__PURE__ */ new Map();
99
+ const helpers = /* @__PURE__ */ new Map();
100
+ const helper = (base) => {
101
+ let found = helpers.get(base);
102
+ if (!found) {
103
+ let name = plan.imports.claim(base);
104
+ while (plan.members.has(name)) name = plan.imports.claim(base);
105
+ plan.members.reserve(name);
106
+ if ((base === "modelText" || base === "writeModelText") && !helpers.has("looseToNumber")) helper("looseToNumber");
107
+ found = {
108
+ name,
109
+ code: ""
110
+ };
111
+ helpers.set(base, found);
112
+ found.code = HELPERS[base](name);
113
+ }
114
+ return found.name;
115
+ };
116
+ const classNames = bindingForms(plan.component).classCollection ? helper("classNames") : void 0;
117
+ const styleObject = mergesWholeStyle(plan.component) ? helper("styleObject") : void 0;
118
+ const rules = templateRules(plan);
119
+ let server;
120
+ const render = mapElements(plan.component.render, (element) => {
121
+ const model = element.attributes.find((attribute) => attribute.kind === "Model");
122
+ if (!model) return element;
123
+ const [reference] = model.value.refs;
124
+ if (reference?.kind !== "Binding") throw new Error("A `v-model` binds no state.");
125
+ const binding = bindingById(plan, reference.binding);
126
+ const signal = `this.${binding.name}`;
127
+ const ref = element.attributes.find((attribute) => attribute.kind === "Ref");
128
+ let variable;
129
+ const field = () => {
130
+ if (ref && ref.kind === "Ref") return bindingById(plan, ref.binding).name;
131
+ variable ??= claimVariable(plan, `${binding.name}Field`);
132
+ return variable;
133
+ };
134
+ const valueOf = () => {
135
+ const value = element.attributes.find((attribute) => (attribute.kind === "Static" || attribute.kind === "Bound") && attribute.name === "value");
136
+ if (value?.kind === "Bound") return rewriteExpression(value.value, plan.component, rules, "render");
137
+ return JSON.stringify(value?.kind === "Static" && value.value !== true ? value.value : "on");
138
+ };
139
+ const printed = [];
140
+ const bind = (name, code) => printed.push({
141
+ name,
142
+ text: `${name}="${angularCode(code, "attribute")}"`
143
+ });
144
+ const listen = (event, statement) => {
145
+ const first = writeFirst(element, event);
146
+ if (first) writes.set(first, statement);
147
+ else printed.push({
148
+ name: `(${event})`,
149
+ text: `(${event})="${angularCode(statement, "event")}"`
150
+ });
151
+ };
152
+ const text = model.control === "text" || model.control === "textarea";
153
+ const number = model.control === "number" || model.number === true;
154
+ if ((text || model.control === "number") && (model.trim || number)) {
155
+ const modifiers = `{ ${[model.trim ? "trim: true" : "", number ? "number: true" : ""].filter(Boolean).join(", ")} }`;
156
+ const name = field();
157
+ bind("[value]", `${helper("modelText")}(${name}, ${signal}(), ${modifiers})`);
158
+ const write = `${helper("writeModelText")}(${signal}, ${name}, ${modifiers})`;
159
+ const trim = model.trim ? `${name}.value = ${name}.value.trim()` : void 0;
160
+ if (model.lazy) listen("change", trim ? `${write}; ${trim}` : write);
161
+ else {
162
+ listen("input", write);
163
+ if (trim) listen("change", trim);
164
+ }
165
+ } else if (text) {
166
+ const name = field();
167
+ bind("[value]", `${signal}()`);
168
+ listen(model.lazy ? "change" : "input", `${signal}.set(${name}.value)`);
169
+ } else if (model.control === "checkbox") {
170
+ const name = field();
171
+ bind("[checked]", `${signal}()`);
172
+ listen("change", `${signal}.set(${name}.checked)`);
173
+ } else if (model.control === "radio") {
174
+ const value = valueOf();
175
+ bind("[checked]", `${signal}() === ${value}`);
176
+ listen("change", `${signal}.set(${value})`);
177
+ } else if (model.control === "checkbox-group") {
178
+ const value = valueOf();
179
+ const name = field();
180
+ bind("[checked]", `${signal}().includes(${value})`);
181
+ listen("change", `${signal}.set(${helper("toggle")}(${signal}(), ${value}, ${name}.checked))`);
182
+ } else {
183
+ const multiple = model.control === "select-multiple";
184
+ const name = field();
185
+ const chosen = multiple ? `${helper("selectedValues")}(${name})` : `${name}.value`;
186
+ listen("change", `${signal}.set(${generic(plan.component, reference.binding) ? `$any(${chosen})` : chosen})`);
187
+ server ??= claimVariable(plan, "onServer");
188
+ if (variable !== void 0) printed.unshift({
189
+ name: `#${variable}`,
190
+ text: `#${variable}`
191
+ });
192
+ attributes.set(model, printed);
193
+ const withSelected = (option) => {
194
+ if (option.tag !== "option") return option;
195
+ const added = {
196
+ kind: "Static",
197
+ name: "selected",
198
+ value: true,
199
+ span: option.span
200
+ };
201
+ const value = optionValue(plan, option, rules, () => helper("optionText"));
202
+ const selected = multiple ? `${signal}().includes(${value})` : `${signal}() === ${value}`;
203
+ options.set(added, `[selected]="${angularCode(selected, "attribute")}" [defaultSelected]="${angularCode(`${server} && ${selected}`, "attribute")}"`);
204
+ return {
205
+ ...option,
206
+ attributes: [...option.attributes, added]
207
+ };
208
+ };
209
+ return {
210
+ ...element,
211
+ children: element.children.map((child) => mapElements(child, withSelected))
212
+ };
213
+ }
214
+ if (variable !== void 0) printed.unshift({
215
+ name: `#${variable}`,
216
+ text: `#${variable}`
217
+ });
218
+ attributes.set(model, printed);
219
+ return element;
220
+ });
221
+ const used = [...helpers.entries()];
222
+ return {
223
+ attributes,
224
+ writes,
225
+ options,
226
+ render,
227
+ ...server === void 0 ? {} : { server },
228
+ ...classNames === void 0 ? {} : { classNames },
229
+ ...styleObject === void 0 ? {} : { styleObject },
230
+ helpers: used.filter(([base]) => base !== "looseToNumber").map(([, each]) => each),
231
+ support: used.filter(([base]) => base === "looseToNumber").map(([, each]) => each)
232
+ };
233
+ }
234
+ /**
235
+ * The author's listener of the element's event whose template listener the model's write joins,
236
+ * ahead of the listener's own statement: Vue's `vModel*` directives listen in `created`, before
237
+ * the element's own listeners, so the model is written first whatever the attributes' order, and
238
+ * one template listener per event keeps Angular's attributes unique. That is the first listener of
239
+ * the event in the bubble phase, which writes the template listener: alone, or chaining the others,
240
+ * a `once` or `passive` one among them (./listeners.ts). A capture listener runs before the bubble
241
+ * phase at its target, on Vue too, so it keeps its directive.
242
+ */
243
+ function writeFirst(element, event) {
244
+ return element.attributes.find((attribute) => attribute.kind === "Event" && attribute.event === event && !attribute.capture);
245
+ }
246
+ /** HTML's ASCII whitespace, which an option's text value strips at its edges and collapses. */
247
+ const ASCII_WHITESPACE = /[\t\n\f\r ]+/g;
248
+ const ASCII_EDGES = /^[\t\n\f\r ]+|[\t\n\f\r ]+$/g;
249
+ /**
250
+ * The value an option gives its select's model, as Vue's `vModelSelect` reads it: its bound
251
+ * `value`, its static one, or else its text, which is an option's value without the attribute.
252
+ * HTML strips and collapses the text's ASCII whitespace: a static text here, a text with an
253
+ * interpolation through `optionText` as it renders.
254
+ */
255
+ function optionValue(plan, option, rules, optionText) {
256
+ const value = option.attributes.find((attribute) => (attribute.kind === "Static" || attribute.kind === "Bound") && attribute.name === "value");
257
+ if (value?.kind === "Bound") return rewriteExpression(value.value, plan.component, rules, "render");
258
+ if (value?.kind === "Static") return JSON.stringify(value.value === true ? "" : value.value);
259
+ const [only] = option.children;
260
+ if (option.children.length === 1 && only?.kind === "Text") return JSON.stringify(only.value.replace(ASCII_EDGES, "").replace(ASCII_WHITESPACE, " "));
261
+ const parts = option.children.flatMap((child) => {
262
+ if (child.kind === "Text") return [JSON.stringify(child.value)];
263
+ if (child.kind === "Interpolation") return [`((${rewriteExpression(child.value, plan.component, rules, "render")}) ?? "")`];
264
+ return [];
265
+ });
266
+ return `${optionText()}(${["\"\"", ...parts].join(" + ")})`;
267
+ }
268
+ /** Whether a binding's declared type names a type parameter of its component (ADR-0068). */
269
+ function generic(component, binding) {
270
+ const parameters = new Set(component.typeParameters?.map(({ name }) => name));
271
+ if (!parameters.size) return false;
272
+ const item = component.setup.find((each) => "binding" in each && each.binding === binding);
273
+ const type = item && "type" in item ? item.type : void 0;
274
+ return type !== void 0 && [...typeNames(type)].some((name) => parameters.has(name));
275
+ }
276
+ /** A template variable's name, free beside the class's members and the lists' variables. */
277
+ function claimVariable(plan, base) {
278
+ let name = plan.members.claim(base);
279
+ while (plan.loopNames.has(name)) name = plan.members.claim(base);
280
+ return name;
281
+ }
282
+ /** The render tree with each element replaced by what `map` makes of it, children first. */
283
+ function mapElements(node, map) {
284
+ const visit = (value) => {
285
+ if (Array.isArray(value)) return value.map(visit);
286
+ if (typeof value !== "object" || value === null) return value;
287
+ if (value.kind === "Element") {
288
+ const element = value;
289
+ return map({
290
+ ...element,
291
+ children: element.children.map((child) => visit(child))
292
+ });
293
+ }
294
+ const copy = {};
295
+ for (const [key, child] of Object.entries(value)) copy[key] = CHILD_KEYS.has(key) ? visit(child) : child;
296
+ return copy;
297
+ };
298
+ return visit(node);
299
+ }
300
+ /** The keys under which a render node, a branch or a fill holds render nodes. */
301
+ const CHILD_KEYS = /* @__PURE__ */ new Set([
302
+ "children",
303
+ "branches",
304
+ "body",
305
+ "fills",
306
+ "fallback"
307
+ ]);
308
+ export { planModels };
@@ -0,0 +1,54 @@
1
+ import { codeNames, typeNames, typeSpecifier } from "@unframework.dev/codegen";
2
+ /**
3
+ * The module's values an output reaches (ADR-0070): those its bindings read, and those its
4
+ * constants read in turn. Each value import is added to `imports` under the source's own name,
5
+ * and each type import its constants name; the constants are copied as written, since a module
6
+ * name keeps its name in every Angular output.
7
+ */
8
+ function moduleReads(bindings, module, imports, file) {
9
+ const values = new Set(bindings.filter((binding) => binding.kind === "import" || binding.kind === "moduleConst").map((binding) => binding.name));
10
+ const constants = module.constants ?? [];
11
+ for (let size = -1; size !== values.size;) {
12
+ size = values.size;
13
+ for (const constant of constants) {
14
+ if (!values.has(constant.name)) continue;
15
+ for (const reference of constant.value.refs) if (reference.kind === "Binding") values.add(reference.binding.split("@")[0]);
16
+ }
17
+ }
18
+ for (const entry of module.moduleImports ?? []) for (const name of entry.names) {
19
+ if (!values.has(name.local)) continue;
20
+ if (name.imported === "default") imports.addDefault(entry.specifier, name.local, { exact: true });
21
+ else imports.add(entry.specifier, name.imported, {
22
+ local: name.local,
23
+ exact: true
24
+ });
25
+ }
26
+ const declared = constants.filter((constant) => values.has(constant.name));
27
+ const named = /* @__PURE__ */ new Set();
28
+ for (const constant of declared) {
29
+ if (constant.type) for (const name of typeNames(constant.type)) named.add(name);
30
+ for (const name of codeNames(constant.value.code)) named.add(name);
31
+ }
32
+ const types = /* @__PURE__ */ new Map();
33
+ for (let size = -1; size !== types.size;) {
34
+ size = types.size;
35
+ for (const declaration of module.types) {
36
+ if (types.has(declaration.name) || !named.has(declaration.name)) continue;
37
+ types.set(declaration.name, declaration);
38
+ for (const name of codeNames(declaration.code, "statements")) named.add(name);
39
+ }
40
+ }
41
+ for (const entry of module.typeImports ?? []) for (const name of entry.names) {
42
+ if (!named.has(name.local)) continue;
43
+ imports.add(typeSpecifier(entry.specifier, module, file), name.imported, {
44
+ type: true,
45
+ local: name.local,
46
+ exact: true
47
+ });
48
+ }
49
+ return {
50
+ constants: declared.map((constant) => `const ${constant.name}${constant.type ? `: ${constant.type.code}` : ""} = ${constant.value.code};`),
51
+ types: module.types.filter((declaration) => types.has(declaration.name))
52
+ };
53
+ }
54
+ export { moduleReads };
@@ -0,0 +1,157 @@
1
+ /** Whether a reference's own read is narrowed: its whole span is a narrowed path. */
2
+ function narrowedWhole(reference) {
3
+ return reference.narrowed?.some(({ span }) => span.end === reference.span.end) === true;
4
+ }
5
+ /**
6
+ * Code with a `!` after each narrowed member path that runs past its reference
7
+ * (`draft.value.email!`), for the references `asserts` takes; the same code when there is none.
8
+ * The spans after each `!` move with the text: a span that ends where a path does holds its `!`.
9
+ */
10
+ function assertedCode(code, asserts) {
11
+ const at = code.refs.flatMap((reference) => reference.kind === "Binding" && asserts(reference) ? (reference.narrowed ?? []).filter(({ span }) => span.end > reference.span.end).map(({ span }) => span.end) : []).toSorted((a, b) => a - b);
12
+ if (at.length === 0) return code;
13
+ const offset = code.span.start;
14
+ let text = "";
15
+ let from = 0;
16
+ for (const position of at) {
17
+ text += `${code.code.slice(from, position - offset)}!`;
18
+ from = position - offset;
19
+ }
20
+ text += code.code.slice(from);
21
+ const start = (position) => position + at.filter((each) => each < position).length;
22
+ const end = (position) => position + at.filter((each) => each <= position).length;
23
+ const moved = (span) => ({
24
+ start: start(span.start),
25
+ end: end(span.end)
26
+ });
27
+ return {
28
+ code: text,
29
+ span: {
30
+ start: code.span.start,
31
+ end: end(code.span.end)
32
+ },
33
+ refs: code.refs.map((reference) => movedReference(reference, moved))
34
+ };
35
+ }
36
+ /** A function whose body is {@link assertedCode}'s. */
37
+ function assertedFunction(fn, asserts) {
38
+ const body = assertedCode(fn.body, asserts);
39
+ return body === fn.body ? fn : {
40
+ ...fn,
41
+ body
42
+ };
43
+ }
44
+ /**
45
+ * The component with every narrowed path of its setup code asserted (`assertedCode`): the setup is
46
+ * the class's code, which reads every prop and ref's value through a call.
47
+ */
48
+ function assertedSetup(component) {
49
+ return {
50
+ ...component,
51
+ setup: component.setup.map((item) => {
52
+ switch (item.kind) {
53
+ case "State":
54
+ case "Variable": return item.initial ? {
55
+ ...item,
56
+ initial: code(item.initial)
57
+ } : item;
58
+ case "Const": return {
59
+ ...item,
60
+ value: code(item.value)
61
+ };
62
+ case "Derived": return {
63
+ ...item,
64
+ getter: fn(item.getter)
65
+ };
66
+ case "Function": return {
67
+ ...item,
68
+ function: fn(item.function)
69
+ };
70
+ case "Watch": return {
71
+ ...item,
72
+ sources: item.sources.map((source) => source.kind === "Getter" ? {
73
+ ...source,
74
+ getter: fn(source.getter)
75
+ } : source),
76
+ callback: fn(item.callback)
77
+ };
78
+ case "WatchEffect": return {
79
+ ...item,
80
+ effect: fn(item.effect)
81
+ };
82
+ case "Lifecycle": return {
83
+ ...item,
84
+ callback: fn(item.callback)
85
+ };
86
+ case "TemplateRef":
87
+ case "Id":
88
+ case "Model":
89
+ case "Provide":
90
+ case "Inject": return item;
91
+ case "Use": return {
92
+ ...item,
93
+ arguments: item.arguments.map((argument) => {
94
+ switch (argument.kind) {
95
+ case "Value": return {
96
+ ...argument,
97
+ value: code(argument.value)
98
+ };
99
+ case "Getter": return {
100
+ ...argument,
101
+ getter: fn(argument.getter)
102
+ };
103
+ case "Callback": return {
104
+ ...argument,
105
+ callback: fn(argument.callback)
106
+ };
107
+ default: return unreachable(argument);
108
+ }
109
+ })
110
+ };
111
+ default: return unreachable(item);
112
+ }
113
+ })
114
+ };
115
+ }
116
+ /** Every reference: class code reads each through a call. */
117
+ const all = () => true;
118
+ const code = (each) => assertedCode(each, all);
119
+ const fn = (each) => assertedFunction(each, all);
120
+ /** A reference with each of its spans moved. */
121
+ function movedReference(reference, moved) {
122
+ switch (reference.kind) {
123
+ case "Binding": return {
124
+ ...reference,
125
+ span: moved(reference.span),
126
+ ...reference.narrowed ? { narrowed: reference.narrowed.map((path) => ({
127
+ ...path,
128
+ span: moved(path.span)
129
+ })) } : {}
130
+ };
131
+ case "Write": return {
132
+ ...reference,
133
+ span: moved(reference.span),
134
+ target: moved(reference.target),
135
+ ...reference.value ? { value: moved(reference.value) } : {}
136
+ };
137
+ case "Emit": return {
138
+ ...reference,
139
+ span: moved(reference.span),
140
+ arguments: reference.arguments.map(moved)
141
+ };
142
+ case "Global":
143
+ case "Import":
144
+ case "Event":
145
+ case "Api":
146
+ case "Slot": return {
147
+ ...reference,
148
+ span: moved(reference.span)
149
+ };
150
+ default: return unreachable(reference);
151
+ }
152
+ }
153
+ /** The `never` default of an exhaustive switch (./plan.ts imports this module). */
154
+ function unreachable(value) {
155
+ throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
156
+ }
157
+ export { assertedCode, assertedFunction, assertedSetup, narrowedWhole };