-
-
Notifications
You must be signed in to change notification settings - Fork 96
/
serialize.ts
176 lines (149 loc) · 5.51 KB
/
serialize.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
import type { Context, CSSRules, Prefixer, Rule } from '@tw-in-js/types'
import * as is from '../internal/is'
import { join, includes, escape, hyphenate } from '../internal/util'
import {
responsivePrecedence,
descending,
declarationPropertyPrecedence,
declarationValuePrecedence,
makeVariantPresedenceCalculator,
} from '../internal/presedence'
import { variants } from '../tailwind/variants'
export interface RuleWithPresedence {
r: string
p: number
}
const stringifyBlock = (body: string, selector: string): string => selector + '{' + body + '}'
export const serialize = (
prefix: Prefixer,
{ theme, tag }: Context,
): ((css: CSSRules, className?: string, rule?: Rule) => RuleWithPresedence[]) => {
// Hash/Tag custom variables during serialization
const tagVar = (_: string, property: string): string => '--' + tag(property)
const tagVars = (value: string): string => `${value}`.replace(/--(tw-[\w-]+)\b/g, tagVar)
const stringifyDeclaration = (property: string, value: string | string[]): string => {
property = tagVars(property)
return is.array(value)
? join(
value.filter(Boolean).map((value) => prefix(property, tagVars(value))),
';',
)
: prefix(property, tagVars(value))
}
// List of css rule with presedence to be injected
let rules: RuleWithPresedence[]
const stringify = (
atRules: string[],
selector: string,
presedence: number,
css: CSSRules,
): void => {
// 1. Properties
// 3. *
// 2. @...
// 3. :pseudo
// 4. &
let declarations = ''
let numberOfDeclarations = 0
let maxPropertyPresedence = 0
let maxValuePresedence = 0
Object.keys(css).forEach((key) => {
const value = css[key] as CSSRules
if (is.object(value) && !is.array(value)) {
// If the value is an object this must be a nested block
// like '@media ...', '@supports ... ', ':pseudo ...', '& > ...'
// If these are the `@` rule
if (key[0] === '@') {
if (key[1] === 'f') {
// Handling the `@font-face` where the
// block doesn't need the brackets wrapped
stringify([], key, 0, value)
} else if (key[1] === 'k') {
// To prevent
// "@keyframes spin{from{transform:rotate(0deg)}}"
// "@keyframes spin{to{transform:rotate(360deg)}}"
// we generate waypoint without prefix and grap them from the stack
// "from{transform:rotate(0deg)}"
// "to{transform:rotate(360deg)}"
// => "@keyframes name{from{transform:rotate(0deg)}from{transform:rotate(0deg)}}"
const currentSize = rules.length
stringify([], '', 0, value)
const waypoints = rules.splice(currentSize, rules.length - currentSize)
rules.push({
r: stringifyBlock(
join(
waypoints.map((p) => p.r),
'',
),
key,
),
// eslint-disable-next-line unicorn/no-reduce
p: waypoints.reduce((sum, p) => sum + p.p, 0),
})
} else {
stringify(atRules.concat(key), selector, presedence | responsivePrecedence(key), value)
}
} else {
// Call the serialize for this block
const hasNestedSelector = selector && includes(key, '&')
stringify(
atRules,
hasNestedSelector
? // Go over the selector and replace the matching selectors respecting multiple selectors
selector.replace(/([^,])+/g, (selectorPart) =>
// Same for the key
key.replace(/([^,])+/g, (keyPart) =>
// If the current part has a nested selector replace it
includes(keyPart, '&') ? keyPart.replace(/&/g, selectorPart) : keyPart,
),
)
: key,
hasNestedSelector ? presedence : 0,
value,
)
}
} else if (value) {
// It is a Property
const property = hyphenate(key)
// Update presedence
numberOfDeclarations += 1
maxPropertyPresedence = Math.max(
maxPropertyPresedence,
declarationPropertyPrecedence(property),
)
maxValuePresedence = Math.max(maxValuePresedence, declarationValuePrecedence(String(value)))
declarations = (declarations && declarations + ';') + stringifyDeclaration(property, value)
}
})
if (numberOfDeclarations) {
// Inject declarations
rules.push({
// eslint-disable-next-line unicorn/no-reduce
r: atRules.reduceRight(stringifyBlock, stringifyBlock(declarations, selector)),
// Calculate precedence
p:
presedence *
// Declarations: 12 bits = 4096
(1 << 12) +
// 4: number of declarations (descending)
(((descending(numberOfDeclarations) & 15) << 8) |
// 4: greatest precedence of properties
((maxPropertyPresedence & 15) << 4) |
// 4: greatest precedence of values
(maxValuePresedence & 15)),
})
}
}
const variantPresedence = makeVariantPresedenceCalculator(theme, variants)
return (css, className, rule) => {
rules = []
stringify(
[],
className ? '.' + escape(className) : '',
// eslint-disable-next-line unicorn/no-reduce
rule ? rule.variants.reduceRight(variantPresedence, 0) : 0,
css,
)
return rules
}
}