@teacss/classes 0.10.8 → 0.10.9

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/dist/merge.js DELETED
@@ -1,475 +0,0 @@
1
- /** Fixed declaration policy and Official numbered typography grouping. */
2
- import { StringCache, TupleCache } from "./cache.js";
3
- import { equalRows, finalizerFlags, importantRows, prefixes, rows, typographyNames } from "./generated/merge-policy.js";
4
- import { appendOwnArrayValue, normalizeInput, toClassString } from "./input.js";
5
- import { expandClassGroups } from "./syntax/group.js";
6
- import { splitClassTokens } from "./syntax/literal.js";
7
- import { parseClassToken } from "./syntax/token.js";
8
- const ids = new Map(prefixes.map((prefix, id) => [prefix, id]));
9
- const dimensionFamilies = [
10
- ["dimensions", "w", "h"],
11
- ["min-dimensions", "min-w", "min-h"],
12
- ["max-dimensions", "max-w", "max-h"],
13
- ["size", "inline-size", "block-size"],
14
- ["min-size", "min-inline-size", "min-block-size"],
15
- ["max-size", "max-inline-size", "max-block-size"],
16
- ];
17
- const dimensionEffects = new Map();
18
- const dimensionCombinations = new Map();
19
- for (let group = 0; group < dimensionFamilies.length; group++) {
20
- const [combined, first, second] = dimensionFamilies[group];
21
- const combinedId = ids.get(combined);
22
- const firstId = ids.get(first);
23
- const secondId = ids.get(second);
24
- if (combinedId === undefined || firstId === undefined || secondId === undefined)
25
- continue;
26
- dimensionEffects.set(combinedId, [group * 2, group * 2 + 1]);
27
- dimensionEffects.set(firstId, [group * 2]);
28
- dimensionEffects.set(secondId, [group * 2 + 1]);
29
- dimensionCombinations.set(combinedId, group);
30
- }
31
- const unsafeFragment = /[{}[\]()\\'"\x60]|\/\*/;
32
- const namedLanguage = /^!?lang-[a-zA-Z]+(?:-[a-zA-Z0-9]+)*$/;
33
- const stateCount = prefixes.length * 2;
34
- const MAX_SCRATCH = 4096; // Power of two, matching shared scratch growth.
35
- function tokenWeight(key, token) {
36
- return 2 * (key.length + token.raw.length + token.condition.length + token.identity.length);
37
- }
38
- /** Selector roles in the engine's assembly order: `<prefix><subject><suffix><combinator><pseudo-element>`, then parent at-rules. */
39
- export const PREFIX = 1;
40
- export const SUFFIX = 2;
41
- export const COMBINATOR = 4;
42
- export const PSEUDO_ELEMENT = 8;
43
- export const PARENT = 16;
44
- const roleOrder = [PREFIX, SUFFIX, COMBINATOR, PSEUDO_ELEMENT, PARENT];
45
- const ALL_ROLES = PREFIX | SUFFIX | COMBINATOR | PSEUDO_ELEMENT | PARENT;
46
- const subjectStates = new Set([
47
- "hover",
48
- "focus",
49
- "focus-visible",
50
- "focus-within",
51
- "active",
52
- "visited",
53
- "target",
54
- "checked",
55
- "disabled",
56
- "enabled",
57
- "required",
58
- "optional",
59
- "valid",
60
- "invalid",
61
- "user-valid",
62
- "user-invalid",
63
- "in-range",
64
- "out-of-range",
65
- "read-only",
66
- "read-write",
67
- "default",
68
- "indeterminate",
69
- "placeholder-shown",
70
- "autofill",
71
- "empty",
72
- "root",
73
- "first",
74
- "last",
75
- "only",
76
- "odd",
77
- "even",
78
- "first-of-type",
79
- "last-of-type",
80
- "only-of-type",
81
- "open",
82
- "inert",
83
- ]);
84
- const targetGuards = new Set(["dark", "light", "surface-hairline", "surface-layered", "rtl", "ltr"]);
85
- /**
86
- * The roles a condition's CSS occupies, mirroring the Standard resolvers. A role
87
- * the condition may not use is harmless: it only keeps more condition keys apart.
88
- */
89
- export function conditionRoles(condition) {
90
- const value = condition.startsWith("!") ? condition.slice(1) : condition;
91
- const pseudoElement = value.includes(":") ? PSEUDO_ELEMENT : 0;
92
- switch (value[0]) {
93
- case ":":
94
- return value[1] === ":" ? PSEUDO_ELEMENT : ALL_ROLES;
95
- case ".":
96
- case "#":
97
- return SUFFIX | pseudoElement;
98
- case ">":
99
- case "_":
100
- case "+":
101
- case "~":
102
- return COMBINATOR | pseudoElement;
103
- case "[":
104
- return PREFIX | SUFFIX | pseudoElement;
105
- }
106
- if (subjectStates.has(value) || /^(?:nth(?:-last)?(?:-of-type)?-\[|data-|aria-|lang-)/.test(value))
107
- return SUFFIX;
108
- if (/^(?:group|peer|in)-/.test(value))
109
- return PREFIX;
110
- if (targetGuards.has(value))
111
- return COMBINATOR;
112
- // Media features, at-rules, containers and breakpoints, including configured names.
113
- return PARENT;
114
- }
115
- function conditionKey(conditions) {
116
- if (!conditions.length)
117
- return "";
118
- if (conditions.length === 1)
119
- return "\0" + conditionIdentity(conditions[0]);
120
- // The engine assembles each role in authored order, so only the order across roles is free,
121
- // and the order within a run of target guards: they all land on the same compound as
122
- // `:is(X, X *)`, which commute, while a combinator between them moves the later ones.
123
- const identities = conditions.map(conditionIdentity);
124
- const roles = conditions.map(conditionRoles);
125
- const guards = [];
126
- let key = "\x01";
127
- for (const role of roleOrder) {
128
- for (let index = 0; index < identities.length; index++) {
129
- if (!(roles[index] & role))
130
- continue;
131
- const part = identities[index].length + ":" + identities[index];
132
- const value = conditions[index];
133
- if (targetGuards.has(value.startsWith("!") ? value.slice(1) : value)) {
134
- guards.push(part);
135
- continue;
136
- }
137
- key += guards.sort().join("") + part;
138
- guards.length = 0;
139
- }
140
- key += guards.sort().join("") + "|";
141
- guards.length = 0;
142
- }
143
- return key;
144
- }
145
- function conditionIdentity(condition) {
146
- // Only named language tags are case-insensitive; preserve selector text and order.
147
- return namedLanguage.test(condition) ? condition.toLowerCase() : condition;
148
- }
149
- function classify(raw) {
150
- const { keyword, property, body, important, conditions } = parseClassToken(raw);
151
- const prefix = property ?? body;
152
- const id = keyword ? -1 : (ids.get(prefix) ?? -1);
153
- return {
154
- raw,
155
- id,
156
- important: +important,
157
- condition: conditionKey(conditions),
158
- // This fixed keyword group replaces all three typography metrics. Other
159
- // shortcuts keep their own identity; their declarations are never expanded.
160
- identity: keyword ? (typographyNames.has(prefix) ? "t" : "k" + prefix) : id < 0 ? "d" + prefix : "",
161
- family: id >= 0 ? finalizerFlags[id] : 0,
162
- };
163
- }
164
- function createScratch(size = 0) {
165
- return { dropped: new Uint8Array(size), blocked: new Uint32Array(stateCount), expanded: new Uint32Array(stateCount), epoch: 0 };
166
- }
167
- export function createRuntime(options = {}) {
168
- const tuples = options.tupleCache === false ? undefined : new TupleCache();
169
- const results = options.resultCache === false ? undefined : new StringCache(1500, 1048576, (key, value) => 2 * (key.length + value.length));
170
- const descriptors = options.descriptorCache === false ? undefined : new StringCache(4096, 524288, tokenWeight);
171
- const scratch = createScratch();
172
- const epochLimit = options.epochLimit ?? 0xffffffff;
173
- let active = false;
174
- function read(raw, persistent) {
175
- const cached = persistent ? descriptors?.get(raw) : undefined;
176
- if (cached !== undefined)
177
- return cached;
178
- // A short slice must not pin its entire class-list parent in a persistent cache.
179
- // Splitting UTF-16 units and joining detaches storage without changing lone surrogates.
180
- const owned = persistent && descriptors ? raw.split("").join("") : raw;
181
- const token = classify(owned);
182
- if (persistent)
183
- descriptors?.set(owned, token);
184
- return token;
185
- }
186
- function nextEpoch(work) {
187
- if (work.epoch >= epochLimit) {
188
- work.blocked.fill(0);
189
- work.expanded.fill(0);
190
- work.epoch = 0;
191
- }
192
- return ++work.epoch;
193
- }
194
- function merge(tokens) {
195
- const size = tokens.length;
196
- if (size === 0)
197
- return "";
198
- if (size === 1)
199
- return tokens[0].raw;
200
- const work = active || size > MAX_SCRATCH ? createScratch(size) : scratch;
201
- const previousActive = active;
202
- active = true;
203
- // Large and reentrant calls already have exact capacity; only shared
204
- // scratch grows here, with size bounded by the power-of-two MAX_SCRATCH.
205
- if (work.dropped.length < size)
206
- work.dropped = new Uint8Array(2 ** Math.ceil(Math.log2(size)));
207
- const dropped = work.dropped;
208
- dropped.fill(0, 0, size);
209
- try {
210
- let sameCondition = true;
211
- for (let index = 1; index < size; index++) {
212
- if (tokens[index].condition !== tokens[0].condition) {
213
- sameCondition = false;
214
- break;
215
- }
216
- }
217
- function bucket(indices) {
218
- // Callers already exclude empty and single-token buckets.
219
- const length = indices?.length ?? size;
220
- // A two-item bucket needs only one compiled verdict and no sequence workspace.
221
- if (length === 2) {
222
- const first = indices ? indices[0] : 0;
223
- const second = indices ? indices[1] : 1;
224
- const a = tokens[first];
225
- const b = tokens[second];
226
- if (a.id >= 0 && b.id >= 0 && !(a.family || b.family)) {
227
- if (a.important === b.important) {
228
- if (a.id === b.id || rows[equalRows[b.id]].includes(a.id))
229
- dropped[first] = 1;
230
- }
231
- else {
232
- const winner = a.important ? a : b;
233
- const loser = a.important ? b : a;
234
- if (winner.id === loser.id || rows[importantRows[winner.id]].includes(loser.id))
235
- dropped[a.important ? second : first] = 1;
236
- }
237
- return;
238
- }
239
- }
240
- const components = new Uint8Array(5);
241
- const barriers = new Int32Array(5).fill(-1);
242
- // Finalizers observe the original sequence, before any pair deletion.
243
- for (let position = length - 1; position >= 0; position--) {
244
- const index = indices ? indices[position] : position;
245
- const token = tokens[index];
246
- if (!token.family || !token.important)
247
- continue;
248
- const family = token.family >> 1;
249
- if (!(token.family & 1))
250
- components[family] = 1;
251
- else if (components[family] && barriers[family] < 0)
252
- barriers[family] = index;
253
- }
254
- let unknown;
255
- for (let position = 0; position < length; position++) {
256
- const index = indices ? indices[position] : position;
257
- const token = tokens[index];
258
- const family = token.family >> 1;
259
- if (family && (index <= barriers[family] || (token.family & 1 && !token.important && components[family]))) {
260
- dropped[index] = 2;
261
- }
262
- else if (token.id < 0) {
263
- const winners = (unknown ??= new Map());
264
- const previous = winners.get(token.identity);
265
- if (previous !== undefined) {
266
- if (tokens[previous].important && !token.important) {
267
- dropped[index] = 1;
268
- continue;
269
- }
270
- dropped[previous] = 1;
271
- }
272
- winners.set(token.identity, index);
273
- }
274
- }
275
- const { blocked, expanded } = work;
276
- // An earlier important token may delete a later ordinary token.
277
- let epoch = nextEpoch(work);
278
- for (let position = 0; position < length; position++) {
279
- const index = indices ? indices[position] : position;
280
- const token = tokens[index];
281
- if (token.id < 0 || dropped[index] === 2)
282
- continue;
283
- if (!token.important) {
284
- if (blocked[token.id] === epoch)
285
- dropped[index] = 1;
286
- }
287
- else if (expanded[token.id] !== epoch) {
288
- blocked[token.id] = epoch;
289
- const victims = rows[importantRows[token.id]];
290
- for (let edge = 0; edge < victims.length; edge++)
291
- blocked[victims[edge]] = epoch;
292
- expanded[token.id] = epoch;
293
- }
294
- }
295
- // Later equal-importance tokens and important tokens delete earlier items.
296
- epoch = nextEpoch(work);
297
- for (let position = length - 1; position >= 0; position--) {
298
- const index = indices ? indices[position] : position;
299
- const token = tokens[index];
300
- if (token.id < 0 || dropped[index] === 2)
301
- continue;
302
- const state = token.id * 2 + token.important;
303
- if (blocked[state] === epoch)
304
- dropped[index] = 1;
305
- if (expanded[state] === epoch)
306
- continue;
307
- blocked[state] = epoch;
308
- const equal = rows[equalRows[token.id]];
309
- for (let edge = 0; edge < equal.length; edge++)
310
- blocked[equal[edge] * 2 + token.important] = epoch;
311
- if (token.important) {
312
- blocked[state - 1] = epoch;
313
- const strong = rows[importantRows[token.id]];
314
- for (let edge = 0; edge < strong.length; edge++)
315
- blocked[strong[edge] * 2] = epoch;
316
- }
317
- // Pair-deleted tokens still contribute their full adjacency row.
318
- expanded[state] = epoch;
319
- }
320
- // A combined sizing token survives a single-axis override. Remove it
321
- // only when the two axes have independent winning declarations.
322
- let hasCombination = false;
323
- for (let position = 0; position < length; position++) {
324
- const index = indices ? indices[position] : position;
325
- if (dimensionCombinations.has(tokens[index].id)) {
326
- hasCombination = true;
327
- break;
328
- }
329
- }
330
- if (hasCombination) {
331
- const winners = new Int32Array(dimensionFamilies.length * 2).fill(-1);
332
- for (let position = 0; position < length; position++) {
333
- const index = indices ? indices[position] : position;
334
- const token = tokens[index];
335
- const effects = dimensionEffects.get(token.id);
336
- if (effects === undefined)
337
- continue;
338
- for (const effect of effects) {
339
- const previous = winners[effect];
340
- if (previous < 0 || token.important >= tokens[previous].important)
341
- winners[effect] = index;
342
- }
343
- }
344
- for (let position = 0; position < length; position++) {
345
- const index = indices ? indices[position] : position;
346
- const group = dimensionCombinations.get(tokens[index].id);
347
- if (group !== undefined && winners[group * 2] !== index && winners[group * 2 + 1] !== index)
348
- dropped[index] = 1;
349
- }
350
- }
351
- }
352
- if (sameCondition)
353
- bucket();
354
- else {
355
- const groups = new Map();
356
- for (let index = 0; index < size; index++) {
357
- const key = tokens[index].condition;
358
- const group = groups.get(key);
359
- if (group === undefined)
360
- groups.set(key, index);
361
- else if (typeof group === "number")
362
- groups.set(key, [group, index]);
363
- else
364
- appendOwnArrayValue(group, index);
365
- }
366
- for (const group of groups.values()) {
367
- if (typeof group !== "number")
368
- bucket(group);
369
- }
370
- }
371
- let result = "";
372
- for (let index = 0; index < size; index++) {
373
- if (dropped[index] === 0)
374
- result += (result ? " " : "") + tokens[index].raw;
375
- }
376
- return result;
377
- }
378
- finally {
379
- active = previousActive;
380
- }
381
- }
382
- function parse(input) {
383
- const raws = splitClassTokens(expandClassGroups(input).trim());
384
- const tokens = [];
385
- // Bypass persistent substring caching when the parent input can exceed the budget.
386
- const persistent = input.length * 2 <= 524288;
387
- for (let index = 0; index < raws.length; index++)
388
- appendOwnArrayValue(tokens, read(raws[index], persistent));
389
- return tokens;
390
- }
391
- function run(input) {
392
- const cached = results?.get(input);
393
- if (cached !== undefined)
394
- return cached;
395
- const result = merge(parse(input));
396
- results?.set(input, result);
397
- return result;
398
- }
399
- const cn = (...args) => {
400
- if (!args.length)
401
- return "";
402
- let strings = args.length <= 4;
403
- if (strings) {
404
- for (let index = 0; index < args.length; index++) {
405
- if (typeof args[index] !== "string") {
406
- strings = false;
407
- break;
408
- }
409
- }
410
- }
411
- if (!strings)
412
- return run(normalizeInput(args));
413
- const values = args;
414
- const cached = tuples?.get(values);
415
- if (cached !== undefined)
416
- return cached;
417
- let input = "";
418
- for (let index = 0; index < values.length; index++) {
419
- if (values[index])
420
- input += (input ? " " : "") + values[index];
421
- }
422
- const result = run(input);
423
- tuples?.set(values, result);
424
- return result;
425
- };
426
- function prepareFragment(raw) {
427
- return { raw, tokens: unsafeFragment.test(raw) ? undefined : parse(raw) };
428
- }
429
- function mergePrepared(fragments, caller) {
430
- if (fragments.length === 0 && Array.isArray(caller))
431
- return cn(caller);
432
- const tail = caller === undefined ? "" : toClassString([caller]);
433
- let input = "";
434
- let safe = !unsafeFragment.test(tail);
435
- for (let index = 0; index < fragments.length; index++) {
436
- const fragment = fragments[index];
437
- if (fragment.raw)
438
- input += (input ? " " : "") + fragment.raw;
439
- safe &&= fragment.tokens !== undefined;
440
- }
441
- if (tail)
442
- input += (input ? " " : "") + tail;
443
- if (!safe)
444
- return run(input);
445
- const cached = results?.get(input);
446
- if (cached !== undefined)
447
- return cached;
448
- const tokens = [];
449
- for (let index = 0; index < fragments.length; index++) {
450
- const prepared = fragments[index].tokens;
451
- for (let item = 0; item < prepared.length; item++)
452
- appendOwnArrayValue(tokens, prepared[item]);
453
- }
454
- if (tail) {
455
- const parsed = parse(tail);
456
- for (let index = 0; index < parsed.length; index++)
457
- appendOwnArrayValue(tokens, parsed[index]);
458
- }
459
- const result = merge(tokens);
460
- results?.set(input, result);
461
- return result;
462
- }
463
- return {
464
- cn,
465
- prepareFragment,
466
- mergePrepared,
467
- inspect: () => ({
468
- tuples: { size: tuples?.size ?? 0, bytes: tuples?.bytes ?? 0, nodes: tuples?.nodes ?? 0 },
469
- results: { size: results?.values.size ?? 0, bytes: results?.bytes ?? 0 },
470
- descriptors: { size: descriptors?.values.size ?? 0, bytes: descriptors?.bytes ?? 0 },
471
- scratch: { bytes: scratch.dropped.byteLength + scratch.blocked.byteLength + scratch.expanded.byteLength },
472
- }),
473
- };
474
- }
475
- export const { cn, prepareFragment, mergePrepared } = /* @__PURE__ */ createRuntime();