@molecule/app-angular 3.12.1 → 3.13.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.
@@ -8,11 +8,19 @@
8
8
  * ({@link setElementPresent}, {@link useHostPresence});
9
9
  * - an element rendered in another parent, React's `createPortal`
10
10
  * ({@link placeElement});
11
+ * - an element or a slot's content rendered beside the component's host,
12
+ * React's fragment root ({@link placeElementBefore},
13
+ * {@link placeContentBefore});
11
14
  * - a slot's content rendered in another parent ({@link placeContent});
12
15
  * - one wrapper element per projected child, React's
13
16
  * `children.map((c) => <div>{c}</div>)` ({@link WrappedChildren},
14
17
  * {@link MolWrapEachChild}).
15
18
  *
19
+ * A node that was placed still has one parent in the rendered tree, the one
20
+ * React context follows ({@link renderedParent}), and what a consumer binds on
21
+ * the tag of a component whose host left the page lands on the component's
22
+ * root ({@link setHostRoot}).
23
+ *
16
24
  * Angular keeps inserting, moving and removing the nodes it created, and it
17
25
  * finds their place through the nodes themselves: it inserts a view before the
18
26
  * first node of the next view, under the parent of the container's anchor
@@ -20,9 +28,15 @@
20
28
  * placement rules are applied where Angular places nodes, in its renderer
21
29
  * ({@link provideDomPlacement}); components never move a node themselves.
22
30
  *
31
+ * A host or a capture that is out of the page has no `parentNode`, so a
32
+ * component never reads one to decide where something goes: it names the
33
+ * element to stand in front of ({@link placeElementBefore},
34
+ * {@link placeContentBefore}), which follows that element wherever it is, and
35
+ * finds its rendered ancestors with {@link renderedParent}.
36
+ *
23
37
  * @module
24
38
  */
25
- import { afterEveryRender, ChangeDetectorRef, DestroyRef, Directive, effect, ElementRef, inject, Injectable, InjectionToken, makeEnvironmentProviders, provideEnvironmentInitializer, RendererFactory2, signal, } from '@angular/core';
39
+ import { afterEveryRender, ChangeDetectorRef, DestroyRef, Directive, effect, ElementRef, inject, Injectable, InjectionToken, isDevMode, makeEnvironmentProviders, provideEnvironmentInitializer, reflectComponentType, RendererFactory2, signal, untracked, } from '@angular/core';
26
40
  import * as i0 from "@angular/core";
27
41
  /** Set once {@link provideDomPlacement} decorated the application's renderer factory. */
28
42
  const DOM_PLACEMENT = new InjectionToken('@molecule/app-angular DOM placement');
@@ -41,7 +55,284 @@ const wrapperOwners = new WeakMap();
41
55
  * a view's root nodes, so an element moved out of a component goes when its
42
56
  * placeholder's view goes (React unmounts a portal with its owner).
43
57
  */
