Skip to content

Commit

Permalink
fix(theme): Allow listing values with number keys
Browse files Browse the repository at this point in the history
  • Loading branch information
Brijesh Bittu committed Dec 30, 2024
1 parent 9989784 commit a25f5e7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 16 deletions.
25 changes: 15 additions & 10 deletions packages/pigment-css-theme/src/theme.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
export interface Theme {}

type Join<K extends string | number, P extends string> = K extends string | number
? P extends ''
? `${K}`
: `${P}.${K}`
type Join<K, P> = K extends string | number
? P extends string | number
? `${K}${P extends '' ? '' : '.'}${P}`
: never
: never;

type PathsToLeaves<T extends object, P extends string = ''> = {
[K in keyof T]: T[K] extends object
? PathsToLeaves<T[K], Join<K & string, P>>
: Join<K & string, P>;
}[keyof T];
type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...0[]];

type PathsToLeaves<T, D extends number = 10> = T extends object
? {
[K in keyof T]-?: K extends string | number
? T[K] extends object
? Join<K, PathsToLeaves<T[K], Prev[D]>>
: `${K}`
: never;
}[keyof T]
: '';
export type ThemeKey = `$${PathsToLeaves<Theme>}`;

/**
Expand All @@ -28,7 +33,7 @@ export type ThemeKey = `$${PathsToLeaves<Theme>}`;
* // override Theme type as per docs
*
* const cls1 = css({
* border: `1px solid t('$palette.main')`,
* border: `1px solid ${t('$palette.main')}`,
* })
* ```
*/
Expand Down
29 changes: 23 additions & 6 deletions packages/pigment-css-theme/tests/theme.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
import { t } from '../src';

const theme = {
gray: {
surface: {
1: 'hsl(0 0% 99%)',
'2': 'hsl(0 0% 97.5%)',
},
},
br: {
circle: '50%',
pill: '9999px',
},
};

type UserTheme = typeof theme;

declare module '../src' {
interface Theme {
palette: {
main: string;
};
}
interface Theme extends UserTheme {}
}

t('$palette.main');
t('$gray.surface.1');
t('$gray.surface.2');
// @ts-expect-error 3 does not exist
t('$gray.surface.3');
t('$br.circle');
// @ts-expect-error circle1 does not exist
t('$br.circle1');

// @ts-expect-error
t('$palette.secondary');

0 comments on commit a25f5e7

Please sign in to comment.