@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/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { emitComposable } from "./composable.js";
2
2
  import { firstUse, keyOf, planComposition, refObjectCode, slotDirectiveCode, tokenType } from "./composition.js";
3
- import { RUNNER_HELPER, directiveClassCode, directiveClassName, directiveFile, emitDirective, runnerCode, runnerNames } from "./directive.js";
4
- import { directiveCode, scopeDirectiveCode, teleportDirectiveCode, textCaretDirectiveCode, transitionDirectiveCode, transitionRegionCode, trustedHtmlPipeCode } from "./directives.js";
3
+ import { hoistedDefaultSlot } from "./default-slot.js";
4
+ import { QUEUE_HELPER, RUNNER_HELPER, directiveClassCode, directiveClassName, directiveFile, emitDirective, runnerCode, runnerNames } from "./directive.js";
5
+ import { directiveCode, scopeDirectiveCode, spaced, teleportDirectiveCode, textCaretDirectiveCode, transitionDirectiveCode, transitionRegionCode, trustedHtmlPipeCode } from "./directives.js";
6
+ import { ATTRIBUTES_INPUT, ELEMENT_MEMBER, LISTENERS_INPUT, childApi, fallthroughDirectiveCode, planFallthrough, planRootElement } from "./fallthrough.js";
5
7
  import { planListeners } from "./listeners.js";
6
8
  import { classMembers } from "./members.js";
7
9
  import { planModels } from "./models.js";
@@ -9,12 +11,13 @@ import { moduleReads } from "./modules.js";
9
11
  import { outputName } from "./outputs.js";
10
12
  import { ANGULAR_MEMBERS, bindingById, formOf, memberOf, moduleMember, planComponent, slotQuery } from "./plan.js";
11
13
  import { classRules } from "./rules.js";
12
- import { fallthroughRoot, template, templateReads } from "./template.js";
14
+ import { directiveModule, importShared } from "./shared.js";
15
+ import { template, templateReads } from "./template.js";
13
16
  import { declaredTypes } from "./types.js";
14
- import { Placeholders, addTypeImports, angularDialect, candidateAttributes, codeKind, codeNames, componentTypes, defineTarget, directiveSpecifier, exportDeclaration, exportsOf, importedDirectives, js, kebabCase, moduleHelperName, ownDirectives, printExpression, printProgram, rewriteCode, scopeRoots, sourceNames, typeDeclarationCode, typeExportsCode, typeNames } from "@unframework.dev/codegen";
17
+ import { Placeholders, addTypeImports, angularDialect, codeKind, codeNames, componentTypes, defineTarget, directiveSpecifier, exportDeclaration, exportsOf, importedDirectives, js, kebabCase, moduleHelperName, ownDirectives, printExpression, printProgram, rewriteCode, scopeRoots, sourceNames, typeDeclarationCode, typeExportsCode, typeNames } from "@unframework.dev/codegen";
15
18
  import { codeOf, functionsOf, walk } from "@unframework.dev/ir";
16
19
  /** The note the emulated cells share: why a listener's option needs a directive. */
