@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.
package/dist/template.js CHANGED
@@ -1,12 +1,17 @@
1
1
  import { selectorOf } from "./composition.js";
2
+ import { hoistedDefaultSlot } from "./default-slot.js";
2
3
  import { TELEPORT_ATTRIBUTE, TELEPORT_HOST_INPUT } from "./directives.js";
4
+ import { ATTRIBUTES_INPUT, ELEMENT_REF, FALLTHROUGH_ATTRIBUTE, LISTENERS_INPUT, childApi } from "./fallthrough.js";
3
5
  import { outputName } from "./outputs.js";
4
6
  import { bindingById, memberOf, unreachable } from "./plan.js";
5
7
  import { readThroughLet, templateRules } from "./rules.js";
6
- import { angularCode, angularDialect, printMarkup, spreadStyleExpression, staticClassValue, vueClassValue } from "@unframework.dev/codegen";
7
- import { expressionsOf, walk } from "@unframework.dev/ir";
8
+ import { angularCode, angularDialect, printMarkup, spreadStyleExpression, staticClassValue, test, vueClassValue } from "@unframework.dev/codegen";
9
+ import { BINDABLE_BOOLEAN_ATTRIBUTES, expressionsOf, walk } from "@unframework.dev/ir";
8
10
  /** The consumer's `style`, which the root merges over its own (ADR-0056). */
9
11
  const CONSUMER_STYLE = "this.style()";
12
+ /** The consumer's attributes and listeners, which the root takes (ADR-0118). */
13
+ const CONSUMER_ATTRIBUTES = `this.${ATTRIBUTES_INPUT}()`;
14
+ const CONSUMER_LISTENERS = `this.${LISTENERS_INPUT}()`;
10
15
  /** The template's indentation: two levels, inside the decorator's object. */
11
16
  const INDENT = " ";
12
17
  const LEVEL = 2;
@@ -27,7 +32,7 @@ const LEVEL = 2;
27
32
  * (NG8009), so a signal a list's key reads is read there from the class, `this.label()`, and
28
33
  * counts as no use of its variable (an unread `@let` is NG8112).
29
34
  */
30
- function template(plan, listeners, reads, composition, models, fallthrough, scope, teleportHost, transition) {
35
+ function template(plan, listeners, reads, composition, models, fallthrough, scope, teleportHost, transition, defaultSlot) {
31
36
  const { component } = plan;
32
37
  const level = plan.resolved === void 0 ? LEVEL : 3;
33
38
  const pad = INDENT.repeat(level);
@@ -42,8 +47,37 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
42
47
  if ("binding" in item) declare(item.binding);
43
48
  if (item.kind === "Use") for (const member of item.members) declare(member.binding);
44
49
  }
50
+ const render = fallthrough.plan ? withFallthrough(models.render, fallthrough.plan) : models.render;
51
+ const found = defaultSlot && hoistedDefaultSlot(render);
52
+ const hoisted = found && {
53
+ ...found,
54
+ ref: defaultSlot.ref
55
+ };
56
+ /** Where a case renders the slot: the template, through `ngTemplateOutlet`. */
57
+ const renderSlot = (ref) => ({
58
+ kind: "tag",
59
+ tag: "ng-container",
60
+ attributes: [{
61
+ name: "[ngTemplateOutlet]",
62
+ text: `[ngTemplateOutlet]="${ref}"`
63
+ }]
64
+ });
45
65
  const dialect = {
46
66
  ...angularDialect,
67
+ dynamic: (printed) => {
68
+ const pieces = angularDialect.dynamic(printed);
69
+ if (printed.node !== hoisted?.dynamic) return pieces;
70
+ return [{
71
+ kind: "tag",
72
+ tag: "ng-template",
73
+ attributes: [{
74
+ name: `#${hoisted.ref}`,
75
+ text: `#${hoisted.ref}`
76
+ }],
77
+ content: angularDialect.slotOutlet({ node: hoisted.outlet })
78
+ }, ...pieces];
79
+ },
80
+ slotOutlet: (outlet) => hoisted && outlet.node === hoisted.outlet ? [renderSlot(hoisted.ref)] : angularDialect.slotOutlet(outlet),
47
81
  teleport: ({ node }) => [{
48
82
  kind: "wrapper",
49
83
  tag: "ng-template",
@@ -113,6 +147,12 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
113
147
  }];
114
148
  },
115
149
  modelAttribute: ({ attribute }) => models.attributes.get(attribute),
150
+ restAttribute: () => [{
151
+ name: `[${FALLTHROUGH_ATTRIBUTE}]`,
152
+ text: `[${FALLTHROUGH_ATTRIBUTE}]="{ attributes: ${CONSUMER_ATTRIBUTES}, listeners: ${CONSUMER_LISTENERS} }"`
153
+ }],
154
+ boundAttribute: (name, code, context) => context.element.attributes.some((attribute) => attribute.kind === "Rest") ? consumerFirst(name, code, context) : angularDialect.boundAttribute(name, code, context),
155
+ fallthroughAttributes: (passed, context) => fallthroughRecords(passed, context, plan, fallthrough.plan),
116
156
  classAttribute: (written, context) => {
117
157
  const { classNames } = models;
118
158
  if (!classNames || !written.some((part) => part.kind === "Dynamic" && part.collection)) return angularDialect.classAttribute(written, context);
@@ -141,7 +181,6 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
141
181
  return angularDialect.styleAttribute(parts, context);
142
182
  }
143
183
  };
