@unframework.dev/target-angular 0.3.0 → 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/index.js CHANGED
@@ -1,7 +1,8 @@
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 { QUEUE_HELPER, RUNNER_HELPER, directiveClassCode, directiveClassName, directiveFile, emitDirective, runnerCode, runnerNames } from "./directive.js";
4
+ import { directiveCode, scopeDirectiveCode, spaced, teleportDirectiveCode, textCaretDirectiveCode, transitionDirectiveCode, transitionRegionCode, trustedHtmlPipeCode } from "./directives.js";
5
+ import { ATTRIBUTES_INPUT, ELEMENT_MEMBER, LISTENERS_INPUT, childApi, fallthroughDirectiveCode, planFallthrough, planRootElement } from "./fallthrough.js";
5
6
  import { planListeners } from "./listeners.js";
6
7
  import { classMembers } from "./members.js";
7
8
  import { planModels } from "./models.js";
@@ -9,12 +10,13 @@ import { moduleReads } from "./modules.js";
9
10
  import { outputName } from "./outputs.js";
10
11
  import { ANGULAR_MEMBERS, bindingById, formOf, memberOf, moduleMember, planComponent, slotQuery } from "./plan.js";
11
12
  import { classRules } from "./rules.js";
12
- import { fallthroughRoot, template, templateReads } from "./template.js";
13
+ import { directiveModule, importShared } from "./shared.js";
14
+ import { template, templateReads } from "./template.js";
13
15
  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";
16
+ 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
17
  import { codeOf, functionsOf, walk } from "@unframework.dev/ir";
