Skip to content

Commit

Permalink
perf(css): caching css property names
Browse files Browse the repository at this point in the history
  • Loading branch information
juanrgm committed May 11, 2023
1 parent ba63359 commit bfd31f1
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilled-melons-wash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@suid/css": patch
---

Caching CSS property names
3 changes: 3 additions & 0 deletions packages/css/src/createStyleObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type StyleObject = {
export class StyleCache {
ids = new Map<string /* id */, number>();
rules = new Map<string /* rule */, StyleObject>();
propertyNames = new Map<string /* property */, string>();
create(name: string, rules: string, componentId: string) {
let styleObject = this.rules.get(rules);
if (styleObject) return styleObject;
Expand Down Expand Up @@ -62,12 +63,14 @@ function create(name: string, rules: string, id: string) {
function createStyleObject(options: StyleObjectOptions) {
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");
Expand Down
18 changes: 16 additions & 2 deletions packages/css/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ type RenderOptions = {
[name: string]: (value: any) => any;
};
onPropertyValue?: (name: string, value: unknown) => any;
propertyNameCache?: Map<string, string>;
};
function renderSelector(
propKey: string,
Expand All @@ -36,6 +37,14 @@ function renderSelector(
);
}

function snakeCaseWithCache(name: string, cache?: Map<string, string>) {
if (!cache) return snakeCase(name);
let result = cache.get(name);
if (result) return result;
cache.set(name, (result = snakeCase(name)));
return result;
}

function render(
css: Record<string, any>,
selectors: string[] = [],
Expand Down Expand Up @@ -84,10 +93,15 @@ function render(
? options.onPropertyValue(extraPropKey, inValue)
: inValue;
if (value !== undefined && value !== null)
props.push(`${snakeCase(extraPropKey)}: ${value};`);
props.push(
`${snakeCaseWithCache(
extraPropKey,
options.propertyNameCache
)}: ${value};`
);
}
} else {
propKey = snakeCase(propKey);
propKey = snakeCaseWithCache(propKey, options.propertyNameCache);
const value = options.onPropertyValue
? options.onPropertyValue(propKey, propValue)
: propValue;
Expand Down

0 comments on commit bfd31f1

Please sign in to comment.