Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvements/stylecaching #373

Merged
merged 4 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bambooapp/bamboo-molecules",
"version": "0.3.75",
"version": "0.4.0",
"repository": {
"type": "git",
"url": "git+https://github.com/webbeetechnologies/bamboo-molecules.git"
Expand Down
4 changes: 2 additions & 2 deletions src/core/theme/ProvideTheme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ export const defaultExtractStyles = memoize(
const normalizedComponentStyles = normalizeStyles(
theme[componentName],
theme[colorMode],
componentName,
`${componentName}`,
);
const normalizedStyleProp = normalizeStyles(style, theme[colorMode], componentName);
const normalizedStyleProp = normalizeStyles(style, theme[colorMode], `${componentName}`);

return { ...normalizedComponentStyles, ...normalizedStyleProp };
},
Expand Down
5 changes: 2 additions & 3 deletions src/hooks/useNormalizeStyles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ export const useNormalizeStyles = (

const uniqueId = useId();

cacheKey = cacheKey || uniqueId;
return useMemo(
() => normalizeStyles(style, currentTheme, cacheKey),
[style, currentTheme, cacheKey],
() => normalizeStyles(style, currentTheme, cacheKey ?? uniqueId),
[style, currentTheme, cacheKey, uniqueId],
);
};
8 changes: 4 additions & 4 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import normalizeStyles from './normalizeStyles';
import { resolveComponentStyles } from './resolveComponentStyles';
import { normalizeStylesCache } from './normalizeStyles';
import { resolveComponentStylesCache } from './resolveComponentStyles';
export { default as normalizeStyles } from './normalizeStyles';
export { resolveComponentStyles, flattenStateStyles } from './resolveComponentStyles';
export { default as mergeRefs } from './mergeRefs';
Expand Down Expand Up @@ -28,8 +28,8 @@ export { normalizeToNumberString, NormalizeToNumberStringProps } from './normali
export { addEventListener, addListener } from './addEventListener';

export const clearStylesCache = () => {
normalizeStyles.cache.clear();
resolveComponentStyles.cache.clear();
normalizeStylesCache.clear();
resolveComponentStylesCache.clear();
};

export { getYearRange } from './getyearRange';
Expand Down
10 changes: 5 additions & 5 deletions src/utils/normalizeStyles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { get, allArgumentResolver } from './lodash'; // Assuming you have a `get

import { LRUCache } from 'lru-cache';

const cache = new LRUCache({
max: 1000,
export const normalizeStylesCache = new LRUCache({
max: 500,
});

export const maybeIsToken = (value: any) => typeof value === 'string' && value.includes('.');
Expand Down Expand Up @@ -34,8 +34,8 @@ function normalizeStyles(
const cacheKey = `${_cacheKey}_${currentTheme.themeName}_${allArgumentResolver(styles)}`;

// Check if the result is cached
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
if (normalizeStylesCache.has(cacheKey)) {
return normalizeStylesCache.get(cacheKey);
}

// Proceed to normalize styles
Expand Down Expand Up @@ -65,7 +65,7 @@ function normalizeStyles(
}

// Cache the result
cache.set(cacheKey, normalizedStyles);
normalizeStylesCache.set(cacheKey, normalizedStyles);

return normalizedStyles;
}
Expand Down
113 changes: 78 additions & 35 deletions src/utils/resolveComponentStyles.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,88 @@
import deepmerge from 'ts-deepmerge';
import { LRUCache } from 'lru-cache';
import type { ResolveComponentStylesArgs } from '../core/theme/types';
import type { ComponentSize } from '../types';
import { createMemoizedFunction } from './lodash';

const resolveComponentStylesMemo = createMemoizedFunction();
type CacheKey = string;
type CacheValue = any;

export const resolveComponentStylesCache = new LRUCache<CacheKey, CacheValue>({
max: 500,
});

const emptyObj = {};

export const resolveComponentStyles = resolveComponentStylesMemo(
({
componentTheme,
variant,
states,
size,
style = emptyObj, // style prop from the component
}: ResolveComponentStylesArgs) => {
const {
variants,
states: componentStates = emptyObj,
sizes: componentSizes = emptyObj,
...styles
} = componentTheme ?? emptyObj;

const variantStyles = variant ? variants?.[variant] || emptyObj : emptyObj;
const {
states: variantStates = emptyObj,
sizes: variantSizes = emptyObj,
...nonStateStyles
} = variantStyles; // filtering the unused state styles

return deepmerge(
styles,
nonStateStyles,
flattenStateStyles(states, componentStates),
flattenStateStyles(states, variantStates),
resolveSizeStyles(size, componentSizes),
resolveSizeStyles(size, variantSizes),
style,
);
},
);
export const resolveComponentStyles = (args: ResolveComponentStylesArgs): any => {
// Generate a unique cache key based on the arguments
const cacheKey = generateCacheKey(args);

// Check if the result is in the cache
if (resolveComponentStylesCache.has(cacheKey)) {
return resolveComponentStylesCache.get(cacheKey);
}

// Compute the styles
const result = computeComponentStyles(args);

// Store the result in the cache
resolveComponentStylesCache.set(cacheKey, result);

return result;
};

// Helper function to generate a cache key
const generateCacheKey = (args: ResolveComponentStylesArgs): string => {
const sortObjectKeys = (obj: any): any => {
if (Array.isArray(obj)) {
return obj.map(sortObjectKeys);
} else if (obj !== null && typeof obj === 'object') {
return Object.keys(obj)
.sort()
.reduce((result, key) => {
result[key] = sortObjectKeys(obj[key]);
return result;
}, {} as any);
} else {
return obj;
}
};

const sortedArgs = sortObjectKeys(args);
return JSON.stringify(sortedArgs);
};

// Function to compute the component styles
const computeComponentStyles = ({
componentTheme,
variant,
states,
size,
style = emptyObj,
}: ResolveComponentStylesArgs): any => {
const {
variants,
states: componentStates = emptyObj,
sizes: componentSizes = emptyObj,
...styles
} = componentTheme ?? emptyObj;

const variantStyles = variant ? variants?.[variant] || emptyObj : emptyObj;
const {
states: variantStates = emptyObj,
sizes: variantSizes = emptyObj,
...nonStateStyles
} = variantStyles; // filtering unused state styles

return deepmerge(
styles,
nonStateStyles,
flattenStateStyles(states, componentStates),
flattenStateStyles(states, variantStates),
resolveSizeStyles(size, componentSizes),
resolveSizeStyles(size, variantSizes),
style,
);
};

export const flattenStateStyles = (
states: { [key: string]: boolean } | undefined,
Expand Down
Loading