All files / src/custom-element/mixins ChildMixin.ts

80.95% Statements 17/21
81.82% Branches 18/22
71.43% Functions 5/7
80% Lines 16/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72            11x           37x         37x       43x   37x         29x   29x         111x   102x   102x   203x   2x     201x     102x     111x                                     11x
/**
 * Mixin for the child element to attach itself to the children collection of the parent element
 * So the parent can manage is children
 * @param Base 
 * @returns 
 */
const ChildMixin = Base =>
 
    class Child extends Base {
 
        static readonly _isCustomElement: boolean = true;
 
        private _adoptingParent = null;
 
        /**
         * The children elements of this one
         */
        protected adoptedChildren: Set<Node> = new Set<Node>();
 
        connectedCallback(node: Node) {
 
            super.connectedCallback?.(node);
 
            (this.adoptingParent as any)?.addAdoptedChild(this); // It might be null for the topmost custom element
        }
 
        disconnectedCallback(node: Node) {
 
            super.disconnectedCallback?.(node);
 
            (this.adoptingParent as any)?.removeAdoptedChild(this); // It might be null for the topmost custom element
        }
 
        protected get adoptingParent(): Node {
 
            if (this._adoptingParent === null) {
 
                let parent = this.parentNode;
 
                while (parent !== null) {
 
                    if (parent.constructor._isCustomElement) {  // It is a custom element
 
                        break;
                    }
 
                    parent = parent.parentNode;
                }
 
                this._adoptingParent = parent;
            }
 
            return this._adoptingParent;
        }
 
        protected async addAdoptedChild(child: Node) {
 
            this.adoptedChildren.add(child);
 
            if ((child.constructor as any)._isCustomElement) {  // It is a custom element
 
                await (child as any)._updatePromise; // Wait for this child to mount/update
            }   
        }
 
        protected removeAdoptedChild(child: Node) {
 
            this.adoptedChildren.delete(child);
        }
    }
 
export default ChildMixin;