forked from jantimon/css-variable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
229 lines (219 loc) · 6.33 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
export type CSSPixelValue = '0' | `${string}px`;
export type CSSLengthValue = '0' | `${string}${| "%"
| "ch"
| "cm"
| "em"
| "ex"
| "in"
| "mm"
| "pc"
| "pt"
| "px"
| "rem"
| "vh"
| "vmax"
| "vmin"
| "vw"
}`;
export type CSSAngleValue = `${string}${| "deg"
| "grad"
| "rad"
| "turn"
}`;
export type CSSHexColor = `#${string}`;
type CSSVariableOptions<TValue> = { value: TValue | CSSVariable<TValue> };
/**
* Usually css-variable should always be used with its babel plugin
*
* However in some scenarios e.g. storybook / jest it might be difficult
* to setup.
* For those cases this counter provides a very basic fallback to generate
* different ids.
*/
let fallbackId = 9 ** 9;
export class CSSVariable<TValue = string> extends (
// Inherit from String to be compatible to most CSS-in-JS solutions
// Hacky cast to any for reduced autocomplete
String as any as { new(base: string): { toString: () => string } }
) {
/** Name e.g. `--baseSize` */
readonly name: string;
/** Value e.g. `var(--baseSize, 12px)` */
readonly val: string;
/**
* Creates a new CSS Variable with a unique autogenerated name
*
* E.g. `var(--1isaui4-0)`
*/
constructor();
/**
* Creates a new CSS Variable with a custom defined name
*
* E.g. `var(--baseSize)`
*/
constructor(uniqueName: string);
/**
* Creates a new CSS Variable with a unique autogenerated name
* and a fallback value
*
* E.g. `var(--1isaui4-0, 12px)`
*/
constructor(options: CSSVariableOptions<TValue>);
/**
* Creates a new CSS Variable with a unique autogenerated name
* and a fallback value
*
* E.g. `var(--baseSize, 12px)`
*/
constructor(uniqueName: string, options: CSSVariableOptions<TValue>);
/*#__PURE__*/
constructor(
...args: Array<string | CSSVariableOptions<TValue>>
) {
const optionArg = args.find(
(arg): arg is CSSVariableOptions<TValue> => typeof arg === "object"
);
const name =
"--" +
(args.filter((arg): arg is string => typeof arg === "string").join('-').toLowerCase() ||
// Fallback if babel plugin is missing
(fallbackId++).toString(16));
const val = `var(${name}${optionArg ? `, ${optionArg.value}` : ""})`;
super(val);
this.val = val;
this.name = name;
}
/** Returns the variable name e.g. `--baseSize` */
getName() {
return this.name;
}
/** Create a CSS Object e.g. `{ "--baseSize": '12px' }` */
toStyle(newValue: TValue | CSSVariable<TValue>) {
return { [this.name]: (`${newValue}` as unknown as TValue) };
}
/** Create a CSS String e.g. `--baseSize:12px;` */
toCSS(newValue: TValue | CSSVariable<TValue>) {
return `${this.name}:${newValue};`;
}
}
type ICreateVar = {
/**
* Creates a new CSS Variable with a unique autogenerated name
*
* E.g. `var(--1isaui4-0)`
*/
<TValue = string>(): CSSVariable<TValue>;
/**
* Creates a new CSS Variable with a custom defined name
*
* E.g. `var(--baseSize)`
*/
<TValue = string>(uniqueName: string): CSSVariable<TValue>;
/**
* Creates a new CSS Variable with a unique autogenerated name
* and a fallback value
*
* E.g. `var(--1isaui4-0, 12px)`
*/
<TValue>(options: CSSVariableOptions<TValue>): CSSVariable<TValue>;
/**
* Creates a new CSS Variable with a unique autogenerated name
* and a fallback value
*
* E.g. `var(--baseSize, 12px)`
*/
<TValue>(uniqueName: string, options: CSSVariableOptions<TValue>): CSSVariable<TValue>;
}
export const createVar: ICreateVar = (...args: any[]) => new (CSSVariable as any)(...args);
/**
* A theme structure groups multiple CSSVariable instances
* in a nested object structure e.g.:
*
* ```ts
* const theme = {
* colors: {
* primary: createVar(),
* secondary: createVar()
* },
* spacings: {
* small: createVar(),
* large: createVar()
* }
* }
* ```
*/
type ThemeStructure = { [key: string]: CSSVariable | ThemeStructure };
/** The allowed value type for the given CSSVariable */
export type CSSVariableValueArgument<T> = T extends CSSVariable<infer U> ? U : T
/**
* The ThemeValues type is a helper to map a ThemeStructure to a value type
* to guarantee that the structure and values in createGlobalTheme match
*/
type ThemeValues<TThemeStructure extends ThemeStructure> = {
[Property in keyof TThemeStructure]: TThemeStructure[Property] extends CSSVariable
? CSSVariableValueArgument<TThemeStructure[Property]> | CSSVariable<CSSVariableValueArgument<TThemeStructure[Property]>>
: TThemeStructure[Property] extends ThemeStructure
? ThemeValues<TThemeStructure[Property]>
: never;
};
type DeepPartial<T> = T extends Function ? T : (T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T);
/**
* Assign multiple CSSVariables for a given flat or nested Theme Contract
*
* @example
* ```js
* const theme = {
* colors: {
* primary: createVar(),
* secondary: createVar(),
* }
* }
*
* const brightThemeCSS = assignVars(theme, {
* colors: {
* primary: "#6290C3",
* }
* })
*
* console.log(brightThemeCSS) // -> `--1isaui4-0:#6290C3;`
* ```
*/
export const assignVars = <TTheme extends ThemeStructure>(
cssVariables: TTheme,
cssVariableValues: DeepPartial<ThemeValues<TTheme>>
): string =>
Object.keys(cssVariableValues)
.map((key) =>
typeof cssVariableValues[key] === "string"
? (cssVariables[key] as CSSVariable).toCSS(cssVariableValues[key] as string)
: assignVars(
cssVariables[key] as ThemeStructure,
cssVariableValues[key] as ThemeValues<ThemeStructure>
)
)
.join("");
/**
* Serialize all CSS Variable values for an entire nested or flat Theme Contract
*
* @example
* ```js
* const theme = {
* colors: {
* primary: createVar(),
* secondary: createVar(),
* }
* }
*
* const brightThemeCSS = createGlobalTheme(":root", theme, {
* colors: {
* primary: "#6290C3",
* secondary: "#C2E7DA",
* }
* })
*
* console.log(brightThemeCSS) // -> `:root { --1isaui4-0:#6290C3; --1isaui4-1:#C2E7DA; }`
* ```
*/
export const createGlobalTheme = <TTheme extends ThemeStructure>(scope: string | undefined | null,
cssVariables: TTheme,
cssVariableValues: ThemeValues<TTheme>): string => `${scope ? `${scope}{` : ''}${assignVars(cssVariables, cssVariableValues as DeepPartial<ThemeValues<TTheme>>)}${scope ? '}' : ''}`;