144
- const render = fallthrough ? withFallthrough(models.render) : models.render;
145
184
  const markup = printMarkup(render, dialect, {
146
185
  indent: INDENT,
147
186
  level,
@@ -150,7 +189,7 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
150
189
  rewrite: templateRules(plan, reads.signals),
151
190
  handler: (attribute) => listeners.statements.get(attribute),
152
191
  attribute: (attribute) => attribute.kind === "Event" ? listeners.attributes.get(attribute) : models.options.get(attribute),
153
- scopeRootAttributes: ({ span }) => scope?.roots.has(`${span.start}:${span.end}`) ? [`[ufScope]="this.${scope.host}"`] : []
192
+ scopeRootAttributes: ({ span }) => [...scope?.roots.has(`${span.start}:${span.end}`) ? [`[ufScope]="this.${scope.host}"`] : [], ...fallthrough.rootElement && sameSpan(fallthrough.rootElement.root.span, span) ? [`#${ELEMENT_REF}`] : []]
154
193
  });
155
194
  const outer = INDENT.repeat(LEVEL);
156
195
  const selects = composition.slots.map(({ attribute }) => `${outer}<ng-content select="[${attribute}]" />`);
@@ -158,24 +197,19 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
158
197
  return [plan.resolved === void 0 ? content : `${outer}@if (${plan.resolved}()) {\n${content}\n${outer}}`, ...selects].join("\n");
159
198
  }
160
199
  /**
161
- * The component's root (an element, or a fragment of one element, one component or one
162
- * `<component is>` over tags, ADR-0119), which a consumer's `class` and `style` fall through to
163
- * (ADR-0054), or none. A `<component is>` takes them in each `@case`.
200
+ * The render tree with what the consumer passes merged into the node that takes it (ADR-0056,
201
+ * ADR-0118), the root or the rest's element: `this.class()` among its class's parts,
202
+ * `this.style()` as its whole style, whose own declarations it overrides as Vue's merge does,
203
+ * and the records of attributes and listeners, which an element takes through the fallthrough
204
+ * directive, written where its `Rest` is, and a root component through its own inputs, merged
205
+ * with the ones the component passes it itself (`fallthroughAttributes`).
164
206
  */
