@suid/css
Version:
CSS render in JS.
56 lines (55 loc) • 1.86 kB
JavaScript
import render from "./render";
import { toArray } from "./utils/array";
import { resolveFunction } from "./utils/function";
export class StyleCache {
ids = new Map();
rules = new Map();
propertyNames = new Map();
create(name, rules, componentId) {
let styleObject = this.rules.get(rules);
if (styleObject)
return styleObject;
let componentIndex = this.ids.get(componentId);
// Same component (createUniqueId) but different rules
if (typeof componentIndex === "number") {
// Use a new id for the new rule
this.ids.set(componentId, ++componentIndex);
componentId += `_${componentIndex}`;
}
styleObject = create(name, rules, componentId);
this.save(styleObject, rules);
return styleObject;
}
save(style, rules) {
this.ids.set(style.id, 0);
this.rules.set(rules, style);
}
delete(style) {
this.ids.delete(style.id);
this.rules.delete(style.rules);
}
}
function create(name, rules, id) {
return {
id,
name,
className: `${name}-${id}`,
rules: rules.replaceAll(`$id`, `${id}`),
};
}
function createStyleObject(options) {
const className = `${options.name}-$id`;
const propsValues = toArray(resolveFunction(options.props));
const propertyNameCache = options.cache?.propertyNames;
const rules = propsValues
.map((v) => typeof v === "string"
? `.${className} {\n${v}\n}`
: render(v, [`.${className}`], {
extraProperties: options.extraProperties,
propertyNameCache,
}).join("\n"))
.join("\n");
return (options.cache?.create(options.name, rules, options.componentId) ||
create(options.name, rules, options.componentId));
}
export default createStyleObject;