@unframework.dev/target-angular 0.2.1 → 0.4.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/template.js CHANGED
@@ -1,12 +1,16 @@
1
1
  import { selectorOf } from "./composition.js";
2
2
  import { TELEPORT_ATTRIBUTE, TELEPORT_HOST_INPUT } from "./directives.js";
3
+ import { ATTRIBUTES_INPUT, ELEMENT_REF, FALLTHROUGH_ATTRIBUTE, LISTENERS_INPUT, childApi } from "./fallthrough.js";
3
4
  import { outputName } from "./outputs.js";
4
5
  import { bindingById, memberOf, unreachable } from "./plan.js";
5
6
  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";
7
+ import { angularCode, angularDialect, printMarkup, spreadStyleExpression, staticClassValue, test, vueClassValue } from "@unframework.dev/codegen";
8
+ import { BINDABLE_BOOLEAN_ATTRIBUTES, expressionsOf, walk } from "@unframework.dev/ir";
8
9
  /** The consumer's `style`, which the root merges over its own (ADR-0056). */
9
10
  const CONSUMER_STYLE = "this.style()";
11
+ /** The consumer's attributes and listeners, which the root takes (ADR-0118). */
12
+ const CONSUMER_ATTRIBUTES = `this.${ATTRIBUTES_INPUT}()`;
13
+ const CONSUMER_LISTENERS = `this.${LISTENERS_INPUT}()`;
10
14
  /** The template's indentation: two levels, inside the decorator's object. */
11
15
  const INDENT = " ";
12
16
  const LEVEL = 2;
@@ -113,6 +117,12 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
113
117
  }];
114
118
  },
115
119
  modelAttribute: ({ attribute }) => models.attributes.get(attribute),
120
+ restAttribute: () => [{
121
+ name: `[${FALLTHROUGH_ATTRIBUTE}]`,
122
+ text: `[${FALLTHROUGH_ATTRIBUTE}]="{ attributes: ${CONSUMER_ATTRIBUTES}, listeners: ${CONSUMER_LISTENERS} }"`
123
+ }],
124
+ boundAttribute: (name, code, context) => context.element.attributes.some((attribute) => attribute.kind === "Rest") ? consumerFirst(name, code, context) : angularDialect.boundAttribute(name, code, context),
125
+ fallthroughAttributes: (passed, context) => fallthroughRecords(passed, context, plan, fallthrough.plan),
116
126
  classAttribute: (written, context) => {
117
127
  const { classNames } = models;
118
128
  if (!classNames || !written.some((part) => part.kind === "Dynamic" && part.collection)) return angularDialect.classAttribute(written, context);
@@ -141,7 +151,7 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
141
151
  return angularDialect.styleAttribute(parts, context);
142
152
  }
143
153
  };
144
- const render = fallthrough ? withFallthrough(models.render) : models.render;
154
+ const render = fallthrough.plan ? withFallthrough(models.render, fallthrough.plan) : models.render;
145
155
  const markup = printMarkup(render, dialect, {
146
156
  indent: INDENT,
147
157
  level,
@@ -150,7 +160,7 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
150
160
  rewrite: templateRules(plan, reads.signals),
151
161
  handler: (attribute) => listeners.statements.get(attribute),
152
162
  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}"`] : []
163
+ scopeRootAttributes: ({ span }) => [...scope?.roots.has(`${span.start}:${span.end}`) ? [`[ufScope]="this.${scope.host}"`] : [], ...fallthrough.rootElement && sameSpan(fallthrough.rootElement.root.span, span) ? [`#${ELEMENT_REF}`] : []]
154
164
  });
155
165
  const outer = INDENT.repeat(LEVEL);
156
166
  const selects = composition.slots.map(({ attribute }) => `${outer}<ng-content select="[${attribute}]" />`);
@@ -158,21 +168,19 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
158
168
  return [plan.resolved === void 0 ? content : `${outer}@if (${plan.resolved}()) {\n${content}\n${outer}}`, ...selects].join("\n");
159
169
  }
