Published
Edited
Sep 11, 2022
Importers
Insert cell
Insert cell
function serializeCss(obj) {
return visitStyle(obj).join("\n");

function visitStyle(obj, lines = [], prefixes = [""]) {
for (let [key, style] of Object.entries(obj)) {
const selectors = [];
for (let sel of key.split(",").map((_) => _.trim())) {
for (const prefix of prefixes) {
const selector = sel.replace(/^(.)/, (_, ch) =>
ch === "&" ? prefix : prefix.length > 0 ? prefix + " " + ch : ch
);
selectors.push(selector);
}
}
const selectorRules = [];
const extensions = [];
for (let [key, value] of Object.entries(style)) {
if (typeof value === "object") {
visitStyle({ [key]: value }, extensions, selectors);
} else {
key = toKebabCase(key);
selectorRules.push(` ${key}: ${value};`);
}
}
if (selectorRules.length) {
lines.push(`${selectors.join(",\n")} {`);
lines.push(...selectorRules);
lines.push(`}`);
}
lines.push(...extensions);
}
return lines;
}

function toKebabCase(str) {
return str.replace(
/([^A-Z]?)([A-Z])/g,
(_, a, b) => a.toLowerCase() + "-" + b.toLowerCase()
);
}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more