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

94.44% Statements 17/18
71.43% Branches 5/7
100% Functions 4/4
94.44% Lines 17/18

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              15x   15x         81x             95x   95x   95x     60x   60x     95x             60x           60x   60x   60x   60x   60x             60x         15x
import { NodePatchingData } from "../../renderer/NodePatcher";
 
/**
 * Patches the template with the style of the component if there is any
 * @param Base 
 * @returns 
 */
const StylePatcherMixin = Base =>
 
    class StylePatcher extends Base {
 
        /**
         * Whether the styles were already added to the document
         */
        protected stylesAdded: boolean = false;
 
        beforeRender(patchingData: NodePatchingData): NodePatchingData {
 
            const {
                constructor,
                stylesAdded: _stylesAdded = false
            } = this;
 
            const styles = (constructor as any).metadata.styles;
 
            if (styles.length > 0 &&
                _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.join(''));
 
                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;
        }
    }
 
 
export default StylePatcherMixin;