All files / src/custom-element/mixins/core StylePatcherMixin.ts

94.12% Statements 16/17
71.43% Branches 5/7
100% Functions 3/3
94.12% Lines 16/17

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              17x   17x         85x             93x   93x   93x     66x   66x     93x             66x           66x   66x   66x   66x   66x             66x      
import { NodePatchingData } from "../../../renderer/NodePatcher";
 
/**
 * Patches the template with the style of the component if there is any
 * @param Base 
 * @returns 
 */
export default function StylePatcherMixin(Base):any {
 
    return class StylePatcher extends Base {
 
        /**
         * Whether the styles were already added to the document
         */
        protected stylesAdded: boolean = false;
 
        beforeRender(patchingData: NodePatchingData): NodePatchingData {
 
            const {
                constructor,
                stylesAdded = false
            } = this;
 
            const styles = (constructor as any).metadata.styles;
 
            if (styles !== undefined &&
                stylesAdded === false) { // Add a style element to the document
 
                patchingData = this.addStyles(patchingData, styles);
 
                this.stylesAdded = true;
            }
 
            return patchingData;
        }
 
        addStyles(node: NodePatchingData, styles: string): NodePatchingData {
 
            const {
                shadowRoot
            } = this;
 
            // Not optimal adding the same style sheet to the shadow root when the component is constructed
            // Better to add an adopted stylesheet but that is not widely supported by all the browsers
            // Or add the stylesheet to the template content since it is a static text but then the component can have different patching data
            // and we need to research the relation between component and patching data
            Eif (shadowRoot !== null) {
 
                const styleNode = document.createElement('style');
 
                const styleContent = document.createTextNode(styles);
 
                styleNode.appendChild(styleContent);
 
                shadowRoot.appendChild(styleNode); // Append the style
            }
            else { // this.shadowRoot === null
 
                throw Error('Not implemented'); // Maybe append the style to the parent document/ shadow root? More research when we encounter the specific scenario
            }
 
            return node;
        }
    }
}