17
- const OPTION_NOTE = "A template's `(event)` binding takes no listener options: the file declares an attribute directive per event and option (`[ufClickCapture]`) that listens with `Renderer2.listen` and re-emits the event (ADR-0047).";
20
+ const OPTION_NOTE = "A template's `(event)` binding takes no listener options: an attribute directive per event and option (`[ufClickCapture]`), shared in the tree's `_unframework/`, listens with `Renderer2.listen` and re-emits the event (ADR-0047).";
18
21
  /**
19
22
  * The Angular 22 target: standalone, zoneless components. The host element gets
20
23
  * `display: contents`, so it adds no box of its own (decision D6, ADR-0010). `standalone` and
@@ -83,7 +86,7 @@ const angular = defineTarget({
83
86
  "style-binding": {
84
87
  support: "emulated",
85
88
  helper: "styleObject",
86
- note: "A style bound to a value is Angular's own `[style]`, but where an object spread merges it, on the root that takes a consumer's style and on a component or a `<component is>`, an inline helper splits a declaration list into an object as Vue does (ADR-0065)."
89
+ note: "A style bound to a value is Angular's own `[style]`, but where an object spread merges it, on the root that takes a consumer's style and on a component or a `<component is>`, a shared helper, `styleObject`, splits a declaration list into an object as Vue does (ADR-0065)."
87
90
  },
88
91
  "attribute-spread": { support: "native" },
89
92
  "raw-html": {
@@ -127,12 +130,12 @@ const angular = defineTarget({
127
130
  "model-modifiers": {
128
131
  support: "emulated",
129
132
  helper: "modelText",
130
- note: "A `v-model`'s modifiers and a number control's cast follow Vue's `vModelText` through an inline helper, `modelText` (ADR-0054)."
133
+ note: "A `v-model`'s modifiers and a number control's cast follow Vue's `vModelText` through a shared helper, `modelText` (ADR-0054)."
131
134
  },
132
135
  fallthrough: {
133
136
  support: "emulated",
134
- helper: "fallthrough",
135
- note: "A component that inherits `class` and `style` declares them as inputs, merges them into its root element and clears them from its host, which keeps only `display: contents` (ADR-0056)."
137
+ helper: "Fallthrough",
138
+ note: "Angular has no attribute spread, and a host that carries an attribute is not unwrapped. A component that takes what its consumer passes declares it as inputs, which the consumer binds on the host, and clears `class` and `style` from the host, which keeps only `display: contents` (ADR-0056): `class` and `style` merge into the element that takes them, its root or the props' rest's element, and the other attributes and native listeners come as two records, `ufAttributes` and `ufListeners`, which an attribute directive shared in the tree's `_unframework/`, `Fallthrough` (`[ufFallthrough]`), sets on that element through `Renderer2`, the consumer's attribute winning, and listens to in the browser after the element's own listeners. A root component passes them on to its own (ADR-0118). A hand-written consumer's attribute on the host stays on the host."
136
139
  },
137
140
  "contextual-root": {
138
141
  support: "unsupported",
@@ -140,7 +143,11 @@ const angular = defineTarget({
140
143
  severity: "error",
141
144
  reason: "A root element HTML or ARIA ties to its parent (`li`, `tr`, `option`, …) renders inside Angular's host element, which breaks the parent's content model: axe reports `list` and `listitem`, and the HTML parser moves a host out of a table (ADR-0056)."
142
145
  },
143
- expose: { support: "native" },
146
+ expose: {
147
+ support: "emulated",
148
+ helper: "ufElement",
149
+ note: "`defineExpose` makes the functions public members, which a ref on the component, `viewChild`, reads. A component that exposes nothing declares `ufElement`, a `viewChild` of its root element, `ElementRef<HTMLButtonElement>`, or a `computed` of its root component's own, since its host is no element a ref may hold; the parent's ref is a `computed` of the child's `ufElement`, typed as the source types the element (ADR-0118)."
150
+ },
144
151
  context: { support: "native" },
145
152
  "reactive-context": {
146
153
  support: "emulated",
@@ -157,7 +164,7 @@ const angular = defineTarget({
157
164
  support: "unsupported",
158
165
  code: "UF4003",
159
166
  severity: "info",
160
- reason: "Each root node of a child binds an inline attribute directive, `[ufScope]`, that moves the scope attributes its styled parents put on its host onto the node, so their rules reach it. But the root renders inside its host element, which selectors see: a parent's rule that reaches the root through a combinator (`>`, `+`, `~`) or a structural pseudo-class (`:first-child`, `:nth-child()`, …) matches the host's place, not the root's, and may match differently. A root Angular binds nothing on (`{{` in an attribute, ADR-0037) takes no scope attribute."
167
+ reason: "Each root node of a child binds a shared attribute directive, `ScopeAttributes` (`[ufScope]`), that moves the scope attributes its styled parents put on its host onto the node, so their rules reach it. But the root renders inside its host element, which selectors see: a parent's rule that reaches the root through a combinator (`>`, `+`, `~`) or a structural pseudo-class (`:first-child`, `:nth-child()`, …) matches the host's place, not the root's, and may match differently. A root Angular binds nothing on (`{{` in an attribute, ADR-0037) takes no scope attribute."
161
168
  },
162
169
  "slotted-styles": { support: "native" },
163
170
  "sheet-order": {
@@ -181,7 +188,7 @@ const angular = defineTarget({
181
188
  directive: {
182
189
  support: "emulated",
183
190
  helper: RUNNER_HELPER,
184
- note: "A directive is a standalone attribute directive, `[vFocusTrap]`, whose `afterRenderEffect` passes its value to an inline helper, `runDirective`. Angular creates projected content before a child puts it in the document and keeps it while the child takes it out, so the helper runs `mounted` and `unmounted` as a `MutationObserver` sees the element come and go, and `updated` behind `Object.is`. Angular mounts a parent before a child in its view and a child in an `@if` before its parent, so the hooks go through an inline queue, `queueHook`, which runs them in Vue's order once the turn ends."
191
+ note: "A directive is a standalone attribute directive, `[vFocusTrap]`, whose `afterRenderEffect` passes its value to an inline helper, `runDirective`. Angular creates projected content before a child puts it in the document and keeps it while the child takes it out, so the helper runs `mounted` and `unmounted` as a `MutationObserver` sees the element come and go, and `updated` behind `Object.is`. Angular mounts a parent before a child in its view and a child in an `@if` before its parent, so the hooks go through a shared queue, `queueHook`, which runs them in Vue's order once the turn ends."
185
192
  },
186
193
  transition: {
187
194
  support: "emulated",
@@ -195,15 +202,47 @@ const angular = defineTarget({
195
202
  }
196
203
  },
197
204
  emit(component, context) {
205
+ if (reportsLiteralFallthrough(component, context)) return [];
198
206
  return [emitComponent(component, context)];
199
207
  },
200
208
  emitComposable,
201
209
  emitDirective
202
210
  });
211
+ /**
212
+ * Reports what the component passes a child whose element it would land on Angular prints in a
213
+ * literal region (ADR-0037): Angular binds nothing there, so the child declares no input to take
214
+ * it, and it is not supported yet (UF1002, ADR-0122). Returns whether it reported.
215
+ */
216
+ function reportsLiteralFallthrough(component, context) {
217
+ let reported = false;
218
+ walk(component.render, { enter(node) {
219
+ if (node.kind !== "Component") return;
220
+ const literal = childApi(context.module, node.component)?.literal;
221
+ if (literal === void 0) return;
222
+ for (const attribute of node.attributes) {
223
+ if (![
224
+ "Static",
225
+ "Bound",
226
+ "Event",
227
+ "Class",
228
+ "Style"
229
+ ].includes(attribute.kind)) continue;
230
+ reported = true;
231
+ context.report({
232
+ code: "UF1002",
233
+ severity: "error",
234
+ message: `The angular target does not pass what falls through to ${node.component}'s root yet: its \`${literal}\` attribute holds \`{{\`, so Angular prints the root where it binds nothing (ADR-0037).`,
235
+ span: attribute.span
236
+ });
237
+ }
238
+ } });
239
+ return reported;
240
+ }
203
241
  /** A component's output file. */
