@mapcss/preset-svg
Version:
SVG as CSS for MapCSS
47 lines (46 loc) • 1.63 kB
JavaScript
import { deepMerge } from "./deps.js";
/** PostCSS AST to JavaScript Object(CSS-in-JS) */
export function toObject(ast) {
return ast.nodes.reduce((acc, cur) => {
if (cur.type === "atrule") {
const atRule = constructAtRule(cur.name, cur.params);
return deepMerge(acc, { [atRule]: toObject(cur) });
}
if (cur.type === "rule") {
return deepMerge(acc, { [cur.selector]: toObject(cur) });
}
if (cur.type === "decl") {
const prop = constructProp(cur.prop, cur.variable);
const value = constructValue(cur.value, cur.important);
return deepMerge(acc, { [prop]: value });
}
return acc;
}, {});
}
export function constructAtRule(name, params) {
const withParams = params ? ` ${params}` : "";
const atRule = `@${name}${withParams}`;
return atRule;
}
export function constructValue(value, important) {
value = value.trim();
if (important) {
const IMPORTANT = "!important";
return value ? `${value} ${IMPORTANT}` : IMPORTANT;
}
// Convert only numbers without a unit to type `number`.
if (/^[\d.\s]+$/.test(value)) {
const number = Number.parseFloat(value);
return Number.isFinite(number) ? number : value;
}
return value;
}
export function constructProp(prop, variable) {
prop = prop.trim();
// if custom property, just return
return variable ? prop : camelCase(prop);
}
export function camelCase(value) {
// $ is SASS variable
return value.toLowerCase().replace(/-(\w|$)/g, (_, char) => char.toUpperCase());
}