44
- const elsewhere = new Set();
58
+ const elsewhere = new WeakSet();
59
+ /**
60
+ * A node → what {@link placeElementBefore} and {@link placeContentBefore}
61
+ * rendered in front of it, in render order. It stands in front of the node
62
+ * wherever Angular puts the node.
63
+ */
64
+ const leaders = new WeakMap();
65
+ /** An element rendered in front of another node → that node. */
66
+ const led = new WeakMap();
67
+ /** A capture whose content is rendered in front of another node → that node. */
68
+ const ledContent = new WeakMap();
69
+ /** A placeholder → the absent element whose place it holds. */
70
+ const heldPlaces = new WeakMap();
71
+ /**
72
+ * Set once anything was rendered outside its place ({@link placeElement},
73
+ * {@link placeContent}); until then a removal has nothing to take along.
74
+ */
75
+ let rendersElsewhere = false;
76
+ /** A host whose component calls {@link usePlacement} → what the consumer bound on its tag. */
77
+ const tagBindings = new WeakMap();
78
+ /** Attributes that are Angular's own, never the consumer's. */
79
+ const isFrameworkAttribute = (name) => name.startsWith('_ng') || name.startsWith('ng-') || name === 'ngskiphydration';
80
+ /**
81
+ * The input and output names of the component a view belongs to; the input
82
+ * names lower-cased, as the DOM writes attribute names.
83
+ *
84
+ * @param view - The component's own change detector, whose context is the
85
+ * component instance once Angular created it.
86
+ * @returns The names.
87
+ */
88
+ function memberNames(view) {
89
+ const component = view?.context;
90
+ const mirror = component ? reflectComponentType(component.constructor) : null;
91
+ return {
92
+ inputs: new Set((mirror?.inputs ?? []).map((input) => input.templateName.toLowerCase())),
93
+ outputs: new Set((mirror?.outputs ?? []).map((output) => output.templateName)),
94
+ };
95
+ }
96
+ /**
97
+ * Whether an element is out of the page with its place held: a host whose
98
+ * component rendered its DOM in the host's place.
99
+ *
100
+ * @param element - The host.
101
+ * @returns Whether it is absent.
102
+ */
103
+ const isAbsent = (element) => placeholders.has(element) && !elsewhere.has(element);
104
+ /**
105
+ * The elements a host renders in its own place: the elements placed in front
106
+ * of it and the top-level elements of the content placed in front of it.
107
+ *
108
+ * @param host - The host.
109
+ * @returns The elements, in order.
110
+ */
111
+ function ledElements(host) {
112
+ const elements = [];
113
+ for (const leader of leaders.get(host) ?? []) {
114
+ if (!leader.content) {
115
+ if (leader.node.nodeType === 1)
116
+ elements.push(leader.node);
117
+ continue;
118
+ }
119
+ const range = contentRanges.get(leader.node);
120
+ if (range === undefined)
121
+ continue;
122
+ for (let node = range.start.nextSibling; node !== null && node !== range.end; node = node.nextSibling) {
123
+ if (node.nodeType === 1)
124
+ elements.push(node);
125
+ }
126
+ }
127
+ return elements;
128
+ }
129
+ /**
130
+ * Takes what was written for a tag off the root that carried it and puts it
131
+ * back on the host, where the next root finds it.
132
+ *
133
+ * @param host - The host.
134
+ * @param bindings - Its bindings.
135
+ */
136
+ function returnTagAttributes(host, bindings) {
137
+ const target = bindings.target;
138
+ if (target === null)
139
+ return;
140
+ for (const [name, value] of bindings.attributes) {
141
+ target.removeAttribute(name);
142
+ host.setAttribute(name, value);
143
+ }
144
+ for (const name of bindings.classes) {
145
+ target.classList.remove(name);
146
+ host.classList.add(name);
147
+ }
148
+ for (const [name, value] of bindings.styles) {
149
+ ;
150
+ target.style.removeProperty(name);
151
+ host.style.setProperty(name, value);
152
+ }
153
+ bindings.attributes.clear();
154
+ bindings.classes.clear();
155
+ bindings.styles.clear();
156
+ bindings.target = null;
157
+ }
158
+ /**
159
+ * Moves everything the consumer wrote on the host onto the root that stands
160
+ * for it.
161
+ *
162
+ * @param host - The host.
163
+ * @param bindings - Its bindings, with `target` set.
164
+ */
165
+ function moveTagAttributes(host, bindings) {
166
+ const target = bindings.target;
167
+ for (const attribute of Array.from(host.attributes)) {
168
+ const name = attribute.name;
169
+ if (isFrameworkAttribute(name) || bindings.except.has(name) || bindings.inputs().has(name))
170
+ continue;
171
+ if (name === 'class') {
172
+ for (const token of Array.from(host.classList)) {
173
+ target.classList.add(token);
174
+ bindings.classes.add(token);
175
+ }
176
+ }
177
+ else if (name === 'style') {
178
+ const style = host.style;
179
+ for (const property of Array.from(style)) {
180
+ const value = style.getPropertyValue(property);
181
+ target.style.setProperty(property, value, style.getPropertyPriority(property));
182
+ bindings.styles.set(property, value);
183
+ }
184
+ }
185
+ else {
186
+ target.setAttribute(name, attribute.value);
187
+ bindings.attributes.set(name, attribute.value);
188
+ }
189
+ host.removeAttribute(name);
190
+ }
191
+ }
192
+ /**
193
+ * Applies what the consumer bound on a component's tag to the DOM the
194
+ * component rendered in its host's place; see {@link setHostRoot}.
195
+ *
196
+ * @param host - The host.
197
+ * @param settled - Whether the render is complete (the moment to refuse a
198
+ * binding that has nowhere to land).
199
+ */
200
+ function syncTagBindings(host, settled) {
201
+ const bindings = tagBindings.get(host);
202
+ if (bindings === undefined)
203
+ return;
204
+ // Nothing bound on the tag (the usual case): nothing to read.
205
+ if (bindings.listeners.size === 0 && bindings.target === null && !host.hasAttributes())
206
+ return;
207
+ const absent = isAbsent(host);
208
+ const named = bindings.named;
209
+ const first = leaders.get(host);
210
+ // Listeners: the named root, else every element in the host's place (the
211
+ // events that bubbled to the host while it enclosed them).
212
+ const roots = !absent
213
+ ? []
214
+ : named !== undefined
215
+ ? named === null
216
+ ? []
217
+ : [named]
218
+ : bindings.listeners.size > 0
219
+ ? ledElements(host)
220
+ : [];
221
+ for (const listener of bindings.listeners) {
222
+ // Angular also listens natively for a name that is one of the component's outputs; the consumer means the output.
223
+ if (bindings.outputs().has(listener.name))
224
+ continue;
225
+ for (const [root, detach] of listener.attached) {
226
+ if (roots.includes(root))
227
+ continue;
228
+ detach();
229
+ listener.attached.delete(root);
230
+ }
231
+ if (bindings.renderer === null)
232
+ continue;
233
+ for (const root of roots) {
234
+ if (listener.attached.has(root))
235
+ continue;
236
+ const listen = bindings.renderer.listen;
237
+ listener.attached.set(root, listen.call(bindings.renderer, root, listener.name, listener.callback, listener.options));
238
+ }
239
+ }
240
+ // Attributes, classes and styles: the named root, else the component's one element.
241
+ const single = first?.length === 1 && !first[0].content && first[0].node.nodeType === 1
242
+ ? first[0].node
243
+ : null;
244
+ const target = !absent ? null : named !== undefined ? named : single;
245
+ if (target !== bindings.target) {
246
+ returnTagAttributes(host, bindings);
247
+ bindings.target = target;
248
+ }
249
+ if (target !== null)
250
+ moveTagAttributes(host, bindings);
251
+ if (!settled || !absent || !isDevMode())
252
+ return;
253
+ const nowhere = named === undefined && (first?.length ?? 0) === 0;
254
+ const unheard = Array.from(bindings.listeners).filter((listener) => !bindings.outputs().has(listener.name));
255
+ if (nowhere && unheard.length > 0) {
256
+ const names = unheard.map((listener) => `(${listener.name})`).join(', ');
257
+ throw new Error(`${names} is bound on <${bindings.tag}>, which renders no element in its place, so it can never fire. ` +
258
+ `Bind it on an element inside, or use the component's own outputs.`);
259
+ }
260
+ }
261
+ /**
262
+ * Names the element that stands for the calling component's host: React's
263
+ * `{...rest}` target. Call it in the component's {@link usePlacement}
264
+ * function, for a component whose host is out of the page.
265
+ *
266
+ * An Angular consumer binds on the component's tag: `<mol-switch
267
+ * (keydown)="…" class="…" data-testid="…" [attr.aria-label]="…">`. With the
268
+ * host out of the page those would do nothing. Instead, while the host is
269
+ * absent:
270
+ *
271
+ * - native listeners are attached to the root (`$event.currentTarget` is the
272
+ * root, as it is in React);
273
+ * - attributes, class names and styles the consumer writes on the tag are
274
+ * written on the root, in the same instruction, and the ones already on the
275
+ * host are moved there.
276
+ *
277
+ * A component that calls nothing gets the common case for free: with one
278
+ * element in its place (`placeElementBefore(root, host)`) that element is the
279
+ * root; with several elements or projected content in its place, listeners go
280
+ * to each of them (the events that used to bubble to the host) and attributes
281
+ * stay on the host. A component with nothing in its place (a portal) names its
282
+ * root, or a listener on its tag throws in dev mode: it could never fire.
283
+ *
284
+ * @param host - The component's host element.
285
+ * @param root - The element that stands for it, or `null` while React renders
286
+ * none.
287
+ * @param options - `except`: attribute names the component reads off its host
288
+ * itself (it merges them with its own), which stay on the host.
289
+ * @param options.except - Those attribute names.
290
+ */
291
+ export function setHostRoot(host, root, options = {}) {
292
+ const bindings = tagBindings.get(host);
293
+ if (bindings === undefined) {
294
+ throw new Error('setHostRoot() is called in the usePlacement() function of the component whose host it is.');
295
+ }
296
+ bindings.named = root ?? null;
297
+ if (options.except !== undefined)
298
+ bindings.except = new Set(options.except);
299
+ }
300
+ /** The placement function that is running now. */
301
+ let running = null;
302
+ /** A parent whose child list a placement function read → the functions to run again when Angular changes it. */
303
+ const contentReaders = new WeakMap();
304
+ /**
305
+ * Records that the running placement function depends on `parent`'s children.
306
+ *
307
+ * @param parent - The capture, or the parent its content was moved to.
308
+ */
309
+ function readBy(parent) {
310
+ if (parent === null || running === null)
311
+ return;
312
+ let readers = contentReaders.get(parent);
313
+ if (readers === undefined)
314
+ contentReaders.set(parent, (readers = new Set()));
315
+ readers.add(running);
316
+ }
317
+ /**
318
+ * Runs again every placement function that read `parent`'s children: Angular
319
+ * just added, removed or changed one of them.
320
+ *
321
+ * @param parent - The parent Angular changed.
322
+ */
323
+ function contentChanged(parent) {
324
+ if (parent === null)
325
+ return;
326
+ const readers = contentReaders.get(parent);
327
+ if (readers === undefined)
328
+ return;
329
+ for (const placement of Array.from(readers)) {
330
+ if (placement.destroyed)
331
+ readers.delete(placement);
332
+ else
333
+ placement.run();
334
+ }
335
+ }
45
336
  /**
46
337
  * Whether Angular's node is one React child: an element, or a text node that
47
338
  * is not template indentation. Angular creates an interpolated text node empty
@@ -69,6 +360,13 @@ function isChild(node) {
69
360
  */
