|
1 | | -import { attr, FASTElement } from '@microsoft/fast-element'; |
| 1 | +import { attr, FASTElement, Updates } from '@microsoft/fast-element'; |
2 | 2 |
|
3 | 3 | /** |
4 | 4 | * The base class used for constructing a fluent-avatar custom element |
5 | 5 | * @public |
6 | 6 | */ |
7 | 7 | export class BaseAvatar extends FASTElement { |
| 8 | + /** |
| 9 | + * Signal to remove event listeners when the component is disconnected. |
| 10 | + * |
| 11 | + * @internal |
| 12 | + */ |
| 13 | + private abortSignal?: AbortController; |
| 14 | + |
| 15 | + /** |
| 16 | + * Reference to the default slot element. |
| 17 | + * @internal |
| 18 | + */ |
| 19 | + public defaultSlot!: HTMLSlotElement; |
| 20 | + |
8 | 21 | /** |
9 | 22 | * The internal {@link https://developer.mozilla.org/docs/Web/API/ElementInternals | `ElementInternals`} instance for the component. |
10 | 23 | * |
@@ -32,9 +45,54 @@ export class BaseAvatar extends FASTElement { |
32 | 45 | @attr |
33 | 46 | public initials?: string | undefined; |
34 | 47 |
|
| 48 | + connectedCallback(): void { |
| 49 | + super.connectedCallback(); |
| 50 | + this.slotchangeHandler(); |
| 51 | + } |
| 52 | + |
35 | 53 | constructor() { |
36 | 54 | super(); |
37 | 55 |
|
38 | 56 | this.elementInternals.role = 'img'; |
39 | 57 | } |
| 58 | + |
| 59 | + disconnectedCallback(): void { |
| 60 | + this.abortSignal?.abort(); |
| 61 | + this.abortSignal = undefined; |
| 62 | + |
| 63 | + super.disconnectedCallback(); |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Removes any empty text nodes from the default slot when the slotted content changes. |
| 68 | + * |
| 69 | + * @param e - The event object |
| 70 | + * @internal |
| 71 | + */ |
| 72 | + public slotchangeHandler(): void { |
| 73 | + this.normalize(); |
| 74 | + |
| 75 | + const elements = this.defaultSlot.assignedElements(); |
| 76 | + |
| 77 | + if (!elements.length && !this.innerText.trim()) { |
| 78 | + const nodes = this.defaultSlot.assignedNodes() as Element[]; |
| 79 | + |
| 80 | + nodes |
| 81 | + .filter(node => node.nodeType === Node.TEXT_NODE) |
| 82 | + .forEach(node => { |
| 83 | + this.removeChild(node); |
| 84 | + }); |
| 85 | + } |
| 86 | + |
| 87 | + Updates.enqueue(() => { |
| 88 | + if (!this.abortSignal || this.abortSignal.signal.aborted) { |
| 89 | + this.abortSignal = new AbortController(); |
| 90 | + } |
| 91 | + |
| 92 | + this.defaultSlot.addEventListener('slotchange', () => this.slotchangeHandler(), { |
| 93 | + once: true, |
| 94 | + signal: this.abortSignal.signal, |
| 95 | + }); |
| 96 | + }); |
| 97 | + } |
40 | 98 | } |
0 commit comments