@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/README.md CHANGED
@@ -7,13 +7,15 @@ templates, whose host element has `display: contents` (decision D6, ADR-0010).
7
7
 
8
8
  One `<kebab-name>.ts` file per component (plan §6), in this order: the imports from
9
9
  `@angular/core`, `@angular/common` and `@angular/platform-browser`, of the children's output files, of the composables'
10
- (`./use-toggle`, ADR-0069) and of the values the source imports from `.ts` modules, each under a
11
- name no source name takes; the type declarations; the module's constants the component reads, and
10
+ (`./use-toggle`, ADR-0069), of the shared helper modules in the tree's `_unframework/`
11
+ (ADR-0121) and of the values the source imports from `.ts` modules, each under a name no source
12
+ name takes; the type declarations; the module's constants the component reads, and
12
13
  those they read, as written (`const GAP = sizes.sm * 2;`, ADR-0070); the application's id
13
14
  counter, an injection token (`idCounter`, ADR-0095), when the component makes ids; the
14
15
  injection tokens of the module's keys; the inline helpers (`refObject`, the native controls'
15
- `modelText`, `toggle`, `selectedValues`, `optionText`); the slot directives; the pipe `innerHTML`
16
- reads its markup through (`TrustedHtmlPipe`, ADR-0097); the directives its listeners'
16
+ `toggle`, `selectedValues`, `optionText` and their model helpers where the helpers are not
17
+ shared); the slot directives; where the helpers are not shared, the pipe `innerHTML`
18
+ reads its markup through (`TrustedHtmlPipe`, ADR-0097) and the directives its listeners'
17
19
  options need; the component.
18
20
 
19
21
  - **Types.** The source's type declarations the output reads (its inputs' and outputs' types, the
@@ -109,6 +111,7 @@ the template itself, which reads through `@let`, and a template statement's inpu
109
111
  | `const { on, toggle } = useToggle(false)` | `protected readonly toggle_1 = useToggle(false)`, read as `this.toggle_1.on()` and `@let on = this.toggle_1.on();` (below) |
110
112
  | `emit("change", value)` | `this.change.emit(value)`, by the payload rule |
111
113
  | `nextTick()` | `this.nextTick()`, a private method that renders in a microtask with `ApplicationRef.tick()` (emulated, `next-tick`) |
114
+ | `if (isDev) { … }` | `if (typeof ngDevMode === "undefined" \|\| ngDevMode) { … }`, at the top level in `ngOnInit` (ADR-0117) |
112
115
  | `watch(source, callback, options)` | an `effect()` created in `ngOnInit`; `afterRenderEffect()` with `flush: "post"` (below) |
113
116
  | `watchEffect(effect)` | `afterRenderEffect(effect)` in the constructor: after the render, in the browser only |
114
117
  | `onMounted(callback)` | `afterNextRender(callback)` in the constructor: in the browser, once the view is in the document |
@@ -255,7 +258,7 @@ parent, so the composable's effects stay the component's view effects.
255
258
  | `defineModel("value", { default: 0 })` | `readonly value = model<number>(0)`, read and written as a signal; `model<number>(0, { alias: "value" })` where its binding has another name |
256
259
  | `v-model:value={cups.value}` | `[(value)]="this.cups"`, on the signal |
257
260
  | `v-model` on a control | `#nameField [value]="this.name()" (input)="this.name.set(nameField.value)"`, `[checked]` and `(change)` for a box, `[selected]` on a select's options, and a bound `<textarea>` the `TextCaret` directive, which puts a hydrated field's caret after its text (ADR-0095) |
258
- | `class` and `style` on a component | `[class]`, `[style]`: the child's `class` and `style` inputs, merged into its root; the host clears both |
261
+ | `class` and `style` on a component | `[class]`, `[style]`: the child's `class` and `style` inputs, merged into its root; the host clears both; any other attribute and DOM listener in `[ufAttributes]` and `[ufListeners]` (ADR-0118) |
259
262
  | `defineExpose({ focus })`, `ref={search}` | `focus` public; `viewChild<{ focus(): void }>("search")`, read as `this.search()?.focus()` |
260
263
  | `export const LocaleKey: InjectionKey<T>` | `export const LocaleKey = new InjectionToken<T>("…")` in the module's main component's file |
261
264
  | `provide(LocaleKey, locale)` | `providers: [{ provide: LocaleKey, useFactory: () => inject(LocaleProvider).locale() }]`; `useValue` for a constant |
@@ -287,7 +290,13 @@ parent, so the composable's effects stay the component's view effects.
287
290
  `inheritAttrs: false`, declares `class` and `style` inputs and merges them into its root: the
288
291
  class among its parts, the style in one map after the root's own, so a property the consumer
289
292
  leaves `undefined` removes the root's, as Vue's merge does. The host clears both with