70
361
  function placeOf(ref, parent) {
71
362
  let node = placeholders.get(ref) ?? ref;
363
+ // What stands in front of `ref` is part of it: a node goes before all of it.
364
+ const leader = leaders.get(ref)?.[0];
365
+ if (leader !== undefined) {
366
+ const first = leader.content ? contentRanges.get(leader.node)?.start : leader.node;
367
+ if (first !== undefined && first.parentNode === node.parentNode)
368
+ node = first;
369
+ }
72
370
  while (node.parentNode !== null && node.parentNode !== parent) {
73
371
  if (!wrapperOwners.has(node.parentNode))
74
372
  break;
@@ -76,6 +374,59 @@ function placeOf(ref, parent) {
76
374
  }
77
375
  return node;
78
376
  }
377
+ /**
378
+ * Forgets that an element, or a capture's content, stands in front of another
379
+ * node: it is back in its own place, or Angular is placing it itself.
380
+ *
381
+ * @param node - The element, or the capture.
382
+ * @param content - Whether it is the capture's content.
383
+ */
384
+ function stopLeading(node, content = false) {
385
+ const map = content ? ledContent : led;
386
+ const sibling = map.get(node);
387
+ if (sibling === undefined)
388
+ return;
389
+ map.delete(node);
390
+ const rest = (leaders.get(sibling) ?? []).filter((leader) => leader.node !== node || leader.content !== content);
391
+ if (rest.length > 0)
392
+ leaders.set(sibling, rest);
393
+ else
394
+ leaders.delete(sibling);
395
+ }
396
+ /**
397
+ * Puts what stands in front of `node` in front of it again: Angular just
398
+ * inserted or moved `node` alone.
399
+ *
400
+ * @param node - The node Angular placed.
401
+ */
402
+ function leadAgain(node) {
403
+ const list = leaders.get(node);
404
+ if (list === undefined)
405
+ return;
406
+ // An absent node, or one rendered elsewhere, holds its place with its placeholder.
407
+ const place = placeholders.get(node) ?? node;
408
+ const parent = place.parentNode;
409
+ if (parent === null)
410
+ return;
411
+ let next = place;
412
+ for (let i = list.length - 1; i >= 0; i--) {
413
+ const leader = list[i];
414
+ if (!leader.content) {
415
+ if (leader.node.nextSibling !== next)
416
+ parent.insertBefore(leader.node, next);
417
+ next = leader.node;
418
+ continue;
419
+ }
420
+ const range = contentRanges.get(leader.node);
421
+ if (range === undefined)
422
+ continue;
423
+ if (range.end.nextSibling !== next)
424
+ for (const part of runOf(range))
425
+ parent.insertBefore(part, next);
426
+ runParents.add(parent);
427
+ next = range.start;
428
+ }
429
+ }
79
430
  /**
80
431
  * Forgets an absent element's placeholder: Angular is removing or re-placing
81
432
  * the element, so the old place is no longer its place.
@@ -88,6 +439,7 @@ function dropPlaceholder(node) {
88
439
  return;
89
440
  placeholders.delete(node);
90
441
  elsewhere.delete(node);
442
+ stopLeading(node);
91
443
  const wrapper = placeholder.parentNode;
92
444
  placeholder.remove();
93
445
  dropEmptyWrapper(wrapper);
@@ -108,24 +460,37 @@ function dropEmptyWrapper(node) {
108
460
  owner.refresh();
109
461
  }
110
462
  /**
111
- * Removes every element rendered elsewhere whose place was inside a subtree
112
- * Angular just removed.
463
+ * Puts everything whose place is inside a subtree Angular is removing back in
464
+ * that place, so it leaves the page with the subtree (React unmounts a portal
465
+ * and a slot with the element that rendered them) and is there again if
466
+ * Angular re-inserts the subtree: an element {@link placeElement} rendered in
467
+ * another parent goes back to its placeholder, a capture's content
468
+ * {@link placeContent} moved goes back inside the capture. It walks the removed
469
+ * nodes once and follows what it puts back, so nesting needs no order.
113
470
  *
114
- * @param removed - The node Angular removed.
471
+ * @param node - The node Angular is removing, then each node below it.
115
472
  */
116
- function dropElsewhereInside(removed) {
117
- for (const element of elsewhere) {
118
- const placeholder = placeholders.get(element);
119
- if (placeholder === undefined) {
120
- elsewhere.delete(element);
121
- continue;
473
+ function takeAlong(node) {
474
+ const range = contentRanges.get(node);
475
+ if (range !== undefined && range.start.parentNode !== node)
476
+ returnContent(node, range);
477
+ const held = heldPlaces.get(node);
478
+ if (held !== undefined) {
479
+ if (elsewhere.has(held)) {
480
+ elsewhere.delete(held);
481
+ placeholders.delete(held);
482
+ stopLeading(held);
483
+ node.replaceWith(held);
122
484
  }
123
- if (!removed.contains(placeholder))
124
- continue;
125
- elsewhere.delete(element);
126
- placeholders.delete(element);
127
- element.remove();
485
+ // An absent element is not below its placeholder; what it holds is.
486
+ takeAlong(held);
487
+ return;
128
488
  }
489
+ if (node.firstChild === null)
490
+ return;
491
+ // A copy: putting something back moves nodes of this list.
492
+ for (const child of Array.from(node.childNodes))
493
+ takeAlong(child);
129
494
  }
130
495
  /**
131
496
  * Restores an absent host as soon as Angular renders a node into it, so the
@@ -171,21 +536,119 @@ function withPlacement(renderer) {
171
536
  renderer.appendChild(parent, node);
172
537
  else
173
538
  renderer.insertBefore(parent, node, before, isMove);
539
+ leadAgain(child);
174
540
  if (from !== parent)
175
541
  dropEmptyWrapper(from);
176
542
  owner?.refresh();
177
543
  restoreAbsentHostOf(parent);
544
+ contentChanged(parent);
178
545
  };
179
546
  placed.appendChild = (parent, child) => insert(parent, child, null);
180
547
  placed.insertBefore = (parent, child, ref, isMove) => insert(parent, child, ref ?? null, isMove);
181
548
  placed.removeChild = (parent, child, ...rest) => {
549
+ if (rendersElsewhere)
550
+ takeAlong(child);
182
551
  dropPlaceholder(child);
183
552
  const from = child.parentNode;
184
553
  renderer.removeChild(parent, child, ...rest);
185
554
  dropEmptyWrapper(from);
186
- if (elsewhere.size > 0)
187
- dropElsewhereInside(child);
555
+ contentChanged(from);
556
+ };
557
+ placed.setValue = (node, value) => {
558
+ renderer.setValue(node, value);
559
+ contentChanged(node.parentNode);
560
+ };
561
+ // What the consumer binds on the tag of a component that places its own DOM
562
+ // lands on the root that stands for the host (setHostRoot).
563
+ placed.listen = ((target, name, callback, options) => {
564
+ const listen = renderer.listen;
565
+ const off = listen.call(renderer, target, name, callback, options);
566
+ const bindings = typeof target === 'object' && target !== null ? tagBindings.get(target) : undefined;
567
+ if (bindings === undefined)
568
+ return off;
569
+ const listener = { name, callback, options, attached: new Map() };
570
+ // The decorated renderer: a root that is itself such a host passes the listener on.
571
+ bindings.renderer = placed;
572
+ bindings.listeners.add(listener);
573
+ syncTagBindings(target, false);
574
+ return () => {
575
+ off();
576
+ bindings.listeners.delete(listener);
577
+ for (const detach of listener.attached.values())
578
+ detach();
579
+ listener.attached.clear();
580
+ };
581
+ });
582
+ const forwards = (el, name) => {
583
+ const bindings = tagBindings.get(el);
584
+ if (bindings === undefined || bindings.target === null)
585
+ return undefined;
586
+ return isFrameworkAttribute(name) || bindings.except.has(name) ? undefined : bindings;
587
+ };
588
+ placed.setAttribute = (el, name, value, namespace) => {
589
+ const bindings = namespace ? undefined : forwards(el, name);
590
+ if (bindings === undefined || name === 'class' || name === 'style') {
591
+ renderer.setAttribute(el, name, value, namespace);
592
+ if (bindings !== undefined)
593
+ moveTagAttributes(el, bindings);
594
+ return;
595
+ }
596
+ ;
597
+ bindings.target.setAttribute(name, value);
598
+ bindings.attributes.set(name, value);
599
+ };
600
+ placed.removeAttribute = (el, name, namespace) => {
601
+ const bindings = namespace ? undefined : forwards(el, name);
602
+ if (bindings === undefined || !bindings.attributes.has(name)) {
603
+ renderer.removeAttribute(el, name, namespace);
604
+ return;
605
+ }
606
+ ;
607
+ bindings.target.removeAttribute(name);
608
+ bindings.attributes.delete(name);
609
+ };
610
+ placed.addClass = (el, name) => {
611
+ const bindings = forwards(el, 'class');
612
+ if (bindings === undefined) {
613
+ renderer.addClass(el, name);
614
+ return;
615
+ }
616
+ ;
617
+ bindings.target.classList.add(name);
618
+ bindings.classes.add(name);
188
619
  };
620
+ placed.removeClass = (el, name) => {
621
+ const bindings = forwards(el, 'class');
622
+ if (bindings === undefined || !bindings.classes.has(name)) {
623
+ renderer.removeClass(el, name);
624
+ return;
625
+ }
626
+ ;
627
+ bindings.target.classList.remove(name);
628
+ bindings.classes.delete(name);
629
+ };
630
+ placed.setStyle = ((el, style, value, flags) => {
631
+ const bindings = forwards(el, 'style');
632
+ if (bindings === undefined) {
633
+ ;
634
+ renderer.setStyle(el, style, value, flags);
635
+ return;
636
+ }
637
+ ;
638
+ renderer.setStyle(bindings.target, style, value, flags);
639
+ bindings.styles.set(style, value);
640
+ });
641
+ placed.removeStyle = ((el, style, flags) => {
642
+ const bindings = forwards(el, 'style');
643
+ if (bindings === undefined || !bindings.styles.has(style)) {
644
+ ;
645
+ renderer.removeStyle(el, style, flags);
646
+ return;
647
+ }
648
+ ;
649
+ renderer.removeStyle(bindings.target, style, flags);
650
+ bindings.styles.delete(style);
651
+ });
189
652
  return placed;
190
653
  }
191
654
  /**
@@ -237,6 +700,8 @@ function assertDomPlacement(user) {
237
700
  * holds an `<ng-content>`). "Attached" means the element has a parent, not
238
701
  * that it is in the document, so it also works inside a host that is itself
239
702
  * absent. An element that was never taken out is left where Angular put it.
703
+ * An element rendered elsewhere ({@link placeElement}, {@link placeElementBefore})
704
+ * leaves that parent too, and `true` puts it back in its own place.
240
705
  * Angular may remove or move the element while it is absent; its placeholder
241
706
  * goes then.
242
707
  *
@@ -252,16 +717,42 @@ export function setElementPresent(element, present) {
252
717
  return;
253
718
  placeholders.delete(element);
254
719
  elsewhere.delete(element);
720
+ stopLeading(element);
255
721
  // A placeholder whose parent was removed meanwhile has nowhere to restore to.
256
722
  if (placeholder.parentNode !== null)
257
723
  placeholder.replaceWith(element);
258
724
  }
725
+ else if (placeholder !== undefined && elsewhere.has(element)) {
726
+ // Rendered elsewhere (placeElement, placeElementBefore): it leaves that
727
+ // parent, and the placeholder it already has keeps its own place.
728
+ elsewhere.delete(element);
729
+ stopLeading(element);
730
+ element.remove();
731
+ }
259
732
  else if (placeholder === undefined && element.parentNode !== null) {
260
733
  const comment = element.ownerDocument.createComment('');
261
734
  element.replaceWith(comment);
262
735
  placeholders.set(element, comment);
736
+ heldPlaces.set(comment, element);
263
737
  }
264
738
  }
739
+ /**
740
+ * The element a placeholder stands in for while the element is out of its own
741
+ * place ({@link setElementPresent}, {@link placeElement},
742
+ * {@link placeElementBefore}). A slot's children ({@link SlotReader.nodes})
743
+ * list such an element as its placeholder; a component that took one of its
744
+ * slot's children out of the page finds that child again with this.
745
+ *
746
+ * @param node - A node of the rendered tree.
747
+ * @returns The element whose place the node holds, or `undefined` when the
748
+ * node is not a current placeholder.
749
+ */
750
+ export function heldElement(node) {
751
+ if (!node)
752
+ return undefined;
753
+ const held = heldPlaces.get(node);
754
+ return held !== undefined && placeholders.get(held) === node ? held : undefined;
755
+ }
265
756
  /**
266
757
  * Renders an element in another parent while it keeps its place in Angular's
267
758
  * view: Angular's equivalent of React's `createPortal(child, document.body)`.
@@ -271,9 +762,6 @@ export function setElementPresent(element, present) {
271
762
  * it is elsewhere, the element follows Angular and the next call moves it
272
763
  * again. When Angular removes the view that holds its place, the element is
273
764
  * removed from the other parent too, as React unmounts a portal.
274
- *
275
- * @param element - The element (nothing happens without one).
276
- * @param target - The parent to render it in, or `null` for its own place.
277
765
  */
278
766
  export function placeElement(element, target) {
279
767
  if (!element)
@@ -286,13 +774,169 @@ export function placeElement(element, target) {
286
774
  const comment = element.ownerDocument.createComment('');
287
775
  element.replaceWith(comment);
288
776
  placeholders.set(element, comment);
777
+ heldPlaces.set(comment, element);
289
778
  }
779
+ stopLeading(element);
290
780
  elsewhere.add(element);
781
+ rendersElsewhere = true;
291
782
  if (element.parentNode !== target)
292
783
  target.appendChild(element);
293
784
  }
785
+ /**
786
+ * Renders an element of the component's template immediately in front of
787
+ * another node, as its sibling: Angular's equivalent of a React component whose
788
+ * root is a fragment, `<><div>{children}</div>{portal}</>`, where the node is
789
+ * the component's host (kept in the DOM with `display: contents`).
790
+ *
791
+ * The element then belongs to the node's place. Angular inserts a new sibling
792
+ * before the element, not between the two; when Angular moves the node (a
793
+ * consumer `@for` reorders), the element moves with it; when Angular removes
794
+ * the node, the element goes back to its own place inside it and leaves the
795
+ * page with it. Several elements placed before the same node stand in the
796
+ * order they were placed. Calling it again moves nothing while the element
797
+ * already stands there.
798
+ *
799
+ * "In front of the node" means in front of the node's place. A host that is
800
+ * absent (`setElementPresent(host, false)`) holds its place with a comment, and
801
+ * the element stands in front of that: this is how a fragment root renders
802
+ * React's exact DOM, with no host element among the siblings at all. A node
803
+ * another component rendered elsewhere ({@link placeElement}) is likewise
804
+ * led at its place, not where it was rendered.
805
+ *
806
+ * Nothing happens while the node has no parent; call it
807
+ * from the component's {@link usePlacement} function, which runs again.
808
+ * `placeElement(element, null)` puts the element back in its own place.
809
+ *
810
+ * @param element - The element (nothing happens without one).
811
+ * @param sibling - The node it stands in front of, usually the host.
812
+ */
813
+ export function placeElementBefore(element, sibling) {
814
+ if (!element || !sibling || (placeholders.get(sibling) ?? sibling).parentNode === null)
815
+ return;
816
+ if (led.get(element) !== sibling) {
817
+ stopLeading(element);
818
+ if (!placeholders.has(element) && element.parentNode !== null) {
819
+ const comment = element.ownerDocument.createComment('');
820
+ element.replaceWith(comment);
821
+ placeholders.set(element, comment);
822
+ heldPlaces.set(comment, element);
823
+ }
824
+ elsewhere.add(element);
825
+ rendersElsewhere = true;
826
+ led.set(element, sibling);
827
+ leaders.set(sibling, [...(leaders.get(sibling) ?? []), { node: element, content: false }]);
828
+ }
829
+ leadAgain(sibling);
830
+ }
294
831
  /** A capture element → the comments that bracket its content wherever it is. */
295
832
  const contentRanges = new WeakMap();
833
+ /** One of those comments → its capture. */
834
+ const rangeCaptures = new WeakMap();
835
+ /**
836
+ * The parents a capture's content was rendered in, outside the capture. Only
837
+ * their children can belong to a run, so only they cost {@link renderedParent}
838
+ * a look at the siblings. A parent the content left stays listed; it costs the
839
+ * look and nothing else.
840
+ */
841
+ const runParents = new WeakSet();
842
+ /**
843
+ * A node's parent in the rendered tree: the parent React context follows.
844
+ * It is the DOM parent, except where this module placed the node:
845
+ *
846
+ * - an element that is absent, or rendered in another parent
847
+ * ({@link setElementPresent}, {@link placeElement},
848
+ * {@link placeElementBefore}), belongs where its placeholder is, the place
849
+ * the template gave it. A portal's content therefore has the component that
850
+ * declared it as an ancestor, not `document.body`, as in React.
851
+ * - a top-level node of a capture's content that renders outside the capture
852
+ * ({@link placeContent}, {@link placeContentBefore}) belongs to the capture.
853
+ * With `placeContentBefore(host, host)` that is the host: what a provider
854
+ * renders in its own place is the provider's child, and a sibling that merely
855
+ * shares the DOM parent is not.
856
+ *
857
+ * So a component looks its context up from its own host and registers one on
858
+ * its own host, whether or not the host is in the page.
859
+ *
860
+ * @param node - The node.
861
+ * @returns Its parent in the rendered tree, or `null` at the top (or for a
862
+ * node that has no place: never inserted, or removed).
863
+ */
864
+ export function renderedParent(node) {
865
+ if (!node)
866
+ return null;
867
+ const place = placeholders.get(node) ?? node;
868
+ const parent = place.parentNode;
869
+ if (parent === null)
870
+ return null;
871
+ if (runParents.has(parent)) {
872
+ for (let prev = place.previousSibling; prev !== null; prev = prev.previousSibling) {
873
+ if (prev.nodeType !== 8)
874
+ continue;
875
+ const capture = rangeCaptures.get(prev);
876
+ if (capture === undefined)
877
+ continue;
878
+ const range = contentRanges.get(capture);
879
+ // Inside this run: its capture is the parent.
880
+ if (prev === range.start)
881
+ return capture;
882
+ // An earlier run ended here: none of it encloses the node.
883
+ prev = range.start;
884
+ }
885
+ }
886
+ return parent.nodeType === 1 ? parent : null;
887
+ }
888
+ /**
889
+ * Moves a capture's content from wherever it was rendered back inside the
890
+ * capture: the place Angular put it, and where Angular takes it from when it
891
+ * projects it again.
892
+ *
893
+ * @param capture - The element Angular projected the content into.
894
+ * @param range - The comments that bracket the content.
895
+ * @param range.start - The comment before the content.
896
+ * @param range.end - The comment after the content.
897
+ */
898
+ function returnContent(capture, range) {
899
+ stopLeading(capture, true);
900
+ for (const node of runOf(range))
901
+ capture.appendChild(node);
902
+ }
903
+ /**
904
+ * A capture's content with the two comments that bracket it.
905
+ *
906
+ * @param range - The comments that bracket the content.
907
+ * @param range.start - The comment before the content.
908
+ * @param range.end - The comment after the content.
909
+ * @returns The nodes, in order.
910
+ */
911
+ function runOf(range) {
912
+ const run = [];
913
+ for (let node = range.start; node !== null; node = node.nextSibling) {
914
+ run.push(node);
915
+ if (node === range.end)
916
+ break;
917
+ }
918
+ return run;
919
+ }
920
+ /**
921
+ * The comments that bracket a capture's content, created around the content
922
+ * the first time.
923
+ *
924
+ * @param capture - The element Angular projected the content into.
925
+ * @returns The two comments.
926
+ */
927
+ function rangeOf(capture) {
928
+ let range = contentRanges.get(capture);
929
+ if (range === undefined) {
930
+ const document = capture.ownerDocument;
931
+ range = { start: document.createComment(''), end: document.createComment('') };
932
+ capture.prepend(range.start);
933
+ capture.append(range.end);
934
+ contentRanges.set(capture, range);
935
+ rangeCaptures.set(range.start, capture);
936
+ rangeCaptures.set(range.end, capture);
937
+ }
938
+ return range;
939
+ }
296
940
  /**
297
941
  * Renders a capture element's content somewhere else: Angular's equivalent of
298
942
  * React placing the same `{slot}` in a different parent depending on props
@@ -304,7 +948,8 @@ const contentRanges = new WeakMap();
304
948
  * view under the parent of its anchor, before a node of the same run. Never
305
949
  * move a filtered or remembered list of nodes instead; the anchors or the
306
950
  * nodes Angular adds later stay behind (NG05106). Calling it again with the
307
- * same target moves nothing.
951
+ * same target moves nothing. When Angular removes the capture (its view went),
952
+ * the content goes back inside it and leaves the page with it.
308
953
  *
309
954
  * @param capture - The element Angular projected the content into.
310
955
  * @param target - The parent to render the content in, or `null` to put it
@@ -315,28 +960,61 @@ const contentRanges = new WeakMap();
315
960
  export function placeContent(capture, target, before = null) {
316
961
  if (!capture)
317
962
  return;
318
- let range = contentRanges.get(capture);
319
- if (range === undefined) {
320
- if (target === null)
321
- return;
322
- const document = capture.ownerDocument;
323
- range = { start: document.createComment(''), end: document.createComment('') };
324
- capture.prepend(range.start);
325
- capture.append(range.end);
326
- contentRanges.set(capture, range);
963
+ if (target === null && !contentRanges.has(capture))
964
+ return;
965
+ const range = rangeOf(capture);
966
+ if (target === null) {
967
+ if (range.start.parentNode !== capture)
968
+ returnContent(capture, range);
969
+ return;
327
970
  }
328
- const parent = target ?? capture;
329
- if (range.start.parentNode === parent)
971
+ // Rendered here from now on, wherever placeContentBefore had it follow a node.
972
+ const followed = ledContent.has(capture);
973
+ stopLeading(capture, true);
974
+ if (range.start.parentNode === target && !followed)
330
975
  return;
331
- const run = [];
332
- for (let node = range.start; node !== null; node = node.nextSibling) {
333
- run.push(node);
334
- if (node === range.end)
335
- break;
976
+ // An absent element holds its place with its placeholder.
977
+ const place = before === null ? null : (placeholders.get(before) ?? before);
978
+ for (const node of runOf(range))
979
+ target.insertBefore(node, place);
980
+ runParents.add(target);
981
+ rendersElsewhere = true;
982
+ readBy(target);
983
+ }
984
+ /**
985
+ * Renders a capture's content immediately in front of another node, as its
986
+ * siblings, with no element around it: Angular's equivalent of a React
987
+ * component whose root is a fragment of what it was given, `<>{children}</>`
988
+ * (a provider or a gate that renders no DOM of its own). The node is usually
989
+ * the component's host, and the capture may be the host itself:
990
+ * `placeContentBefore(host, host)` renders everything the host holds in front
991
+ * of it and leaves the host empty.
992
+ *
993
+ * The content then belongs to the node's place, as an element does with
994
+ * {@link placeElementBefore}: Angular inserts a new sibling before the content,
995
+ * the content moves with the node, and it goes back inside the capture when
996
+ * Angular removes the node. Angular's block anchors move with the content, so
997
+ * an `@if` in the component's own template around `<ng-content>` and the
998
+ * consumer's blocks render at the new place from the first node on. Nothing
999
+ * happens while the node has no parent; call it from the component's
1000
+ * {@link usePlacement} function. `placeContent(capture, null)` puts the
1001
+ * content back.
1002
+ *
1003
+ * @param capture - The element that holds the content (nothing happens
1004
+ * without one).
1005
+ * @param sibling - The node the content stands in front of, usually the host.
1006
+ */
1007
+ export function placeContentBefore(capture, sibling) {
1008
+ if (!capture || !sibling || (placeholders.get(sibling) ?? sibling).parentNode === null)
1009
+ return;
1010
+ rangeOf(capture);
1011
+ if (ledContent.get(capture) !== sibling) {
1012
+ stopLeading(capture, true);
1013
+ ledContent.set(capture, sibling);
1014
+ leaders.set(sibling, [...(leaders.get(sibling) ?? []), { node: capture, content: true }]);
1015
+ rendersElsewhere = true;
336
1016
  }
337
- const ref = target === null ? null : before;
338
- for (const node of run)
339
- parent.insertBefore(node, ref);
1017
+ leadAgain(sibling);
340
1018
  }
341
1019
  /**
342
1020
  * Whether a slot renders anything, React's `{slot && …}` for projected
@@ -346,23 +1024,203 @@ export function placeContent(capture, target, before = null) {
346
1024
  * content.
347
1025
  *
348
1026
  * @param capture - The element Angular projected the content into.
1027
+ * @param ownLeadingNodes - How many of the capture's first child nodes the
1028
+ * port's own template renders before the slot (its own text), which are not
1029
+ * content.
349
1030
  * @returns Whether the slot has content.
350
1031
  */
351
- export function hasContent(capture) {
1032
+ function contentOf(capture, ownLeadingNodes = 0) {
1033
+ return childrenOf(capture, true, ownLeadingNodes).length > 0;
1034
+ }
1035
+ /**
1036
+ * A slot's React children, wherever {@link placeContent} rendered them: its
1037
+ * elements and its text that is not template indentation, in order. A
1038
+ * projected component that renders nothing counts as the placeholder that
1039
+ * holds its place.
1040
+ *
1041
+ * @param capture - The element Angular projected the content into.
1042
+ * @param firstOnly - Stop at the first child.
1043
+ * @param ownLeadingNodes - How many of the capture's first child nodes the
1044
+ * port's own template renders before the slot, which are not children.
1045
+ * @returns The children.
1046
+ */
1047
+ function childrenOf(capture, firstOnly, ownLeadingNodes = 0) {
1048
+ const children = [];
352
1049
  if (!capture)
353
- return false;
1050
+ return children;
354
1051
  const range = contentRanges.get(capture);
355
- const nodes = [];
356
- if (range === undefined || range.start.parentNode === capture) {
357
- nodes.push(...Array.from(capture.childNodes));
358
- }
359
- else {
360
- for (let node = range.start.nextSibling; node !== null && node !== range.end;) {
361
- nodes.push(node);
362
- node = node.nextSibling;
1052
+ const moved = range !== undefined && range.start.parentNode !== capture;
1053
+ readBy(capture);
1054
+ if (moved)
1055
+ readBy(range.start.parentNode);
1056
+ const end = moved ? range.end : null;
1057
+ let node = moved ? range.start.nextSibling : capture.firstChild;
1058
+ for (let skipped = 0; skipped < ownLeadingNodes && node !== null && node !== end; skipped += 1) {
1059
+ node = node.nextSibling;
1060
+ }
1061
+ for (; node !== null && node !== end; node = node.nextSibling) {
1062
+ const isContent = node.nodeType === 1 ||
1063
+ (node.nodeType === 3 && node.data.trim() !== '') ||
1064
+ // A projected component that renders nothing is still a child React was given.
1065
+ heldPlaces.has(node);
1066
+ if (!isContent)
1067
+ continue;
1068
+ children.push(node);
1069
+ if (firstOnly)
1070
+ break;
1071
+ }
1072
+ return children;
1073
+ }
1074
+ /**
1075
+ * Reads a slot from a lifecycle hook, which can lag the content: a hook runs
1076
+ * before the consumer's `@if` adds its node, and no hook runs at all when the
1077
+ * content comes through an `OnPush` component in between. Read slots in the
1078
+ * function passed to {@link usePlacement} instead; this export goes in the
1079
+ * next major version.
1080
+ *
1081
+ * @param capture - The capture.
1082
+ * @returns Whether the slot has content.
1083
+ * @deprecated Use the reader {@link usePlacement} passes.
1084
+ */
1085
+ export function hasContent(capture) {
1086
+ return contentOf(capture);
1087
+ }
1088
+ /**
1089
+ * Gives {@link usePlacement} the component's own moments. A component that
1090
+ * calls `usePlacement` lists it in `hostDirectives`; `usePlacement` throws
1091
+ * without it. Its hooks fire exactly when the component's own would: after the
1092
+ * component's view was first rendered (its view queries are set), and each
1093
+ * time the parent checks the component (its inputs are set).
1094
+ */
1095
+ export class MolPlacement {
1096
+ constructor() {
1097
+ this.runs = [];
1098
+ }
1099
+ /**
1100
+ * Adds a placement function to run at the component's moments.
1101
+ *
1102
+ * @param run - Runs it.
1103
+ * @internal
1104
+ */
1105
+ add(run) {
1106
+ this.runs.push(run);
1107
+ }
1108
+ /** The component's view exists and its view queries are set. */
1109
+ ngAfterViewInit() {
1110
+ for (const run of this.runs)
1111
+ run();
1112
+ }
1113
+ /** The parent set the component's inputs. */
1114
+ ngDoCheck() {
1115
+ for (const run of this.runs)
1116
+ run();
1117
+ }
1118
+ static { this.ɵfac = function MolPlacement_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MolPlacement)(); }; }
1119
+ static { this.ɵdir = /*@__PURE__*/ i0.ɵɵdefineDirective({ type: MolPlacement }); }
1120
+ }
1121
+ (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(MolPlacement, [{
1122
+ type: Directive,
1123
+ args: [{ standalone: true }]
1124
+ }], null, null); })();
1125
+ /**
1126
+ * Registers the calling component's placement function: the one place where
1127
+ * it decides, from its inputs and its projected content, which of its template
1128
+ * elements are present ({@link setElementPresent}) and where its slots render
1129
+ * ({@link placeContent}, {@link placeElement}). Call it in the constructor.
1130
+ *
1131
+ * The component writes no lifecycle hook for this. The function runs:
1132
+ *
1133
+ * - right after Angular adds, removes or changes a node of a slot the function
1134
+ * read, in the same instruction — in whatever pass and from whatever
1135
+ * template the node came, so the decision never lags the content and the new
1136
+ * content is in the page before its own `ngAfterViewInit`;
1137
+ * - when a signal it read changed (an effect);
1138
+ * - when the component's view was first rendered and each time its parent
1139
+ * checks it ({@link MolPlacement}, which the component lists in
1140
+ * `hostDirectives`), so a plain input is followed in any kind of change
1141
+ * detection, a bare `detectChanges()` included;
1142
+ * - after every render.
1143
+ *
1144
+ * `hasContent` is the only way to ask whether a slot has content, and it works
1145
+ * only while the function runs: a lifecycle hook cannot read a slot, because
1146
+ * no hook runs at a moment when the slot is known to be current
1147
+ * (`ngDoCheck` runs before the consumer's `@if` adds its node; no hook at all
1148
+ * runs when the content comes through an `OnPush` component in between).
1149
+ *
1150
+ * @param place - The placement function. It gets `hasContent`.
1151
+ */
1152
+ export function usePlacement(place) {
1153
+ assertDomPlacement('usePlacement');
1154
+ const moments = inject(MolPlacement, { self: true, optional: true });
1155
+ if (moments === null) {
1156
+ throw new Error('usePlacement() needs `hostDirectives: [MolPlacement]` in the decorator of the component that calls it ' +
1157
+ "(from @molecule/app-angular): it runs the placement function at the component's own moments.");
1158
+ }
1159
+ const inRun = () => {
1160
+ if (running !== placement) {
1161
+ throw new Error('hasContent() was called outside its usePlacement() function. A lifecycle hook cannot read a ' +
1162
+ 'slot: decide presence and placement inside the function passed to usePlacement().');
363
1163
  }
1164
+ };
1165
+ const hasContent = ((capture, ownLeadingNodes) => {
1166
+ inRun();
1167
+ return contentOf(capture, ownLeadingNodes);
1168
+ });
1169
+ hasContent.nodes = (capture) => {
1170
+ inRun();
1171
+ return childrenOf(capture, false);
1172
+ };
1173
+ const host = inject(ElementRef).nativeElement;
1174
+ // Absent when a test calls usePlacement outside a component.
1175
+ const view = inject(ChangeDetectorRef, { optional: true });
1176
+ let names;
1177
+ if (host.nodeType === 1 && !tagBindings.has(host)) {
1178
+ tagBindings.set(host, {
1179
+ renderer: null,
1180
+ listeners: new Set(),
1181
+ named: undefined,
1182
+ except: new Set(),
1183
+ target: null,
1184
+ attributes: new Map(),
1185
+ classes: new Set(),
1186
+ styles: new Map(),
1187
+ tag: host.tagName.toLowerCase(),
1188
+ inputs: () => (names ??= memberNames(view)).inputs,
1189
+ outputs: () => (names ??= memberNames(view)).outputs,
1190
+ });
364
1191
  }
365
- return nodes.some((node) => node.nodeType === 1 || (node.nodeType === 3 && (node.textContent ?? '').trim() !== ''));
1192
+ let settled = false;
1193
+ const call = () => {
1194
+ if (placement.destroyed || running === placement)
1195
+ return;
1196
+ const outer = running;
1197
+ running = placement;
1198
+ try {
1199
+ place(hasContent);
1200
+ }
1201
+ finally {
1202
+ running = outer;
1203
+ }
1204
+ if (host.nodeType === 1)
1205
+ syncTagBindings(host, settled);
1206
+ };
1207
+ const placement = { run: () => untracked(call), destroyed: false };
1208
+ effect(call);
1209
+ moments.add(placement.run);
1210
+ afterEveryRender({
1211
+ write: () => {
1212
+ settled = true;
1213
+ try {
1214
+ placement.run();
1215
+ }
1216
+ finally {
1217
+ settled = false;
1218
+ }
1219
+ },
1220
+ });
1221
+ inject(DestroyRef).onDestroy(() => {
1222
+ placement.destroyed = true;
1223
+ });
366
1224
  }
367
1225
  /**
368
1226
  * Keeps the calling component's host element out of the DOM while