165
- function fallthroughRoot(render) {
166
- if (render.kind === "Element") return render;
167
- const [only] = render.children;
168
- if (render.children.length !== 1) return void 0;
169
- if (only?.kind === "Element" || only?.kind === "Component") return only;
170
- return only?.kind === "Dynamic" && only.candidates.every((each) => each.kind === "Tag") ? only : void 0;
207
+ function withFallthrough(render, fallthrough) {
208
+ const { target } = fallthrough;
209
+ return mapNodes(render, (node) => node.kind === target.kind && node.span.start === target.span.start && node.span.end === target.span.end ? takingPassed(node, fallthrough) : void 0);
171
210
  }
172
- /**
173
- * The render tree with the consumer's `class` and `style` inputs merged into the root
174
- * (ADR-0056): `this.class()` among its class's parts, and `this.style()` as its whole style,
175
- * whose own declarations it overrides as Vue's merge does.
176
- */
177
- function withFallthrough(render) {
178
- const root = fallthroughRoot(render);
211
+ /** The node that takes what the consumer passes, with it merged in (see `withFallthrough`). */
212
+ function takingPassed(root, fallthrough) {
179
213
  const span = root.span;
180
214
  const expression = (code) => ({
181
215
  code,
@@ -244,15 +278,125 @@ function withFallthrough(render) {
244
278
  declarations: [declaration],
245
279
  span
246
280
  });
247
- const merged = {
281
+ if (fallthrough.passes && root.kind !== "Component" && !fallthrough.rest) attributes.push({
282
+ kind: "Rest",
283
+ span
284
+ });
285
+ if (fallthrough.passes && root.kind === "Component") {
286
+ const has = (...kinds) => attributes.some(({ kind }) => kinds.includes(kind));
287
+ const prop = (name, code) => ({
288
+ kind: "Prop",
289
+ name,
290
+ value: expression(code),
291
+ span
292
+ });
293
+ if (!has("Static", "Bound")) attributes.push(prop(ATTRIBUTES_INPUT, CONSUMER_ATTRIBUTES));
294
+ if (!has("Event")) attributes.push(prop(LISTENERS_INPUT, CONSUMER_LISTENERS));
295
+ }
296
+ return {
248
297
  ...root,
249
298
  attributes
250
299
  };
251
- if (render.kind === "Element") return merged;
252
- return {
253
- ...render,
254
- children: [merged]
300
+ }
301
+ /**
302
+ * A tree with each element, component or `<component is>` node `replace` gives another for
303
+ * replaced, and every object on the way to it copied: the others, attributes included, are the
304
+ * tree's own, which the listeners' and models' plans name.
305
+ */
306
+ function mapNodes(value, replace) {
307
+ if (Array.isArray(value)) {
308
+ let changed = false;
309
+ const next = value.map((item) => {
310
+ const mapped = mapNodes(item, replace);
311
+ if (mapped !== item) changed = true;
312
+ return mapped;
313
+ });
314
+ return changed ? next : value;
315
+ }
316
+ if (value === null || typeof value !== "object") return value;
317
+ const { kind } = value;
318
+ if (kind === "Element" || kind === "Component" || kind === "Dynamic") {
319
+ const replaced = replace(value);
320
+ if (replaced) return replaced;
321
+ }
322
+ let changed = false;
323
+ const next = {};
324
+ for (const [key, child] of Object.entries(value)) {
325
+ const mapped = key === "attributes" || key === "span" ? child : mapNodes(child, replace);
326
+ if (mapped !== child) changed = true;
327
+ next[key] = mapped;
328
+ }
329
+ return changed ? next : value;
330
+ }
331
+ /** Whether two spans are one. */
332
+ function sameSpan(a, b) {
333
+ return a.start === b.start && a.end === b.end;
334
+ }
335
+ /**
336
+ * The records a component element binds for what falls through it (ADR-0118):
337
+ * `[ufAttributes]="{ id: 'save', 'aria-pressed': pressed }"`, each attribute's value as
338
+ * `[attr.name]` would bind it (a boolean attribute's `''` or `null`), and
339
+ * `[ufListeners]="{ click: () => onSave() }"`, each listener's template statement in an arrow
340
+ * whose parameter is `$event`. On the root component of a component that takes its own
341
+ * consumer's, they merge with the consumer's: its attributes win, and its listener of an event
342
+ * runs after the component's own, which the method the statement calls chains (./listeners.ts).
343
+ */
344
+ function fallthroughRecords(passed, context, plan, own) {
345
+ const forwards = own !== void 0 && own.passes && own.target.kind === "Component" && sameSpan(own.target.span, context.component.span);
346
+ const svg = childApi(plan.module, context.component.component)?.fallthroughTag === "svg";
347
+ const attributes = [];
348
+ const listeners = [];
349
+ for (const entry of passed) switch (entry.kind) {
350
+ case "Static": {
351
+ const { name, value } = entry.attribute;
352
+ attributes.push(`${recordKey(name)}: ${JSON.stringify(value === true ? "" : value)}`);
353
+ break;
354
+ }
355
+ case "Bound": {
356
+ const { name } = entry.attribute;
357
+ const value = !svg && BINDABLE_BOOLEAN_ATTRIBUTES.has(name) ? `${test(entry.code)} ? "" : null` : entry.code;
358
+ attributes.push(`${recordKey(name)}: ${value}`);
359
+ break;
360
+ }
361
+ case "Event": {
362
+ const { attribute, statement } = entry.event;
363
+ if (statement === void 0) throw new Error(`The \`${attribute.event}\` listener has no template statement.`);
364
+ const parameter = statement.includes("$event") ? "$event" : "";
365
+ listeners.push(`${recordKey(attribute.event)}: (${parameter}) => ${statement}`);
366
+ break;
367
+ }
368
+ default: unreachable(entry);
369
+ }
370
+ const printed = [];
371
+ const record = (input, entries, consumer) => {
372
+ if (!entries.length) return;
373
+ const all = !forwards ? entries : input === "ufAttributes" ? [...entries, `...${consumer}`] : [`...${consumer}`, ...entries];
374
+ printed.push({
375
+ name: `[${input}]`,
376
+ text: `[${input}]="${angularCode(`{ ${all.join(", ")} }`, "attribute")}"`
377
+ });
255
378
  };
379
+ record(ATTRIBUTES_INPUT, attributes, CONSUMER_ATTRIBUTES);
380
+ record(LISTENERS_INPUT, listeners, CONSUMER_LISTENERS);
381
+ return printed;
382
+ }
383
+ /**
384
+ * An attribute the element that takes the consumer's binds itself, merged as Vue merges `$attrs`
385
+ * on each render (ADR-0118): the consumer's value where its record has the name, even a nullish
386
+ * one, which removes the attribute, and the element's own otherwise,
387
+ * `[attr.type]="'type' in (this.ufAttributes() ?? {}) ? this.ufAttributes()?.['type'] : kind"`.
388
+ * The record holds a boolean attribute's value as `[attr.name]` binds it already
389
+ * (`fallthroughRecords`), so only the element's own is tested.
390
+ */
391
+ function consumerFirst(name, code, { namespace }) {
392
+ const own = namespace === "html" && BINDABLE_BOOLEAN_ATTRIBUTES.has(name) ? `${test(code)} ? "" : null` : code;
393
+ const key = JSON.stringify(name);
394
+ const merged = `${key} in (${CONSUMER_ATTRIBUTES} ?? {}) ? ${CONSUMER_ATTRIBUTES}?.[${key}] : ${own}`;
395
+ return `[attr.${name}]="${angularCode(merged, "attribute")}"`;
396
+ }
397
+ /** A record's key: the name itself where it is an identifier, quoted otherwise. */
398
+ function recordKey(name) {
399
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
256
400
  }
257
401
  /**
258
402
  * The bindings the template reads through a variable or as members, and those lists' keys read
@@ -304,6 +448,6 @@ function templateReads(plan, listeners) {
304
448
  }
305
449
  /** A string literal in a bound attribute's expression: single-quoted, its quotes escaped. */
306
450
  function angularString(value) {
307
- return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/&/g, "&amp;").replace(/"/g, "&quot;")}'`;
451
+ return `'${value.replaceAll("\\", String.raw`\\`).replaceAll("'", String.raw`\'`).replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}'`;
308
452
  }
309
- export { fallthroughRoot, template, templateReads };
453
+ export { template, templateReads };
@@ -21,4 +21,4 @@ export declare function setInputs(ref: ComponentRef<unknown>, set: Set<string>,
21
21
  * the value for one required member, and the tuple of the arguments otherwise; the listener gets
22
22
  * the arguments back, exactly as many as the component passed.
23
23
  */
24
- export declare function outputBindings(on?: Readonly<Record<string, MountListener>>, events?: readonly MountEvent[]): Binding[];
24
+ export declare function outputBindings(on?: Readonly<Record<string, MountListener>>, events?: ReadonlyArray<MountEvent>): Array<Binding>;
@@ -9,6 +9,14 @@ import { Worker } from "node:worker_threads";
9
9
  */
10
10
  const VIRTUAL_ID = /\.uf\.tsx?(?:\.[^/?]+)?\.ts$/;
11
11
  /**
12
+ * A shared helper module's id (ADR-0121), `<helper root>/_unframework/angular/ScopeAttributes.ts`,
13
+ * which the unframework plugin serves too, or the path an output imports it by,
14
+ * `<helper root>/_unframework/ScopeAttributes.ts`, whose text `getCompiled` gives as well. A helper
15
+ * module imports its siblings (`./looseToNumber`) beside its id. It is one of ours only while
16
+ * `getCompiled` gives its text: a project file at the path is the project's.
17
+ */
18
+ const HELPER_ID = /\/_unframework\/(?:[^/?]+\/)?[^/?]+\.ts$/;
19
+ /**
12
20
  * A relative import or re-export in generated code, of a child's output (`./field`, ADR-0053)
13
21
  * or of a file on disk: `import … from "./x"`, `export … from "./x"` or `import "./x"`. Its
14
22
  * specifier is the first group.
@@ -34,6 +42,11 @@ function ngtscVirtual(compiler, declarations = []) {
34
42
  let api;
35
43
  /** The virtual module each relative import of a virtual module resolved to, by importer. */
36
44
  const children = /* @__PURE__ */ new Map();
45
+ /** The shared helper module a path names, without its extension, while the plugin serves it. */
46
+ function helperModule(path) {
47
+ const id = `${path}.ts`;
48
+ return HELPER_ID.test(id) && api.getCompiled(id) !== void 0 ? id : void 0;
49
+ }
37
50
  function compile(id, code) {
38
51
  const sources = /* @__PURE__ */ new Map([[id, code]]);
39
52
  const sheets = /* @__PURE__ */ new Map();
@@ -46,7 +59,7 @@ function ngtscVirtual(compiler, declarations = []) {
46
59
  }
47
60
  for (const [, specifier = ""] of text.matchAll(RELATIVE_IMPORT)) {
48
61
  const key = childKey(file, specifier);
49
- const child = COMPONENT_IMPORT.test(specifier) ? `${resolve(dirname(file), specifier)}.ts` : children.get(key);
62
+ const child = COMPONENT_IMPORT.test(specifier) ? `${resolve(dirname(file), specifier)}.ts` : children.get(key) ?? helperModule(resolve(dirname(file), specifier));
50
63
  if (!child) continue;
51
64
  if (!COMPONENT_IMPORT.test(specifier)) resolved.set(key, child);
52
65
  const source = sources.has(child) ? void 0 : api.getCompiled(child);
@@ -70,9 +83,10 @@ function ngtscVirtual(compiler, declarations = []) {
70
83
  api = candidate;
71
84
  },
72
85
  transform: {
73
- filter: { id: /\.uf\.tsx?(?:\.[^/?]+)?\.ts(?:\?|$)/ },
86
+ filter: { id: /(?:\.uf\.tsx?(?:\.[^/?]+)?|\/_unframework\/(?:[^/?]+\/)?[^/?]+)\.ts(?:\?|$)/ },
74
87
  async handler(code, rawId) {
75
88
  const id = rawId.split("?")[0];
89
+ if (HELPER_ID.test(id) && api.getCompiled(id) === void 0) return null;
76
90
  const client = this.environment.mode === "dev" && this.environment.config.consumer === "client";
77
91
  for (const [, fileName = ""] of code.matchAll(RELATIVE_IMPORT)) {
78
92
  if (COMPONENT_IMPORT.test(fileName)) continue;
@@ -171,7 +171,7 @@ function formatDiagnostics(compiler, diagnostics) {
171
171
  }).join("\n");
172
172
  }
173
173
  function positionOf(diagnostic) {
174
- if (!diagnostic.file || diagnostic.start === void 0) return void 0;
174
+ if (!diagnostic.file || diagnostic.start === void 0) return;
175
175
  const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
176
176
  return {
177
177
  line: line + 1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unframework.dev/target-angular",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "The Angular 22 target of the Unframework compiler: emits idiomatic Angular components from the portable IR, declares their capabilities, and provides the toolchain the tests use.",
5
5
  "keywords": [
6
6
  "angular",
@@ -47,8 +47,8 @@
47
47
  "access": "public"
48
48
  },
49
49
  "dependencies": {
50
- "@unframework.dev/codegen": "0.3.0",
51
- "@unframework.dev/ir": "0.3.0"
50
+ "@unframework.dev/codegen": "0.4.0",
51
+ "@unframework.dev/ir": "0.4.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@angular/common": "22.2.1",
@@ -57,7 +57,7 @@
57
57
  "@angular/platform-browser": "22.2.1",
58
58
  "@angular/platform-server": "22.2.1",
59
59
  "@types/node": "^24.19.0",
60
- "@uxfront/typescript-config": "^0.1.0",
60
+ "@uxfront/typescript-config": "^0.2.0",
61
61
  "@vitest/browser-playwright": "5.0.3",
62
62
  "playwright": "1.63.0",
63
63
  "rxjs": "^7.8.2",