290
- `[attr.class]` and `[attr.style]` bindings, keeping only `display: contents`.
293
+ `[attr.class]` and `[attr.style]` bindings, keeping only `display: contents`. Its other
294
+ attributes and DOM listeners a consumer passes arrive in two more inputs, `ufAttributes` and
295
+ `ufListeners`, which the `Fallthrough` directive on its fallthrough element (its root, or the
296
+ element that spreads the props' rest) sets through `Renderer2`, the consumer's value winning
297
+ and the root's own listener running first (ADR-0118). The directive and the listeners' types
298
+ are shared helper modules (ADR-0121). A ref on a component that exposes nothing
299
+ reads its `ufElement`, a `viewChild` of its root, which a root component forwards.
291
300
  - **Context.** An injected value is read once the inputs are set, from the injector the class
292
301
  holds: a consumer projected into its provider is created before the provider's inputs are set,
293
302
  which a provided value may read (NG0950). A key of a ref (`InjectionKey<Ref<number>>`) holds
@@ -359,9 +368,11 @@ parent's attribute on a child's tag, and the child's `-s` on the content filled
359
368
  sheet uses `:slotted()`, through `<ng-content>` and `ng-template` slots alike. The parent's
360
369
  attribute lands on the child's host, which must keep only `display: contents`, and a template
361
370
  cannot write an attribute whose name it does not know. So each root node of a component binds an
362
- inline attribute directive to its host, `[ufScope]="this.host"` (`ScopeAttributes`, with the host
371
+ shared attribute directive to its host, `[ufScope]="this.host"` (`ScopeAttributes`, with the host
363
372
  in a protected `host` member): in `ngOnInit` it takes the host's `data-uf-*` attributes off it,
364
- keeps their names in a module `WeakMap` for a root that renders later, and sets them on its node.
373
+ keeps their names in its module's `WeakMap` for a root that renders later, and sets them on its
374
+ node. The map is keyed by the host, which only its own component's roots read, so one map serves
375
+ the tree (ADR-0121, R2).
365
376
  Its root nodes are those Vue's fallthrough reaches (`scopeRoots`): the root element, component or
366
377
  each candidate of a root `<component is>`, or each branch of a root conditional that renders one
367
378
  alone. A root component's own root directive runs after this one has set them on its host, so they
@@ -384,7 +395,7 @@ object), `style-binding` (emulated, `styleObject`, for a style bound to a value
384
395
  spreads; ADR-0065), `raw-html` (emulated, `TrustedHtmlPipe`, a pure pipe that marks `innerHTML`'s
385
396
  markup trusted, so Angular's sanitiser keeps it as written; ADR-0097) and composition's cells that ADR-0056 decides: `named-slot`, `scoped-slot` and
386
397
  `slot-forwarding` (emulated, the slot directives `uf<Component><Slot>`), `model-array`
387
- (`toggle`), `model-modifiers` (`modelText`), `fallthrough` (`fallthrough`), `reactive-context`
398
+ (`toggle`), `model-modifiers` (`modelText`), `fallthrough` (the shared `Fallthrough` directive), `expose` (`ufElement`, where a component exposes nothing), `reactive-context`
388
399
  (`refObject`) and `dynamic-component` (`@switch`), all emulated, `default-slot-presence` and
389
400
  `contextual-root`, unsupported (UF4001, errors), `child-root-scope` and `sheet-order`,
390
401
  unsupported (UF4003 and UF4002, info), and `generic-slot-props`, unsupported (UF4004, info): slot
@@ -394,12 +405,30 @@ cannot infer. Where an unsupported cell is reported, the
394
405
  output still compiles: default-slot presence reads `true`, and the forwarded default slot
395
406
  re-projects `<ng-content />`.
396
407
 
397
- `directive` is emulated (ADR-0099): a standalone attribute directive, `VFocusTrap` in `v-focus-trap.ts` for a `.uf.ts` module's, bound as `[vFocusTrap]` and in the component's `imports`, whose `afterRenderEffect` passes the value to an inline `runDirective` and whose `DestroyRef` stops it. The helper runs the hooks as a `MutationObserver` sees the element come into the document and leave it, since Angular creates projected content before a child puts it there, and queues them through an inline `queueHook`, which runs them in Vue's order.
408
+ `directive` is emulated (ADR-0099): a standalone attribute directive, `VFocusTrap` in `v-focus-trap.ts` for a `.uf.ts` module's, bound as `[vFocusTrap]` and in the component's `imports`, whose `afterRenderEffect` passes the value to an inline `runDirective` and whose `DestroyRef` stops it. The helper runs the hooks as a `MutationObserver` sees the element come into the document and leave it, since Angular creates projected content before a child puts it there, and queues them through a shared `queueHook`, which runs them in Vue's order.
398
409
 
399
410
  `transition` is emulated (ADR-0100): a `<Transition>`'s element takes an inline directive, `Transition`, bound as `[ufTransition]="'fade'"`, and a conditional child sits in `<ng-container [ufTransitionRegion]="…">`, whose inline directive, `TransitionRegion`, is created with the transition and holds the branch shown. The element's directive runs Vue's enter classes once its region has rendered, or with `appear`, and the leave through `(animate.leave)`'s function form, which holds the element's removal until the leave ends. Angular runs that function too when a view around the element goes, so the directive lets the element go at once while its region still shows its branch.
400
411
 
401
412
  `teleport` is emulated (ADR-0098): an `<ng-template ufTeleport>` whose inline directive, `Teleport`, creates its view in its own view container once the application has rendered and moves the view's nodes into `to`. A render's teleports mount in the document's order, and a root teleport takes its parents' scope attributes off the host.
402
413
 
414
+ The shared helpers are modules of their own in the tree's `_unframework/` (ADR-0121), put
415
+ through `EmitContext.helper` and printed by `src/shared.ts`: `ScopeAttributes.ts`,
416
+ `TextCaret.ts`, `TrustedHtmlPipe.ts`, `styleObject.ts`, `modelText.ts`, `writeModelText.ts`,
417
+ `looseToNumber.ts`, `queueHook.ts`, `Fallthrough.ts`, `Listeners.ts` and one module for each
418
+ event and option a listener uses, such as `ClickCapture.ts`. Each imports Angular by its own
419
+ names, so its text depends only on the helper, and a helper that calls another imports it as its
420
+ sibling (`./looseToNumber`). `Listeners.ts` holds the types of the fallthrough listeners' record,
421
+ `Listeners` and, for an SVG element, `SvgListeners`, which a component imports with
422
+ `import type`, and which `Fallthrough`'s input takes either of.
423
+
424
+ A component imports each without the extension, `import { ScopeAttributes } from
425
+ "./_unframework/ScopeAttributes"`, under one name in every component of a source, and lists a
426
+ directive or a pipe in its `imports`. `Transition` and `TransitionRegion` stay inline: the
427
+ directive finds its region through `inject`, which looks through every ancestor's injector,
428
+ across component hosts, so a shared region class would let a child's transition read its
429
+ parent's region (R2). The directive runner, `Teleport`, `idCounter` and the short helpers stay
430
+ inline too. A context without `helper` gets every helper printed inline, as before.
431
+
403
432
  Inline content on either side of a child component's host reads with a space in the accessible
404
433
  name: Chrome adds one at every `display: contents` element, so Angular reads `Build passing` where
405
434
  the other targets read `Buildpassing`. `harness/quarantine/angular.ts` lists the cells until M3's
@@ -413,7 +442,9 @@ Tests and tooling build, check and run the Angular output through three subpaths
413
442
  - `vite("browser" | "ssr", context)`: Angular's AOT compiler (ngtsc, strict templates) for
414
443
  the unframework plugin's virtual `X.uf.tsx.ts` modules and its modules of composables,
415
444
  `X.uf.ts.ts`, which a component's program reads so its template is checked against the
416
- composable's types (ADR-0069), Analog with `jit: false`, and the
445
+ composable's types (ADR-0069), and for the shared helper modules it serves,
446
+ `_unframework/angular/ScopeAttributes.ts`, which a component's program reads too and which compile
447
+ ahead of time on their own (ADR-0121), Analog with `jit: false`, and the
417
448
  Angular linker, over the pre-bundled framework in the browser and over the packages the SSR
418
449
  module graph inlines on the server, so no JIT compiler runs.
419
450
  - `frameworkCompile(files, context)` (L3) and `typecheck(files, context)` (L4): one ngtsc
@@ -156,7 +156,8 @@ function itemCode(item, context) {
156
156
  case "Model":
157
157
  case "Provide":
158
158
  case "Inject":
159
- case "Use": throw new Error(`A composable holds a \`${item.kind}\` item, which the analyser rejects.`);
159
+ case "Use":
160
+ case "DevCheck": throw new Error(`A composable holds a \`${item.kind}\` item, which the analyser rejects.`);
160
161
  default: return unreachable(item);
161
162
  }
162
163
  }
@@ -12,7 +12,7 @@ function selectorOf(name) {
12
12
  * selector in camel case and the slot's name (`ufCardTitle`).
13
13
  */
14
14
  function slotAttribute(name, slot) {
15
- return `${selectorOf(name).replace(/-(\w)/g, (_, next) => next.toUpperCase())}${pascalCase(slot)}`;
15
+ return `${selectorOf(name).replaceAll(/-(\w)/g, (_, next) => next.toUpperCase())}${pascalCase(slot)}`;
16
16
  }
17
17
  /** Whether a slot is written through a directive: any but the default slot without props. */
18
18
  function usesDirective(slot, scoped) {
@@ -209,6 +209,6 @@ function aliases(props) {
209
209
  }
210
210
  /** A prop's name as a context key a template variable can read: `data-id` → `dataId`. */
211
211
  function contextAlias(key) {
212
- return key.replace(/[^A-Za-z0-9_$]+(.)?/g, (_, next) => next?.toUpperCase() ?? "").replace(/^(?=\d)/, "_");
212
+ return key.replaceAll(/[^A-Za-z0-9_$]+(.)?/g, (_, next) => next?.toUpperCase() ?? "").replace(/^(?=\d)/, "_");
213
213
  }
214
214
  export { childEvent, firstUse, keyOf, outputFile, planComposition, refObjectCode, selectorOf, slotDirectiveCode, tokenType, usesDirective };
package/dist/directive.js CHANGED
@@ -1,6 +1,9 @@
1
+ import { importShared } from "./shared.js";
1
2
  import { ImportSet, NameScope, dependencyImports, directiveDependencies, directiveElement, directiveHooksObject, directiveModuleNames, directiveRunnerCode, hookQueueCode, js, kebabCase, printProgram, wrapperNames } from "@unframework.dev/codegen";
2
3
  /** The inline helper that runs a directive's hooks as its element comes and goes. */
3
4
  const RUNNER_HELPER = "runDirective";
5
+ /** The helper that queues the hooks, shared in `_unframework/` where helpers are (ADR-0121). */
6
+ const QUEUE_HELPER = "queueHook";
4
7
  /** The runner's names, each claimed through `claim` from its base. */
5
8
  function runnerNames(claim) {
6
9
  return {
@@ -11,12 +14,12 @@ function runnerNames(claim) {
11
14
  watches: claim("documentWatches"),
12
15
  checker: claim("directiveCheck"),
13
16
  leftWatch: claim("watchLeft"),
14
- queue: claim("queueHook")
17
+ queue: claim(QUEUE_HELPER)
15
18
  };
16
19
  }
17
- /** The runner and the queue it calls, as a file declares them. */
18
- function runnerCode(names) {
19
- return [...directiveRunnerCode(names), hookQueueCode(names.queue)].map((code) => `${code}\n`);
20
+ /** The runner and the queue it calls, as a file declares them: the queue unless it is shared. */
21
+ function runnerCode(names, queue = true) {
22
+ return [...directiveRunnerCode(names), ...queue ? [hookQueueCode(names.queue)] : []].map((code) => `${code}\n`);
20
23
  }
21
24
  /** The class an Angular directive is declared as: `VFocusTrap` for `vFocusTrap`. */
22
25
  function directiveClassName(name) {
@@ -64,17 +67,22 @@ function emitDirective(directive, context) {
64
67
  const imports = new ImportSet(new NameScope(directiveModuleNames(directive, dependencies)));
65
68
  const runner = runnerNames((base) => imports.claim(base));
66
69
  const directiveCode = directiveClassCode(directive, directiveClassName(directive.name), runner.run, imports);
70
+ const path = `${directiveFile(directive.name)}.ts`;
71
+ if (context.helper) importShared(context.helper, path, imports, [{
72
+ name: QUEUE_HELPER,
73
+ local: runner.queue
74
+ }]);
67
75
  return [{
68
- path: `${directiveFile(directive.name)}.ts`,
76
+ path,
69
77
  contents: [
70
78
  printProgram(js.program(imports.toDeclarations())).trim(),
71
79
  ...dependencyImports(dependencies),
72
80
  "",
73
81
  ...dependencies.types.map((code) => `${code}\n`),
74
82
  ...dependencies.constants.length ? [`${dependencies.constants.join("\n")}\n`] : [],
75
- ...runnerCode(runner),
83
+ ...runnerCode(runner, context.helper === void 0),
76
84
  directiveCode
77
85
  ].join("\n")
78
86
  }];
79
87
  }
80
- export { RUNNER_HELPER, directiveClassCode, directiveClassName, directiveFile, emitDirective, runnerCode, runnerNames };
88
+ export { QUEUE_HELPER, RUNNER_HELPER, directiveClassCode, directiveClassName, directiveFile, emitDirective, runnerCode, runnerNames };
@@ -343,4 +343,13 @@ class ${className} implements ${core("PipeTransform", true)} {
343
343
  }
344
344
  `;
345
345
  }
346
- export { TELEPORT_ATTRIBUTE, TELEPORT_HOST_INPUT, TRANSITION_APPEAR_INPUT, TRANSITION_ATTRIBUTE, TRANSITION_BRANCH_INPUT, TRANSITION_REGION_ATTRIBUTE, directiveCode, scopeDirectiveCode, teleportDirectiveCode, textCaretDirectiveCode, transitionDirectiveCode, transitionRegionCode, trustedHtmlPipeCode };
346
+ /**
347
+ * A printed class with a blank line before each of its methods, as Angular code sets them apart
348
+ * from the fields and from each other (oxfmt keeps a blank line, and adds none). Read before the
349
+ * placeholders are spliced: a member starts at the class's indentation, and a method's line ends
350
+ * with its body's `{` where a field's holds ` = `.
351
+ */
352
+ function spaced(printed) {
353
+ return printed.replaceAll(/\n(?= {2}[^\s}][^\n]*\{\n)(?! {2}[^\n]* = )/g, "\n\n");
354
+ }
355
+ export { TELEPORT_ATTRIBUTE, TELEPORT_HOST_INPUT, TRANSITION_APPEAR_INPUT, TRANSITION_ATTRIBUTE, TRANSITION_BRANCH_INPUT, TRANSITION_REGION_ATTRIBUTE, directiveCode, scopeDirectiveCode, spaced, teleportDirectiveCode, textCaretDirectiveCode, transitionDirectiveCode, transitionRegionCode, trustedHtmlPipeCode };
package/dist/effects.js CHANGED
@@ -80,7 +80,7 @@ function watcherCode(item, plan, rules, names) {
80
80
  */
81
81
  function watchedSignal(source, plan) {
82
82
  const binding = source.kind === "Ref" ? bindingById(plan, source.binding) : source.getter.expression && source.getter.body.refs.length === 1 && source.getter.body.refs[0].kind === "Binding" && source.getter.body.refs[0].span.start === source.getter.body.span.start && source.getter.body.refs[0].span.end === source.getter.body.span.end ? bindingById(plan, source.getter.body.refs[0].binding) : void 0;
83
- if (binding === void 0) return void 0;
83
+ if (binding === void 0) return;
84
84
  const form = formOf(plan, binding);
85
85
  switch (form) {
86
86
  case "input":
@@ -0,0 +1,117 @@
1
+ /** The DOM interface of an element by its tag: `button` → `HTMLButtonElement`. */
2
+ const ELEMENT_INTERFACES = /* @__PURE__ */ new Map([
3
+ ["a", "HTMLAnchorElement"],
4
+ ["abbr", "HTMLElement"],
5
+ ["address", "HTMLElement"],
6
+ ["area", "HTMLAreaElement"],
7
+ ["article", "HTMLElement"],
8
+ ["aside", "HTMLElement"],
9
+ ["audio", "HTMLAudioElement"],
10
+ ["b", "HTMLElement"],
11
+ ["base", "HTMLBaseElement"],
12
+ ["bdi", "HTMLElement"],
13
+ ["bdo", "HTMLElement"],
14
+ ["blockquote", "HTMLQuoteElement"],
15
+ ["body", "HTMLBodyElement"],
16
+ ["br", "HTMLBRElement"],
17
+ ["button", "HTMLButtonElement"],
18
+ ["canvas", "HTMLCanvasElement"],
19
+ ["caption", "HTMLTableCaptionElement"],
20
+ ["cite", "HTMLElement"],
21
+ ["code", "HTMLElement"],
22
+ ["col", "HTMLTableColElement"],
23
+ ["colgroup", "HTMLTableColElement"],
24
+ ["data", "HTMLDataElement"],
25
+ ["datalist", "HTMLDataListElement"],
26
+ ["dd", "HTMLElement"],
27
+ ["del", "HTMLModElement"],
28
+ ["details", "HTMLDetailsElement"],
29
+ ["dfn", "HTMLElement"],
30
+ ["dialog", "HTMLDialogElement"],
31
+ ["div", "HTMLDivElement"],
32
+ ["dl", "HTMLDListElement"],
33
+ ["dt", "HTMLElement"],
34
+ ["em", "HTMLElement"],
35
+ ["embed", "HTMLEmbedElement"],
36
+ ["fieldset", "HTMLFieldSetElement"],
37
+ ["figcaption", "HTMLElement"],
38
+ ["figure", "HTMLElement"],
39
+ ["footer", "HTMLElement"],
40
+ ["form", "HTMLFormElement"],
41
+ ["h1", "HTMLHeadingElement"],
42
+ ["h2", "HTMLHeadingElement"],
43
+ ["h3", "HTMLHeadingElement"],
44
+ ["h4", "HTMLHeadingElement"],
45
+ ["h5", "HTMLHeadingElement"],
46
+ ["h6", "HTMLHeadingElement"],
47
+ ["head", "HTMLHeadElement"],
48
+ ["header", "HTMLElement"],
49
+ ["hgroup", "HTMLElement"],
50
+ ["hr", "HTMLHRElement"],
51
+ ["html", "HTMLHtmlElement"],
52
+ ["i", "HTMLElement"],
53
+ ["iframe", "HTMLIFrameElement"],
54
+ ["img", "HTMLImageElement"],
55
+ ["input", "HTMLInputElement"],
56
+ ["ins", "HTMLModElement"],
57
+ ["kbd", "HTMLElement"],
58
+ ["label", "HTMLLabelElement"],
59
+ ["legend", "HTMLLegendElement"],
60
+ ["li", "HTMLLIElement"],
61
+ ["link", "HTMLLinkElement"],
62
+ ["main", "HTMLElement"],
63
+ ["map", "HTMLMapElement"],
64
+ ["mark", "HTMLElement"],
65
+ ["menu", "HTMLMenuElement"],
66
+ ["meta", "HTMLMetaElement"],
67
+ ["meter", "HTMLMeterElement"],
68
+ ["nav", "HTMLElement"],
69
+ ["noscript", "HTMLElement"],
70
+ ["object", "HTMLObjectElement"],
71
+ ["ol", "HTMLOListElement"],
72
+ ["optgroup", "HTMLOptGroupElement"],
73
+ ["option", "HTMLOptionElement"],
74
+ ["output", "HTMLOutputElement"],
75
+ ["p", "HTMLParagraphElement"],
76
+ ["picture", "HTMLPictureElement"],
77
+ ["pre", "HTMLPreElement"],
78
+ ["progress", "HTMLProgressElement"],
79
+ ["q", "HTMLQuoteElement"],
80
+ ["rp", "HTMLElement"],
81
+ ["rt", "HTMLElement"],
82
+ ["ruby", "HTMLElement"],
83
+ ["s", "HTMLElement"],
84
+ ["samp", "HTMLElement"],
85
+ ["script", "HTMLScriptElement"],
86
+ ["search", "HTMLElement"],
87
+ ["section", "HTMLElement"],
88
+ ["select", "HTMLSelectElement"],
89
+ ["slot", "HTMLSlotElement"],
90
+ ["small", "HTMLElement"],
91
+ ["source", "HTMLSourceElement"],
92
+ ["span", "HTMLSpanElement"],
93
+ ["strong", "HTMLElement"],
94
+ ["style", "HTMLStyleElement"],
95
+ ["sub", "HTMLElement"],
96
+ ["summary", "HTMLElement"],
97
+ ["sup", "HTMLElement"],
98
+ ["table", "HTMLTableElement"],
99
+ ["tbody", "HTMLTableSectionElement"],
100
+ ["td", "HTMLTableCellElement"],
101
+ ["template", "HTMLTemplateElement"],
102
+ ["textarea", "HTMLTextAreaElement"],
103
+ ["tfoot", "HTMLTableSectionElement"],
104
+ ["th", "HTMLTableCellElement"],
105
+ ["thead", "HTMLTableSectionElement"],
106
+ ["time", "HTMLTimeElement"],
107
+ ["title", "HTMLTitleElement"],
108
+ ["tr", "HTMLTableRowElement"],
109
+ ["track", "HTMLTrackElement"],
110
+ ["u", "HTMLElement"],
111
+ ["ul", "HTMLUListElement"],
112
+ ["var", "HTMLElement"],
113
+ ["video", "HTMLVideoElement"],
114
+ ["wbr", "HTMLElement"],
115
+ ["svg", "SVGSVGElement"]
116
+ ]);
117
+ export { ELEMENT_INTERFACES };
@@ -0,0 +1,283 @@
1
+ import { ELEMENT_INTERFACES } from "./elements.js";
2
+ import { angularDialect, candidateAttributes } from "@unframework.dev/codegen";
3
+ import { walk } from "@unframework.dev/ir";
4
+ /** The input that takes the consumer's attributes, each by its name. */
5
+ const ATTRIBUTES_INPUT = "ufAttributes";
6
+ /** The input that takes the consumer's native listeners, each by its event's name. */
7
+ const LISTENERS_INPUT = "ufListeners";
8
+ /** The member that holds the element a ref on the component holds, where it exposes nothing. */
9
+ const ELEMENT_MEMBER = "ufElement";
10
+ /** The template ref the root carries for {@link ELEMENT_MEMBER}'s query. */
11
+ const ELEMENT_REF = "ufElement";
12
+ /** The attribute of the directive that puts the records on their element. */
13
+ const FALLTHROUGH_ATTRIBUTE = "ufFallthrough";
14
+ /**
15
+ * The names a component that takes fallthrough declares beside its own (ADR-0056, ADR-0118):
16
+ * a prop, an event or an exposed function of one of them is UF2003, and a setup binding of one
17
+ * is renamed.
18
+ */
19
+ const FALLTHROUGH_MEMBERS = [
20
+ "class",
21
+ "style",
22
+ ATTRIBUTES_INPUT,
23
+ LISTENERS_INPUT,
24
+ ELEMENT_MEMBER
25
+ ];
26
+ /**
27
+ * The component's root (an element, or a fragment of one element, one component or one
28
+ * `<component is>` over tags, ADR-0119), which what a consumer passes falls through to
29
+ * (ADR-0054, ADR-0118), or none. A `<component is>` takes only `class` and `style`, in each
30
+ * `@case`.
31
+ */
32
+ function fallthroughRoot(render) {
33
+ if (render.kind === "Element") return render;
34
+ const [only] = render.children;
35
+ if (render.children.length !== 1) return;
36
+ if (only?.kind === "Element" || only?.kind === "Component") return only;
37
+ return only?.kind === "Dynamic" && only.candidates.every((each) => each.kind === "Tag") ? only : void 0;
38
+ }
39
+ /**
40
+ * The API of the component a template renders by its local name: from its import, or from the
41
+ * module's own component, read as the analyser reads it (`fillRootComponents`).
42
+ */
43
+ function childApi(module, local, seen = /* @__PURE__ */ new Set()) {
44
+ for (const entry of module.imports ?? []) {
45
+ const imported = entry.names.find((name) => name.kind === "Component" && name.local === local);
46
+ if (!imported) continue;
47
+ const api = entry.api.components.find((each) => imported.imported === "default" ? each.export === "default" : each.export === "named" && each.name === imported.imported);
48
+ if (!api) return;
49
+ const refTag = api.refTag ?? api.refTags?.[0];
50
+ const takes = api.fallthroughTag ?? (api.inheritAttrs ? api.rootTags?.[0] : void 0);
51
+ const literal = takes === void 0 ? void 0 : api.fallthroughOwn?.attributes.find(({ name, value }) => name !== "class" && name !== "style" && typeof value === "string" && value.includes("{{"))?.name;
52
+ const fallthroughTag = literal === void 0 ? takes : void 0;
53
+ return {
54
+ exposes: api.exposes.length > 0,
55
+ ...refTag === void 0 ? {} : { refTag },
56
+ ...fallthroughTag === void 0 ? {} : { fallthroughTag },
57
+ ...literal === void 0 ? {} : { literal }
58
+ };
59
+ }
60
+ const own = module.components.find((each) => each.name === local);
61
+ if (!own || seen.has(local)) return;
62
+ const next = /* @__PURE__ */ new Set([...seen, local]);
63
+ const exposes = (own.exposes?.functions.length ?? 0) > 0;
64
+ const root = fallthroughRoot(own.render);
65
+ const rootChild = root?.kind === "Component" ? childApi(module, root.component, next) : void 0;
66
+ const rootTag = root?.kind === "Element" ? root.tag : root?.kind === "Dynamic" && root.candidates[0]?.kind === "Tag" ? root.candidates[0].tag : void 0;
67
+ const refTag = exposes ? void 0 : rootTag ?? (rootChild && !rootChild.exposes ? rootChild.refTag : void 0);
68
+ const rest = own.inheritAttrs === false ? restElement(own.render)?.element : void 0;
69
+ const takes = own.inheritAttrs === false ? rest?.tag : rootTag ?? rootChild?.fallthroughTag;
70
+ const literal = takes === void 0 ? rootChild?.literal : literalAttribute(rest ? [rest] : root?.kind === "Dynamic" ? tagElements(root) : root?.kind === "Element" ? [root] : []);
71
+ const fallthroughTag = literal === void 0 ? takes : void 0;
72
+ return {
73
+ exposes,
74
+ ...refTag === void 0 ? {} : { refTag },
75
+ ...fallthroughTag === void 0 ? {} : { fallthroughTag },
76
+ ...literal === void 0 ? {} : { literal }
77
+ };
78
+ }
79
+ /** Each tag of a `<component is>` over tags as the element its `@case` writes. */
80
+ function tagElements(root) {
81
+ return root.candidates.flatMap((candidate) => candidate.kind === "Tag" ? [{
82
+ kind: "Element",
83
+ tag: candidate.tag,
84
+ attributes: candidateAttributes(root, candidate.tag),
85
+ children: root.children,
86
+ span: root.span
87
+ }] : []);
88
+ }
89
+ /** The static attribute holding `{{` that puts one of `elements` in a literal region (ADR-0037). */
90
+ function literalAttribute(elements) {
91
+ for (const element of elements) {
92
+ if (angularDialect.literalRegion?.(element) === void 0) continue;
93
+ const found = element.attributes.find((attribute) => attribute.kind === "Static" && attribute.value !== true && attribute.value.includes("{{"));
94
+ if (found?.kind === "Static") return found.name;
95
+ }
96
+ }
97
+ /**
98
+ * How the component takes what its consumer passes (ADR-0056, ADR-0118), or `undefined` where it
99
+ * takes nothing: its root, one element or one component, unless it sets `inheritAttrs: false`,
100
+ * when the element that spreads the props' rest takes it, if one does. An element Angular binds
101
+ * nothing on (`{{` in an attribute, ADR-0037) takes nothing.
102
+ */
103
+ function planFallthrough(component, module) {
104
+ if (component.inheritAttrs === false) {
105
+ const found = restElement(component.render);
106
+ if (!found || angularDialect.literalRegion?.(found.element) !== void 0) return;
107
+ return {
108
+ target: found.element,
109
+ rest: true,
110
+ passes: true,
111
+ events: found.svg ? "SVGElementEventMap" : "HTMLElementEventMap"
112
+ };
113
+ }
114
+ const root = fallthroughRoot(component.render);
115
+ if (!root) return;
116
+ if (root.kind === "Element") {
117
+ if (angularDialect.literalRegion?.(root) !== void 0) return;
118
+ return {
119
+ target: root,
120
+ rest: false,
121
+ passes: true,
122
+ events: eventsOf(root.tag)
123
+ };
124
+ }
125
+ if (root.kind === "Dynamic") {
126
+ if (!root.candidates.every((candidate) => candidate.kind === "Tag" && angularDialect.literalRegion?.({
127
+ kind: "Element",
128
+ tag: candidate.tag,
129
+ attributes: candidateAttributes(root, candidate.tag),
130
+ children: root.children,
131
+ span: root.span
132
+ }) === void 0)) return;
133
+ return {
134
+ target: root,
135
+ rest: false,
136
+ passes: true,
137
+ events: "HTMLElementEventMap"
138
+ };
139
+ }
140
+ const tag = childApi(module, root.component)?.fallthroughTag;
141
+ return {
142
+ target: root,
143
+ rest: false,
144
+ passes: tag !== void 0,
145
+ events: eventsOf(tag)
146
+ };
147
+ }
148
+ /** The event map of the element a tag names. */
149
+ function eventsOf(tag) {
150
+ return tag === "svg" ? "SVGElementEventMap" : "HTMLElementEventMap";
151
+ }
152
+ /**
153
+ * The element a ref on the component holds (ADR-0118), where it exposes nothing: its root
154
+ * element, or its root component's own, which that component declares. `undefined` where a ref
155
+ * holds no element.
156
+ */
157
+ function planRootElement(component, module) {
158
+ if (component.exposes?.functions.length) return;
159
+ const root = fallthroughRoot(component.render);
160
+ if (!root) return;
161
+ if (root.kind === "Dynamic") {
162
+ const types = root.candidates.map((candidate) => candidate.kind === "Tag" ? ELEMENT_INTERFACES.get(candidate.tag) : void 0);
163
+ if (types.some((type) => type === void 0)) return;
164
+ return {
165
+ root,
166
+ type: [...new Set(types)].join(" | ")
167
+ };
168
+ }
169
+ if (root.kind === "Element") {
170
+ const type = ELEMENT_INTERFACES.get(root.tag);
171
+ if (type === void 0 || angularDialect.literalRegion?.(root) !== void 0) return;
172
+ return {
173
+ root,
174
+ type
175
+ };
176
+ }
177
+ const child = childApi(module, root.component, /* @__PURE__ */ new Set([component.name]));
178
+ return child && !child.exposes && child.refTag !== void 0 ? { root } : void 0;
179
+ }
180
+ /** The element that spreads the props' rest, which the analyser allows on one element. */
181
+ function restElement(render) {
182
+ let found;
183
+ const svg = [];
184
+ walk(render, {
185
+ enter(node) {
186
+ if (found || node.kind !== "Element") return;
187
+ svg.push(node.tag === "svg" || svg.at(-1) === true);
188
+ if (node.attributes.some((attribute) => attribute.kind === "Rest")) found = {
189
+ element: node,
190
+ svg: svg.at(-1)
191
+ };
192
+ },
193
+ leave(node) {
194
+ if (node.kind === "Element") svg.pop();
195
+ }
196
+ });
197
+ return found;
198
+ }
199
+ /**
200
+ * The directive that puts what a consumer passes on the element that takes it (ADR-0118), and
201
+ * the type of the listeners' record. Angular has no attribute spread, so it emulates Vue's
202
+ * `$attrs`: as the record changes it sets each attribute through `Renderer2`, removes one that
203
+ * is `null` or `undefined` as `[attr.name]` does, and so overrides the element's own attribute
204
+ * of the name, the consumer's winning, on the server and in the browser. It writes only as the
205
+ * record changes, so an attribute the element binds itself binds the consumer's value where the
206
+ * record has its name (`consumerFirst` in ./template.ts), or Angular would write the element's
207
+ * own over it each time that binding changes. In the browser it listens to each event with
208
+ * `Renderer2.listen`, again on a new handler, and stops with the element. Its inputs are set
209
+ * after the element's own listeners are added, so those run first.
210
+ */
211
+ function fallthroughDirectiveCode(names, events, core, common) {
212
+ const { directive: className, listeners } = names;
213
+ const type = listenersTypeCode(listeners, events);
214
+ if (className === void 0) return type;
215
+ return `${type}\n${fallthroughClassCode(className, listeners, core, common)}`;
216
+ }
217
+ /**
218
+ * The directive's class (see {@link fallthroughDirectiveCode}), whose records' listeners are of
219
+ * the type `listeners` names: one type, inline, or the union of both event maps' types, where the
220
+ * directive is shared in `_unframework/` (ADR-0121) and so takes either.
221
+ */
222
+ function fallthroughClassCode(className, listeners, core, common) {
223
+ return [
224
+ "/**",
225
+ " * Puts what a consumer passes the component, and the component does not declare, on the element",
226
+ " * that takes it (ADR-0118): the attributes, the consumer's winning over the element's own, and",
227
+ " * the native listeners, which run after the element's own.",
228
+ " */",
229
+ `@${core("Directive")}({ selector: "[${FALLTHROUGH_ATTRIBUTE}]" })`,
230
+ `export class ${className} implements ${core("OnChanges", true)}, ${core("OnDestroy", true)} {`,
231
+ ` readonly ${FALLTHROUGH_ATTRIBUTE} = ${core("input")}.required<{`,
232
+ " attributes: Record<string, unknown> | undefined;",
233
+ ` listeners: ${listeners} | undefined;`,
234
+ " }>();",
235
+ ` private readonly element = ${core("inject")}<${core("ElementRef")}<Element>>(${core("ElementRef")});`,
236
+ ` private readonly renderer = ${core("inject")}(${core("Renderer2")});`,
237
+ ` private readonly browser = ${common("isPlatformBrowser")}(${core("inject")}(${core("PLATFORM_ID")}));`,
238
+ " private readonly listening = new Map<string, { handler: unknown; stop: () => void }>();",
239
+ " private written: Record<string, unknown> = {};",
240
+ "",
241
+ " ngOnChanges(): void {",
242
+ " const element = this.element.nativeElement;",
243
+ ` const { attributes = {}, listeners = {} } = this.${FALLTHROUGH_ATTRIBUTE}();`,
244
+ " for (const name of Object.keys(this.written)) {",
245
+ " if (!(name in attributes)) this.renderer.removeAttribute(element, name);",
246
+ " }",
247
+ " for (const [name, value] of Object.entries(attributes)) {",
248
+ " if (value === null || value === undefined) this.renderer.removeAttribute(element, name);",
249
+ " else this.renderer.setAttribute(element, name, String(value));",
250
+ " }",
251
+ " this.written = attributes;",
252
+ " if (!this.browser) return;",
253
+ " const handlers = new Map(Object.entries(listeners));",
254
+ " for (const [event, { handler, stop }] of this.listening) {",
255
+ " if (handlers.get(event) === handler) continue;",
256
+ " stop();",
257
+ " this.listening.delete(event);",
258
+ " }",
259
+ " for (const [event, handler] of handlers) {",
260
+ " if (handler === undefined || this.listening.has(event)) continue;",
261
+ " this.listening.set(event, { handler, stop: this.renderer.listen(element, event, handler) });",
262
+ " }",
263
+ " }",
264
+ "",
265
+ " ngOnDestroy(): void {",
266
+ " for (const { stop } of this.listening.values()) stop();",
267
+ " }",
268
+ "}",
269
+ ""
270
+ ].join("\n");
271
+ }
272
+ /**
273
+ * The type of the listeners' record: a handler of each event, typed by its event. `exported`
274
+ * exports it, from the module where it is shared (ADR-0121).
275
+ */
276
+ function listenersTypeCode(name, events, exported = false) {
277
+ return [
278
+ events === "SVGElementEventMap" ? "/** A native listener of each event a consumer passes an SVG element, by name (ADR-0118). */" : "/** A native listener of each event a consumer passes, by the event's name (ADR-0118). */",
279
+ `${exported ? "export " : ""}type ${name} = { [K in keyof ${events}]?: (event: ${events}[K]) => void };`,
280
+ ""
281
+ ].join("\n");
282
+ }
283
+ export { ATTRIBUTES_INPUT, ELEMENT_MEMBER, ELEMENT_REF, FALLTHROUGH_ATTRIBUTE, FALLTHROUGH_MEMBERS, LISTENERS_INPUT, childApi, fallthroughClassCode, fallthroughDirectiveCode, fallthroughRoot, listenersTypeCode, planFallthrough, planRootElement };