All files / src/custom-element/helpers/css/style applyStyle.ts

100% Statements 21/21
100% Branches 2/2
100% Functions 8/8
100% Lines 17/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              1x   5x   5x   5x   9x   9x   9x   4x   4x       5x   11x           9x   9x 20x     11x   11x                       11x  
interface Rule {
 
    key: string;
 
    value: string;
}
 
export default function applyStyle(strings: TemplateStringsArray, ...values: any): Function {
 
    const rules: Rule[] = [];
 
    const length = strings.length;
 
    for (let i = 0; i < length; ++i) {
 
        const s = strings[i].trim();
 
        addRules(rules, s);
 
        if (s.endsWith(':')) { // Complete the last rule with the value 
 
            const lastRule = rules[rules.length - 1];
 
            lastRule.value = values[i];
        }
    }
 
    return component => {
 
        rules.forEach(rule => component.style[rule.key] = rule.value);
    };
}
 
function addRules(rules: Rule[], s: string) {
 
    const rulesText = s.trim().split(';');
 
    rulesText
        .filter(r => r !== '') // Remove empty entries
        .forEach(r => {
 
            const parts = r.split(":");
 
            rules.push({
                key: cssToJs(parts[0].trim()),
                value: parts[1].trim()
            });
        });
}
 
/**
 * Converts from css rule key (e.g. "background-color") to javascript property key (e.g. "background-color")
 * @param s 
 * @returns 
 */
const cssToJs: (string) => string = s => s.replace(/\W+\w/g, match => match.slice(-1).toUpperCase());