Skip to content

Commit

Permalink
fix: auto-convert dynamic property keys and values
Browse files Browse the repository at this point in the history
  • Loading branch information
kripod committed Mar 30, 2020
1 parent ff203cd commit 4bca582
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
5 changes: 4 additions & 1 deletion packages/example-gatsby/src/components/Text.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ export function Text({ className = '', ...restProps }: TextProps): JSX.Element {

return (
<p
className={`${className} ${sx({ color: 'white', bg: 'black' })}`}
className={`${className} ${sx({
color: 'white',
backgroundColor: 'black',
})}`}
{...restProps}
/>
);
Expand Down
2 changes: 1 addition & 1 deletion packages/glaze/src/useStyling.treat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default styleMap((theme) => {
if (scale) {
const tokens = Object.entries(theme.scales[scale] || {});
tokens.forEach(([key, value]) => {
result[`${property}:${key}`] = { [property]: value };
result[`${property}-${key}`] = { [property]: value };
});
}
});
Expand Down
14 changes: 10 additions & 4 deletions packages/glaze/src/useStyling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import { Style } from 'treat';
import { GlazeContext } from './GlazeContext';
import styleRefs from './useStyling.treat';

function kebabCaseReplacer(match: string): string {
return `-${match.toLowerCase()}`;
}

export type ThemedStyle = Style & {
// TODO: Add more precise styles for aliases and shorthands
[key: string]: CSSProperties[keyof CSSProperties];
Expand Down Expand Up @@ -53,11 +57,9 @@ export function useStyling(): (themedStyle: ThemedStyle) => string {

// eslint-disable-next-line no-loop-func
(theme.shorthands[shorthand] || [shorthand]).forEach((key) => {
const style = `${key}:${value}`;

// TODO: Support selectors and media queries
if (typeof value !== 'object') {
let appendedClassName = staticClassNames[style];
let appendedClassName = staticClassNames[`${key}-${value}`];

// Attach a class dynamically if needed
// TODO: Improve support for SSR
Expand All @@ -66,10 +68,14 @@ export function useStyling(): (themedStyle: ThemedStyle) => string {
appendedClassName =
process.env.NODE_ENV !== 'production'
? `DYNAMIC_${key}-${value}`
: `d_${hash(style)}`;
: `d_${hash(`${key}-${value}`)}`;
let usageCount = instancesByClassName.get(appendedClassName);
if (!usageCount) {
usageCount = 0;
// Convert CSS property to kebab-case and normalize numeric value
const style = `${key.replace(/[A-Z]/g, kebabCaseReplacer)}:${
typeof value !== 'number' ? value : `${value}px`
}`;
const element = document.createElement('style');
element.id = appendedClassName;
element.textContent = `.${appendedClassName}{${style}}`;
Expand Down

0 comments on commit 4bca582

Please sign in to comment.