@unframework.dev/target-angular 0.1.3 → 0.2.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/README.md CHANGED
@@ -6,13 +6,14 @@ templates, whose host element has `display: contents` (decision D6, ADR-0010).
6
6
  ## Output
7
7
 
8
8
  One `<kebab-name>.ts` file per component (plan §6), in this order: the imports from
9
- `@angular/core` and `@angular/common`, of the children's output files, of the composables'
9
+ `@angular/core`, `@angular/common` and `@angular/platform-browser`, of the children's output files, of the composables'
10
10
  (`./use-toggle`, ADR-0069) and of the values the source imports from `.ts` modules, each under a
11
11
  name no source name takes; the type declarations; the module's constants the component reads, and
12
- those they read, as written (`const GAP = sizes.sm * 2;`, ADR-0070); `let nextId = 0;` when the
13
- component makes ids; the
12
+ those they read, as written (`const GAP = sizes.sm * 2;`, ADR-0070); the application's id
13
+ counter, an injection token (`idCounter`, ADR-0095), when the component makes ids; the
14
14
  injection tokens of the module's keys; the inline helpers (`refObject`, the native controls'
15
- `modelText`, `toggle`, `selectedValues`, `optionText`); the slot directives; the directives its listeners'
15
+ `modelText`, `toggle`, `selectedValues`, `optionText`); the slot directives; the pipe `innerHTML`
16
+ reads its markup through (`TrustedHtmlPipe`, ADR-0097); the directives its listeners'
16
17
  options need; the component.
17
18
 
18
19
  - **Types.** The source's type declarations the output reads (its inputs' and outputs' types, the
@@ -103,7 +104,7 @@ the template itself, which reads through `@let`, and a template statement's inpu
103
104
  | `let timer: T` | a field: `private timer: T \| undefined;`, `private refreshes = 0;` |
104
105
  | `let remaining = limit` (an input) | `private remaining!: number;`, assigned in `ngOnInit` (below) |
105
106
  | `const input = useTemplateRef<T>()` | `viewChild<ElementRef<T>>("input")`, with `#input` on the element |
106
- | `const id = useId()` | `` `uf-id-<component>-${nextId++}` ``: a module counter (emulated, `use-id`) |
107
+ | `const id = useId()` | `` `uf-id-<component>-${inject(idCounter).next++}` ``: a counter per application (emulated, `use-id`) |
107
108
  | `function save()`, arrow `const` | a method; one passed as a value (`setTimeout(tick, 100)`) an arrow field, which keeps `this`, declared before the other fields |
108
109
  | `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) |
109
110
  | `emit("change", value)` | `this.change.emit(value)`, by the payload rule |
@@ -112,6 +113,7 @@ the template itself, which reads through `@let`, and a template statement's inpu
112
113
  | `watchEffect(effect)` | `afterRenderEffect(effect)` in the constructor: after the render, in the browser only |
113
114
  | `onMounted(callback)` | `afterNextRender(callback)` in the constructor: in the browser, once the view is in the document |
114
115
  | `onUnmounted(callback)` | in `ngOnDestroy`, in the browser only |
116
+ | `const user = await loadUser(id)` | `protected user!: …;`, assigned in `ngOnInit` inside `PendingTasks.run`, the template behind `@if (resolved())` (below) |
115
117
 
116
118
  A watcher is created in `ngOnInit`, once the inputs are set, so the source's value at creation is
117
119
  known and typed: `let lastCount = currentCount();`. Its source goes through a `computed`
@@ -159,6 +161,23 @@ returns runs in a function of its own (`(() => { … })();`), so its `return` en
159
161
  `ngOnDestroy`. A callback the class runs (a hook, an effect, a watcher's) returns no value, as
160
162
  none is read: its `return x;` keeps only what `x` changes.
161
163
 
164
+ An async setup (ADR-0101) goes on in `ngOnInit`, where the inputs are set, inside
165
+ `this.pendingTasks.run(async () => { … })`: the server's render waits for the application to be
166
+ stable, which a pending task holds off, and so does every settle of the harness. Each awaited
167
+ binding is a field `ngOnInit` assigns, `protected user!: User;` with its annotation, or typed by
168
+ what the promise resolves to through a private method that makes it,
169
+ `Awaited<ReturnType<typeof this.initialUser>>` and `this.user = await this.initialUser();`. After
170
+ the awaits, `if (this.destroyRef.destroyed) return;` ends a setup whose component went while it
171
+ waited, then `ngOnInit`'s other code runs (the seeded reads, the watchers, and every hook and
172
+ `watchEffect`, registered there with `{ injector }`), then `this.resolved.set(true)`. What reads an
173
+ awaited binding is deferred as what reads an input is: a state is `linkedSignal`, a constant a
174
+ setup-once `computed`, a `let` assigned in `ngOnInit`, a composable's call made there. The
175
+ template, its `@let`s included, sits in `@if (resolved()) { … }`, which renders nothing but its
176
+ anchor comment until then; on a hydrated page Angular keeps the server's view of the `@if` and
177
+ claims it once `resolved` is set. `ngOnDestroy` runs the `onUnmounted` hooks only
178
+ `if (this.resolved())`. `PendingTasks.run` is a developer preview; `add()` with `finally` is its
179
+ stable form, and the target uses `run`, which reports a rejection to the `ErrorHandler`.
180
+
162
181
  ### Composables (ADR-0069)
163
182
 
164
183
  A `.uf.ts` module's composable is its own module, `use-toggle.ts` (`src/composable.ts`). It is an
@@ -235,7 +254,7 @@ parent, so the composable's effects stay the component's view effects.
235
254
  | `slots.title` as a condition | `this.titleTemplate()`, read from the class past any template variable |
236
255
  | `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 |
