@ou-imdt/utils
Version:
Utility library for interactive media development
36 lines (29 loc) • 1.1 kB
JavaScript
export const styleText = Symbol('styleText');
export const styleMap = Symbol('styleMap');
export default (superClass) => class MappedStylesMixin extends superClass {
static get [styleText]() {
return '';
};
static get [styleMap]() {
return {};
};
static get mappedStyles() {
const entries = Object.entries(this[styleMap]);
const styleSheet = new CSSStyleSheet();
styleSheet.replaceSync(this[styleText]);
[...styleSheet.cssRules].forEach((rule) => {
if (!(rule instanceof CSSStyleRule)) return;
const { selectorText, cssText } = rule;
const ruleIndex = [...styleSheet.cssRules].indexOf(rule);
const matched = entries.some(([selector, replacement], index) => {
if (!(new RegExp(`^${RegExp.escape(selector)}\s*[,{]`).test(selectorText))) return false;
styleSheet.deleteRule(ruleIndex);
styleSheet.insertRule(cssText.replace(selectorText, replacement), ruleIndex);
entries.splice(index, 1);
return true;
});
if (!matched) styleSheet.deleteRule(ruleIndex);
});
return styleSheet;
}
}