mr-class-style-generator
Version:
A utility to apply inline styles from custom class names like mr-fs-[10vw]
60 lines (54 loc) • 1.95 kB
JavaScript
function ApplyMrStyles(startWith = "mr") {
const matchedClassNames = [];
function traverse(element) {
for (const child of element.children) {
try {
const classAttr = child.getAttribute("class")?.trim();
if (classAttr && classAttr.startsWith(startWith) && classAttr.length > 3) {
matchedClassNames.push(classAttr);
}
} catch (err) {
console.warn("Error reading class attribute:", err);
}
traverse(child);
}
}
function generateDynamicStyles(classNames) {
return classNames
.map((className) => {
try {
const escapedClass = className.replace(/\[/g, "\\[").replace(/\]/g, "\\]");
const [, type, rawValue] = className.split("-");
const value = rawValue.replace(/\[|\]/g, "");
if (type === "fs") {
return `.${escapedClass} {\n font-size: ${value};\n}`;
}
return '';
} catch (err) {
console.warn(`Error parsing class "${className}":`, err);
return '';
}
})
.filter(Boolean)
.join("\n\n");
}
function injectStyles(cssRules) {
try {
const style = document.createElement("style");
style.textContent = cssRules;
document.head.appendChild(style);
} catch (err) {
console.error("Failed to inject styles:", err);
}
}
try {
traverse(document.body);
if (matchedClassNames.length > 0) {
const css = generateDynamicStyles(matchedClassNames);
injectStyles(css);
}
} catch (err) {
console.error("Error applying MR styles:", err);
}
}
export default ApplyMrStyles;