@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/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { emitComposable } from "./composable.js";
2
2
  import { firstUse, keyOf, planComposition, refObjectCode, slotDirectiveCode, tokenType } from "./composition.js";
3
- import { directiveCode, scopeDirectiveCode } from "./directives.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";
4
5
  import { planListeners } from "./listeners.js";
5
6
  import { classMembers } from "./members.js";
6
7
  import { planModels } from "./models.js";
@@ -10,7 +11,7 @@ import { ANGULAR_MEMBERS, bindingById, formOf, memberOf, moduleMember, planCompo
10
11
  import { classRules } from "./rules.js";
11
12
  import { fallthroughRoot, template, templateReads } from "./template.js";
12
13
  import { declaredTypes } from "./types.js";
13
- import { Placeholders, addTypeImports, angularDialect, codeKind, codeNames, componentTypes, defineTarget, exportDeclaration, exportsOf, js, kebabCase, moduleHelperName, printExpression, printProgram, rewriteCode, scopeRoots, sourceNames, typeDeclarationCode, typeExportsCode, typeNames } from "@unframework.dev/codegen";
14
+ 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";
14
15
  import { codeOf, functionsOf, walk } from "@unframework.dev/ir";
15
16
  /** The note the emulated cells share: why a listener's option needs a directive. */
16
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).";
@@ -59,8 +60,8 @@ const angular = defineTarget({
59
60
  "conditional-event-control": { support: "native" },
60
61
  "use-id": {
61
62
  support: "emulated",
62
- helper: "nextId",
63
- note: "Angular has no id API: a module counter makes each instance's ids, `uf-id-<component>-<n>`, as Angular Material makes its own."
63
+ helper: "idCounter",
64
+ note: "Angular has no id API: a counter makes each instance's ids, `uf-id-<component>-<n>`, as Angular Material makes its own. It is one per application, an injection token's, so a server render and the client that hydrates it count the same ids (ADR-0095)."
64
65
  },
65
66
  "next-tick": {
66
67
  support: "emulated",
@@ -85,6 +86,11 @@ const angular = defineTarget({
85
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)."
86
87
  },
87
88
  "attribute-spread": { support: "native" },
89
+ "raw-html": {
90
+ support: "emulated",
91
+ helper: "TrustedHtmlPipe",
92
+ note: "A pure pipe passes the markup through `DomSanitizer.bypassSecurityTrustHtml`, so Angular renders it as written instead of sanitising it."
93
+ },
88
94
  svg: { support: "native" },
89
95
  component: { support: "native" },
90
96
  "component-event": { support: "native" },
@@ -168,12 +174,31 @@ const angular = defineTarget({
168
174
  reason: "Angular infers a component's type parameter from its inputs alone, and a slot's directive cannot infer it, so a scoped slot's context takes the parameter's constraint, where the other targets type the consumer's fill by the type argument (ADR-0068)."
169
175
  },
170
176
  composables: { support: "native" },
171
- "composable-effect-order": { support: "native" }
177
+ "composable-effect-order": { support: "native" },
178
+ hydration: { support: "native" },
179
+ "async-setup": { support: "native" },
180
+ "keyed-identity": { support: "native" },
181
+ directive: {
182
+ support: "emulated",
183
+ 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."
185
+ },
186
+ transition: {
187
+ support: "emulated",
188
+ helper: "Transition",
189
+ note: "A `<Transition>`'s element takes an inline directive, `ufTransition`, and a conditional child sits in an `<ng-container>` whose inline directive, `TransitionRegion`, is created with the transition and holds the branch shown. The 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 something around the element removes it, so the directive lets the element go at once while its region still shows its branch (ADR-0100)."
190
+ },
191
+ teleport: {
192
+ support: "emulated",
193
+ helper: "Teleport",
194
+ note: "A `<Teleport>` is an `<ng-template>` whose inline directive, once the application has rendered, creates its view in its own view container and moves the view's nodes into `to`, as the CDK's `DomPortalOutlet` does, and removes them with the component (ADR-0098)."
195
+ }
172
196
  },
173
197
  emit(component, context) {
174
198
  return [emitComponent(component, context)];
175
199
  },
176
- emitComposable
200
+ emitComposable,
201
+ emitDirective
177
202
  });
178
203
  /** A component's output file. */
179
204
  function emitComponent(component, context) {
@@ -218,13 +243,30 @@ function emitComponent(component, context) {
218
243
  reportApiClashes(component, composition, fallthrough, context);
219
244
  const refObject = component.setup.some((item) => (item.kind === "Provide" || item.kind === "Inject" && item.fallback) && keyOf(plan, item.key).ref) ? imports.claim("refObject") : void 0;
220
245
  const provided = providers(plan, rules, composition, className, refObject);
221
- const nextId = component.setup.some((item) => item.kind === "Id") ? imports.claim("nextId") : void 0;
246
+ const nextId = component.setup.some((item) => item.kind === "Id") ? imports.claim("idCounter") : void 0;
222
247
  const directives = listeners.directives.map((spec) => directiveCode(spec, imports, placeholders));
248
+ const trustedHtml = rendersRawHtml(component) ? imports.claim("TrustedHtmlPipe") : void 0;
249
+ const teleport = holdsTeleport(component) ? imports.claim("Teleport") : void 0;
250
+ const transition = holdsTransition(component) ? {
251
+ className: imports.claim("Transition"),
252
+ regionClass: imports.claim("TransitionRegion"),
253
+ regions: holdsTransition(component, true),
254
+ ref: plan.members.claim("transition")
255
+ } : void 0;
256
+ const appliedImports = importedDirectives(component, module).map(({ specifier, imported }) => imports.add(directiveSpecifier(specifier, directiveFile(imported)), directiveClassName(imported), { exact: true }));
257
+ const ownApplied = ownDirectives(component, module);
258
+ const runner = ownApplied.length ? runnerNames((base) => imports.claim(base)) : void 0;
259
+ const ownClasses = ownApplied.map((directive) => ({
260
+ directive,
261
+ className: imports.claim(directiveClassName(directive.name))
262
+ }));
223
263
  const roots = scopedRoots(component);
224
264
  const scope = roots.size ? {
225
265
  ...scopeNames(component, module, imports),
226
266
  host: plan.members.claim("host")
227
267
  } : void 0;
268
+ const { render } = component;
269
+ const teleportHost = teleport !== void 0 && render.kind === "Fragment" && render.children.length === 1 && render.children[0].kind === "Teleport" ? scope?.host ?? plan.members.claim("host") : void 0;
228
270
  const { members, implements: interfaces } = classMembers({
229
271
  plan,
230
272
  placeholders,
@@ -248,10 +290,16 @@ function emitComponent(component, context) {
248
290
  });
249
291
  const metadata = js.objectExpression([
250
292
  ["selector", js.stringLiteral(`uf-${kebabCase(component.name)}`)],
251
- ...composition.imports.length || directives.length || scope ? [["imports", js.arrayExpression([
293
+ ...composition.imports.length || directives.length || scope || models.textCaret || trustedHtml || teleport || transition || appliedImports.length || ownClasses.length ? [["imports", js.arrayExpression([
252
294
  ...composition.imports,
253
295
  ...listeners.directives.map(({ className: name }) => name),
254
- ...scope ? [scope.className] : []
296
+ ...scope ? [scope.className] : [],
297
+ ...models.textCaret === void 0 ? [] : [models.textCaret],
298
+ ...trustedHtml === void 0 ? [] : [trustedHtml],
299
+ ...teleport === void 0 ? [] : [teleport],
300
+ ...transition === void 0 ? [] : [transition.className, ...transition.regions ? [transition.regionClass] : []],
301
+ ...appliedImports,
302
+ ...ownClasses.map(({ className: name }) => name)
255
303
  ].map((name) => js.identifier(name)))]] : [],
256
304
  ...provided.code.length ? [["providers", js.arrayExpression(provided.code.map((code) => placeholders.expression(code)))]] : [],
257
305
  ["host", clearsHost ? js.objectExpression([["[attr.class]", js.stringLiteral("null")], ["[attr.style]", js.stringLiteral("'display: contents;'")]]) : js.objectExpression([["style", js.stringLiteral("display: contents")]])],
@@ -259,15 +307,16 @@ function emitComponent(component, context) {
259
307
  ["template", js.templateLiteral(`\n${template(plan, listeners, reads, composition, models, fallthrough, scope && {
260
308
  roots,
261
309
  host: scope.host
262
- })}\n `)],
310
+ }, teleportHost, transition)}\n `)],
263
311
  ...component.styles ? [["styleUrl", js.stringLiteral(`./${module.file.slice(module.file.lastIndexOf("/") + 1)}.css`)], ["encapsulation", js.memberExpression(js.identifier(imports.add("@angular/core", "ViewEncapsulation")), "None")]] : []
264
312
  ]);
265
313
  const decorator = () => `@${printExpression(js.callExpression(js.identifier(decoratorName), [metadata]))}`;
266
- const hostMember = scope && [js.propertyDefinition(scope.host, placeholders.expression(`${imports.add("@angular/core", "inject")}<${imports.add("@angular/core", "ElementRef")}<HTMLElement>>(${imports.add("@angular/core", "ElementRef")}).nativeElement`), {
314
+ const hostName = scope?.host ?? teleportHost;
315
+ const hostMember = hostName !== void 0 && [js.propertyDefinition(hostName, placeholders.expression(`${imports.add("@angular/core", "inject")}<${imports.add("@angular/core", "ElementRef")}<HTMLElement>>(${imports.add("@angular/core", "ElementRef")}).nativeElement`), {
267
316
  accessibility: "protected",
268
317
  readonly: true
269
318
  })];
270
- const declaration = js.classDeclaration(className, [], [...members, ...hostMember ?? []], { implements: interfaces });
319
+ const declaration = js.classDeclaration(className, [], [...members, ...hostMember || []], { implements: interfaces });
271
320
  declaration.typeParameters = typeParameters(component, placeholders);
272
321
  const statements = exportDeclaration(className, declaration, exportsOf(component.name, module.exports));
273
322
  const types = declaredTypes(closure, typeRoots(component, module));
@@ -291,7 +340,13 @@ function emitComponent(component, context) {
291
340
  ...refObject === void 0 ? [] : [refObjectCode(refObject)],
292
341
  ...[...models.helpers, ...models.support].map(({ code }) => `${code}\n`),
293
342
  ...composition.slots.map((slot) => slotDirectiveCode(component.name, slot, imports.add("@angular/core", "Directive"), component.typeParameters)),
294
- ...scope ? [scopeDirectiveCode(scope, imports)] : []
343
+ ...scope ? [scopeDirectiveCode(scope, imports)] : [],
344
+ ...models.textCaret === void 0 ? [] : [textCaretDirectiveCode(models.textCaret, imports)],
345
+ ...trustedHtml === void 0 ? [] : [trustedHtmlPipeCode(trustedHtml, imports)],
346
+ ...teleport === void 0 ? [] : [teleportDirectiveCode(teleport, imports)],
347
+ ...transition === void 0 ? [] : [transitionRegionCode(transition.regionClass, imports), transitionDirectiveCode(transition.className, transition.regionClass, imports)],
348
+ ...runner === void 0 ? [] : runnerCode(runner),
349
+ ...ownClasses.map(({ directive, className: name }) => directiveClassCode(directive, name, runner?.run ?? "runDirective", imports))
295
350
  ];
296
351
  if (models.helpers.some(({ code }) => code.includes("WritableSignal"))) imports.add("@angular/core", "WritableSignal", { type: true });
297
352
  addTypeImports(component, module, imports, kebabCase);
@@ -301,11 +356,12 @@ function emitComponent(component, context) {
301
356
  code: typeDeclarationCode(type),
302
357
  span: type.span
303
358
  })), ...typeExportsCode(component, module, kebabCase)].toSorted((a, b) => a.span.start - b.span.start);
359
+ const idCounter = nextId === void 0 ? void 0 : `const ${nextId} = new ${imports.add("@angular/core", "InjectionToken")}<{ next: number }>("${nextId}", {\n factory: () => ({ next: 0 }),\n});\n`;
304
360
  const contents = placeholders.print(() => [
305
361
  printProgram(js.program(imports.toDeclarations())),
306
362
  ...typeCode.map(({ code }) => `${code}\n`),
307
363
  ...constants.constants.length ? [`${constants.constants.join("\n")}\n`] : [],
308
- ...nextId === void 0 ? [] : [`let ${nextId} = 0;\n`],
364
+ ...idCounter === void 0 ? [] : [idCounter],
309
365
  ...declarations,
310
366
  ...directives.map(({ decorator: written, statements: declared }) => `${written}\n${spaced(printProgram(js.program(declared)))}`),
311
367
  decorator(),
@@ -316,6 +372,33 @@ function emitComponent(component, context) {
316
372
  contents
317
373
  };
318
374
  }
375
+ /** Whether an element of the component's template sets `innerHTML` (ADR-0097). */
376
+ function rendersRawHtml(component) {
377
+ let found = false;
378
+ walk(component.render, { enter: (node) => {
379
+ if (node.kind === "Element" && node.attributes.some(({ kind }) => kind === "RawHtml")) found = true;
380
+ return found ? false : void 0;
381
+ } });
382
+ return found;
383
+ }
384
+ /** Whether the template holds a `<Transition>`, or one around a conditional (ADR-0100). */
385
+ function holdsTransition(component, conditional = false) {
386
+ let found = false;
387
+ walk(component.render, { enter: (node) => {
388
+ if (node.kind === "Transition" && (!conditional || node.children[0]?.kind === "If")) found = true;
389
+ return found ? false : void 0;
390
+ } });
391
+ return found;
392
+ }
393
+ /** Whether the template holds a `<Teleport>` (ADR-0098). */
394
+ function holdsTeleport(component) {
395
+ let found = false;
396
+ walk(component.render, { enter: (node) => {
397
+ if (node.kind === "Teleport") found = true;
398
+ return found ? false : void 0;
399
+ } });
400
+ return found;
401
+ }
319
402
  /** A span's key in a set of root nodes. */
320
403
  function spanKey({ start, end }) {
321
404
  return `${start}:${end}`;
package/dist/members.js CHANGED
@@ -10,13 +10,17 @@ import { functionBodyText, functionText, js, kebabCase, parameterText, pascalCas
10
10
  const SERVICES = [
11
11
  "injector",
12
12
  "platformId",
13
- "appRef"
13
+ "appRef",
14
+ "pendingTasks",
15
+ "destroyRef"
14
16
  ];
15
17
  /** Each service's token, by the member that holds it. */
16
18
  const TOKENS = {
17
19
  injector: "Injector",
18
20
  platformId: "PLATFORM_ID",
19
- appRef: "ApplicationRef"
21
+ appRef: "ApplicationRef",
22
+ pendingTasks: "PendingTasks",
23
+ destroyRef: "DestroyRef"
20
24
  };
21
25
  /** The class's members, and the interfaces it implements (`OnInit`). */
22
26
  function classMembers(context) {
@@ -64,21 +68,22 @@ function classMembers(context) {
64
68
  }));
65
69
  }
66
70
  const injected = /* @__PURE__ */ new Map();
71
+ const service = (name) => {
72
+ let entry = injected.get(name);
73
+ if (!entry) {
74
+ entry = {
75
+ member: plan.members.claim(name),
76
+ token: TOKENS[name]
77
+ };
78
+ injected.set(name, entry);
79
+ }
80
+ return entry.member;
81
+ };
67
82
  const names = {
68
83
  core,
69
84
  common: (name) => imports.add("@angular/common", name),
70
85
  type: (name) => imports.add("@angular/core", name, { type: true }),
71
- member: (name) => {
72
- let entry = injected.get(name);
73
- if (!entry) {
74
- entry = {
75
- member: plan.members.claim(name),
76
- token: TOKENS[name]
77
- };
78
- injected.set(name, entry);
79
- }
80
- return entry.member;
81
- }
86
+ member: service
82
87
  };
83
88
  const fields = [];
84
89
  const arrows = [];
@@ -117,9 +122,33 @@ function classMembers(context) {
117
122
  initCode[initCode.length - 1] = pins.join("\n");
118
123
  };
119
124
  const methods = [];
125
+ const awaits = [];
120
126
  const expression = (code) => placeholders.expression(code);
121
127
  const typed = (type) => type ? [placeholders.type(type)] : [];
122
128
  for (const item of component.setup) switch (item.kind) {
129
+ case "Await": {
130
+ const { name } = bindingById(plan, item.binding);
131
+ if (awaits.length === 0 && plan.resolved !== void 0) fields.push(js.propertyDefinition(plan.resolved, js.callExpression(js.identifier(core("signal")), [js.booleanLiteral(false)]), {
132
+ accessibility: "protected",
133
+ readonly: true
134
+ }));
135
+ let type = item.type?.code;
136
+ if (type === void 0) {
137
+ const initial = plan.members.claim(`initial${pascalCase(name)}`);
138
+ type = `Awaited<ReturnType<typeof this.${initial}>>`;
139
+ methods.push(js.methodDefinition(initial, [], statements(placeholders, `return ${pure(context, item.value)};`), { accessibility: "private" }));
140
+ awaits.push(`this.${name} = await this.${initial}();`);
141
+ } else awaits.push(`this.${name} = await ${pure(context, item.value)};`);
142
+ const field = js.propertyDefinition(name, null, {
143
+ accessibility: visibility(name),
144
+ typeAnnotation: placeholders.type(type)
145
+ });
146
+ fields.push({
147
+ ...field,
148
+ definite: true
149
+ });
150
+ break;
151
+ }
123
152
  case "State": {
124
153
  const { name } = bindingById(plan, item.binding);
125
154
  const form = formOf(plan, bindingById(plan, item.binding));
@@ -155,7 +184,7 @@ function classMembers(context) {
155
184
  case "Id": {
156
185
  const { name } = bindingById(plan, item.binding);
157
186
  if (context.nextId === void 0) throw new Error("An id is declared without a counter.");
158
- const id = `\`uf-id-${kebabCase(component.name)}-\${${context.nextId}++}\``;
187
+ const id = `\`uf-id-${kebabCase(component.name)}-\${${core("inject")}(${context.nextId}).next++}\``;
159
188
  fields.push(js.propertyDefinition(name, expression(id), {
160
189
  accessibility: visibility(name),
161
190
  readonly: true
@@ -337,6 +366,16 @@ function classMembers(context) {
337
366
  returnType: placeholders.type("Promise<void>")
338
367
  }));
339
368
  }
369
+ if (awaits.length && plan.resolved !== void 0) {
370
+ const rest = ["// Destroyed while it waited: the rest of the setup never runs.", `if (this.${service("destroyRef")}.destroyed) return;`].join("\n");
371
+ const body = [
372
+ awaits.join("\n"),
373
+ rest,
374
+ ...initCode,
375
+ `this.${plan.resolved}.set(true);`
376
+ ];
377
+ initCode.splice(0, initCode.length, `this.${service("pendingTasks")}.run(async () => {\n${body.join("\n\n")}\n});`);
378
+ }
340
379
  const services = SERVICES.flatMap((name) => injected.get(name) ?? []).map(({ member, token }) => js.propertyDefinition(member, js.callExpression(js.identifier(core("inject")), [js.identifier(core(token))]), {
341
380
  accessibility: "private",
342
381
  readonly: true
@@ -366,6 +405,7 @@ function classMembers(context) {
366
405
  implementing.push(imports.add("@angular/core", "OnInit", { type: true }));
367
406
  lifecycle.push(js.methodDefinition("ngOnInit", [], statements(placeholders, initCode.join("\n\n")), { returnType: js.keywordType("void") }));
368
407
  }
408
+ if (unmounted.length && plan.resolved !== void 0) unmounted.splice(0, unmounted.length, `if (this.${plan.resolved}()) {\n${unmounted.join("\n")}\n}`);
369
409
  if ([...destroyCode, ...unmounted].length) {
370
410
  implementing.push(imports.add("@angular/core", "OnDestroy", { type: true }));
371
411
  const why = destroyCode.length ? ["// Before Angular stops the outputs: a cleanup may still emit, as on every target."] : [];
package/dist/models.js CHANGED
@@ -117,6 +117,7 @@ function planModels(plan) {
117
117
  const styleObject = mergesWholeStyle(plan.component) ? helper("styleObject") : void 0;
118
118
  const rules = templateRules(plan);
119
119
  let server;
120
+ let textCaret;
120
121
  const render = mapElements(plan.component.render, (element) => {
121
122
  const model = element.attributes.find((attribute) => attribute.kind === "Model");
122
123
  if (!model) return element;
@@ -200,7 +201,7 @@ function planModels(plan) {
200
201
  };
201
202
  const value = optionValue(plan, option, rules, () => helper("optionText"));
202
203
  const selected = multiple ? `${signal}().includes(${value})` : `${signal}() === ${value}`;
203
- options.set(added, `[selected]="${angularCode(selected, "attribute")}" [defaultSelected]="${angularCode(`${server} && ${selected}`, "attribute")}"`);
204
+ options.set(added, `[defaultSelected]="${angularCode(`${server} && ${selected}`, "attribute")}" [selected]="${angularCode(selected, "attribute")}"`);
204
205
  return {
205
206
  ...option,
206
207
  attributes: [...option.attributes, added]
@@ -211,6 +212,7 @@ function planModels(plan) {
211
212
  children: element.children.map((child) => mapElements(child, withSelected))
212
213
  };
213
214
  }
215
+ if (model.control === "textarea") textCaret ??= plan.imports.claim("TextCaret");
214
216
  if (variable !== void 0) printed.unshift({
215
217
  name: `#${variable}`,
216
218
  text: `#${variable}`
@@ -227,6 +229,7 @@ function planModels(plan) {
227
229
  ...server === void 0 ? {} : { server },
228
230
  ...classNames === void 0 ? {} : { classNames },
229
231
  ...styleObject === void 0 ? {} : { styleObject },
232
+ ...textCaret === void 0 ? {} : { textCaret },
230
233
  helpers: used.filter(([base]) => base !== "looseToNumber").map(([, each]) => each),
231
234
  support: used.filter(([base]) => base === "looseToNumber").map(([, each]) => each)
232
235
  };
package/dist/narrowing.js CHANGED
@@ -55,7 +55,8 @@ function assertedSetup(component) {
55
55
  ...item,
56
56
  initial: code(item.initial)
57
57
  } : item;
58
- case "Const": return {
58
+ case "Const":
59
+ case "Await": return {
59
60
  ...item,
60
61
  value: code(item.value)
61
62
  };
package/dist/plan.js CHANGED
@@ -23,6 +23,7 @@ const ANGULAR_IMPORTS = [
23
23
  "OnDestroy",
24
24
  "OnInit",
25
25
  "PLATFORM_ID",
26
+ "PendingTasks",
26
27
  "Renderer2",
27
28
  "Signal",
28
29
  "InjectionToken",
@@ -104,6 +105,7 @@ function planComponent(declared, module) {
104
105
  ...injector === void 0 ? {} : { injector }
105
106
  }];
106
107
  });
108
+ const resolved = component.setup.some((item) => item.kind === "Await") ? claimMember("resolved") : void 0;
107
109
  const results = new Map(calls.flatMap(({ item, holder }) => item.members.map(({ member, binding }) => [binding, `${holder}.${member}`])));
108
110
  return {
109
111
  component,
@@ -130,7 +132,8 @@ function planComponent(declared, module) {
130
132
  calls,
131
133
  results,
132
134
  moduleMembers,
133
- late
135
+ late,
136
+ ...resolved === void 0 ? {} : { resolved }
134
137
  };
135
138
  }
136
139
  /** A module's constant or a value imported from a `.ts` module (ADR-0070). */
@@ -197,6 +200,7 @@ function outputSafeName(name, kind) {
197
200
  case "state":
198
201
  case "derived":
199
202
  case "localConst":
203
+ case "awaited":
200
204
  case "localVar":
201
205
  case "prop":
202
206
  case "loopVar":
@@ -246,7 +250,8 @@ function formsOf(component) {
246
250
  case "templateRef":
247
251
  case "localConst":
248
252
  case "localFn":
249
- case "localVar": break;
253
+ case "localVar":
254
+ case "awaited": break;
250
255
  case "slotScope":
251
256
  forms.set(binding.id, "loop");
252
257
  break;
@@ -276,6 +281,11 @@ function formsOf(component) {
276
281
  let defers = false;
277
282
  const late = /* @__PURE__ */ new Set();
278
283
  for (const item of component.setup) switch (item.kind) {
284
+ case "Await":
285
+ forms.set(item.binding, "value");
286
+ lazy.add(item.binding);
287
+ defers = true;
288
+ break;
279
289
  case "State": {
280
290
  const linked = item.initial !== void 0 && readsLazily(item.initial);
281
291
  forms.set(item.binding, linked ? "linked" : "signal");
@@ -374,6 +384,7 @@ function escapingFunctions(component) {
374
384
  if (item.initial) visit(item.initial);
375
385
  break;
376
386
  case "Const":
387
+ case "Await":
377
388
  visit(item.value);
378
389
  break;
379
390
  case "Derived":
@@ -407,6 +418,10 @@ function escapingFunctions(component) {
407
418
  case "Model": break;
408
419
  default: unreachable(item);
409
420
  }
421
+ walk(component.render, { enter(node) {
422
+ if (node.kind !== "Element") return;
423
+ for (const attribute of node.attributes) if (attribute.kind === "Directive") visit(attribute.value);
424
+ } });
410
425
  return escaping;
411
426
  }
412
427
  /** Whether a binding is a list's item or index, which the `@for` declares: no member. */
@@ -418,6 +433,7 @@ function isLoopVariable(kind) {
418
433
  case "derived":
419
434
  case "templateRef":
420
435
  case "localConst":
436
+ case "awaited":
421
437
  case "localFn":
422
438
  case "localVar":
423
439
  case "emit":
@@ -446,6 +462,7 @@ function isFunction(kind) {
446
462
  case "derived":
447
463
  case "templateRef":
448
464
  case "localConst":
465
+ case "awaited":
449
466
  case "localVar":
450
467
  case "emit":
451
468
  case "model":
@@ -465,15 +482,17 @@ function isFunction(kind) {
465
482
  }
466
483
  /**
467
484
  * Whether a binding of this kind is read lazily whatever its item: an input (unset while the
468
- * class constructs) or a derived value (a `computed` that may read one). A state or a constant
469
- * is lazy when its own value reads one (`formsOf`).
485
+ * class constructs), a derived value (a `computed` that may read one) or an awaited value (set
486
+ * once its promise resolves, ADR-0101). A state or a constant is lazy when its own value reads
487
+ * one (`formsOf`).
470
488
  */
471
489
  function readLazily(kind) {
472
490
  switch (kind) {
473
491
  case "prop":
474
492
  case "model":
475
493
  case "derived":
476
- case "context": return true;
494
+ case "context":
495
+ case "awaited": return true;
477
496
  case "loopVar":
478
497
  case "state":
479
498
  case "templateRef":
package/dist/seeded.js CHANGED
@@ -274,6 +274,7 @@ function bindingType(id, plan, declarations, seen) {
274
274
  case "Const": return item.type?.code ?? valueType(item.value, plan, declarations, next);
275
275
  case "Variable": return item.type?.code ?? (item.initial && valueType(item.initial, plan, declarations, next));
276
276
  case "Id": return "string";
277
+ case "Await": return item.type?.code;
277
278
  default: return;
278
279
  }
279
280
  }
package/dist/template.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { selectorOf } from "./composition.js";
2
+ import { TELEPORT_ATTRIBUTE, TELEPORT_HOST_INPUT } from "./directives.js";
2
3
  import { outputName } from "./outputs.js";
3
4
  import { bindingById, memberOf, unreachable } from "./plan.js";
4
5
  import { readThroughLet, templateRules } from "./rules.js";
@@ -26,9 +27,10 @@ const LEVEL = 2;
26
27
  * (NG8009), so a signal a list's key reads is read there from the class, `this.label()`, and
27
28
  * counts as no use of its variable (an unread `@let` is NG8112).
28
29
  */
29
- function template(plan, listeners, reads, composition, models, fallthrough, scope) {
30
+ function template(plan, listeners, reads, composition, models, fallthrough, scope, teleportHost, transition) {
30
31
  const { component } = plan;
31
- const pad = INDENT.repeat(LEVEL);
32
+ const level = plan.resolved === void 0 ? LEVEL : 3;
33
+ const pad = INDENT.repeat(level);
32
34
  const lets = [];
33
35
  const declare = (id) => {
34
36
  if (id === void 0 || !reads.read.has(id)) return;
@@ -42,6 +44,65 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
42
44
  }
43
45
  const dialect = {
44
46
  ...angularDialect,
47
+ teleport: ({ node }) => [{
48
+ kind: "wrapper",
49
+ tag: "ng-template",
50
+ attributes: [{
51
+ name: TELEPORT_ATTRIBUTE,
52
+ text: angularDialect.attribute(TELEPORT_ATTRIBUTE, node.to, "")
53
+ }, ...teleportHost !== void 0 && component.render.kind === "Fragment" && component.render.children[0]?.span.start === node.span.start ? [{
54
+ name: TELEPORT_HOST_INPUT,
55
+ text: `[${TELEPORT_HOST_INPUT}]="this.${teleportHost}"`
56
+ }] : []],
57
+ content: {
58
+ kind: "nodes",
59
+ nodes: node.children,
60
+ container: node
61
+ }
62
+ }],
63
+ ...transition && {
64
+ transition: ({ node, container, branch }) => {
65
+ const nodes = {
66
+ kind: "nodes",
67
+ nodes: node.children,
68
+ container
69
+ };
70
+ if (node.children[0]?.kind !== "If") return [nodes];
71
+ return [{
72
+ kind: "wrapper",
73
+ tag: "ng-container",
74
+ attributes: [{
75
+ name: "ufTransitionRegion",
76
+ text: `[ufTransitionRegion]="${branch}"`
77
+ }],
78
+ content: nodes
79
+ }];
80
+ },
81
+ transitionAttributes: ({ node, branch }) => [
82
+ {
83
+ name: "ufTransition",
84
+ text: `[ufTransition]="${angularString(node.name)}"`
85
+ },
86
+ ...node.appear ? [{
87
+ name: "ufTransitionAppear",
88
+ text: `[ufTransitionAppear]="true"`
89
+ }] : [],
90
+ ...branch === void 0 ? [] : [
91
+ {
92
+ name: "ufTransitionBranch",
93
+ text: `[ufTransitionBranch]="${branch}"`
94
+ },
95
+ {
96
+ name: `#${transition.ref}`,
97
+ text: `#${transition.ref}="ufTransition"`
98
+ },
99
+ {
100
+ name: "(animate.leave)",
101
+ text: `(animate.leave)="${transition.ref}.leave($event)"`
102
+ }
103
+ ]
104
+ ]
105
+ },
45
106
  componentTag: (name) => composition.tags.get(name) ?? selectorOf(name),
46
107
  componentEvent: ({ attribute }) => {
47
108
  const name = `(${outputName(attribute.event)})`;
@@ -83,7 +144,7 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
83
144
  const render = fallthrough ? withFallthrough(models.render) : models.render;
84
145
  const markup = printMarkup(render, dialect, {
85
146
  indent: INDENT,
86
- level: LEVEL,
147
+ level,
87
148
  component,
88
149
  module: plan.module,
89
150
  rewrite: templateRules(plan, reads.signals),
@@ -91,12 +152,10 @@ function template(plan, listeners, reads, composition, models, fallthrough, scop
91
152
  attribute: (attribute) => attribute.kind === "Event" ? listeners.attributes.get(attribute) : models.options.get(attribute),
92
153
  scopeRootAttributes: ({ span }) => scope?.roots.has(`${span.start}:${span.end}`) ? [`[ufScope]="this.${scope.host}"`] : []
93
154
  });
94
- const selects = composition.slots.map(({ attribute }) => `${pad}<ng-content select="[${attribute}]" />`);
95
- return [
96
- ...lets,
97
- markup,
98
- ...selects
99
- ].join("\n");
155
+ const outer = INDENT.repeat(LEVEL);
156
+ const selects = composition.slots.map(({ attribute }) => `${outer}<ng-content select="[${attribute}]" />`);
157
+ const content = [...lets, markup].join("\n");
158
+ return [plan.resolved === void 0 ? content : `${outer}@if (${plan.resolved}()) {\n${content}\n${outer}}`, ...selects].join("\n");
100
159
  }
101
160
  /**
102
161
  * The component's root (an element, or a fragment of one element or component), which a
@@ -240,4 +299,8 @@ function templateReads(plan, listeners) {
240
299
  signals
241
300
  };
242
301
  }
302
+ /** A string literal in a bound attribute's expression: single-quoted, its quotes escaped. */
303
+ function angularString(value) {
304
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/&/g, "&amp;").replace(/"/g, "&quot;")}'`;
305
+ }
243
306
  export { fallthroughRoot, template, templateReads };
@@ -1,4 +1,5 @@
1
- import { MountAdapter } from "@unframework.dev/codegen";
1
+ import { MountAdapter, MountEvent, MountListener } from "@unframework.dev/codegen";
2
+ import { Binding, ComponentRef } from "@angular/core";
2
3
  /**
3
4
  * Mounts a component as its own zoneless application. `createComponent` rather than
4
5
  * `bootstrapApplication`: it sets inputs before the first change detection, and adds neither
@@ -7,4 +8,17 @@ import { MountAdapter } from "@unframework.dev/codegen";
7
8
  * component's outputs, each named as its event (ADR-0012), when it is created, as a parent's
8
9
  * `(change)` would be: they outlive every rerender, which sets inputs only.
9
10
  */
10
- export declare const mount: MountAdapter;
11
+ export declare const mount: MountAdapter;
12
+ /**
13
+ * Sets every input `props` has, and each input set before that `props` lacks to `undefined`:
14
+ * an input cannot be unset, and the emitted input's transform turns `undefined` into its
15
+ * default (ADR-0043). For a name that is not an input, Angular logs NG0303, which fails L13.
16
+ */
17
+ export declare function setInputs(ref: ComponentRef<unknown>, set: Set<string>, props: Readonly<Record<string, unknown>>): void;
18
+ /**
19
+ * A binding of each listener to the output of its event's name. An `output()` emits one value,
20
+ * so the target emits a payload by its shape (ADR-0047): nothing for an event without members,
21
+ * the value for one required member, and the tuple of the arguments otherwise; the listener gets
22
+ * the arguments back, exactly as many as the component passed.
23
+ */
24
+ export declare function outputBindings(on?: Readonly<Record<string, MountListener>>, events?: readonly MountEvent[]): Binding[];
@@ -76,4 +76,4 @@ function outputBindings(on = {}, events = []) {
76
76
  });
77
77
  });
78
78
  }
79
- export { mount };
79
+ export { mount, outputBindings, setInputs };
@@ -0,0 +1,12 @@
1
+ import { HydrateAdapter } from "@unframework.dev/codegen";
2
+ /**
3
+ * Hydrates `html` (from `renderForHydration`) as a zoneless application with
4
+ * `provideClientHydration()`: the hydration marker (`<!--nghm-->`) and the state script
5
+ * (`ng-state`) go where Angular reads them, as direct children of `<body>`, and the host element
6
+ * into the container, where `createComponent` takes it as its host and hydrates the view the
7
+ * server's `ngh` annotations describe. An NG05xx error, thrown while the component is created
8
+ * or reported through the `ErrorHandler` in a later change detection, and the NG0505 warning
9
+ * that hydration never started, are mismatches. The marker and the script are removed once the
10
+ * component has hydrated, so the next test's hydration never reads them.
11
+ */
12
+ export declare const hydrate: HydrateAdapter;