160
170
  /**
161
- * The component's root (an element, or a fragment of one element or component), which a
162
- * consumer's `class` and `style` fall through to (ADR-0054), or none.
171
+ * The render tree with what the consumer passes merged into the node that takes it (ADR-0056,
172
+ * ADR-0118), the root or the rest's element: `this.class()` among its class's parts,
173
+ * `this.style()` as its whole style, whose own declarations it overrides as Vue's merge does,
174
+ * and the records of attributes and listeners, which an element takes through the fallthrough
175
+ * directive, written where its `Rest` is, and a root component through its own inputs, merged
176
+ * with the ones the component passes it itself (`fallthroughAttributes`).
163
177
  */
164
- function fallthroughRoot(render) {
165
- if (render.kind === "Element") return render;
166
- const [only] = render.children;
167
- return render.children.length === 1 && (only?.kind === "Element" || only?.kind === "Component") ? only : void 0;
178
+ function withFallthrough(render, fallthrough) {
179
+ const { target } = fallthrough;
180
+ 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);
168
181
  }
169
- /**
170
- * The render tree with the consumer's `class` and `style` inputs merged into the root
171
- * (ADR-0056): `this.class()` among its class's parts, and `this.style()` as its whole style,
172
- * whose own declarations it overrides as Vue's merge does.
173
- */
174
- function withFallthrough(render) {
175
- const root = fallthroughRoot(render);
182
+ /** The node that takes what the consumer passes, with it merged in (see `withFallthrough`). */
183
+ function takingPassed(root, fallthrough) {
176
184
  const span = root.span;
177
185
  const expression = (code) => ({
178
186
  code,
@@ -241,15 +249,125 @@ function withFallthrough(render) {
241
249
  declarations: [declaration],
242
250
  span
243
251
  });
244
- const merged = {
252
+ if (fallthrough.passes && root.kind !== "Component" && !fallthrough.rest) attributes.push({
253
+ kind: "Rest",
254
+ span
255
+ });
256
+ if (fallthrough.passes && root.kind === "Component") {
257
+ const has = (...kinds) => attributes.some(({ kind }) => kinds.includes(kind));
258
+ const prop = (name, code) => ({
259
+ kind: "Prop",
260
+ name,
261
+ value: expression(code),
262
+ span
263
+ });
264
+ if (!has("Static", "Bound")) attributes.push(prop(ATTRIBUTES_INPUT, CONSUMER_ATTRIBUTES));
265
+ if (!has("Event")) attributes.push(prop(LISTENERS_INPUT, CONSUMER_LISTENERS));
266
+ }
267
+ return {
245
268
  ...root,
246
269
  attributes
247
270
  };
248
- if (render.kind === "Element") return merged;
249
- return {
250
- ...render,
251
- children: [merged]
271
+ }
272
+ /**
273
+ * A tree with each element, component or `<component is>` node `replace` gives another for
274
+ * replaced, and every object on the way to it copied: the others, attributes included, are the
275
+ * tree's own, which the listeners' and models' plans name.
276
+ */
277
+ function mapNodes(value, replace) {
278
+ if (Array.isArray(value)) {
279
+ let changed = false;
280
+ const next = value.map((item) => {
281
+ const mapped = mapNodes(item, replace);
282
+ if (mapped !== item) changed = true;
283
+ return mapped;
284
+ });
285
+ return changed ? next : value;
286
+ }
287
+ if (value === null || typeof value !== "object") return value;
288
+ const { kind } = value;
289
+ if (kind === "Element" || kind === "Component" || kind === "Dynamic") {
290
+ const replaced = replace(value);
291
+ if (replaced) return replaced;
292
+ }
293
+ let changed = false;
294
+ const next = {};
295
+ for (const [key, child] of Object.entries(value)) {
296
+ const mapped = key === "attributes" || key === "span" ? child : mapNodes(child, replace);
297
+ if (mapped !== child) changed = true;
298
+ next[key] = mapped;
299
+ }
300
+ return changed ? next : value;
301
+ }
302
+ /** Whether two spans are one. */
303
+ function sameSpan(a, b) {
304
+ return a.start === b.start && a.end === b.end;
305
+ }
306
+ /**
307
+ * The records a component element binds for what falls through it (ADR-0118):
308
+ * `[ufAttributes]="{ id: 'save', 'aria-pressed': pressed }"`, each attribute's value as
309
+ * `[attr.name]` would bind it (a boolean attribute's `''` or `null`), and
310
+ * `[ufListeners]="{ click: () => onSave() }"`, each listener's template statement in an arrow
311
+ * whose parameter is `$event`. On the root component of a component that takes its own
312
+ * consumer's, they merge with the consumer's: its attributes win, and its listener of an event
313
+ * runs after the component's own, which the method the statement calls chains (./listeners.ts).
314
+ */
315
+ function fallthroughRecords(passed, context, plan, own) {
316
+ const forwards = own !== void 0 && own.passes && own.target.kind === "Component" && sameSpan(own.target.span, context.component.span);
317
+ const svg = childApi(plan.module, context.component.component)?.fallthroughTag === "svg";
318
+ const attributes = [];
319
+ const listeners = [];
320
+ for (const entry of passed) switch (entry.kind) {
321
+ case "Static": {
322
+ const { name, value } = entry.attribute;
323
+ attributes.push(`${recordKey(name)}: ${JSON.stringify(value === true ? "" : value)}`);
324
+ break;
325
+ }
326
+ case "Bound": {
327
+ const { name } = entry.attribute;
328
+ const value = !svg && BINDABLE_BOOLEAN_ATTRIBUTES.has(name) ? `${test(entry.code)} ? "" : null` : entry.code;
329
+ attributes.push(`${recordKey(name)}: ${value}`);
330
+ break;
331
+ }
332
+ case "Event": {
333
+ const { attribute, statement } = entry.event;
334
+ if (statement === void 0) throw new Error(`The \`${attribute.event}\` listener has no template statement.`);
335
+ const parameter = statement.includes("$event") ? "$event" : "";
336
+ listeners.push(`${recordKey(attribute.event)}: (${parameter}) => ${statement}`);
337
+ break;
338
+ }
339
+ default: unreachable(entry);
340
+ }
341
+ const printed = [];
342
+ const record = (input, entries, consumer) => {
343
+ if (!entries.length) return;
344
+ const all = !forwards ? entries : input === "ufAttributes" ? [...entries, `...${consumer}`] : [`...${consumer}`, ...entries];
345
+ printed.push({
346
+ name: `[${input}]`,
347
+ text: `[${input}]="${angularCode(`{ ${all.join(", ")} }`, "attribute")}"`
348
+ });
252
349
  };
350
+ record(ATTRIBUTES_INPUT, attributes, CONSUMER_ATTRIBUTES);
351
+ record(LISTENERS_INPUT, listeners, CONSUMER_LISTENERS);
352
+ return printed;
353
+ }
354
+ /**
355
+ * An attribute the element that takes the consumer's binds itself, merged as Vue merges `$attrs`
356
+ * on each render (ADR-0118): the consumer's value where its record has the name, even a nullish
357
+ * one, which removes the attribute, and the element's own otherwise,
358
+ * `[attr.type]="'type' in (this.ufAttributes() ?? {}) ? this.ufAttributes()?.['type'] : kind"`.
359
+ * The record holds a boolean attribute's value as `[attr.name]` binds it already
360
+ * (`fallthroughRecords`), so only the element's own is tested.
361
+ */
362
+ function consumerFirst(name, code, { namespace }) {
363
+ const own = namespace === "html" && BINDABLE_BOOLEAN_ATTRIBUTES.has(name) ? `${test(code)} ? "" : null` : code;
364
+ const key = JSON.stringify(name);
365
+ const merged = `${key} in (${CONSUMER_ATTRIBUTES} ?? {}) ? ${CONSUMER_ATTRIBUTES}?.[${key}] : ${own}`;
366
+ return `[attr.${name}]="${angularCode(merged, "attribute")}"`;
367
+ }
368
+ /** A record's key: the name itself where it is an identifier, quoted otherwise. */
369
+ function recordKey(name) {
370
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
253
371
  }
254
372
  /**
255
373
  * The bindings the template reads through a variable or as members, and those lists' keys read
@@ -301,6 +419,6 @@ function templateReads(plan, listeners) {
301
419
  }
302
420
  /** A string literal in a bound attribute's expression: single-quoted, its quotes escaped. */
303
421
  function angularString(value) {
304
- return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/&/g, "&amp;").replace(/"/g, "&quot;")}'`;
422
+ return `'${value.replaceAll("\\", String.raw`\\`).replaceAll("'", String.raw`\'`).replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}'`;
305
423
  }
306
- export { fallthroughRoot, template, templateReads };
424
+ 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.2.1",
3
+ "version": "0.4.0",
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.2.1",
51
- "@unframework.dev/ir": "0.2.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",