204
242
  function emitComponent(component, context) {
205
243
  const { module } = context;
206
- const plan = planComponent(component, module);
244
+ const shares = context.helper !== void 0;
245
+ const plan = planComponent(component, module, shares);
207
246
  const { imports } = plan;
208
247
  const composition = planComposition(plan);
209
248
  for (const [local, selector] of composition.clashes) context.report({
@@ -225,7 +264,10 @@ function emitComponent(component, context) {
225
264
  const nextTick = codeOf(component).some(({ code }) => code.refs.some((reference) => reference.kind === "Api")) ? plan.members.claim("nextTick") : void 0;
226
265
  const rules = classRules(plan, nextTick);
227
266
  const closure = componentTypes(component, module);
228
- const listeners = planListeners(plan, nextTick, models.writes);
267
+ const fallthrough = planFallthrough(component, module);
268
+ const rootElement = planRootElement(component, module);
269
+ const forwards = fallthrough?.passes && fallthrough.target.kind === "Component" ? fallthrough.target : void 0;
270
+ const listeners = planListeners(plan, nextTick, models.writes, forwards);
229
271
  const reads = templateReads(plan, listeners);
230
272
  const templateBindings = [
231
273
  ...reads.read,
@@ -237,21 +279,14 @@ function emitComponent(component, context) {
237
279
  for (const method of listeners.methods) templateMembers.add(method.name);
238
280
  for (const guard of listeners.guards) templateMembers.add(guard);
239
281
  for (const slot of reads.slots) templateMembers.add(slotQuery(slot));
240
- const root = fallthroughRoot(component.render);
241
- const fallthrough = component.inheritAttrs !== false && root !== void 0 && (root.kind === "Component" || (root.kind === "Dynamic" ? root.candidates.every((candidate) => candidate.kind === "Tag" && angularDialect.literalRegion?.({
242
- kind: "Element",
243
- tag: candidate.tag,
244
- attributes: candidateAttributes(root, candidate.tag),
245
- children: root.children,
246
- span: root.span
247
- }) === void 0) : angularDialect.literalRegion?.(root) === void 0));
248
- const clearsHost = fallthrough || component.inheritAttrs === false;
249
- reportApiClashes(component, composition, fallthrough, context);
282
+ const clearsHost = fallthrough !== void 0 || component.inheritAttrs === false;
283
+ reportApiClashes(component, composition, fallthrough, rootElement !== void 0, context);
284
+ const passes = !fallthrough?.passes ? void 0 : shares ? sharedFallthroughNames(plan, fallthrough) : fallthroughNames(component, module, imports, fallthrough.target.kind !== "Component");
250
285
  const refObject = component.setup.some((item) => (item.kind === "Provide" || item.kind === "Inject" && item.fallback) && keyOf(plan, item.key).ref) ? imports.claim("refObject") : void 0;
251
286
  const provided = providers(plan, rules, composition, className, refObject);
252
287
  const nextId = component.setup.some((item) => item.kind === "Id") ? imports.claim("idCounter") : void 0;
253
- const directives = listeners.directives.map((spec) => directiveCode(spec, imports, placeholders));
254
- const trustedHtml = rendersRawHtml(component) ? imports.claim("TrustedHtmlPipe") : void 0;
288
+ const directives = shares ? [] : listeners.directives.map((spec) => directiveCode(spec, imports, placeholders));
289
+ const trustedHtml = rendersRawHtml(component) ? plan.helper("TrustedHtmlPipe") : void 0;
255
290
  const teleport = holdsTeleport(component) ? imports.claim("Teleport") : void 0;
256
291
  const transition = holdsTransition(component) ? {
257
292
  className: imports.claim("Transition"),
@@ -259,16 +294,20 @@ function emitComponent(component, context) {
259
294
  regions: holdsTransition(component, true),
260
295
  ref: plan.members.claim("transition")
261
296
  } : void 0;
297
+ const defaultSlot = hoistedDefaultSlot(component.render) ? { ref: plan.members.claim("defaultSlot") } : void 0;
262
298
  const appliedImports = importedDirectives(component, module).map(({ specifier, imported }) => imports.add(directiveSpecifier(specifier, directiveFile(imported)), directiveClassName(imported), { exact: true }));
263
299
  const ownApplied = ownDirectives(component, module);
264
- const runner = ownApplied.length ? runnerNames((base) => imports.claim(base)) : void 0;
300
+ const runner = ownApplied.length ? runnerNames((base) => base === "queueHook" ? plan.helper(base) : imports.claim(base)) : void 0;
265
301
  const ownClasses = ownApplied.map((directive) => ({
266
302
  directive,
267
303
  className: imports.claim(directiveClassName(directive.name))
268
304
  }));
269
- const roots = scopedRoots(component);
305
+ const roots = scopedRoots(component, fallthrough?.rest === true);
270
306
  const scope = roots.size ? {
271
- ...scopeNames(component, module, imports),
307
+ ...shares ? {
308
+ className: plan.helper("ScopeAttributes"),
309
+ scopes: ""
310
+ } : scopeNames(component, module, imports),
272
311
  host: plan.members.claim("host")
273
312
  } : void 0;
274
313
  const { render } = component;
@@ -288,7 +327,14 @@ function emitComponent(component, context) {
288
327
  ...nextId === void 0 ? {} : { nextId },
289
328
  ...refObject === void 0 ? {} : { refObject },
290
329
  slots: composition.slots,
291
- fallthrough,
330
+ ...fallthrough === void 0 ? {} : { fallthrough: {
331
+ passes: passes !== void 0,
332
+ listeners: passes?.listeners ?? ""
333
+ } },
334
+ ...rootElement === void 0 ? {} : { rootElement: rootElement.root.kind === "Component" ? { component: {
335
+ className: rootElement.root.component,
336
+ query: plan.members.claim("rootComponent")
337
+ } } : { type: rootElement.type } },
292
338
  keyNames: composition.keyNames,
293
339
  external: provided.external,
294
340
  helpers: models.helpers,
@@ -296,10 +342,11 @@ function emitComponent(component, context) {
296
342
  });
297
343
  const metadata = js.objectExpression([
298
344
  ["selector", js.stringLiteral(`uf-${kebabCase(component.name)}`)],
299
- ...composition.imports.length || directives.length || scope || models.textCaret || trustedHtml || teleport || transition || appliedImports.length || ownClasses.length ? [["imports", js.arrayExpression([
345
+ ...composition.imports.length || directives.length || scope || passes?.directive !== void 0 || models.textCaret || trustedHtml || teleport || transition || appliedImports.length || ownClasses.length ? [["imports", js.arrayExpression([
300
346
  ...composition.imports,
301
347
  ...listeners.directives.map(({ className: name }) => name),
302
348
  ...scope ? [scope.className] : [],
349
+ ...passes?.directive === void 0 ? [] : [passes.directive],
303
350
  ...models.textCaret === void 0 ? [] : [models.textCaret],
304
351
  ...trustedHtml === void 0 ? [] : [trustedHtml],
305
352
  ...teleport === void 0 ? [] : [teleport],
@@ -310,10 +357,13 @@ function emitComponent(component, context) {
310
357
  ...provided.code.length ? [["providers", js.arrayExpression(provided.code.map((code) => placeholders.expression(code)))]] : [],
311
358
  ["host", clearsHost ? js.objectExpression([["[attr.class]", js.stringLiteral("null")], ["[attr.style]", js.stringLiteral("'display: contents;'")]]) : js.objectExpression([["style", js.stringLiteral("display: contents")]])],
312
359
  ["preserveWhitespaces", js.booleanLiteral(false)],
313
- ["template", js.templateLiteral(`\n${template(plan, listeners, reads, composition, models, fallthrough, scope && {
360
+ ["template", js.templateLiteral(`\n${template(plan, listeners, reads, composition, models, {
361
+ ...fallthrough === void 0 ? {} : { plan: fallthrough },
362
+ ...rootElement === void 0 ? {} : { rootElement }
363
+ }, scope && {
314
364
  roots,
315
365
  host: scope.host
316
- }, teleportHost, transition)}\n `)],
366
+ }, teleportHost, transition, defaultSlot)}\n `)],
317
367
  ...component.styles ? [["styleUrl", js.stringLiteral(`./${module.file.slice(module.file.lastIndexOf("/") + 1)}.css`)], ["encapsulation", js.memberExpression(js.identifier(imports.add("@angular/core", "ViewEncapsulation")), "None")]] : []
318
368
  ]);
319
369
  const decorator = () => `@${printExpression(js.callExpression(js.identifier(decoratorName), [metadata]))}`;
@@ -344,17 +394,54 @@ function emitComponent(component, context) {
344
394
  const declarations = [
345
395
  ...composition.keys.map((key) => `export const ${key.name} = new ${imports.add("@angular/core", "InjectionToken")}<${tokenType(key)}>(${JSON.stringify(key.description)});\n`),
346
396
  ...refObject === void 0 ? [] : [refObjectCode(refObject)],
347
- ...[...models.helpers, ...models.support].map(({ code }) => `${code}\n`),
397
+ ...[...models.helpers, ...models.support].filter(({ shared }) => shared === void 0).map(({ code }) => `${code}\n`),
348
398
  ...composition.slots.map((slot) => slotDirectiveCode(component.name, slot, imports.add("@angular/core", "Directive"), component.typeParameters)),
349
- ...scope ? [scopeDirectiveCode(scope, imports)] : [],
350
- ...models.textCaret === void 0 ? [] : [textCaretDirectiveCode(models.textCaret, imports)],
351
- ...trustedHtml === void 0 ? [] : [trustedHtmlPipeCode(trustedHtml, imports)],
399
+ ...scope && !shares ? [scopeDirectiveCode(scope, imports)] : [],
400
+ ...passes === void 0 || shares ? [] : [fallthroughDirectiveCode(passes, fallthrough.events, (name, type = false) => imports.add("@angular/core", name, { type }), (name) => imports.add("@angular/common", name))],
401
+ ...models.textCaret === void 0 || shares ? [] : [textCaretDirectiveCode(models.textCaret, imports)],
402
+ ...trustedHtml === void 0 || shares ? [] : [trustedHtmlPipeCode(trustedHtml, imports)],
352
403
  ...teleport === void 0 ? [] : [teleportDirectiveCode(teleport, imports)],
353
404
  ...transition === void 0 ? [] : [transitionRegionCode(transition.regionClass, imports), transitionDirectiveCode(transition.className, transition.regionClass, imports)],
354
- ...runner === void 0 ? [] : runnerCode(runner),
405
+ ...runner === void 0 ? [] : runnerCode(runner, !shares),
355
406
  ...ownClasses.map(({ directive, className: name }) => directiveClassCode(directive, name, runner?.run ?? "runDirective", imports))
356
407
  ];
357
408
  if (models.helpers.some(({ code }) => code.includes("WritableSignal"))) imports.add("@angular/core", "WritableSignal", { type: true });
409
+ const path = `${kebabCase(component.name)}.ts`;
410
+ if (context.helper) importShared(context.helper, path, imports, [
411
+ ...listeners.directives.map((spec) => ({
412
+ name: spec.name,
413
+ local: spec.className,
414
+ contents: directiveModule(spec)
415
+ })),
416
+ ...scope ? [{
417
+ name: "ScopeAttributes",
418
+ local: scope.className
419
+ }] : [],
420
+ ...passes === void 0 ? [] : [{
421
+ name: listenersExport(fallthrough),
422
+ local: passes.listeners,
423
+ type: true
424
+ }, ...passes.directive === void 0 ? [] : [{
425
+ name: "Fallthrough",
426
+ local: passes.directive
427
+ }]],
428
+ ...models.helpers.flatMap(({ name, shared }) => shared === void 0 ? [] : [{
429
+ name: shared,
430
+ local: name
431
+ }]),
432
+ ...models.textCaret === void 0 ? [] : [{
433
+ name: "TextCaret",
434
+ local: models.textCaret
435
+ }],
436
+ ...trustedHtml === void 0 ? [] : [{
437
+ name: "TrustedHtmlPipe",
438
+ local: trustedHtml
439
+ }],
440
+ ...runner === void 0 ? [] : [{
441
+ name: QUEUE_HELPER,
442
+ local: runner.queue
443
+ }]
444
+ ]);
358
445
  addTypeImports(component, module, imports, kebabCase);
359
446
  const own = new Set(types.map(({ name }) => name));
360
447
  const constants = moduleReads(component.bindings, module, imports, kebabCase);
@@ -363,19 +450,18 @@ function emitComponent(component, context) {
363
450
  span: type.span
364
451
  })), ...typeExportsCode(component, module, kebabCase)].toSorted((a, b) => a.span.start - b.span.start);
365
452
  const idCounter = nextId === void 0 ? void 0 : `const ${nextId} = new ${imports.add("@angular/core", "InjectionToken")}<{ next: number }>("${nextId}", {\n factory: () => ({ next: 0 }),\n});\n`;
366
- const contents = placeholders.print(() => [
367
- printProgram(js.program(imports.toDeclarations())),
368
- ...typeCode.map(({ code }) => `${code}\n`),
369
- ...constants.constants.length ? [`${constants.constants.join("\n")}\n`] : [],
370
- ...idCounter === void 0 ? [] : [idCounter],
371
- ...declarations,
372
- ...directives.map(({ decorator: written, statements: declared }) => `${written}\n${spaced(printProgram(js.program(declared)))}`),
373
- decorator(),
374
- spaced(printProgram(js.program(statements)))
375
- ].join("\n"));
376
453
  return {
377
- path: `${kebabCase(component.name)}.ts`,
378
- contents
454
+ path,
455
+ contents: placeholders.print(() => [
456
+ printProgram(js.program(imports.toDeclarations())),
457
+ ...typeCode.map(({ code }) => `${code}\n`),
458
+ ...constants.constants.length ? [`${constants.constants.join("\n")}\n`] : [],
459
+ ...idCounter === void 0 ? [] : [idCounter],
460
+ ...declarations,
461
+ ...directives.map(({ decorator: written, statements: declared }) => `${written}\n${spaced(printProgram(js.program(declared)))}`),
462
+ decorator(),
463
+ spaced(printProgram(js.program(statements)))
464
+ ].join("\n"))
379
465
  };
380
466
  }
381
467
  /** Whether an element of the component's template sets `innerHTML` (ADR-0097). */
@@ -412,33 +498,68 @@ function spanKey({ start, end }) {
412
498
  /**
413
499
  * The component's root nodes that take its styled parents' scope attributes (`scopeRoots`, the
414
500
  * child-root rule, ADR-0063), by {@link spanKey}: all but an element Angular binds nothing on
415
- * (`{{` in an attribute, ADR-0037), which takes no fallthrough either.
501
+ * (`{{` in an attribute, ADR-0037), which takes no fallthrough either. A component that spreads
502
+ * its props' rest keeps them on its root, as it would without `inheritAttrs: false`: the rest
503
+ * takes everything else its consumer passes (ADR-0118).
416
504
  */
417
- function scopedRoots(component) {
418
- const roots = new Set(scopeRoots(component).map(spanKey));
505
+ function scopedRoots(component, rest) {
506
+ const { inheritAttrs: _, ...inheriting } = component;
507
+ const roots = new Set(scopeRoots(rest ? inheriting : component).map(spanKey));
419
508
  walk(component.render, { enter(node) {
420
509
  if (node.kind === "Element" && angularDialect.literalRegion?.(node) !== void 0) roots.delete(spanKey(node.span));
421
510
  } });
422
511
  return roots;
423
512
  }
513
+ /** The names of the scope directive's code, claimed as {@link helperClaim} does. */
514
+ function scopeNames(component, module, imports) {
515
+ const claim = helperClaim(component, module, imports);
516
+ return {
517
+ className: claim("ScopeAttributes"),
518
+ scopes: claim("scopes")
519
+ };
520
+ }
424
521
  /**
425
- * The names of the scope directive's code. A source's components are joined into one module
426
- * where it is loaded (ADR-0053): each claims them from bases of its own (`ScopeAttributes_1`),
522
+ * The names of the fallthrough directive's code (ADR-0118), claimed as the scope directive's
523
+ * are: the type of the listeners' record, and the directive, where an element takes the records
524
+ * (a root component takes them through its own inputs).
525
+ */
526
+ function fallthroughNames(component, module, imports, directive) {
527
+ const claim = helperClaim(component, module, imports);
528
+ const listeners = claim("Listeners");
529
+ return directive ? {
530
+ listeners,
531
+ directive: claim("Fallthrough")
532
+ } : { listeners };
533
+ }
534
+ /** The export name of the listeners' type the component's records take, in `_unframework/`. */
535
+ function listenersExport(fallthrough) {
536
+ return fallthrough.events === "SVGElementEventMap" ? "SvgListeners" : "Listeners";
537
+ }
538
+ /**
539
+ * The local names of the shared fallthrough directive and its listeners' type (ADR-0121), as
540
+ * `plan.helper` claims them: one per source, so the join writes one import (A3).
541
+ */
542
+ function sharedFallthroughNames(plan, fallthrough) {
543
+ const listeners = plan.helper(listenersExport(fallthrough));
544
+ return fallthrough.target.kind !== "Component" ? {
545
+ listeners,
546
+ directive: plan.helper("Fallthrough")
547
+ } : { listeners };
548
+ }
549
+ /**
550
+ * Claims a helper's name in the component's file. A source's components are joined into one
551
+ * module where it is loaded (ADR-0053): each claims from bases of its own (`ScopeAttributes_1`),
427
552
  * past the names any other component declares.
428
553
  */
429
- function scopeNames(component, module, imports) {
554
+ function helperClaim(component, module, imports) {
430
555
  const index = module.components.findIndex((each) => each.name === component.name);
431
556
  const reserved = module.components.map((each) => sourceNames(each, module));
432
- const claim = (helper) => {
557
+ return (helper) => {
433
558
  const { base, others } = moduleHelperName(helper, reserved, index);
434
559
  imports.reserve(...others);
435
560
  imports.scope.rebase(helper, base);
436
561
  return imports.claim(helper);
437
562
  };
438
- return {
439
- className: claim("ScopeAttributes"),
440
- scopes: claim("scopes")
441
- };
442
563
  }
443
564
  /**
444
565
  * Reports each name of the component's API that another name of it takes on Angular (UF2003).
@@ -449,7 +570,7 @@ function scopeNames(component, module, imports) {
449
570
  * so a clash is reported at the later declaration rather than renamed. A binding is no API:
450
571
  * ./plan.ts renames it.
451
572
  */
452
- function reportApiClashes(component, composition, fallthrough, context) {
573
+ function reportApiClashes(component, composition, fallthrough, rootElement, context) {
453
574
  const taken = /* @__PURE__ */ new Map();
454
575
  const key = ({ space, name }) => `${space} ${name}`;
455
576
  const declare = (names) => {
@@ -480,6 +601,20 @@ function reportApiClashes(component, composition, fallthrough, context) {
480
601
  what
481
602
  }]);
482
603
  }
604
+ if (fallthrough?.passes) for (const [name, what] of [[ATTRIBUTES_INPUT, "the input of the consumer's attributes"], [LISTENERS_INPUT, "the input of the consumer's listeners"]]) declare([{
605
+ space: "member",
606
+ name,
607
+ what
608
+ }, {
609
+ space: "input",
610
+ name,
611
+ what
612
+ }]);
613
+ if (rootElement) declare([{
614
+ space: "member",
615
+ name: ELEMENT_MEMBER,
616
+ what: "the member that holds the root element a ref on the component holds"
617
+ }]);
483
618
  const source = [
484
619
  ...component.props.map(({ name, span }) => {
485
620
  const what = `the prop \`${name}\``;
@@ -636,13 +771,4 @@ function typeParameters(component, placeholders) {
636
771
  end: 0
637
772
  };
638
773
  }
639
- /**
640
- * A printed class with a blank line before each of its methods, as Angular code sets them apart
641
- * from the fields and from each other (oxfmt keeps a blank line, and adds none). Read before the
642
- * placeholders are spliced: a member starts at the class's indentation, and a method's line ends
643
- * with its body's `{` where a field's holds ` = `.
644
- */
645
- function spaced(printed) {
646
- return printed.replace(/\n(?= {2}[^\s}][^\n]*\{\n)(?! {2}[^\n]* = )/g, "\n\n");
647
- }
648
774
  export { angular, angular as default };
package/dist/listeners.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { childEvent } from "./composition.js";
2
+ import { LISTENERS_INPUT } from "./fallthrough.js";
2
3
  import { assertedCode, assertedFunction } from "./narrowing.js";
3
4
  import { bindingById, formOf, isLoopVariable, resultApi, unreachable } from "./plan.js";
4
- import { classRules, statementRead, statementRules } from "./rules.js";
5
+ import { classRead, classRules, statementRead, statementRules } from "./rules.js";
5
6
  import { bodyStatements, returnsValue } from "./statements.js";
6
7
  import { angularCode, parameterText, parseExpression, parseStatementsSource, pascalCase, rewriteCode } from "@unframework.dev/codegen";
7
8
  import { DOM_EVENTS, walk } from "@unframework.dev/ir";
@@ -9,7 +10,7 @@ import { DOM_EVENTS, walk } from "@unframework.dev/ir";
9
10
  * Plans every listener of a component's template, in document order. A native `v-model`'s write
10
11
  * runs first in the template listener of the attribute `writes` gives it (./models.ts).
11
12
  */
12
- function planListeners(plan, nextTick, writes) {
13
+ function planListeners(plan, nextTick, writes, forwards) {
13
14
  const { component } = plan;
14
15
  const statements = /* @__PURE__ */ new Map();
15
16
  const outputs = /* @__PURE__ */ new Map();
@@ -64,6 +65,7 @@ function planListeners(plan, nextTick, writes) {
64
65
  const event = childEvent(plan, child, attribute.event);
65
66
  outputs.set(attribute, outputStatement(plan, attribute, event, methods, collected));
66
67
  }
68
+ if (node.kind === "Component") onComponent(node);
67
69
  return;
68
70
  }
69
71
  const element = node.kind === "Element" ? node : node.kind === "Dynamic" && node.candidates[0]?.kind === "Tag" ? {
@@ -77,6 +79,32 @@ function planListeners(plan, nextTick, writes) {
77
79
  onElement(element);
78
80
  }
79
81
  });
82
+ /**
83
+ * A child's native listeners, which fall through to its element (ADR-0118): each is a template
84
+ * statement the child's `ufListeners` record runs in an arrow, written as an element's is. On
85
+ * the root component of a component that passes its own consumer's listeners on, each calls a
86
+ * method that runs it and then the consumer's listener of its event (`chainStatement`).
87
+ */
88
+ function onComponent(node) {
89
+ const element = {
90
+ kind: "Element",
91
+ tag: node.component,
92
+ attributes: node.attributes.filter((attribute) => attribute.kind === "Static"),
93
+ children: [],
94
+ span: node.span
95
+ };
96
+ const chains = forwards !== void 0 && forwards.span.start === node.span.start && forwards.span.end === node.span.end;
97
+ for (const attribute of node.attributes) {
98
+ if (attribute.kind !== "Event") continue;
99
+ const name = () => handlerName(plan, element, attribute.event, void 0);
100
+ if (chains) {
101
+ statements.set(attribute, chainStatement(plan, attribute, name(), methods, collected));
102
+ continue;
103
+ }
104
+ const { code, valued } = listenerStatement(plan, attribute, name, methods, collected);
105
+ statements.set(attribute, valued ? `void ${code}` : code);
106
+ }
107
+ }
80
108
  function onElement(node) {
81
109
  const groups = orderedGroups(node, writes);
82
110
  for (const attribute of node.attributes) {
@@ -105,7 +133,8 @@ function planListeners(plan, nextTick, writes) {
105
133
  event: attribute.event,
106
134
  option,
107
135
  output,
108
- className: plan.imports.claim(`${pascalCase(attribute.event)}${pascalCase(option)}`),
136
+ name: `${pascalCase(attribute.event)}${pascalCase(option)}`,
137
+ className: plan.helper(`${pascalCase(attribute.event)}${pascalCase(option)}`),
109
138
  eventType: DOM_EVENTS.get(attribute.event) ?? "Event"
110
139
  };
111
140
  directives.set(output, directive);
@@ -210,6 +239,50 @@ function listenerStatement(plan, attribute, methodName, methods, collected) {
210
239
  }
211
240
  }
212
241
  /**
242
+ * The statement of a native listener a component passes its root component, where its own
243
+ * consumer's listeners pass on to that component too (ADR-0118): a call of a method that runs
244
+ * the listener's handler, then the consumer's listener of its event, as Vue's merge runs them
245
+ * (`onBaseClick($event)`). A handler that awaits or destructures its event is a method of its
246
+ * own, which the chain calls, so the consumer's still runs as the handler's first await starts.
247
+ */
248
+ function chainStatement(plan, attribute, name, methods, collected) {
249
+ const { handler, event } = attribute;
250
+ const type = DOM_EVENTS.get(event) ?? "Event";
251
+ const key = /^[A-Za-z_$][\w$]*$/.test(event) ? `.${event}` : `.[${JSON.stringify(event)}]`;
252
+ const consumer = (parameter) => `this.${LISTENERS_INPUT}()?${key}?.(${parameter});`;
253
+ const chain = (parameter, own, typed = `${parameter}: ${type}`) => {
254
+ methods.push({
255
+ name,
256
+ parameters: [typed],
257
+ async: false,
258
+ body: `${own}\n${consumer(parameter)}`
259
+ });
260
+ return `${name}($event)`;
261
+ };
262
+ switch (handler.kind) {
263
+ case "Function": {
264
+ const fn = functionOf(plan.component, handler.binding);
265
+ const parameter = plan.locals.claim("event");
266
+ const call = `${classRead(plan, bindingById(plan, handler.binding))}(${fn.parameters[0]?.event === void 0 ? "" : parameter})`;
267
+ return chain(parameter, `${fn.async ? "void " : ""}${call};`);
268
+ }
269
+ case "Inline": {
270
+ const fn = handler.function;
271
+ const [first] = fn.parameters;
272
+ const body = bodyStatements(assertedFunction(fn, () => true), plan, classRules(plan, collected.nextTick));
273
+ if (!fn.async && (first === void 0 || first.name !== void 0)) {
274
+ if (first?.name === void 0) return chain(plan.locals.claim("event"), body);
275
+ return chain(first.name, body, first.type ? parameterText(first) : void 0);
276
+ }
277
+ const own = plan.members.claim(`${name}Handler`);
278
+ methods.push(hoisted(own, fn, event, body));
279
+ const parameter = plan.locals.claim("event");
280
+ return chain(parameter, `void this.${own}(${first === void 0 ? "" : parameter});`);
281
+ }
282
+ default: return unreachable(handler);
283
+ }
284
+ }
285
+ /**
213
286
  * The name of the method a handler moves to, `on` and what the element says it is
214
287
  * (`elementSubject`), with its option's name for a listener of a group (`onGoOnce`), or, for an
215
288
  * element that says nothing, the event and its option (`onClickCapture`).
@@ -257,13 +330,13 @@ function staticValue(element, name) {
257
330
  /** An element's text, when its children are text alone. */
258
331
  function textOf(element) {
259
332
  const { children } = element;
260
- if (!children.length || !children.every((child) => child.kind === "Text")) return void 0;
333
+ if (!children.length || !children.every((child) => child.kind === "Text")) return;
261
334
  return children.map((child) => child.kind === "Text" ? child.value : "").join("");
262
335
  }
263
336
  /** Up to four ASCII words in PascalCase (`Add one` → `AddOne`), or `undefined`. */
264
337
  function words(text) {
265
338
  const found = text?.match(/[A-Za-z0-9]+/g);
266
- if (!found || found.length > 4) return void 0;
339
+ if (!found || found.length > 4) return;
267
340
  return found.map((word) => `${word[0].toUpperCase()}${word.slice(1).toLowerCase()}`).join("");
268
341
  }
269
342
  /** The function a setup function's binding names. */
@@ -293,8 +366,8 @@ function visitAst(root, visit) {
293
366
  */
294
367
  function templateStatement(plan, fn, { reads, members, globals, tested }, payload = ["$event"]) {
295
368
  const call = singleCall(fn.body, fn.expression === true);
296
- if (!call) return void 0;
297
- if (fn.parameters.some((parameter) => parameter.name === void 0)) return void 0;
369
+ if (!call) return;
370
+ if (fn.parameters.some((parameter) => parameter.name === void 0)) return;
298
371
  const refs = fn.body.refs;
299
372
  const readsLoop = refs.some((reference) => reference.kind === "Binding" && isLoopVariable(bindingById(plan, reference.binding).kind));
300
373
  const readsTested = refs.some((reference) => reference.kind === "Binding" && tested.has(reference.binding) && formOf(plan, bindingById(plan, reference.binding)) === "input");
@@ -336,10 +409,10 @@ function singleCall(body, expression) {
336
409
  const block = statements[0];
337
410
  const inner = statements.length === 1 && block?.type === "BlockStatement" ? block.body : [];
338
411
  const [only] = inner;
339
- if (inner.length !== 1 || only?.type !== "ExpressionStatement") return void 0;
412
+ if (inner.length !== 1 || only?.type !== "ExpressionStatement") return;
340
413
  node = only.expression;
341
414
  }
342
- if (node.type !== "CallExpression" || node.optional) return void 0;
415
+ if (node.type !== "CallExpression" || node.optional) return;
343
416
  const callee = node.callee;
344
417
  const args = node.arguments;
345
418
  if (callee.type !== "Identifier" || args.some((arg) => arg.type === "SpreadElement")) return;
@@ -349,7 +422,7 @@ function singleCall(body, expression) {
349
422
  const callRef = body.refs.find((reference) => reference.span.start === start);
350
423
  const callsFunction = callRef?.kind === "Binding" && callRef.call === true && callRef.span.end === offset + callee.end;
351
424
  const emits = callRef?.kind === "Emit" && callRef.span.end === end;
352
- if (!callsFunction && !emits) return void 0;
425
+ if (!callsFunction && !emits) return;
353
426
  return {
354
427
  code: body.code.slice(node.start, node.end),
355
428
  span: {
@@ -444,7 +517,8 @@ function simpleRead(plan, reference) {
444
517
  case "Import":
445
518
  case "Slot":
446
519
  case "Write":
447
- case "Api": return false;
520
+ case "Api":
521
+ case "Dev": return false;
448
522
  default: return unreachable(reference);
449
523
  }
450
524
  }