@ng-native/tailwind 0.0.1 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -1
- package/config.cjs +238 -0
- package/flatten.cjs +830 -0
- package/native.css +84 -0
- package/package.json +47 -3
- package/preset.cjs +122 -0
- package/shared.css +203 -0
- package/web.css +85 -0
package/flatten.cjs
ADDED
|
@@ -0,0 +1,830 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tailwind's CSS, made into CSS the engine's compiler accepts.
|
|
3
|
+
*
|
|
4
|
+
* Tailwind 4 emits for a browser, and most of what it emits is about being one: cascade layers,
|
|
5
|
+
* `@property` declarations, feature detection, pseudo-element resets, `oklch()` colours, and a
|
|
6
|
+
* spacing scale expressed as `calc(var(--spacing) * n)`. This turns that into the subset a
|
|
7
|
+
* renderer with no CSS parser on device can compile, without changing what any declaration means.
|
|
8
|
+
*
|
|
9
|
+
* The rule of thumb throughout: **anything that is only a browser question is answered here**, at
|
|
10
|
+
* build time, and anything that is a real cascade question is left for the engine, which has a
|
|
11
|
+
* cascade. That is the whole difference from NativeWind, which has to rebuild one.
|
|
12
|
+
*
|
|
13
|
+
* Import `tailwindcss/theme.css` and `tailwindcss/utilities.css` rather than `tailwindcss`, and
|
|
14
|
+
* preflight never arrives - it is `html`, `::before` and `-webkit-*` from end to end. This copes
|
|
15
|
+
* if it does arrive, by dropping what it cannot express, but the warnings are noise nobody needs.
|
|
16
|
+
*/
|
|
17
|
+
const { transform, Features } = require('lightningcss');
|
|
18
|
+
const { markUnitless } = require('@ng-native/metro/css/compile.cjs');
|
|
19
|
+
|
|
20
|
+
/** `@layer a, b;` - the statement that orders layers, which is meaningless once they are gone. */
|
|
21
|
+
const LAYER_STATEMENT = /@layer\s+[^;{]+;/g;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Remove an at-rule and everything inside it, or unwrap it and keep its contents.
|
|
25
|
+
*
|
|
26
|
+
* Written by hand rather than with a regex because the bodies nest: `@supports` holds rules, and
|
|
27
|
+
* `@layer` holds `@supports`. Brace counting is the whole of it.
|
|
28
|
+
*/
|
|
29
|
+
function rewriteAtRule(css, prelude, keepBody) {
|
|
30
|
+
let out = css;
|
|
31
|
+
for (let at = out.indexOf(prelude); at !== -1; at = out.indexOf(prelude, at)) {
|
|
32
|
+
const open = out.indexOf('{', at);
|
|
33
|
+
if (open === -1) break;
|
|
34
|
+
const close = blockEnd(out, open);
|
|
35
|
+
if (close === -1) break;
|
|
36
|
+
const body = keepBody ? out.slice(open + 1, close) : '';
|
|
37
|
+
out = out.slice(0, at) + body + out.slice(close + 1);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The index of the brace that closes the block opened at `open`, or -1. */
|
|
43
|
+
function blockEnd(css, open) {
|
|
44
|
+
let depth = 0;
|
|
45
|
+
for (let i = open; i < css.length; i++) {
|
|
46
|
+
if (css[i] === '{') depth++;
|
|
47
|
+
else if (css[i] === '}' && --depth === 0) return i;
|
|
48
|
+
}
|
|
49
|
+
return -1;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A custom property's value, less `!important`, which belongs to the declaration, not the value. */
|
|
53
|
+
function withoutImportant(value) {
|
|
54
|
+
return value.replace(/\s*!\s*important\s*$/i, '').trim();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The custom properties a sheet declares, and what they resolve to.
|
|
59
|
+
*
|
|
60
|
+
* Two sources: ordinary declarations, wherever they appear, and `@property`'s `initial-value`,
|
|
61
|
+
* which is how Tailwind gives `--tw-border-style` a default of `solid` on the web. Both are
|
|
62
|
+
* static by the time this runs; a custom property that changes at runtime is the app's business
|
|
63
|
+
* and is left alone, because it is never one of these.
|
|
64
|
+
*/
|
|
65
|
+
function collectVariables(css) {
|
|
66
|
+
const values = new Map();
|
|
67
|
+
const conflicting = new Set();
|
|
68
|
+
for (const [, name, value] of css.matchAll(/(--[\w-]+)\s*:\s*([^;{}]+)[;}]/g)) {
|
|
69
|
+
const trimmed = withoutImportant(value);
|
|
70
|
+
if (values.has(name) && values.get(name) !== trimmed) conflicting.add(name);
|
|
71
|
+
values.set(name, trimmed);
|
|
72
|
+
}
|
|
73
|
+
for (const [, name, body] of css.matchAll(/@property\s+(--[\w-]+)\s*\{([^}]*)\}/g)) {
|
|
74
|
+
const initial = /initial-value\s*:\s*([^;}]+)/.exec(body);
|
|
75
|
+
if (initial) values.set(name, initial[1].trim());
|
|
76
|
+
}
|
|
77
|
+
// A property with two different values is a themed one: `--primary` is one colour under `:root`
|
|
78
|
+
// and another under `.dark`, and which applies is a question only the cascade can answer.
|
|
79
|
+
// Substituting picks whichever was written last and paints the dark palette in daylight, so
|
|
80
|
+
// these are left for the engine, which resolves `var()` per node against the tokens in scope.
|
|
81
|
+
//
|
|
82
|
+
// Tailwind's own `--tw-*` plumbing is exempt. Those are set by one utility and read by another
|
|
83
|
+
// on the same node, and every one of them also has a reset value, so they all look themed and
|
|
84
|
+
// none of them is. They stay substituted, which is what they have always been.
|
|
85
|
+
for (const name of conflicting) {
|
|
86
|
+
if (!name.startsWith('--tw-')) values.delete(name);
|
|
87
|
+
}
|
|
88
|
+
return values;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Find the next `var(` and return the whole call, its name and its fallback.
|
|
93
|
+
*
|
|
94
|
+
* Scanned rather than matched: a fallback can be `calc(1.75 / 1.125)` or another `var()`, and a
|
|
95
|
+
* regex that stops at the first `)` silently leaves those alone - which is how the type scale
|
|
96
|
+
* came out empty the first time.
|
|
97
|
+
*/
|
|
98
|
+
function nextVar(css, from) {
|
|
99
|
+
const at = css.indexOf('var(', from);
|
|
100
|
+
if (at === -1) return null;
|
|
101
|
+
let depth = 0;
|
|
102
|
+
for (let i = at + 3; i < css.length; i++) {
|
|
103
|
+
if (css[i] === '(') depth++;
|
|
104
|
+
else if (css[i] === ')' && --depth === 0) {
|
|
105
|
+
const inside = css.slice(at + 4, i);
|
|
106
|
+
const comma = splitOnce(inside);
|
|
107
|
+
return { at, end: i + 1, name: comma.name.trim(), fallback: comma.fallback };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Whether a value refers to the property it is the value of, which would substitute forever.
|
|
115
|
+
*
|
|
116
|
+
* Matched to the end of the name rather than by prefix. `--tw-shadow`'s value mentions
|
|
117
|
+
* `--tw-shadow-color`, which starts with it, and treating that as a self-reference left every
|
|
118
|
+
* Tailwind shadow unsubstituted - so the file-wide reset won instead and no app has ever painted
|
|
119
|
+
* one.
|
|
120
|
+
*/
|
|
121
|
+
function selfReferential(value, name) {
|
|
122
|
+
return new RegExp(`var\\(\\s*${name.replace(/[-]/g, '\\-')}\\s*[,)]`).test(value);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Split `--x, fallback` at the first comma that is not inside parentheses. */
|
|
126
|
+
function splitOnce(inside) {
|
|
127
|
+
let depth = 0;
|
|
128
|
+
for (let i = 0; i < inside.length; i++) {
|
|
129
|
+
if (inside[i] === '(') depth++;
|
|
130
|
+
else if (inside[i] === ')') depth--;
|
|
131
|
+
else if (inside[i] === ',' && depth === 0) {
|
|
132
|
+
return { name: inside.slice(0, i), fallback: inside.slice(i + 1).trim() };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { name: inside, fallback: undefined };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** A rule that resets every `--tw-*` slot on every node: Tailwind's `*, ::before, ::after`. */
|
|
139
|
+
const RESET = /(^|,)\s*\*\s*(,|$)/;
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Custom properties the device supplies at runtime, which no build step can know.
|
|
143
|
+
*
|
|
144
|
+
* They have to survive this untouched, fallback and all: collapsing
|
|
145
|
+
* `var(--safe-area-inset-bottom, 0px)` to `0px` here produces a layout that always sits under the
|
|
146
|
+
* home indicator, and collapsing `var(--hairline, 1px)` to `1px` produces a divider three
|
|
147
|
+
* physical pixels thick - both with nothing in the output to say why. Everything else is
|
|
148
|
+
* substituted, because there is no CSS parser on device to do it later.
|
|
149
|
+
*
|
|
150
|
+
* A gradient's stops are here for a different reason: they are set by one class and read by
|
|
151
|
+
* another, so no build step can know which pair a node will wear. See `expandGradients`.
|
|
152
|
+
*/
|
|
153
|
+
const RUNTIME_SUPPLIED =
|
|
154
|
+
/^--(safe-area-inset-(top|right|bottom|left)|hairline|tw-gradient-(from|via|to)(-position)?)$/;
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The `--tw-*` slots one utility sets and another reads, which only the node can answer.
|
|
158
|
+
*
|
|
159
|
+
* `translate-x-2` sets `--tw-translate-x` and `translate-y-4` sets `--tw-translate-y`, and each
|
|
160
|
+
* reads both. Substituted here, each rule takes the other axis from the `*` reset, and the one the
|
|
161
|
+
* sheet writes last wins with its zero. Left as `var()`, the engine reads each slot from whatever
|
|
162
|
+
* class set it on that node, which is what the web does.
|
|
163
|
+
*
|
|
164
|
+
* Only a slot the sheet sets somewhere other than the reset, read by a rule that does not set it
|
|
165
|
+
* itself or set again by a rule that does not read it, and only where the engine resolves `var()`
|
|
166
|
+
* per node: a transform, a shadow or a filter, or a part of a shadow slot, as `ring-blue-500` sets
|
|
167
|
+
* the colour of `ring-2`'s. Anything else stays settled here.
|
|
168
|
+
*/
|
|
169
|
+
function crossRuleVariables(css) {
|
|
170
|
+
const set = new Set();
|
|
171
|
+
const setWithoutReading = new Set();
|
|
172
|
+
const readElsewhere = new Set();
|
|
173
|
+
const readWhereSet = new Set();
|
|
174
|
+
for (const [, selector, body] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
|
|
175
|
+
if (selectorList(selector).some((one) => one.trim() === '*')) continue;
|
|
176
|
+
const declared = new Set([...body.matchAll(/(--tw-[\w-]+)\s*:/g)].map((match) => match[1]));
|
|
177
|
+
const read = new Set();
|
|
178
|
+
for (const [, property, value] of body.matchAll(/(-?-?[\w-]+)\s*:\s*([^;]+)/g)) {
|
|
179
|
+
const perNode = RESOLVED_PER_NODE.test(property) || SHADOW_SLOT.test(property);
|
|
180
|
+
for (const [, name] of value.matchAll(/var\(\s*(--tw-[\w-]+)/g)) {
|
|
181
|
+
if (perNode || REVERSE_SLOT.test(name)) read.add(name);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
for (const name of declared) {
|
|
185
|
+
set.add(name);
|
|
186
|
+
if (!read.has(name)) setWithoutReading.add(name);
|
|
187
|
+
}
|
|
188
|
+
for (const name of read) (declared.has(name) ? readWhereSet : readElsewhere).add(name);
|
|
189
|
+
}
|
|
190
|
+
// A slot a rule reads where it sets it, which another rule sets without reading: `drop-shadow-lg`
|
|
191
|
+
// reads the `--tw-drop-shadow` it sets, and `drop-shadow-red-500` sets it again, coloured.
|
|
192
|
+
return new Set([
|
|
193
|
+
...[...readElsewhere].filter((name) => set.has(name)),
|
|
194
|
+
...[...readWhereSet].filter((name) => setWithoutReading.has(name)),
|
|
195
|
+
]);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The 0 or 1 `space-x-reverse` and `divide-y-reverse` set, which `space-x-2` and `divide-y-2` read
|
|
200
|
+
* inside a margin or border width's `calc()`: settled here, the reverse class does nothing.
|
|
201
|
+
*/
|
|
202
|
+
const REVERSE_SLOT = /^--tw-(space|divide)-[xy]-reverse$/;
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* A bare number times a reverse slot: `divide-x-[3]` is `calc(3 * var(--tw-divide-x-reverse))`,
|
|
206
|
+
* and the slot is 0 or 1, so the width has no unit and a browser drops it.
|
|
207
|
+
*/
|
|
208
|
+
const UNITLESS_REVERSE =
|
|
209
|
+
/calc\((-?\d*\.?\d+)(\s*\*\s*(?:var\(--tw-(?:space|divide)-[xy]-reverse\)|calc\(1 - var\(--tw-(?:space|divide)-[xy]-reverse\)\)))\)/g;
|
|
210
|
+
|
|
211
|
+
/** Each such number tagged as `markUnitless` tags one, so it is refused as needing a unit. */
|
|
212
|
+
function markUnitlessReverse(css) {
|
|
213
|
+
return css.replace(UNITLESS_REVERSE, (whole, number, rest) =>
|
|
214
|
+
Number(number) === 0 ? whole : `calc(${number}__unitless${rest})`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Properties whose `var()` the engine resolves per node, from the tokens in scope there. */
|
|
219
|
+
const RESOLVED_PER_NODE =
|
|
220
|
+
/^(translate|scale|rotate|transform|box-shadow|text-shadow|filter|font-variant-numeric)$/;
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* A shadow slot, whose own parts another class may set: `ring-blue-500` its colour,
|
|
224
|
+
* `ring-offset-2` the width it is pushed out by, `ring-inset` whether it is inset. A drop shadow
|
|
225
|
+
* keeps its shape in `--tw-drop-shadow-size`, which `drop-shadow-red-500` colours.
|
|
226
|
+
*/
|
|
227
|
+
// Tailwind 3's `--tw-shadow-colored` too: the coloured copy of a shadow, which `shadow-red-500`
|
|
228
|
+
// swaps in and whose colour is a slot of its own.
|
|
229
|
+
const SHADOW_SLOT = /^--tw-[\w-]*shadow(-size|-colored)?$/;
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Replace `var()` with what it resolves to, repeatedly, because theme values reference each other.
|
|
233
|
+
*
|
|
234
|
+
* A reference that resolves to nothing is left as it is: the engine resolves `var()` on device
|
|
235
|
+
* too, and a value the app supplies at runtime - a safe-area inset, say - has to survive this.
|
|
236
|
+
*/
|
|
237
|
+
/**
|
|
238
|
+
* Substitute inside one rule, with that rule's own declarations taking precedence.
|
|
239
|
+
*
|
|
240
|
+
* Tailwind's shadows, rings and filters are all built this way: a `*` reset gives every slot a
|
|
241
|
+
* no-op default, and the utility that needs one declares it in the very rule that reads it.
|
|
242
|
+
* Taking the file-wide value means taking the reset, because it is written last - so `.shadow-lg`
|
|
243
|
+
* resolved its own `--tw-shadow` to `0 0 #0000` and painted nothing, silently, in every app.
|
|
244
|
+
*
|
|
245
|
+
* Only the rule's own block is consulted, not its ancestors'. That is enough for the pattern this
|
|
246
|
+
* exists for, and anything wider is a cascade question the engine answers on device.
|
|
247
|
+
*/
|
|
248
|
+
function substituteInRules(css, values, runtime) {
|
|
249
|
+
return css.replace(/([^{}]+)\{([^{}]*)\}/g, (whole, selector, body) => {
|
|
250
|
+
const local = new Map(values);
|
|
251
|
+
let changed = false;
|
|
252
|
+
for (const [, name, value] of body.matchAll(/(--[\w-]+)\s*:\s*([^;{}]+)[;}]?/g)) {
|
|
253
|
+
const trimmed = withoutImportant(value);
|
|
254
|
+
if (local.get(name) !== trimmed) changed = true;
|
|
255
|
+
local.set(name, trimmed);
|
|
256
|
+
}
|
|
257
|
+
return changed ? `${selector}{${substituteVariables(body, local, runtime)}}` : whole;
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function substituteVariables(css, values, runtime) {
|
|
262
|
+
let out = css;
|
|
263
|
+
for (let pass = 0; pass < 5; pass++) {
|
|
264
|
+
let changed = false;
|
|
265
|
+
let from = 0;
|
|
266
|
+
for (let found = nextVar(out, from); found; found = nextVar(out, from)) {
|
|
267
|
+
// A runtime-supplied property is left exactly as written, fallback and all, because only
|
|
268
|
+
// the device can answer it.
|
|
269
|
+
if (RUNTIME_SUPPLIED.test(found.name) || runtime.has(found.name)) {
|
|
270
|
+
from = found.end;
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
// `initial` in a custom property means it holds nothing, so `var()` takes its fallback.
|
|
274
|
+
// Tailwind writes it in the reset for every optional slot - `--tw-shadow-color: initial` is
|
|
275
|
+
// "nobody asked for a shadow colour" - and substituting the word itself produced a shadow
|
|
276
|
+
// painted the colour `initial`, which is to say no shadow at all.
|
|
277
|
+
const declared = values.get(found.name);
|
|
278
|
+
const value = declared === undefined || declared === 'initial' ? found.fallback : declared;
|
|
279
|
+
if (value === undefined || selfReferential(value, found.name)) {
|
|
280
|
+
from = found.end;
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
out = out.slice(0, found.at) + value + out.slice(found.end);
|
|
284
|
+
from = found.at + value.length;
|
|
285
|
+
changed = true;
|
|
286
|
+
}
|
|
287
|
+
if (!changed) break;
|
|
288
|
+
}
|
|
289
|
+
return out;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* A selector list split into its selectors: at a comma that is neither escaped, as in Tailwind's
|
|
294
|
+
* `.placeholder-\\[rgb\\(1\\,2\\,3\\)\\]`, nor inside parentheses, as in `:is(.a, .b)`.
|
|
295
|
+
*/
|
|
296
|
+
function selectorList(selectors) {
|
|
297
|
+
const list = [''];
|
|
298
|
+
const at = { depth: 0, quote: null };
|
|
299
|
+
for (let i = 0; i < selectors.length; i++) {
|
|
300
|
+
const c = selectors[i];
|
|
301
|
+
if (c === '\\') {
|
|
302
|
+
list[list.length - 1] += c + (selectors[++i] ?? '');
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
nest(at, c);
|
|
306
|
+
if (c === ',' && at.depth === 0 && !at.quote) list.push('');
|
|
307
|
+
else list[list.length - 1] += c;
|
|
308
|
+
}
|
|
309
|
+
return list;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* How deep a selector is at a character: inside brackets or parentheses, or a quoted attribute
|
|
314
|
+
* value, where a comma is part of the value (`[data-x="1,2"]`) rather than between selectors.
|
|
315
|
+
*/
|
|
316
|
+
function nest(at, c) {
|
|
317
|
+
if (at.quote) {
|
|
318
|
+
if (c === at.quote) at.quote = null;
|
|
319
|
+
} else if (c === '"' || c === "'") at.quote = c;
|
|
320
|
+
else if (c === '(' || c === '[') at.depth++;
|
|
321
|
+
else if (c === ')' || c === ']') at.depth--;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Drop the pseudo-element selectors from a list that has others: Tailwind's reset is
|
|
326
|
+
* `*, ::before, ::after, ::backdrop`, and only its `*` addresses anything a template declares.
|
|
327
|
+
*
|
|
328
|
+
* `::before`, `::file-selector-button` and friends would mean synthesising view hierarchy from a
|
|
329
|
+
* stylesheet, which this project refuses on purpose - see ADR 0001. A rule that is *only*
|
|
330
|
+
* pseudo-elements is left whole for the compiler, which refuses it with a warning that says so:
|
|
331
|
+
* `placeholder:text-gray-400` is a class an app asked for, and dropped here it did nothing with
|
|
332
|
+
* nothing to say why.
|
|
333
|
+
*/
|
|
334
|
+
function dropPseudoElementRules(css) {
|
|
335
|
+
return css.replace(/([^{}]+)\{([^{}]*)\}/g, (whole, selectors, body) => {
|
|
336
|
+
if (!selectors.includes('::')) return whole;
|
|
337
|
+
const all = selectorList(selectors).map((one) => one.trim());
|
|
338
|
+
const kept = all.filter((one) => one && !one.includes('::'));
|
|
339
|
+
// Tailwind 3's `::backdrop { --tw-...: ... }`, the reset again for a box native never draws: no
|
|
340
|
+
// author wrote it, so it goes without a word.
|
|
341
|
+
if (!kept.length && /^\s*(--tw-[\w-]+\s*:[^;{}]*;?\s*)*$/.test(body)) return '';
|
|
342
|
+
return kept.length && kept.length < all.length ? `${kept.join(', ')} {${body}}` : whole;
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Fold arithmetic, by handing it to lightningcss with an old target.
|
|
348
|
+
*
|
|
349
|
+
* `calc(0.25rem * 4)` becomes `1rem`, which the engine's own compiler can then translate. The
|
|
350
|
+
* target is a browser old enough to need the lowering; nothing about it reaches a device.
|
|
351
|
+
*
|
|
352
|
+
* Excluding the media-query features is load-bearing rather than tidiness. A target that old
|
|
353
|
+
* lowers everything a browser that age would lack, and that includes Tailwind's own `(width <
|
|
354
|
+
* 500px)` breakpoint and container queries - rewritten as `not (min-width: 500px)`, which the
|
|
355
|
+
* engine's compiler refuses outright (`compile.cjs`'s own `flatten()` hit the same thing for
|
|
356
|
+
* nesting, and fixed it the same way: ask for only the feature that needs lowering, rather than
|
|
357
|
+
* lowering for a target). Left in, every `max-*` variant and range media query compiled to
|
|
358
|
+
* nothing.
|
|
359
|
+
*
|
|
360
|
+
* Colours are excluded too. `oklch()` and the other perceptual spaces are the compiler's to
|
|
361
|
+
* convert, so that one converter decides what every colour is. lightningcss's lowering gamut-maps
|
|
362
|
+
* by an earlier draft of CSS Color 4, in single precision, and most of the palette came out a step
|
|
363
|
+
* or more from the same `oklch()` written in a component's stylesheet.
|
|
364
|
+
*/
|
|
365
|
+
function fold(css) {
|
|
366
|
+
const out = transform({
|
|
367
|
+
filename: 'tailwind.css',
|
|
368
|
+
code: Buffer.from(css),
|
|
369
|
+
minify: false,
|
|
370
|
+
targets: { chrome: 90 << 16 },
|
|
371
|
+
exclude:
|
|
372
|
+
Features.MediaRangeSyntax |
|
|
373
|
+
Features.MediaIntervalSyntax |
|
|
374
|
+
Features.OklabColors |
|
|
375
|
+
Features.LabColors |
|
|
376
|
+
Features.ColorFunction,
|
|
377
|
+
}).code.toString();
|
|
378
|
+
// Lowering can reintroduce feature detection around what it just lowered.
|
|
379
|
+
return rewriteAtRule(foldSimpleCalc(out), '@supports', true);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* The calc() lightningcss leaves: one of plain numbers, and any inside a custom property.
|
|
384
|
+
*
|
|
385
|
+
* Tailwind writes a negative integer as `calc(10 * -1)` for `-z-10`, a spacing slot as
|
|
386
|
+
* `--tw-translate-x: calc(.25rem * 2)`, and a fraction as `calc(1/2 * 100%)`. lightningcss folds
|
|
387
|
+
* none of them - it cannot know what a custom property will be used as - and the compiler refuses
|
|
388
|
+
* all three. Only numbers in one unit are folded, with `*` and `/` before `+` and `-`; a calc() with
|
|
389
|
+
* two units, a var() or brackets in it is left for the compiler to judge.
|
|
390
|
+
*/
|
|
391
|
+
function foldSimpleCalc(css) {
|
|
392
|
+
// Innermost first, and again, so `calc(calc(1rem + 2px) * -1)` comes down to one length.
|
|
393
|
+
for (let before = ''; before !== css;) {
|
|
394
|
+
before = css;
|
|
395
|
+
css = css.replace(/calc\(([^()]*)\)/gi, (whole, inside) => simpleCalc(inside) ?? whole);
|
|
396
|
+
}
|
|
397
|
+
return css;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Points in a rem: fixed, with no root element to change it. See `values.cjs`. */
|
|
401
|
+
const REM = 16;
|
|
402
|
+
|
|
403
|
+
/** One unit's arithmetic, as `<number><unit>`, or null when it is not that simple. */
|
|
404
|
+
function simpleCalc(expression) {
|
|
405
|
+
const terms = [...expression.matchAll(/\s*(-?[\d.]+)([a-z%]*)\s*([*/]|\s[+-]\s|$)/gi)];
|
|
406
|
+
if (terms.map((term) => term[0]).join('') !== expression) return null;
|
|
407
|
+
const sum = products(terms);
|
|
408
|
+
return sum === null ? null : added(sum);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Each run of `*` and `/` as one signed term of the sum around it; null when one cannot be. */
|
|
412
|
+
function products(terms) {
|
|
413
|
+
const sum = [];
|
|
414
|
+
let product = null;
|
|
415
|
+
let op = '';
|
|
416
|
+
let sign = 1;
|
|
417
|
+
for (const [, digits, unit, next] of terms) {
|
|
418
|
+
const value = { n: Number(digits), unit: unit.toLowerCase() };
|
|
419
|
+
product = product === null ? value : combine(product, value, op);
|
|
420
|
+
if (product === null) return null;
|
|
421
|
+
op = next.trim();
|
|
422
|
+
if (op === '*' || op === '/') continue;
|
|
423
|
+
sum.push({ ...product, sign });
|
|
424
|
+
product = null;
|
|
425
|
+
sign = op === '-' ? -1 : 1;
|
|
426
|
+
}
|
|
427
|
+
return sum;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Signed terms added up, in their one unit; null when they are in two. */
|
|
431
|
+
function added(sum) {
|
|
432
|
+
// A rem is 16 points in this engine, as the compiler reads one, so rem and px add up.
|
|
433
|
+
if (sum.some((term) => term.unit === 'px')) {
|
|
434
|
+
for (const term of sum)
|
|
435
|
+
if (term.unit === 'rem') Object.assign(term, { n: term.n * REM, unit: 'px' });
|
|
436
|
+
}
|
|
437
|
+
// Two kinds of value do not add up, zero or not: `calc(0deg + 4px)` is dropped by a browser.
|
|
438
|
+
// A length beside a percentage is one kind, where a zero of either drops out below.
|
|
439
|
+
const kinds = new Set(sum.map((term) => kindOfUnit(term.unit)));
|
|
440
|
+
if (kinds.size > 1 && !(kinds.size === 2 && kinds.has('length') && kinds.has('%'))) return null;
|
|
441
|
+
const units = new Set(sum.filter((term) => term.n !== 0).map((term) => term.unit));
|
|
442
|
+
if (units.size > 1) return null;
|
|
443
|
+
const total = sum.reduce((acc, term) => acc + term.sign * term.n, 0);
|
|
444
|
+
return `${round(total)}${[...units][0] ?? sum[0]?.unit ?? ''}`;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** The kind of value a unit makes: a number, an angle, a time, a percentage or a length. */
|
|
448
|
+
function kindOfUnit(unit) {
|
|
449
|
+
if (unit === '') return 'number';
|
|
450
|
+
if (unit === '%') return '%';
|
|
451
|
+
if (['deg', 'rad', 'grad', 'turn'].includes(unit)) return 'angle';
|
|
452
|
+
if (['s', 'ms'].includes(unit)) return 'time';
|
|
453
|
+
return 'length';
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** `a * b` or `a / b`, keeping the one unit a product may have; null when that is not so. */
|
|
457
|
+
function combine(a, b, op) {
|
|
458
|
+
if (op === '*') {
|
|
459
|
+
if (a.unit && b.unit) return null;
|
|
460
|
+
return { n: a.n * b.n, unit: a.unit || b.unit };
|
|
461
|
+
}
|
|
462
|
+
if (b.unit || b.n === 0) return null;
|
|
463
|
+
return { n: a.n / b.n, unit: a.unit };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Turn a unitless `line-height` into a length, using the font size beside it.
|
|
468
|
+
*
|
|
469
|
+
* CSS reads `line-height: 1.5` as a ratio of the element's font size, and inherits the *ratio*;
|
|
470
|
+
* React Native's `lineHeight` is a number of points and there is no ratio to inherit. Tailwind
|
|
471
|
+
* always emits the two together - `.text-lg` is a size and its leading - so the multiplication can
|
|
472
|
+
* be done here, once, where both are in the same rule. A ratio with no font size beside it is left
|
|
473
|
+
* alone for the compiler to refuse, because guessing an inherited size would be worse than saying
|
|
474
|
+
* nothing.
|
|
475
|
+
*/
|
|
476
|
+
function resolveUnitlessLineHeight(css) {
|
|
477
|
+
return css.replace(/\{([^{}]*)\}/g, (whole, body) => {
|
|
478
|
+
const ratio = /(^|;)\s*line-height\s*:\s*([0-9]*\.?[0-9]+)\s*(?=;|$)/.exec(body);
|
|
479
|
+
if (!ratio) return whole;
|
|
480
|
+
const size = /(^|;)\s*font-size\s*:\s*([0-9]*\.?[0-9]+)(rem|px)\s*(?=;|$)/.exec(body);
|
|
481
|
+
if (!size) return whole;
|
|
482
|
+
const height = Number(size[2]) * Number(ratio[2]);
|
|
483
|
+
return whole.replace(ratio[0], `${ratio[1]} line-height: ${round(height)}${size[3]}`);
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/** Three decimal places is finer than a point on any screen, and keeps the output readable. */
|
|
488
|
+
function round(value) {
|
|
489
|
+
return Math.round(value * 1000) / 1000;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* `border-top-style: solid` and its siblings, logical ones included: `border-y` is
|
|
494
|
+
* `border-block-style` and `border-x` is `border-inline-style`.
|
|
495
|
+
*
|
|
496
|
+
* React Native has one `borderStyle` for the whole box, so a per-side one cannot be expressed;
|
|
497
|
+
* `solid` is also its default, so Tailwind's `border-t` means nothing but its width. A side style
|
|
498
|
+
* that is *not* solid is left to the compiler, which drops it and says so - the app asked for
|
|
499
|
+
* something native cannot do, and should hear about it.
|
|
500
|
+
*/
|
|
501
|
+
function dropRedundantBorderStyles(css) {
|
|
502
|
+
return css.replace(
|
|
503
|
+
/\s*border-(top|right|bottom|left|(inline|block)(-start|-end)?)-style\s*:\s*solid\s*(!\s*important\s*)?;/g,
|
|
504
|
+
'',
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* The `--tw-*` declarations nothing reads once the build has filled every `var()` it could.
|
|
510
|
+
*
|
|
511
|
+
* `ease-in` sets `--tw-ease` for `.transition` to read, and that read is settled here, so the
|
|
512
|
+
* declaration is left over: a token in every bundle, and one the compiler warned about on every
|
|
513
|
+
* `ease-*` class, since a cubic-bezier() is not a value a token can hold. A slot left for the
|
|
514
|
+
* device is still read by a `var()` and stays.
|
|
515
|
+
*/
|
|
516
|
+
function dropUnreadSlots(css) {
|
|
517
|
+
const read = new Set([...css.matchAll(/var\(\s*(--tw-[\w-]+)/g)].map((match) => match[1]));
|
|
518
|
+
// Again until nothing changes: a match takes the `;` that ends its declaration, which is the one
|
|
519
|
+
// the next declaration needs to be found, so one pass leaves every other slot behind.
|
|
520
|
+
let out = css;
|
|
521
|
+
for (let before = ''; before !== out;) {
|
|
522
|
+
before = out;
|
|
523
|
+
out = out.replace(/(^|[;{])\s*(--tw-[\w-]+)\s*:[^;{}]*;?/g, (whole, start, name) =>
|
|
524
|
+
read.has(name) ? whole : start,
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
return out;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* A declaration left with no value once its empty slots were substituted away.
|
|
532
|
+
*
|
|
533
|
+
* `.transform` is `transform: var(--tw-rotate-x,) ... var(--tw-skew-y,)`, five slots nobody set.
|
|
534
|
+
* The web reads the empty result as invalid, which is `none`, so it is no transform at all; kept,
|
|
535
|
+
* the compiler refuses `transform: ` with a warning. A custom property may be empty, and stays.
|
|
536
|
+
*/
|
|
537
|
+
function dropEmptyDeclarations(css) {
|
|
538
|
+
return css.replace(/(^|[;{])\s*[a-z][\w-]*\s*:\s*(!\s*important\s*)?(?=;|})/gi, '$1');
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* The stops a Tailwind gradient is built from, in the order they are painted.
|
|
543
|
+
*
|
|
544
|
+
* Each is set by its own utility class - `from-blue-500`, `via-purple-500`, `to-pink-500` - and
|
|
545
|
+
* the position by another (`from-20%`), so none of them can be resolved here. The fallback is the
|
|
546
|
+
* `@property` default, which is what a sheet that never sets one should paint.
|
|
547
|
+
*/
|
|
548
|
+
const GRADIENT_STOPS = ['from', 'via', 'to'];
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* A gradient Tailwind composed out of custom properties, rewritten as one with holes in it.
|
|
552
|
+
*
|
|
553
|
+
* Tailwind joins the three colour classes to the direction class through `--tw-gradient-stops`,
|
|
554
|
+
* whose value is a *string* of further `var()` references that the browser assembles at paint
|
|
555
|
+
* time. That is a CSS parser's job, and there is no parser on device - so the indirection is
|
|
556
|
+
* undone here, back into a gradient whose stops are plain references the engine's own cascade
|
|
557
|
+
* fills in per node. The middle stop disappears on its own wherever no `via-*` class defined it.
|
|
558
|
+
*
|
|
559
|
+
* The direction is read from the same rule, which is where Tailwind puts it, so a sheet with
|
|
560
|
+
* twenty `bg-linear-*` classes keeps twenty different directions.
|
|
561
|
+
*/
|
|
562
|
+
function expandGradients(css, values) {
|
|
563
|
+
return css.replace(/([^{}]*)\{([^{}]*)\}/g, (rule, selector, body) => {
|
|
564
|
+
if (!body.includes('var(--tw-gradient-stops)')) return rule;
|
|
565
|
+
|
|
566
|
+
const position = /--tw-gradient-position\s*:\s*([^;}]+)/.exec(body)?.[1] ?? '';
|
|
567
|
+
// `in oklab` asks for an interpolation space, which native has no say in.
|
|
568
|
+
const prelude = withoutImportant(position.replace(/\bin\s+[\w-]+/g, ''));
|
|
569
|
+
const stops = GRADIENT_STOPS.map((stop) => {
|
|
570
|
+
const fallback = values.get(`--tw-gradient-${stop}-position`);
|
|
571
|
+
const at = fallback
|
|
572
|
+
? `var(--tw-gradient-${stop}-position, ${fallback})`
|
|
573
|
+
: `var(--tw-gradient-${stop}-position)`;
|
|
574
|
+
return `var(--tw-gradient-${stop}) ${at}`;
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
const expanded = body
|
|
578
|
+
.replace(/--tw-gradient-position\s*:[^;}]*;?/g, '')
|
|
579
|
+
.replace(
|
|
580
|
+
/(linear|radial)-gradient\(\s*var\(--tw-gradient-stops\)\s*\)/g,
|
|
581
|
+
(_, kind) => `${kind}-gradient(${prelude ? `${prelude}, ` : ''}${stops.join(', ')})`,
|
|
582
|
+
);
|
|
583
|
+
return `${selector}{${expanded}}`;
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Tailwind 3's gradients, rewritten in the shape Tailwind 4 writes them, for `expandGradients`.
|
|
589
|
+
*
|
|
590
|
+
* Tailwind 3 puts the direction inline, `linear-gradient(to right, var(--tw-gradient-stops))`, and
|
|
591
|
+
* builds the stop list inside `from-*` and `via-*` rather than naming each stop: `via-white` is a
|
|
592
|
+
* whole `--tw-gradient-stops` with `#fff` written into its middle. Each colour class is turned back
|
|
593
|
+
* into the one stop it names, and each position reset, written as an empty value, into the default
|
|
594
|
+
* Tailwind 4 gives it with `@property`.
|
|
595
|
+
*/
|
|
596
|
+
function normalizeV3Gradients(css) {
|
|
597
|
+
return css
|
|
598
|
+
.replace(
|
|
599
|
+
/background-image\s*:\s*(linear|radial)-gradient\(\s*([^,()]+),\s*var\(--tw-gradient-stops\)\s*\)/g,
|
|
600
|
+
'--tw-gradient-position: $2; background-image: $1-gradient(var(--tw-gradient-stops))',
|
|
601
|
+
)
|
|
602
|
+
.replace(
|
|
603
|
+
/--tw-gradient-stops\s*:\s*var\(--tw-gradient-from\),\s*(.+?)\s+var\(--tw-gradient-via-position\),\s*var\(--tw-gradient-to\)/g,
|
|
604
|
+
'--tw-gradient-via: $1',
|
|
605
|
+
)
|
|
606
|
+
.replace(/\s*var\(--tw-gradient-(from|via|to)-position\)/g, '')
|
|
607
|
+
.replace(/--tw-gradient-(from|via|to)-position\s*:\s*;/g, (_, stop) => {
|
|
608
|
+
return `--tw-gradient-${stop}-position: ${{ from: '0%', via: '50%', to: '100%' }[stop]};`;
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** Tailwind 3's colour with a token alpha: `rgb(59 130 246 / var(--tw-bg-opacity, 1))`, or an `hsl()` one. */
|
|
613
|
+
const OPACITY_COLOUR =
|
|
614
|
+
/([\w-]+)\s*:\s*(rgb|hsl)a?\(\s*([\d.]+)(?:deg)?[\s,]+([\d.]+)%?[\s,]+([\d.]+)%?\s*\/\s*var\(\s*(--tw-[\w-]+-opacity)\s*,\s*1\s*\)\s*\)/g;
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* An `hsl()` colour's channels in sRGB, as a browser gives them when it prints the colour: whole
|
|
618
|
+
* numbers, since the channels token that carries them is read as an `rgb()`.
|
|
619
|
+
*/
|
|
620
|
+
function hslChannels(h, s, l) {
|
|
621
|
+
const [hue, sat, light] = [(((h % 360) + 360) % 360) / 360, s / 100, l / 100];
|
|
622
|
+
const q = light < 0.5 ? light * (1 + sat) : light + sat - light * sat;
|
|
623
|
+
const p = 2 * light - q;
|
|
624
|
+
const channel = (t) => {
|
|
625
|
+
const u = t < 0 ? t + 1 : t > 1 ? t - 1 : t;
|
|
626
|
+
if (u < 1 / 6) return p + (q - p) * 6 * u;
|
|
627
|
+
if (u < 1 / 2) return q;
|
|
628
|
+
if (u < 2 / 3) return p + (q - p) * (2 / 3 - u) * 6;
|
|
629
|
+
return p;
|
|
630
|
+
};
|
|
631
|
+
return [hue + 1 / 3, hue, hue - 1 / 3].map((t) => Math.round(channel(t) * 255));
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Tailwind 3's `bg-opacity-50` and friends, as the channels-and-alpha colour the engine resolves.
|
|
636
|
+
*
|
|
637
|
+
* `.bg-blue-500` is `rgb(59 130 246 / var(--tw-bg-opacity, 1))`, and `.bg-opacity-50` sets only
|
|
638
|
+
* the alpha. The engine has no colour made of written channels and a token alpha, but it does have
|
|
639
|
+
* Bootstrap's `rgba(var(--channels), var(--alpha))`, so the channels move into a token declared
|
|
640
|
+
* beside the colour. Only for an alpha some other rule sets: where none does, the colour is solid
|
|
641
|
+
* and is substituted like any other. A ring's colour is left alone, being a token itself.
|
|
642
|
+
*
|
|
643
|
+
* @returns the rewritten CSS, and the alpha and channel tokens to leave for the engine
|
|
644
|
+
*/
|
|
645
|
+
function opacityChannels(css) {
|
|
646
|
+
const setters = new Set();
|
|
647
|
+
for (const [, selector, body] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
|
|
648
|
+
if (RESET.test(selector.trim())) continue;
|
|
649
|
+
if (/(rgb|hsl)a?\([^)]*var\(--tw-[\w-]+-opacity/.test(body)) continue;
|
|
650
|
+
for (const [, name] of body.matchAll(/(--tw-[\w-]+-opacity)\s*:/g)) setters.add(name);
|
|
651
|
+
}
|
|
652
|
+
const runtime = new Set();
|
|
653
|
+
const out = css.replace(OPACITY_COLOUR, (whole, property, space, a, b2, c, alpha) => {
|
|
654
|
+
if (!setters.has(alpha)) return whole;
|
|
655
|
+
const [r, g, b] = space === 'hsl' ? hslChannels(+a, +b2, +c) : [a, b2, c];
|
|
656
|
+
// One per property: `border-color` and `border-top-color` are both faded by
|
|
657
|
+
// `--tw-border-opacity`, and sharing channels would paint one's colour on the other's sides.
|
|
658
|
+
const channels = `--tw-rgb-${property.replace(/^--tw-/, '')}`;
|
|
659
|
+
runtime.add(alpha).add(channels);
|
|
660
|
+
return `${channels}: ${r}, ${g}, ${b}; ${property}: rgba(var(${channels}), var(${alpha}, 1))`;
|
|
661
|
+
});
|
|
662
|
+
return { css: out, runtime };
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Tailwind 3's empty slots, read the way Tailwind 4 writes them: `var(--tw-blur,)`.
|
|
667
|
+
*
|
|
668
|
+
* Tailwind 3 resets an unused slot to nothing, `--tw-blur: ;`, and reads it with no fallback, so a
|
|
669
|
+
* filter or a ring is a row of `var()`s most of which hold nothing. The compiler drops a token with
|
|
670
|
+
* no value, which left each of those `var()`s unresolved and the whole declaration with it. An
|
|
671
|
+
* empty fallback says the same thing and is what the engine settles.
|
|
672
|
+
*/
|
|
673
|
+
function emptySlotFallbacks(css) {
|
|
674
|
+
const empty = new Set();
|
|
675
|
+
for (const [, selector, body] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
|
|
676
|
+
if (!RESET.test(selector.trim())) continue;
|
|
677
|
+
for (const [, name, value] of body.matchAll(/(--tw-[\w-]+)\s*:([^;{}]*)/g)) {
|
|
678
|
+
if (!value.trim()) empty.add(name);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if (!empty.size) return css;
|
|
682
|
+
return css.replace(/var\(\s*(--tw-[\w-]+)\s*\)/g, (whole, name) =>
|
|
683
|
+
empty.has(name) ? `var(${name},)` : whole,
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** A class selector, escapes and all: `.dark`, `.platform-android`, `.md\:p-4`. */
|
|
688
|
+
const CLASS = String.raw`\.(?:\\.|[\w-])+`;
|
|
689
|
+
// A trailing pseudo-class or attribute selector - `:active`, `[data-disabled]`, `:focus` - is what
|
|
690
|
+
// a same-node variant (`press:`, `focus:`, `disabled:`) stacked on top adds after the `:is()`.
|
|
691
|
+
const STACKED = new RegExp(
|
|
692
|
+
String.raw`^\s*(${CLASS})\s+:is\((${CLASS})\s+((?:\\.|[^()\\])+)\)([^\s]*)\s*$`,
|
|
693
|
+
);
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* Tailwind 3's spelling of the same thing, `.dark .platform-ios .x`, which has no `:is()`. Only
|
|
697
|
+
* the preset's own ancestor classes, so a selector an app wrote is never rewritten.
|
|
698
|
+
*/
|
|
699
|
+
const ANCESTOR = String.raw`\.(?:dark|platform-(?:ios|android|web))`;
|
|
700
|
+
const STACKED_PLAIN_ONE = new RegExp(
|
|
701
|
+
String.raw`^\s*(${ANCESTOR})\s+(${ANCESTOR})\s+([^\s].*?)\s*$`,
|
|
702
|
+
);
|
|
703
|
+
const STACKED_PLAIN = new RegExp(String.raw`(^|,)\s*${ANCESTOR}\s+${ANCESTOR}\s`);
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* A stacked variant, rewritten as the ancestor tests it means.
|
|
707
|
+
*
|
|
708
|
+
* `android:dark:bg-black` comes out of Tailwind as `.dark :is(.platform-android .x)`: an element
|
|
709
|
+
* with some `.platform-android` ancestor and some `.dark` ancestor, in either order or both on one
|
|
710
|
+
* node. The engine refuses a combinator inside `:is()`, so the whole rule used to be dropped and
|
|
711
|
+
* every stacked platform and dark variant silently did nothing. Written out, it is three shapes
|
|
712
|
+
* the engine does match - which matters most for the last, since `mount` and `watchConditions`
|
|
713
|
+
* put both classes on the root.
|
|
714
|
+
*
|
|
715
|
+
* A same-node variant stacked on top of two ancestor ones - `ios:dark:press:bg-red-500` - adds a
|
|
716
|
+
* pseudo-class *after* the closing paren (`.dark :is(.platform-ios .x):active`), which the
|
|
717
|
+
* original pattern did not account for: it only matched a selector ending at the paren, so this
|
|
718
|
+
* shape passed through unexpanded and the compiler refused it the same way. The suffix belongs on
|
|
719
|
+
* the class in each of the three shapes, since it is the thing that has to match on the node
|
|
720
|
+
* itself alongside the ancestor tests.
|
|
721
|
+
*/
|
|
722
|
+
function expandStackedVariants(css) {
|
|
723
|
+
return css.replace(/([^{}]+)\{([^{}]*)\}/g, (whole, selectors, body) => {
|
|
724
|
+
if (!selectors.includes(':is(') && !STACKED_PLAIN.test(selectors)) return whole;
|
|
725
|
+
let changed = false;
|
|
726
|
+
const expanded = selectorList(selectors).flatMap((selector) => {
|
|
727
|
+
const match = STACKED.exec(selector) ?? STACKED_PLAIN_ONE.exec(selector);
|
|
728
|
+
if (!match) return [selector.trim()];
|
|
729
|
+
changed = true;
|
|
730
|
+
const [, outer, inner, rest, suffix = ''] = match;
|
|
731
|
+
const self = `${rest}${suffix}`;
|
|
732
|
+
return [`${outer} ${inner} ${self}`, `${inner} ${outer} ${self}`, `${outer}${inner} ${self}`];
|
|
733
|
+
});
|
|
734
|
+
return changed ? `${expanded.join(', ')}{${body}}` : whole;
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Tailwind's output, as CSS the engine compiles.
|
|
740
|
+
*
|
|
741
|
+
* @param {string} css the CSS the Tailwind CLI produced
|
|
742
|
+
* @returns {string} CSS with the browser-only parts answered or removed
|
|
743
|
+
*/
|
|
744
|
+
/** A compound selector: no whitespace or combinator outside parentheses, escapes allowed. */
|
|
745
|
+
const COMPOUND = String.raw`(?:\\.|\((?:\\.|[^()\\])*\)|[^\s>+~,()\\])+`;
|
|
746
|
+
const WHERE_CHILD = new RegExp(String.raw`:where\((${COMPOUND})\s*>\s*(${COMPOUND})\)`, 'g');
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* `:where(.space-x-2 > :not(:last-child))` as `:where(.space-x-2) > :where(:not(:last-child))`:
|
|
750
|
+
* the same children, at the same zero specificity, in a form the compiler reads. Tailwind 4 writes
|
|
751
|
+
* every `space-*` and `divide-*` utility this way, and the compiler takes only a compound inside
|
|
752
|
+
* `:where()`.
|
|
753
|
+
*/
|
|
754
|
+
function childrenOfWhere(css) {
|
|
755
|
+
return css.replace(WHERE_CHILD, ':where($1) > :where($2)');
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* The `*` reset, less the reverse slots. On the web the reset is in a layer under every utility;
|
|
760
|
+
* unwrapped here it comes after them, and ties with `space-x-reverse`, whose `:where()` has no
|
|
761
|
+
* specificity to beat it by, so the reverse class set its slot to 1 and the reset put it back to
|
|
762
|
+
* 0. Every rule that reads a reverse slot sets it to 0 itself, so the reset's copy says nothing.
|
|
763
|
+
*/
|
|
764
|
+
function resetWithoutReverseSlots(css) {
|
|
765
|
+
return css.replace(/([^{}]+)\{([^{}]*)\}/g, (rule, selector, body) =>
|
|
766
|
+
selectorList(selector).some((one) => one.trim() === '*')
|
|
767
|
+
? `${selector}{${body.replace(/--tw-(space|divide)-[xy]-reverse\s*:[^;}]*;?/g, '')}}`
|
|
768
|
+
: rule,
|
|
769
|
+
);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function flattenTailwind(css) {
|
|
773
|
+
// Before any pass of lightningcss here, which reads `m-[3]`'s bare 3 as 3px and hides it from
|
|
774
|
+
// the compiler: see `markUnitless`.
|
|
775
|
+
let out = childrenOfWhere(markUnitlessReverse(markUnitless(css)).replace(LAYER_STATEMENT, ''));
|
|
776
|
+
out = rewriteAtRule(out, '@layer', true);
|
|
777
|
+
out = rewriteAtRule(out, '@supports', true);
|
|
778
|
+
out = resetWithoutReverseSlots(out);
|
|
779
|
+
out = normalizeV3Gradients(out);
|
|
780
|
+
// Tailwind 3's `space-*` and `divide-*` children: every child after a shown one. Native has no
|
|
781
|
+
// `hidden`, so that is every child but the first, which the engine answers at once; the sibling
|
|
782
|
+
// test is matched on every element and walks back through all its earlier siblings, so a long
|
|
783
|
+
// list paid for it squared on every commit.
|
|
784
|
+
out = out.replace(/>\s*:not\(\[hidden\]\)\s*~\s*:not\(\[hidden\]\)/g, '> :not(:first-child)');
|
|
785
|
+
out = emptySlotFallbacks(out);
|
|
786
|
+
// Tailwind 3's `transform-gpu`: a third dimension that is only a hint to a browser's compositor.
|
|
787
|
+
out = out.replace(
|
|
788
|
+
/translate3d\(([^,()]+(?:\([^()]*\))?),\s*([^,()]+(?:\([^()]*\))?),\s*0\)/g,
|
|
789
|
+
'translate($1, $2)',
|
|
790
|
+
);
|
|
791
|
+
// A browser's vendor-prefixed copy of a property whose standard form is beside it, as Tailwind 3
|
|
792
|
+
// writes `-moz-column-gap` next to `column-gap`. `-webkit-` stays: `-webkit-line-clamp` is how
|
|
793
|
+
// truncation arrives.
|
|
794
|
+
out = out.replace(/(^|[;{])\s*-(?:moz|ms|o)-[\w-]+\s*:[^;{}]*;?/gm, '$1');
|
|
795
|
+
const opacity = opacityChannels(out);
|
|
796
|
+
out = opacity.css;
|
|
797
|
+
const values = collectVariables(out);
|
|
798
|
+
const runtime = new Set([...crossRuleVariables(out), ...opacity.runtime]);
|
|
799
|
+
out = rewriteAtRule(out, '@property', false);
|
|
800
|
+
out = expandGradients(out, values);
|
|
801
|
+
// `via-none` empties the chain, which is how the web takes a `via-*` stop back out. With the
|
|
802
|
+
// chain gone, it says the same by leaving the middle stop with no colour, which is not painted.
|
|
803
|
+
// Only where it is the rule's one declaration, which is `via-none`: the `*` reset writes the same
|
|
804
|
+
// thing, and there it would give every element a token for nothing.
|
|
805
|
+
out = out.replace(
|
|
806
|
+
/\{\s*--tw-gradient-via-stops\s*:\s*initial\s*(!\s*important\s*)?;?\s*\}/g,
|
|
807
|
+
(_, important) => `{ --tw-gradient-via: none${important ? ' !important' : ''}; }`,
|
|
808
|
+
);
|
|
809
|
+
// The chain the gradient used to be assembled through, now that nothing reads it. Left in, it
|
|
810
|
+
// is a token per gradient class in every bundle, holding the word `initial`.
|
|
811
|
+
out = out.replace(/--tw-gradient(-via)?-stops\s*:[^;}]*;?/g, '');
|
|
812
|
+
// The middle stop's reset. Tailwind's fallback for browsers without `@property` gives every
|
|
813
|
+
// element `--tw-gradient-via: #0000`, where the web only puts a via stop in the gradient at all
|
|
814
|
+
// when a `via-*` class asks. Kept, every two-stop gradient paints a transparent stop halfway
|
|
815
|
+
// along, and a dark card shows whatever is behind it through a streak across the middle. With
|
|
816
|
+
// no colour the engine leaves the stop out, which is what the web draws.
|
|
817
|
+
out = out.replace(/--tw-gradient-via\s*:\s*(#0000|transparent|initial)\s*;?/g, '');
|
|
818
|
+
// Rule-local first: a property a rule declares and reads is that rule's business, and the
|
|
819
|
+
// file-wide map holds the `*` reset that would otherwise win.
|
|
820
|
+
out = substituteInRules(out, values, runtime);
|
|
821
|
+
out = substituteVariables(out, values, runtime);
|
|
822
|
+
out = dropUnreadSlots(out);
|
|
823
|
+
out = dropPseudoElementRules(out);
|
|
824
|
+
out = expandStackedVariants(out);
|
|
825
|
+
out = dropRedundantBorderStyles(out);
|
|
826
|
+
out = dropEmptyDeclarations(out);
|
|
827
|
+
return resolveUnitlessLineHeight(fold(out));
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
module.exports = { flattenTailwind };
|