237
256
  | `v-model:value={cups.value}` | `[(value)]="this.cups"`, on the signal |
238
- | `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 |
257
+ | `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) |
239
258
  | `class` and `style` on a component | `[class]`, `[style]`: the child's `class` and `style` inputs, merged into its root; the host clears both |
240
259
  | `defineExpose({ focus })`, `ref={search}` | `focus` public; `viewChild<{ focus(): void }>("search")`, read as `this.search()?.focus()` |
241
260
  | `export const LocaleKey: InjectionKey<T>` | `export const LocaleKey = new InjectionToken<T>("…")` in the module's main component's file |
@@ -358,10 +377,11 @@ reported at a component's first stylesheet import.
358
377
  ### Capabilities
359
378
 
360
379
  Native: everything but `event-capture`, `event-once` and `event-passive` (emulated, the directives
361
- above, helper `uf<Event><Option>`), `use-id` (emulated, `nextId`), `next-tick` (emulated,
380
+ above, helper `uf<Event><Option>`), `use-id` (emulated, `idCounter`), `next-tick` (emulated,
362
381
  `nextTick`), `class-binding` (emulated, `classNames`, for a class part that may be an array or an
363
382
  object), `style-binding` (emulated, `styleObject`, for a style bound to a value that a merge
364
- spreads; ADR-0065) and composition's cells that ADR-0056 decides: `named-slot`, `scoped-slot` and
383
+ spreads; ADR-0065), `raw-html` (emulated, `TrustedHtmlPipe`, a pure pipe that marks `innerHTML`'s
384
+ 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
365
385
  `slot-forwarding` (emulated, the slot directives `uf<Component><Slot>`), `model-array`
366
386
  (`toggle`), `model-modifiers` (`modelText`), `fallthrough` (`fallthrough`), `reactive-context`
367
387
  (`refObject`) and `dynamic-component` (`@switch`), all emulated, `default-slot-presence` and
@@ -373,6 +393,12 @@ cannot infer. Where an unsupported cell is reported, the
373
393
  output still compiles: default-slot presence reads `true`, and the forwarded default slot
374
394
  re-projects `<ng-content />`.
375
395
 
396
+ `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.
397
+
398
+ `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.
399
+
400
+ `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.
401
+
376
402
  Inline content on either side of a child component's host reads with a space in the accessible
377
403
  name: Chrome adds one at every `display: contents` element, so Angular reads `Build passing` where
378
404
  the other targets read `Buildpassing`. `harness/quarantine/angular.ts` lists the cells until M3's
@@ -405,6 +431,11 @@ Tests and tooling build, check and run the Angular output through three subpaths
405
431
  since Angular cannot unset an input (ADR-0043). The test's listeners are bound to the outputs
406
432
  of their events (`outputBinding`, `ufChange` for `change`), and each payload is given back by
407
433
  its event's shape.
434
+ - `@unframework.dev/target-angular/toolchain/hydrate`: the hydrate adapter (L12, ADR-0095), which
435
+ moves the hydration marker and the `ng-state` script into `<body>`, then creates the component on
436
+ the server's host with `provideClientHydration()`, and reports NG05xx as mismatches.
437
+ `renderForHydration` adds `provideClientHydration()` and `provideServerRendering()`, and renders
438
+ one at a time.
408
439
  - `@unframework.dev/target-angular/toolchain/server`: the SSR renderer (`renderApplication`), which
409
440
  returns the component's HTML only. It runs on the `ssr` Vite configuration, which links
410
441
  Angular's packages as they load.
@@ -151,6 +151,7 @@ function itemCode(item, context) {
151
151
  }
152
152
  }
153
153
  case "TemplateRef":
154
+ case "Await":
154
155
  case "Id":
155
156
  case "Model":
156
157
  case "Provide":
@@ -0,0 +1,80 @@
1
+ import { ImportSet, NameScope, dependencyImports, directiveDependencies, directiveElement, directiveHooksObject, directiveModuleNames, directiveRunnerCode, hookQueueCode, js, kebabCase, printProgram, wrapperNames } from "@unframework.dev/codegen";
2
+ /** The inline helper that runs a directive's hooks as its element comes and goes. */
3
+ const RUNNER_HELPER = "runDirective";
4
+ /** The runner's names, each claimed through `claim` from its base. */
5
+ function runnerNames(claim) {
6
+ return {
7
+ run: claim(RUNNER_HELPER),
8
+ hooks: claim("DirectiveHooks"),
9
+ states: claim("directiveStates"),
10
+ watch: claim("watchDocument"),
11
+ watches: claim("documentWatches"),
12
+ checker: claim("directiveCheck"),
13
+ leftWatch: claim("watchLeft"),
14
+ queue: claim("queueHook")
15
+ };
16
+ }
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
+ }
21
+ /** The class an Angular directive is declared as: `VFocusTrap` for `vFocusTrap`. */
22
+ function directiveClassName(name) {
23
+ return `${name[0].toUpperCase()}${name.slice(1)}`;
24
+ }
25
+ /** The file a `.uf.ts` module's directive is written to: `v-focus-trap.ts` for `vFocusTrap`. */
26
+ function directiveFile(name) {
27
+ return kebabCase(name);
28
+ }
29
+ /** `@Directive({ selector: "[vFocusTrap]" }) export class VFocusTrap { … }`. */
30
+ function directiveClassCode(directive, className, run, imports) {
31
+ const core = (name, type = false) => imports.add("@angular/core", name, { type });
32
+ const own = wrapperNames(directive, [
33
+ "hooks",
34
+ "element",
35
+ "stop"
36
+ ]);
37
+ const element = directiveElement(directive);
38
+ const hooks = directiveHooksObject(directive).replaceAll("\n", "\n ");
39
+ const body = [
40
+ `const ${own.hooks} = ${hooks};`,
41
+ `const ${own.element} = this.element.nativeElement;`,
42
+ `let ${own.stop}: (() => void) | undefined;`,
43
+ `${core("afterRenderEffect")}(() => {`,
44
+ ` ${own.stop} = ${run}(${own.hooks}, ${own.element}, this.${directive.name}());`,
45
+ "});",
46
+ `${core("inject")}(${core("DestroyRef")}).onDestroy(() => ${own.stop}?.());`
47
+ ];
48
+ return [
49
+ `@${core("Directive")}({ selector: "[${directive.name}]" })`,
50
+ `export class ${className} {`,
51
+ ` readonly ${directive.name} = ${core("input")}.required<${directive.value.code}>();`,
52
+ ` private readonly element = ${core("inject")}<${core("ElementRef", true)}<${element}>>(${core("ElementRef")});`,
53
+ "",
54
+ " constructor() {",
55
+ ...body.map((line) => ` ${line}`),
56
+ " }",
57
+ "}",
58
+ ""
59
+ ].join("\n");
60
+ }
61
+ /** `v-focus-trap.ts`: a `.uf.ts` module's directive, as a standalone attribute directive. */
62
+ function emitDirective(directive, context) {
63
+ const dependencies = directiveDependencies(directive, context.module);
64
+ const imports = new ImportSet(new NameScope(directiveModuleNames(directive, dependencies)));
65
+ const runner = runnerNames((base) => imports.claim(base));
66
+ const directiveCode = directiveClassCode(directive, directiveClassName(directive.name), runner.run, imports);
67
+ return [{
68
+ path: `${directiveFile(directive.name)}.ts`,
69
+ contents: [
70
+ printProgram(js.program(imports.toDeclarations())).trim(),
71
+ ...dependencyImports(dependencies),
72
+ "",
73
+ ...dependencies.types.map((code) => `${code}\n`),
74
+ ...dependencies.constants.length ? [`${dependencies.constants.join("\n")}\n`] : [],
75
+ ...runnerCode(runner),
76
+ directiveCode
77
+ ].join("\n")
78
+ }];
79
+ }
80
+ export { RUNNER_HELPER, directiveClassCode, directiveClassName, directiveFile, emitDirective, runnerCode, runnerNames };
@@ -1,4 +1,4 @@
1
- import { exportDeclaration, js, printExpression } from "@unframework.dev/codegen";
1
+ import { TRUSTED_HTML_PIPE, exportDeclaration, js, printExpression } from "@unframework.dev/codegen";
2
2
  /**
3
3
  * A directive's declaration, its decorator apart (printed before the class, see ./index.ts):
4
4
  *
@@ -79,4 +79,268 @@ function scopeDirectiveCode(names, imports) {
79
79
  ""
80
80
  ].join("\n");
81
81
  }
82
- export { directiveCode, scopeDirectiveCode };
82
+ /**
83
+ * The directive that puts a bound `<textarea>`'s caret after its text once it is rendered
84
+ * (ADR-0095): once hydrated, the field keeps the server's text with the caret before it, where a
85
+ * client render sets the text of an empty field and leaves the caret after it. It empties the
86
+ * field and sets its text again, as ADR-0060 has React do, which fires no event
87
+ * (`setSelectionRange` would fire `select`). Angular runs a node's `ngOnInit` after its bindings,
88
+ * so in a client render the field already holds its text, and setting it again moves only the
89
+ * caret. It selects a field by that binding, which
90
+ * Angular matches as it does an attribute, so it adds no attribute to the DOM, and only the
91
+ * components that bind a `<textarea>` import it.
92
+ */
93
+ function textCaretDirectiveCode(className, imports) {
94
+ const core = (name, type = false) => imports.add("@angular/core", name, { type });
95
+ return `/** Puts a field's caret after its text, as setting the text of an empty field leaves it. */
96
+ @${core("Directive")}({ selector: "textarea[value]" })
97
+ export class ${className} implements ${core("OnInit", true)} {
98
+ private readonly element = ${core("inject")}<${core("ElementRef", true)}<HTMLTextAreaElement>>(${core("ElementRef")});
99
+
100
+ ngOnInit(): void {
101
+ const field = this.element.nativeElement;
102
+ const text = field.value;
103
+ field.value = "";
104
+ field.value = text;
105
+ }
106
+ }
107
+ `;
108
+ }
109
+ /** The attribute that selects the teleport directive (ADR-0098). */
110
+ const TELEPORT_ATTRIBUTE = "ufTeleport";
111
+ /** The input that hands the teleport directive its component's host, where it is the root. */
112
+ const TELEPORT_HOST_INPUT = "ufTeleportHost";
113
+ /**
114
+ * The directive that mounts a `<Teleport>`'s content into the element `to` selects (ADR-0098):
115
+ * `<ng-template ufTeleport="body">`. After a render that left its anchor in the document, so that
116
+ * neither the server nor the hydrating client renders it, it creates the template's view,
117
+ * attaches it to the application and appends its nodes to `to`, and it refreshes the view after
118
+ * every render, since the view reads the component's `@let` values, which mark it dirty in no
119
+ * signal. The view is in no view container, so neither an insertion nor a slot's projection
120
+ * moves a node it moved. A template projected into a slot that isn't rendered has no anchor in
121
+ * the document: it mounts when the slot renders, and unmounts when the slot goes. Destroying a
122
+ * view removes none of its nodes, so it removes them. At the root of its component, it takes the
123
+ * host's scope attributes off, which its styled parents put there and a teleport root takes
124
+ * nowhere, as Vue drops them. It is exported, as ngtsc's type-check imports every directive a
125
+ * template uses.
126
+ */
127
+ function teleportDirectiveCode(className, imports) {
128
+ const core = (name, type = false) => imports.add("@angular/core", name, { type });
129
+ return `/** The teleports a render created, which mount in the document's order. */
130
+ const ${className}Queue: { anchor: Node; mount: () => void }[] = [];
131
+
132
+ /** Mounts its template's content into the element \`${TELEPORT_ATTRIBUTE}\` selects once rendered, and removes it on destroy. */
133
+ @${core("Directive")}({ selector: "ng-template[${TELEPORT_ATTRIBUTE}]" })
134
+ export class ${className} implements ${core("OnInit", true)} {
135
+ readonly ${TELEPORT_ATTRIBUTE} = ${core("input")}.required<string>();
136
+ readonly ${TELEPORT_HOST_INPUT} = ${core("input")}<HTMLElement>();
137
+ private readonly renderer = ${core("inject")}(${core("Renderer2")});
138
+
139
+ ngOnInit(): void {
140
+ const host = this.${TELEPORT_HOST_INPUT}();
141
+ for (const name of host?.getAttributeNames() ?? []) {
142
+ if (name.startsWith("data-uf-")) this.renderer.removeAttribute(host, name);
143
+ }
144
+ }
145
+
146
+ constructor() {
147
+ const template = ${core("inject")}<${core("TemplateRef", true)}<unknown>>(${core("TemplateRef")});
148
+ const application = ${core("inject")}(${core("ApplicationRef")});
149
+ const document = ${core("inject")}(${core("DOCUMENT")});
150
+ const anchor: Node = ${core("inject")}<${core("ElementRef", true)}<Comment>>(${core("ElementRef")}).nativeElement;
151
+ let view: ${core("EmbeddedViewRef", true)}<unknown> | undefined;
152
+ const mount = () => {
153
+ const target = document.querySelector(this.${TELEPORT_ATTRIBUTE}());
154
+ if (!target) return;
155
+ view = template.createEmbeddedView({});
156
+ application.attachView(view);
157
+ view.detectChanges();
158
+ target.append(...view.rootNodes);
159
+ };
160
+ const unmount = () => {
161
+ const nodes: Node[] = view?.rootNodes ?? [];
162
+ view?.destroy();
163
+ view = undefined;
164
+ for (const node of nodes) node.parentNode?.removeChild(node);
165
+ };
166
+ // Angular runs a render's callbacks in no source order: each teleport queues itself, and the
167
+ // first to write mounts them all in the order of their anchors. A template projected into a
168
+ // slot that isn't rendered has no anchor in the document, so it waits for one.
169
+ ${core("afterEveryRender")}({
170
+ earlyRead: () => {
171
+ if (!view && anchor.isConnected) ${className}Queue.push({ anchor, mount });
172
+ },
173
+ write: () => {
174
+ const due = ${className}Queue.splice(0).sort((a, b) =>
175
+ a.anchor.compareDocumentPosition(b.anchor) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1,
176
+ );
177
+ for (const each of due) each.mount();
178
+ // The view reads the component's state, which this render may have changed.
179
+ if (view && !anchor.isConnected) unmount();
180
+ else view?.detectChanges();
181
+ },
182
+ });
183
+ ${core("inject")}(${core("DestroyRef")}).onDestroy(unmount);
184
+ }
185
+ }
186
+ `;
187
+ }
188
+ /** The attribute that selects the transition directive, and the name it is exported as (ADR-0100). */
189
+ const TRANSITION_ATTRIBUTE = "ufTransition";
190
+ /** The input that runs the enter on the element's first render too (`appear`). */
191
+ const TRANSITION_APPEAR_INPUT = "ufTransitionAppear";
192
+ /** The input that names the element's branch of the transition's conditional. */
193
+ const TRANSITION_BRANCH_INPUT = "ufTransitionBranch";
194
+ /** The attribute that selects a transition's region, around its conditional. */
195
+ const TRANSITION_REGION_ATTRIBUTE = "ufTransitionRegion";
196
+ /**
197
+ * The region of a `<Transition>` whose child is a conditional (ADR-0100):
198
+ * `<ng-container [ufTransitionRegion]="(open) ? 0 : -1">`, created with the transition, whose input
199
+ * is the branch shown. Angular sets it before it renders the conditional inside, so the branch is
200
+ * the new one as Angular removes an element. `ready` turns true once the region has rendered, so an
201
+ * element the conditional creates later enters, and one of the region's first render, as when a
202
+ * condition around the transition shows it again, enters only with `appear`, as on Vue.
203
+ * `afterNextRender` never runs on the server.
204
+ */
205
+ function transitionRegionCode(className, imports) {
206
+ const core = (name) => imports.add("@angular/core", name);
207
+ return `/** A transition's conditional: the branch it shows, and whether it has rendered once. */
208
+ @${core("Directive")}({ selector: "ng-container[${TRANSITION_REGION_ATTRIBUTE}]" })
209
+ export class ${className} {
210
+ readonly ${TRANSITION_REGION_ATTRIBUTE} = ${core("input")}.required<number>();
211
+ ready = false;
212
+
213
+ constructor() {
214
+ ${core("afterNextRender")}(() => {
215
+ this.ready = true;
216
+ });
217
+ }
218
+ }
219
+ `;
220
+ }
221
+ /**
222
+ * The directive that runs Vue's transition classes on its element (ADR-0100):
223
+ * `<p [ufTransition]="'fade'" [ufTransitionBranch]="0">`. After the render that created the
224
+ * element, it runs the enter if its transition's region had rendered before, or with `appear`.
225
+ * Angular's `(animate.leave)` holds the element's removal until `animationComplete()`. Angular
226
+ * also runs the leave of every element in a view that something around it removes, or that goes
227
+ * with its component, where Vue removes the element at once, so the leave runs only when the
228
+ * region shows another branch than the element's, and completes at once otherwise. Each phase adds
229
+ * its `-from` and `-active` classes, swaps `-from` for `-to` two frames later, as Vue does, and
230
+ * removes them at the end: the element's own `transitionend` or `animationend`, or its longest
231
+ * duration and delay, whichever comes first. Angular also completes a leave on any `animationend`
232
+ * that reaches the element, a child's included. It is exported, as ngtsc's type-check imports
233
+ * every directive a template uses.
234
+ */
235
+ function transitionDirectiveCode(className, region, imports) {
236
+ const core = (name, type = false) => imports.add("@angular/core", name, { type });
237
+ return `/** Runs Vue's transition classes of \`${TRANSITION_ATTRIBUTE}\` on its element as it enters and leaves. */
238
+ @${core("Directive")}({ selector: "[${TRANSITION_ATTRIBUTE}]", exportAs: "${TRANSITION_ATTRIBUTE}" })
239
+ export class ${className} implements ${core("OnInit", true)} {
240
+ readonly ${TRANSITION_ATTRIBUTE} = ${core("input")}.required<string>();
241
+ readonly ${TRANSITION_APPEAR_INPUT} = ${core("input")}(false);
242
+ readonly ${TRANSITION_BRANCH_INPUT} = ${core("input")}<number>();
243
+ private readonly region = ${core("inject")}(${region}, { optional: true });
244
+ private readonly element: Element = ${core("inject")}<${core("ElementRef", true)}<Element>>(${core("ElementRef")}).nativeElement;
245
+ private entering = false;
246
+ private stopEnter: (() => void) | undefined;
247
+
248
+ constructor() {
249
+ ${core("afterNextRender")}({
250
+ write: () => {
251
+ if (this.entering) this.stopEnter = this.run("enter");
252
+ },
253
+ });
254
+ ${core("inject")}(${core("DestroyRef")}).onDestroy(() => this.stopEnter?.());
255
+ }
256
+
257
+ ngOnInit(): void {
258
+ // Only an element with a branch of its own reads the region: one of a transition without a
259
+ // conditional finds the region of a transition around it, which says nothing of its own.
260
+ this.entering =
261
+ (this.${TRANSITION_BRANCH_INPUT}() !== undefined && Boolean(this.region?.ready)) ||
262
+ this.${TRANSITION_APPEAR_INPUT}();
263
+ }
264
+
265
+ /**
266
+ * \`(animate.leave)\`: runs the leave when the region shows another branch than the element's,
267
+ * and lets the element go at once when it still shows it: something around it removed it.
268
+ */
269
+ leave(event: ${core("AnimationCallbackEvent", true)}): void {
270
+ this.stopEnter?.();
271
+ if (!this.region || this.region.${TRANSITION_REGION_ATTRIBUTE}() === this.${TRANSITION_BRANCH_INPUT}()) {
272
+ event.animationComplete();
273
+ return;
274
+ }
275
+ this.run("leave", () => event.animationComplete());
276
+ }
277
+
278
+ private run(phase: "enter" | "leave", done?: () => void): () => void {
279
+ const { element } = this;
280
+ const from = \`\${this.${TRANSITION_ATTRIBUTE}()}-\${phase}-from\`;
281
+ const active = \`\${this.${TRANSITION_ATTRIBUTE}()}-\${phase}-active\`;
282
+ const to = \`\${this.${TRANSITION_ATTRIBUTE}()}-\${phase}-to\`;
283
+ let frame = 0;
284
+ let timer: ReturnType<typeof setTimeout> | undefined;
285
+ const stop = () => {
286
+ cancelAnimationFrame(frame);
287
+ clearTimeout(timer);
288
+ element.removeEventListener("transitionend", end);
289
+ element.removeEventListener("animationend", end);
290
+ element.classList.remove(from, active, to);
291
+ };
292
+ const end = (event?: Event) => {
293
+ if (event && event.target !== element) return;
294
+ stop();
295
+ done?.();
296
+ };
297
+ element.classList.add(from, active);
298
+ frame = requestAnimationFrame(() => {
299
+ frame = requestAnimationFrame(() => {
300
+ element.classList.remove(from);
301
+ element.classList.add(to);
302
+ const style = getComputedStyle(element);
303
+ const longest = (delays: string, durations: string) => {
304
+ const each = (list: string) => list.split(", ").map((time) => Number(time.slice(0, -1)) * 1000);
305
+ const delay = each(delays);
306
+ return Math.max(0, ...each(durations).map((duration, index) => duration + (delay[index % delay.length] ?? 0)));
307
+ };
308
+ const time = Math.max(
309
+ longest(style.transitionDelay, style.transitionDuration),
310
+ longest(style.animationDelay, style.animationDuration),
311
+ );
312
+ if (!time) {
313
+ end();
314
+ return;
315
+ }
316
+ element.addEventListener("transitionend", end);
317
+ element.addEventListener("animationend", end);
318
+ timer = setTimeout(end, time + 1);
319
+ });
320
+ });
321
+ return stop;
322
+ }
323
+ }
324
+ `;
325
+ }
326
+ /**
327
+ * The pure pipe `[innerHTML]` reads its markup through (ADR-0097). Angular sanitises a bound
328
+ * `innerHTML`, dropping `id`, `data-*` and `style` attributes, form controls and SVG, and marking
329
+ * the markup trusted renders it as written, as the other targets do. A pure pipe runs again only
330
+ * when the markup changes, so change detection sees one trusted value per string.
331
+ */
332
+ function trustedHtmlPipeCode(className, imports) {
333
+ const core = (name, type = false) => imports.add("@angular/core", name, { type });
334
+ const browser = (name, type = false) => imports.add("@angular/platform-browser", name, { type });
335
+ return `/** Marks markup trusted, so that \`[innerHTML]\` renders it as written. */
336
+ @${core("Pipe")}({ name: "${TRUSTED_HTML_PIPE}" })
337
+ class ${className} implements ${core("PipeTransform", true)} {
338
+ private readonly sanitizer = ${core("inject")}(${browser("DomSanitizer")});
339
+
340
+ transform(html: string): ${browser("SafeHtml", true)} {
341
+ return this.sanitizer.bypassSecurityTrustHtml(html);
342
+ }
343
+ }
344
+ `;
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 };