16
18
  /** 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).";
19
+ 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
20
  /**
19
21
  * The Angular 22 target: standalone, zoneless components. The host element gets
20
22
  * `display: contents`, so it adds no box of its own (decision D6, ADR-0010). `standalone` and
@@ -83,7 +85,7 @@ const angular = defineTarget({
83
85
  "style-binding": {
84
86
  support: "emulated",
85
87
  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)."
88
+ 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
89
  },
88
90
  "attribute-spread": { support: "native" },
89
91
  "raw-html": {
@@ -127,12 +129,12 @@ const angular = defineTarget({
127
129
  "model-modifiers": {
128
130
  support: "emulated",
129
131
  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)."
132
+ note: "A `v-model`'s modifiers and a number control's cast follow Vue's `vModelText` through a shared helper, `modelText` (ADR-0054)."
131
133
  },
132
134
  fallthrough: {
133
135
  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)."
136
+ helper: "Fallthrough",
137
+ 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
138
  },
137
139
  "contextual-root": {
138
140
  support: "unsupported",
@@ -140,7 +142,11 @@ const angular = defineTarget({
140
142
  severity: "error",
141
143
  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
144
  },
143
- expose: { support: "native" },
145
+ expose: {
146
+ support: "emulated",
147
+ helper: "ufElement",
148
+ 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)."
149
+ },
144
150
  context: { support: "native" },
145
151
  "reactive-context": {
146
152
  support: "emulated",
@@ -157,7 +163,7 @@ const angular = defineTarget({
157
163
  support: "unsupported",
158
164
  code: "UF4003",
159
165
  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."
166
+ 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
167
  },
162
168
  "slotted-styles": { support: "native" },
163
169
  "sheet-order": {
@@ -181,7 +187,7 @@ const angular = defineTarget({
181
187
  directive: {
182
188
  support: "emulated",
183
189
  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."
190
+ 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
191
  },
186
192
  transition: {
187
193
  support: "emulated",
@@ -195,15 +201,47 @@ const angular = defineTarget({
195
201
  }
196
202
  },
197
203
  emit(component, context) {
204
+ if (reportsLiteralFallthrough(component, context)) return [];
198
205
  return [emitComponent(component, context)];
199
206
  },
200
207
  emitComposable,
201
208
  emitDirective
202
209
  });
210
+ /**
211
+ * Reports what the component passes a child whose element it would land on Angular prints in a
212
+ * literal region (ADR-0037): Angular binds nothing there, so the child declares no input to take
213
+ * it, and it is not supported yet (UF1002, ADR-0122). Returns whether it reported.
214
+ */
215
+ function reportsLiteralFallthrough(component, context) {
216
+ let reported = false;
217
+ walk(component.render, { enter(node) {
218
+ if (node.kind !== "Component") return;
219
+ const literal = childApi(context.module, node.component)?.literal;
220
+ if (literal === void 0) return;
221
+ for (const attribute of node.attributes) {
222
+ if (![
223
+ "Static",
224
+ "Bound",
225
+ "Event",
226
+ "Class",
227
+ "Style"
228
+ ].includes(attribute.kind)) continue;
229
+ reported = true;
230
+ context.report({
231
+ code: "UF1002",
232
+ severity: "error",
233
+ 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).`,
234
+ span: attribute.span
235
+ });
236
+ }
237
+ } });
238
+ return reported;
239
+ }
203
240
  /** A component's output file. */
204
241
  function emitComponent(component, context) {
205
242
  const { module } = context;
206
- const plan = planComponent(component, module);
243
+ const shares = context.helper !== void 0;
244
+ const plan = planComponent(component, module, shares);
207
245
  const { imports } = plan;
208
246
  const composition = planComposition(plan);
209
247
  for (const [local, selector] of composition.clashes) context.report({
@@ -225,7 +263,10 @@ function emitComponent(component, context) {
225
263
  const nextTick = codeOf(component).some(({ code }) => code.refs.some((reference) => reference.kind === "Api")) ? plan.members.claim("nextTick") : void 0;
226
264
  const rules = classRules(plan, nextTick);
227
265
  const closure = componentTypes(component, module);
228
- const listeners = planListeners(plan, nextTick, models.writes);
266
+ const fallthrough = planFallthrough(component, module);
267
+ const rootElement = planRootElement(component, module);
268
+ const forwards = fallthrough?.passes && fallthrough.target.kind === "Component" ? fallthrough.target : void 0;
269
+ const listeners = planListeners(plan, nextTick, models.writes, forwards);
229
270
  const reads = templateReads(plan, listeners);
230
271
  const templateBindings = [
231
272
  ...reads.read,
@@ -237,21 +278,14 @@ function emitComponent(component, context) {
237
278
  for (const method of listeners.methods) templateMembers.add(method.name);
238
279
  for (const guard of listeners.guards) templateMembers.add(guard);
239
280
  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);
281
+ const clearsHost = fallthrough !== void 0 || component.inheritAttrs === false;
282
+ reportApiClashes(component, composition, fallthrough, rootElement !== void 0, context);
283
+ const passes = !fallthrough?.passes ? void 0 : shares ? sharedFallthroughNames(plan, fallthrough) : fallthroughNames(component, module, imports, fallthrough.target.kind !== "Component");
250
284
  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
285
  const provided = providers(plan, rules, composition, className, refObject);
252
286
  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;
287
+ const directives = shares ? [] : listeners.directives.map((spec) => directiveCode(spec, imports, placeholders));
288
+ const trustedHtml = rendersRawHtml(component) ? plan.helper("TrustedHtmlPipe") : void 0;
255
289
  const teleport = holdsTeleport(component) ? imports.claim("Teleport") : void 0;
256
290
  const transition = holdsTransition(component) ? {
257
291
  className: imports.claim("Transition"),
@@ -261,14 +295,17 @@ function emitComponent(component, context) {
261
295
  } : void 0;
262
296
  const appliedImports = importedDirectives(component, module).map(({ specifier, imported }) => imports.add(directiveSpecifier(specifier, directiveFile(imported)), directiveClassName(imported), { exact: true }));
263
297
  const ownApplied = ownDirectives(component, module);
264
- const runner = ownApplied.length ? runnerNames((base) => imports.claim(base)) : void 0;
298
+ const runner = ownApplied.length ? runnerNames((base) => base === "queueHook" ? plan.helper(base) : imports.claim(base)) : void 0;
265
299
  const ownClasses = ownApplied.map((directive) => ({
266
300
  directive,
267
301
  className: imports.claim(directiveClassName(directive.name))
268
302
  }));
269
- const roots = scopedRoots(component);
303
+ const roots = scopedRoots(component, fallthrough?.rest === true);
270
304
  const scope = roots.size ? {
271
- ...scopeNames(component, module, imports),
305
+ ...shares ? {
306
+ className: plan.helper("ScopeAttributes"),
307
+ scopes: ""
308
+ } : scopeNames(component, module, imports),
272
309
  host: plan.members.claim("host")
273
310
  } : void 0;
274
311
  const { render } = component;
@@ -288,7 +325,14 @@ function emitComponent(component, context) {
288
325
  ...nextId === void 0 ? {} : { nextId },
289
326
  ...refObject === void 0 ? {} : { refObject },
290
327
  slots: composition.slots,
291
- fallthrough,
328
+ ...fallthrough === void 0 ? {} : { fallthrough: {
329
+ passes: passes !== void 0,
330
+ listeners: passes?.listeners ?? ""
331
+ } },
332
+ ...rootElement === void 0 ? {} : { rootElement: rootElement.root.kind === "Component" ? { component: {
333
+ className: rootElement.root.component,
334
+ query: plan.members.claim("rootComponent")
335
+ } } : { type: rootElement.type } },
292
336
  keyNames: composition.keyNames,
293
337
  external: provided.external,
294
338
  helpers: models.helpers,
@@ -296,10 +340,11 @@ function emitComponent(component, context) {
296
340
  });
297
341
  const metadata = js.objectExpression([
298
342
  ["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([
343
+ ...composition.imports.length || directives.length || scope || passes?.directive !== void 0 || models.textCaret || trustedHtml || teleport || transition || appliedImports.length || ownClasses.length ? [["imports", js.arrayExpression([
300
344
  ...composition.imports,
301
345
  ...listeners.directives.map(({ className: name }) => name),
302
346
  ...scope ? [scope.className] : [],
347
+ ...passes?.directive === void 0 ? [] : [passes.directive],
303
348
  ...models.textCaret === void 0 ? [] : [models.textCaret],
304
349
  ...trustedHtml === void 0 ? [] : [trustedHtml],
305
350
  ...teleport === void 0 ? [] : [teleport],
@@ -310,7 +355,10 @@ function emitComponent(component, context) {
310
355
  ...provided.code.length ? [["providers", js.arrayExpression(provided.code.map((code) => placeholders.expression(code)))]] : [],
311
356
  ["host", clearsHost ? js.objectExpression([["[attr.class]", js.stringLiteral("null")], ["[attr.style]", js.stringLiteral("'display: contents;'")]]) : js.objectExpression([["style", js.stringLiteral("display: contents")]])],
312
357
  ["preserveWhitespaces", js.booleanLiteral(false)],
313
- ["template", js.templateLiteral(`\n${template(plan, listeners, reads, composition, models, fallthrough, scope && {
358
+ ["template", js.templateLiteral(`\n${template(plan, listeners, reads, composition, models, {
359
+ ...fallthrough === void 0 ? {} : { plan: fallthrough },
360
+ ...rootElement === void 0 ? {} : { rootElement }
361
+ }, scope && {
314
362
  roots,
315
363
  host: scope.host
316
364
  }, teleportHost, transition)}\n `)],
@@ -344,17 +392,54 @@ function emitComponent(component, context) {
344
392
  const declarations = [
345
393
  ...composition.keys.map((key) => `export const ${key.name} = new ${imports.add("@angular/core", "InjectionToken")}<${tokenType(key)}>(${JSON.stringify(key.description)});\n`),
346
394
  ...refObject === void 0 ? [] : [refObjectCode(refObject)],
347
- ...[...models.helpers, ...models.support].map(({ code }) => `${code}\n`),
395
+ ...[...models.helpers, ...models.support].filter(({ shared }) => shared === void 0).map(({ code }) => `${code}\n`),
348
396
  ...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)],
397
+ ...scope && !shares ? [scopeDirectiveCode(scope, imports)] : [],
398
+ ...passes === void 0 || shares ? [] : [fallthroughDirectiveCode(passes, fallthrough.events, (name, type = false) => imports.add("@angular/core", name, { type }), (name) => imports.add("@angular/common", name))],
399
+ ...models.textCaret === void 0 || shares ? [] : [textCaretDirectiveCode(models.textCaret, imports)],
400
+ ...trustedHtml === void 0 || shares ? [] : [trustedHtmlPipeCode(trustedHtml, imports)],
352
401
  ...teleport === void 0 ? [] : [teleportDirectiveCode(teleport, imports)],
353
402
  ...transition === void 0 ? [] : [transitionRegionCode(transition.regionClass, imports), transitionDirectiveCode(transition.className, transition.regionClass, imports)],
354
- ...runner === void 0 ? [] : runnerCode(runner),
403
+ ...runner === void 0 ? [] : runnerCode(runner, !shares),
355
404
  ...ownClasses.map(({ directive, className: name }) => directiveClassCode(directive, name, runner?.run ?? "runDirective", imports))
356
405
  ];
357
406
  if (models.helpers.some(({ code }) => code.includes("WritableSignal"))) imports.add("@angular/core", "WritableSignal", { type: true });
407
+ const path = `${kebabCase(component.name)}.ts`;
408
+ if (context.helper) importShared(context.helper, path, imports, [
409
+ ...listeners.directives.map((spec) => ({
410
+ name: spec.name,
411
+ local: spec.className,
412
+ contents: directiveModule(spec)
413
+ })),
414
+ ...scope ? [{
415
+ name: "ScopeAttributes",
416
+ local: scope.className
417
+ }] : [],
418
+ ...passes === void 0 ? [] : [{
419
+ name: listenersExport(fallthrough),
420
+ local: passes.listeners,
421
+ type: true
422
+ }, ...passes.directive === void 0 ? [] : [{
423
+ name: "Fallthrough",
424
+ local: passes.directive
425
+ }]],
426
+ ...models.helpers.flatMap(({ name, shared }) => shared === void 0 ? [] : [{
427
+ name: shared,
428
+ local: name
429
+ }]),
430
+ ...models.textCaret === void 0 ? [] : [{
431
+ name: "TextCaret",
432
+ local: models.textCaret
433
+ }],
434
+ ...trustedHtml === void 0 ? [] : [{
435
+ name: "TrustedHtmlPipe",
436
+ local: trustedHtml
437
+ }],
438
+ ...runner === void 0 ? [] : [{
439
+ name: QUEUE_HELPER,
440
+ local: runner.queue
441
+ }]
442
+ ]);
358
443
  addTypeImports(component, module, imports, kebabCase);
359
444
  const own = new Set(types.map(({ name }) => name));
360
445
  const constants = moduleReads(component.bindings, module, imports, kebabCase);
@@ -363,19 +448,18 @@ function emitComponent(component, context) {
363
448
  span: type.span
364
449
  })), ...typeExportsCode(component, module, kebabCase)].toSorted((a, b) => a.span.start - b.span.start);
365
450
  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
451
  return {
377
- path: `${kebabCase(component.name)}.ts`,
378
- contents
452
+ path,
453
+ contents: placeholders.print(() => [
454
+ printProgram(js.program(imports.toDeclarations())),
455
+ ...typeCode.map(({ code }) => `${code}\n`),
456
+ ...constants.constants.length ? [`${constants.constants.join("\n")}\n`] : [],
457
+ ...idCounter === void 0 ? [] : [idCounter],
458
+ ...declarations,
459
+ ...directives.map(({ decorator: written, statements: declared }) => `${written}\n${spaced(printProgram(js.program(declared)))}`),
460
+ decorator(),
461
+ spaced(printProgram(js.program(statements)))
462
+ ].join("\n"))
379
463
  };
380
464
  }
381
465
  /** Whether an element of the component's template sets `innerHTML` (ADR-0097). */
@@ -412,33 +496,68 @@ function spanKey({ start, end }) {
412
496
  /**
413
497
  * The component's root nodes that take its styled parents' scope attributes (`scopeRoots`, the
414
498
  * 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.
499
+ * (`{{` in an attribute, ADR-0037), which takes no fallthrough either. A component that spreads
500
+ * its props' rest keeps them on its root, as it would without `inheritAttrs: false`: the rest
501
+ * takes everything else its consumer passes (ADR-0118).
416
502
  */
417
- function scopedRoots(component) {
418
- const roots = new Set(scopeRoots(component).map(spanKey));
503
+ function scopedRoots(component, rest) {
504
+ const { inheritAttrs: _, ...inheriting } = component;
505
+ const roots = new Set(scopeRoots(rest ? inheriting : component).map(spanKey));
419
506
  walk(component.render, { enter(node) {
420
507
  if (node.kind === "Element" && angularDialect.literalRegion?.(node) !== void 0) roots.delete(spanKey(node.span));
421
508
  } });
422
509
  return roots;
423
510
  }
511
+ /** The names of the scope directive's code, claimed as {@link helperClaim} does. */
512
+ function scopeNames(component, module, imports) {
513
+ const claim = helperClaim(component, module, imports);
514
+ return {
515
+ className: claim("ScopeAttributes"),
516
+ scopes: claim("scopes")
517
+ };
518
+ }
424
519
  /**
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`),
520
+ * The names of the fallthrough directive's code (ADR-0118), claimed as the scope directive's
521
+ * are: the type of the listeners' record, and the directive, where an element takes the records
522
+ * (a root component takes them through its own inputs).
523
+ */
524
+ function fallthroughNames(component, module, imports, directive) {
525
+ const claim = helperClaim(component, module, imports);
526
+ const listeners = claim("Listeners");
527
+ return directive ? {
528
+ listeners,
529
+ directive: claim("Fallthrough")
530
+ } : { listeners };
531
+ }
532
+ /** The export name of the listeners' type the component's records take, in `_unframework/`. */
533
+ function listenersExport(fallthrough) {
534
+ return fallthrough.events === "SVGElementEventMap" ? "SvgListeners" : "Listeners";
535
+ }
536
+ /**
537
+ * The local names of the shared fallthrough directive and its listeners' type (ADR-0121), as
538
+ * `plan.helper` claims them: one per source, so the join writes one import (A3).
539
+ */
540
+ function sharedFallthroughNames(plan, fallthrough) {
541
+ const listeners = plan.helper(listenersExport(fallthrough));
542
+ return fallthrough.target.kind !== "Component" ? {
543
+ listeners,
544
+ directive: plan.helper("Fallthrough")
545
+ } : { listeners };
546
+ }
547
+ /**
548
+ * Claims a helper's name in the component's file. A source's components are joined into one
549
+ * module where it is loaded (ADR-0053): each claims from bases of its own (`ScopeAttributes_1`),
427
550
  * past the names any other component declares.
428
551
  */
429
- function scopeNames(component, module, imports) {
552
+ function helperClaim(component, module, imports) {
430
553
  const index = module.components.findIndex((each) => each.name === component.name);
431
554
  const reserved = module.components.map((each) => sourceNames(each, module));
432
- const claim = (helper) => {
555
+ return (helper) => {
433
556
  const { base, others } = moduleHelperName(helper, reserved, index);
434
557
  imports.reserve(...others);
435
558
  imports.scope.rebase(helper, base);
436
559
  return imports.claim(helper);
437
560
  };
438
- return {
439
- className: claim("ScopeAttributes"),
440
- scopes: claim("scopes")
441
- };
442
561
  }
443
562
  /**
444
563
  * Reports each name of the component's API that another name of it takes on Angular (UF2003).
@@ -449,7 +568,7 @@ function scopeNames(component, module, imports) {
449
568
  * so a clash is reported at the later declaration rather than renamed. A binding is no API:
450
569
  * ./plan.ts renames it.
451
570
  */
452
- function reportApiClashes(component, composition, fallthrough, context) {
571
+ function reportApiClashes(component, composition, fallthrough, rootElement, context) {
453
572
  const taken = /* @__PURE__ */ new Map();
454
573
  const key = ({ space, name }) => `${space} ${name}`;
455
574
  const declare = (names) => {
@@ -480,6 +599,20 @@ function reportApiClashes(component, composition, fallthrough, context) {
480
599
  what
481
600
  }]);
482
601
  }
602
+ 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([{
603
+ space: "member",
604
+ name,
605
+ what
606
+ }, {
607
+ space: "input",
608
+ name,
609
+ what
610
+ }]);
611
+ if (rootElement) declare([{
612
+ space: "member",
613
+ name: ELEMENT_MEMBER,
614
+ what: "the member that holds the root element a ref on the component holds"
615
+ }]);
483
616
  const source = [
484
617
  ...component.props.map(({ name, span }) => {
485
618
  const what = `the prop \`${name}\``;
@@ -636,13 +769,4 @@ function typeParameters(component, placeholders) {
636
769
  end: 0
637
770
  };
638
771
  }
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
772
  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
  }