All files / roosterjs-content-model-core/lib/command/createModelFromHtml convertInlineCss.ts

96.97% Statements 32/33
81.25% Branches 13/16
100% Functions 6/6
95.83% Lines 23/24

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 73 74 751x                                   31x 31x           1x 39x 39x   39x 8x   8x 8x 34x   34x 31x               8x     39x           1x 41x 41x   42x 42x       42x         42x 80x          
import { toArray } from 'roosterjs-content-model-dom';
 
/**
 * @internal
 */
export interface CssRule {
    selectors: string[];
    text: string;
}
 
/**
 * @internal
 *
 * Splits CSS selectors, avoiding splits within parentheses
 * @param selectorText The CSS selector string
 * @return Array of trimmed selectors
 */
function splitSelectors(selectorText: string) {
    const regex = /(?![^(]*\)),/;
    return selectorText.split(regex).map(s => s.trim());
}
 
/**
 * @internal
 */
export function retrieveCssRules(doc: Document): CssRule[] {
    const styles = toArray(doc.querySelectorAll('style'));
    const result: CssRule[] = [];
 
    styles.forEach(styleNode => {
        const sheet = styleNode.sheet;
 
        Eif (sheet) {
            for (let ruleIndex = 0; ruleIndex < sheet.cssRules.length; ruleIndex++) {
                const rule = sheet.cssRules[ruleIndex] as CSSStyleRule;
 
                if (rule.type == CSSRule.STYLE_RULE && rule.selectorText) {
                    result.push({
                        selectors: splitSelectors(rule.selectorText),
                        text: rule.style.cssText,
                    });
                }
            }
        }
 
        styleNode.parentNode?.removeChild(styleNode);
    });
 
    return result;
}
 
/**
 * @internal
 */
export function convertInlineCss(root: ParentNode, cssRules: CssRule[]) {
    for (let i = cssRules.length - 1; i >= 0; i--) {
        const { selectors, text } = cssRules[i];
 
        for (const selector of selectors) {
            Iif (!selector || !selector.trim()) {
                continue;
            }
 
            const nodes = toArray(root.querySelectorAll(selector));
 
            // Always put existing styles after so that they have higher priority
            // Which means if both global style and inline style apply to the same element,
            // inline style will have higher priority
            nodes.forEach(node =>
                node.setAttribute('style', text + (node.getAttribute('style') || ''))
            );
        }
    }
}