-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
index.ts
260 lines (221 loc) · 7.25 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/**
* [[include:src/css/README.md]]
*
* @packageDocumentation
* @module twind/css
*/
import type {
CSSRules,
CSSAtKeyframes,
Context,
CSSProperties,
Directive,
Falsy,
MaybeThunk,
MaybeArray,
ThemeScreenValue,
} from 'twind'
import { apply, hash, directive } from 'twind'
import { evalThunk, merge, buildMediaQuery } from '../internal/util'
export * from 'twind'
export interface CSSFactory<T, I, R> {
(
strings: TemplateStringsArray,
...interpolations: readonly MaybeThunk<MaybeArray<I | string | number | Falsy>>[]
): Directive<R>
(tokens: MaybeThunk<MaybeArray<T | Falsy>>): Directive<R>
(...tokens: readonly MaybeThunk<T | Falsy>[]): Directive<R>
}
const translate = (tokens: unknown[], context: Context): CSSRules => {
const collect = (target: CSSRules, token: MaybeThunk<CSSRules>): CSSRules =>
Array.isArray(token)
? token.reduce(collect, target)
: merge(target as CSSRules, evalThunk(token, context), context)
return (tokens as MaybeThunk<CSSRules>[]).reduce(collect, {} as CSSRules)
}
// Based on https://github.com/cristianbote/goober/blob/master/src/core/astish.js
const newRule = /\s*(?:([\w-%@]+)\s*:?\s*([^{;]+?)\s*(?:;|$|})|([^;}{]*?)\s*{)|(})/gi
const ruleClean = /\/\*[\s\S]*?\*\/|\s+|\n/gm
const decorate = (selectors: string[], currentBlock: CSSRules): CSSRules =>
selectors.reduceRight((rules, selector) => ({ [selector]: rules }), currentBlock)
const saveBlock = (
rules: CSSRules[],
selectors: string[],
currentBlock: CSSRules | undefined | void,
): void => {
if (currentBlock) {
rules.push(decorate(selectors, currentBlock))
}
}
const interleave = (
strings: TemplateStringsArray,
interpolations: unknown[],
context: Context,
): unknown[] => {
let buffer = strings[0]
const result: unknown[] = []
for (let index = 0; index < interpolations.length; ) {
const interpolation = evalThunk(interpolations[index], context)
if (interpolation && typeof interpolation == 'object') {
result.push(buffer, interpolation)
buffer = strings[++index]
} else {
// Join consecutive strings
buffer += ((interpolation || '') as string) + strings[++index]
}
}
result.push(buffer)
return result
}
const astish = (values: unknown[], context: Context): CSSRules[] => {
// Keep track of active selectors => these are the nested keys
const selectors: string[] = []
const rules: CSSRules[] = []
let currentBlock: CSSRules | undefined | void
let match: RegExpExecArray | null
for (let index = 0; index < values.length; index++) {
const value = values[index]
if (typeof value == 'string') {
while ((match = newRule.exec(value.replace(ruleClean, ' ')))) {
if (!match[0]) continue
// `}` => Save current block
if (match[4]) {
currentBlock = saveBlock(rules, selectors, currentBlock)
selectors.pop()
}
// `... {` => Start a new block
if (match[3]) {
// selector {
currentBlock = saveBlock(rules, selectors, currentBlock)
selectors.push(match[3])
} else if (!match[4]) {
if (!currentBlock) currentBlock = {}
const value = match[2] && /\S/.test(match[2]) ? match[2] : (values[++index] as CSSRules)
if (value) {
if (match[1] == '@apply') {
merge(currentBlock, evalThunk(apply(value as string), context), context)
} else {
// a) property: value
currentBlock[match[1]] = value as CSSRules
}
}
}
}
} else {
currentBlock = saveBlock(rules, selectors, currentBlock)
rules.push(decorate(selectors, value as CSSRules))
}
}
saveBlock(rules, selectors, currentBlock)
return rules
}
const cssFactory = (tokens: unknown[], context: Context): CSSRules =>
translate(
Array.isArray(tokens[0] as TemplateStringsArray) &&
Array.isArray((tokens[0] as TemplateStringsArray).raw)
? astish(interleave(tokens[0] as TemplateStringsArray, tokens.slice(1), context), context)
: tokens,
context,
)
export const css: CSSFactory<CSSRules, CSSRules, CSSRules> = (
...tokens: unknown[]
): Directive<CSSRules> => directive(cssFactory, tokens)
const keyframesFactory = (tokens: unknown[], context: Context): string => {
const waypoints = cssFactory(tokens as CSSRules[], context)
const id = hash(JSON.stringify(waypoints))
// Inject the keyframes
context.tw(() => ({ [`@keyframes ${id}`]: waypoints }))
// but return the keyframe id
return id
}
/**
*
* ```js
* const bounce = keyframes({
* 'from, 20%, 53%, 80%, to': {
* transform: 'translate3d(0,0,0)',
* },
* '40%, 43%': {
* transform: 'translate3d(0, -30px, 0)',
* },
* '70%': {
* transform: 'translate3d(0, -15px, 0)',
* },
* '90%': {
* transform: 'translate3d(0, -4px, 0)',
* }
* })
*
* css({
* animation: `${bounce} 1s ease infinite`,
* })
* ```
* @param waypoints
*/
export const keyframes: CSSFactory<CSSAtKeyframes, CSSAtKeyframes | CSSProperties, string> = (
...tokens: unknown[]
): Directive<string> => directive(keyframesFactory, tokens)
/**
*
* ```js
* const bounce = animation('1s ease infinite', {
* 'from, 20%, 53%, 80%, to': {
* transform: 'translate3d(0,0,0)',
* },
* '40%, 43%': {
* transform: 'translate3d(0, -30px, 0)',
* },
* '70%': {
* transform: 'translate3d(0, -15px, 0)',
* },
* '90%': {
* transform: 'translate3d(0, -4px, 0)',
* }
* })
* ```
*/
export interface Animation {
(value: string | CSSRules | ((context: Context) => string)): CSSFactory<
CSSAtKeyframes,
CSSAtKeyframes | CSSProperties,
CSSRules
>
(
value: string | CSSRules | ((context: Context) => string),
waypoints: CSSAtKeyframes | Directive<string>,
): Directive<CSSRules>
}
export const animation = ((
value: string | CSSRules | ((context: Context) => string),
waypoints?: CSSAtKeyframes | Directive<string>,
): Directive<CSSRules> | CSSFactory<CSSAtKeyframes, CSSAtKeyframes | CSSProperties, CSSRules> =>
waypoints === undefined
? (((...args: Parameters<typeof keyframes>): Directive<CSSRules> =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
animation(value, keyframes(...(args as any)))) as CSSFactory<
CSSAtKeyframes,
CSSAtKeyframes | CSSProperties,
CSSRules
>)
: css({
...(value && typeof value == 'object' ? value : { animation: value }),
animationName: typeof waypoints == 'function' ? waypoints : keyframes(waypoints),
})) as Animation
export interface Screen {
(size: string): Directive<string>
(size: string, css: Directive<CSSRules> | MaybeArray<CSSRules | Falsy>): Directive<CSSRules>
}
const screenFactory = (
{ size, rules }: { size: string; rules?: Directive<CSSRules> | MaybeArray<CSSRules | Falsy> },
context: Context,
): string | CSSRules => {
const media = buildMediaQuery(context.theme('screens', size) as ThemeScreenValue)
return rules === undefined
? media
: {
[media]:
typeof rules == 'function' ? evalThunk(rules, context) : cssFactory([rules], context),
}
}
export const screen = ((size: string, rules?: Directive<CSSRules> | MaybeArray<CSSRules | Falsy>) =>
directive(screenFactory, { size, rules })) as Screen