-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimplify.ts
More file actions
1476 lines (1280 loc) · 43.7 KB
/
simplify.ts
File metadata and controls
1476 lines (1280 loc) · 43.7 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Condition Simplification Engine
*
* Simplifies condition trees by applying boolean algebra rules,
* detecting contradictions, merging ranges, and deduplicating terms.
*
* This is critical for:
* 1. Detecting invalid combinations (A & !A → FALSE)
* 2. Reducing CSS output size
* 3. Producing cleaner selectors
*/
import { Lru } from '../parser/lru';
import type {
ConditionNode,
ContainerCondition,
MediaCondition,
ModifierCondition,
NumericBound,
OwnCondition,
RootCondition,
} from './conditions';
import {
and,
createOwnCondition,
createParentCondition,
createRootCondition,
falseCondition,
getConditionUniqueId,
not,
or,
trueCondition,
} from './conditions';
// ============================================================================
// Caching
// ============================================================================
const simplifyCache = new Lru<string, ConditionNode>(5000);
// ============================================================================
// Main Simplify Function
// ============================================================================
/**
* Simplify a condition tree aggressively.
*
* This applies all possible simplification rules:
* - Boolean algebra (identity, annihilator, idempotent, absorption)
* - Contradiction detection (A & !A → FALSE)
* - Tautology detection (A | !A → TRUE)
* - Range intersection for numeric queries
* - Attribute value conflict detection
* - Deduplication and sorting
*/
export function simplifyCondition(node: ConditionNode): ConditionNode {
// Check cache
const key = getConditionUniqueId(node);
const cached = simplifyCache.get(key);
if (cached) {
return cached;
}
const result = simplifyInner(node);
// Cache result
simplifyCache.set(key, result);
return result;
}
/**
* Clear the simplify cache (for testing)
*/
export function clearSimplifyCache(): void {
simplifyCache.clear();
}
// ============================================================================
// Inner Simplification
// ============================================================================
function simplifyInner(node: ConditionNode): ConditionNode {
// Base cases
if (node.kind === 'true' || node.kind === 'false') {
return node;
}
// State conditions: most are leaves, but @root / @own / @parent wrap a
// nested condition that benefits from the same simplification (e.g.
// `@root(schema=dark & schema=light)` → inner is FALSE → wrapper is FALSE).
// Only descend on non-negated wrappers; negated wrappers would need
// additional reasoning (`!@root(FALSE)` = TRUE) that isn't worth the
// surface area for the current bug.
if (node.kind === 'state') {
if (
(node.type === 'root' || node.type === 'own' || node.type === 'parent') &&
!node.negated
) {
const simplifiedInner = simplifyInner(node.innerCondition);
if (simplifiedInner.kind === 'false') return falseCondition();
if (simplifiedInner === node.innerCondition) return node;
if (node.type === 'root') {
return createRootCondition(simplifiedInner, false, node.raw);
}
if (node.type === 'own') {
return createOwnCondition(simplifiedInner, false, node.raw);
}
return createParentCondition(
simplifiedInner,
node.direct,
false,
node.raw,
);
}
return node;
}
// Compound conditions - recursively simplify
if (node.kind === 'compound') {
// First, recursively simplify all children
const simplifiedChildren = node.children.map((c) => simplifyInner(c));
// Then apply compound-specific simplifications
if (node.operator === 'AND') {
return simplifyAnd(simplifiedChildren);
} else {
return simplifyOr(simplifiedChildren);
}
}
return node;
}
// ============================================================================
// AND Simplification
// ============================================================================
function simplifyAnd(children: ConditionNode[]): ConditionNode {
let terms: ConditionNode[] = [];
// ─── Pass 1: flatten + identity/annihilator ────────────────────────────
// Flatten nested ANDs, drop TRUE children, short-circuit on any FALSE.
for (const child of children) {
if (child.kind === 'false') {
// AND with FALSE → FALSE
return falseCondition();
}
if (child.kind === 'true') {
// AND with TRUE → skip (identity)
continue;
}
if (child.kind === 'compound' && child.operator === 'AND') {
// Flatten nested AND
terms.push(...child.children);
} else {
terms.push(child);
}
}
// Empty → TRUE
if (terms.length === 0) {
return trueCondition();
}
// Single term → return it
if (terms.length === 1) {
return terms[0];
}
// ─── Pass 2: filter contradictions ─────────────────────────────────────
// Any of these indicates the conjunction can never be satisfied.
// Check for contradictions
if (hasContradiction(terms)) {
return falseCondition();
}
// Check for range contradictions in media/container queries
if (hasRangeContradiction(terms)) {
return falseCondition();
}
// Check for attribute value conflicts
if (hasAttributeConflict(terms)) {
return falseCondition();
}
// Check for container style query conflicts
if (hasContainerStyleConflict(terms)) {
return falseCondition();
}
// ─── Pass 3: redundancy elimination + canonicalization ─────────────────
// Remove redundant negations implied by positive terms
// e.g., style(--variant: danger) implies NOT style(--variant: success)
// and style(--variant: danger) implies style(--variant) (existence)
terms = removeImpliedNegations(terms);
// Deduplicate (by uniqueId)
terms = deduplicateTerms(terms);
// Try to merge numeric ranges
terms = mergeRanges(terms);
// Sort for canonical form
terms = sortTerms(terms);
// ─── Pass 4: boolean-algebra reductions ────────────────────────────────
// Apply absorption: A & (A | B) → A
terms = applyAbsorptionAnd(terms);
// Apply consensus/resolution: (A | B) & (A | !B) → A
terms = applyConsensusAnd(terms);
// ─── Pass 5: cross-level contradiction pruning ──────────────────────────
// A & OR(!A & X, Y) → A & Y
// For each OR child, prune branches that are impossible given the other
// AND siblings. This catches dead branches left by exclusive negation.
terms = pruneContradictedOrBranches(terms);
if (terms.length === 0) {
return trueCondition();
}
if (terms.length === 1) {
return terms[0];
}
return {
kind: 'compound',
operator: 'AND',
children: terms,
};
}
// ============================================================================
// OR Simplification
// ============================================================================
function simplifyOr(children: ConditionNode[]): ConditionNode {
let terms: ConditionNode[] = [];
// ─── Pass 1: flatten + identity/annihilator ────────────────────────────
// Flatten nested ORs, drop FALSE children, short-circuit on any TRUE.
for (const child of children) {
if (child.kind === 'true') {
// OR with TRUE → TRUE
return trueCondition();
}
if (child.kind === 'false') {
// OR with FALSE → skip (identity)
continue;
}
if (child.kind === 'compound' && child.operator === 'OR') {
// Flatten nested OR
terms.push(...child.children);
} else {
terms.push(child);
}
}
// Empty → FALSE
if (terms.length === 0) {
return falseCondition();
}
// Single term → return it
if (terms.length === 1) {
return terms[0];
}
// ─── Pass 2: filter tautologies ────────────────────────────────────────
// A | !A means the disjunction is always satisfied.
if (hasTautology(terms)) {
return trueCondition();
}
// ─── Pass 3: redundancy elimination + canonicalization ─────────────────
// Deduplicate
terms = deduplicateTerms(terms);
// Sort for canonical form
terms = sortTerms(terms);
// ─── Pass 4: boolean-algebra reductions ────────────────────────────────
// Apply absorption: A | (A & B) → A
terms = applyAbsorptionOr(terms);
// Apply complementary factoring: (A & B) | (A & !B) → A
terms = applyComplementaryFactoring(terms);
if (terms.length === 0) {
return falseCondition();
}
if (terms.length === 1) {
return terms[0];
}
return {
kind: 'compound',
operator: 'OR',
children: terms,
};
}
// ============================================================================
// Contradiction Detection
// ============================================================================
/**
* Check if any pair of terms has complementary negation (A and !A).
* Used for both contradiction detection (in AND) and tautology detection (in OR),
* since the underlying check is identical: the context determines the semantics.
*/
function hasComplementaryPair(terms: ConditionNode[]): boolean {
const uniqueIds = new Set<string>();
for (const term of terms) {
if (term.kind !== 'state') continue;
const id = term.uniqueId;
const negatedId = term.negated ? id.slice(1) : `!${id}`;
if (uniqueIds.has(negatedId)) {
return true;
}
uniqueIds.add(id);
}
return false;
}
const hasContradiction = hasComplementaryPair;
const hasTautology = hasComplementaryPair;
// ============================================================================
// Range Contradiction Detection
// ============================================================================
/**
* Effective bounds computed from conditions (including negated single-bound conditions)
*/
interface EffectiveBounds {
lowerBound: number | null;
lowerInclusive: boolean;
upperBound: number | null;
upperInclusive: boolean;
}
/**
* Excluded range from a negated range condition
*/
interface ExcludedRange {
lower: number;
lowerInclusive: boolean;
upper: number;
upperInclusive: boolean;
}
/**
* Check for range contradictions in media/container queries
* e.g., @media(w < 400px) & @media(w > 800px) → FALSE
*
* Also handles negated conditions:
* - Single-bound negations are inverted (not (w < 600px) → w >= 600px)
* - Range negations create excluded ranges that are checked against positive bounds
*/
function hasRangeContradiction(terms: ConditionNode[]): boolean {
// Group by dimension, separating positive and negated conditions
const mediaByDim = new Map<
string,
{ positive: MediaCondition[]; negated: MediaCondition[] }
>();
const containerByDim = new Map<
string,
{ positive: ContainerCondition[]; negated: ContainerCondition[] }
>();
for (const term of terms) {
if (term.kind !== 'state') continue;
if (term.type === 'media' && term.subtype === 'dimension') {
const key = term.dimension || 'width';
if (!mediaByDim.has(key)) {
mediaByDim.set(key, { positive: [], negated: [] });
}
const group = mediaByDim.get(key)!;
if (term.negated) {
group.negated.push(term);
} else {
group.positive.push(term);
}
}
if (term.type === 'container' && term.subtype === 'dimension') {
const key = `${term.containerName || '_'}:${term.dimension || 'width'}`;
if (!containerByDim.has(key)) {
containerByDim.set(key, { positive: [], negated: [] });
}
const group = containerByDim.get(key)!;
if (term.negated) {
group.negated.push(term);
} else {
group.positive.push(term);
}
}
}
// Check each dimension group for impossible ranges
for (const group of mediaByDim.values()) {
if (rangesAreImpossibleWithNegations(group.positive, group.negated)) {
return true;
}
}
for (const group of containerByDim.values()) {
if (rangesAreImpossibleWithNegations(group.positive, group.negated)) {
return true;
}
}
return false;
}
/**
* Check if conditions are impossible, including negated conditions.
*
* For negated single-bound conditions:
* not (w < 600px) → w >= 600px (inverted to lower bound)
* not (w >= 800px) → w < 800px (inverted to upper bound)
*
* For negated range conditions:
* not (400px <= w < 800px) → excludes [400, 800)
* If the effective bounds fall entirely within an excluded range, it's impossible.
*/
function rangesAreImpossibleWithNegations(
positive: (MediaCondition | ContainerCondition)[],
negated: (MediaCondition | ContainerCondition)[],
): boolean {
// Start with bounds from positive conditions
const bounds = computeEffectiveBounds(positive);
// Apply inverted bounds from single-bound negated conditions
// and collect excluded ranges from range negated conditions
const excludedRanges: ExcludedRange[] = [];
for (const cond of negated) {
const hasLower = cond.lowerBound?.valueNumeric != null;
const hasUpper = cond.upperBound?.valueNumeric != null;
if (hasLower && hasUpper) {
// Range negation: not (lower <= w < upper) excludes [lower, upper)
excludedRanges.push({
lower: cond.lowerBound!.valueNumeric!,
lowerInclusive: cond.lowerBound!.inclusive,
upper: cond.upperBound!.valueNumeric!,
upperInclusive: cond.upperBound!.inclusive,
});
} else if (hasUpper) {
// not (w < upper) → w >= upper (becomes lower bound)
// not (w <= upper) → w > upper (becomes lower bound, exclusive)
const value = cond.upperBound!.valueNumeric!;
const inclusive = !cond.upperBound!.inclusive; // flip inclusivity
if (bounds.lowerBound === null || value > bounds.lowerBound) {
bounds.lowerBound = value;
bounds.lowerInclusive = inclusive;
} else if (value === bounds.lowerBound && !inclusive) {
bounds.lowerInclusive = false;
}
} else if (hasLower) {
// not (w >= lower) → w < lower (becomes upper bound)
// not (w > lower) → w <= lower (becomes upper bound, inclusive)
const value = cond.lowerBound!.valueNumeric!;
const inclusive = !cond.lowerBound!.inclusive; // flip inclusivity
if (bounds.upperBound === null || value < bounds.upperBound) {
bounds.upperBound = value;
bounds.upperInclusive = inclusive;
} else if (value === bounds.upperBound && !inclusive) {
bounds.upperInclusive = false;
}
}
}
// Check if effective bounds are impossible on their own
if (bounds.lowerBound !== null && bounds.upperBound !== null) {
if (bounds.lowerBound > bounds.upperBound) {
return true;
}
if (
bounds.lowerBound === bounds.upperBound &&
(!bounds.lowerInclusive || !bounds.upperInclusive)
) {
return true;
}
}
// Check if effective bounds fall entirely within any excluded range
if (
bounds.lowerBound !== null &&
bounds.upperBound !== null &&
excludedRanges.length > 0
) {
for (const excluded of excludedRanges) {
if (boundsWithinExcludedRange(bounds, excluded)) {
return true;
}
}
}
return false;
}
/**
* Compute effective bounds from positive (non-negated) conditions
*/
function computeEffectiveBounds(
conditions: (MediaCondition | ContainerCondition)[],
): EffectiveBounds {
let lowerBound: number | null = null;
let lowerInclusive = false;
let upperBound: number | null = null;
let upperInclusive = false;
for (const cond of conditions) {
if (cond.lowerBound?.valueNumeric != null) {
const value = cond.lowerBound.valueNumeric;
const inclusive = cond.lowerBound.inclusive;
if (lowerBound === null || value > lowerBound) {
lowerBound = value;
lowerInclusive = inclusive;
} else if (value === lowerBound && !inclusive) {
lowerInclusive = false;
}
}
if (cond.upperBound?.valueNumeric != null) {
const value = cond.upperBound.valueNumeric;
const inclusive = cond.upperBound.inclusive;
if (upperBound === null || value < upperBound) {
upperBound = value;
upperInclusive = inclusive;
} else if (value === upperBound && !inclusive) {
upperInclusive = false;
}
}
}
return { lowerBound, lowerInclusive, upperBound, upperInclusive };
}
/**
* Check if effective bounds fall entirely within an excluded range.
*
* For example:
* Effective: [400, 800)
* Excluded: [400, 800)
* → bounds fall entirely within excluded range → impossible
*/
function boundsWithinExcludedRange(
bounds: EffectiveBounds,
excluded: ExcludedRange,
): boolean {
if (bounds.lowerBound === null || bounds.upperBound === null) {
return false;
}
// Check if bounds.lower >= excluded.lower
let lowerOk = false;
if (bounds.lowerBound > excluded.lower) {
lowerOk = true;
} else if (bounds.lowerBound === excluded.lower) {
// If excluded includes lower, and bounds includes or excludes lower, it's within
// If excluded excludes lower, bounds must also exclude it to be within
lowerOk = excluded.lowerInclusive || !bounds.lowerInclusive;
}
// Check if bounds.upper <= excluded.upper
let upperOk = false;
if (bounds.upperBound < excluded.upper) {
upperOk = true;
} else if (bounds.upperBound === excluded.upper) {
// If excluded includes upper, and bounds includes or excludes upper, it's within
// If excluded excludes upper, bounds must also exclude it to be within
upperOk = excluded.upperInclusive || !bounds.upperInclusive;
}
return lowerOk && upperOk;
}
// ============================================================================
// Attribute Conflict Detection
// ============================================================================
/**
* Check for attribute value conflicts
* e.g., [data-theme="dark"] & [data-theme="light"] → FALSE
* e.g., [data-theme="dark"] & ![data-theme] → FALSE
*/
/**
* Generic value-conflict checker for grouped conditions.
*
* Groups terms by a key, splits into positive/negated, then checks:
* 1. Multiple distinct positive values → conflict
* 2. Positive value + negated existence (value === undefined) → conflict
* 3. Positive value + negated same value → conflict
*/
function hasGroupedValueConflict<T extends { negated: boolean }>(
terms: ConditionNode[],
match: (term: ConditionNode) => T | null,
groupKey: (term: T) => string,
getValue: (term: T) => string | undefined,
): boolean {
const groups = new Map<string, { positive: T[]; negated: T[] }>();
for (const term of terms) {
const matched = match(term);
if (!matched) continue;
const key = groupKey(matched);
let group = groups.get(key);
if (!group) {
group = { positive: [], negated: [] };
groups.set(key, group);
}
if (matched.negated) {
group.negated.push(matched);
} else {
group.positive.push(matched);
}
}
for (const [, group] of groups) {
const positiveValues = group.positive
.map(getValue)
.filter((v) => v !== undefined);
if (new Set(positiveValues).size > 1) return true;
const hasPositiveValue = positiveValues.length > 0;
const hasNegatedExistence = group.negated.some(
(t) => getValue(t) === undefined,
);
if (hasPositiveValue && hasNegatedExistence) return true;
for (const pos of group.positive) {
const posVal = getValue(pos);
if (posVal !== undefined) {
for (const neg of group.negated) {
if (getValue(neg) === posVal) return true;
}
}
}
}
return false;
}
function hasAttributeConflict(terms: ConditionNode[]): boolean {
// Top-level modifiers: `schema=dark & schema=light`.
if (
hasGroupedValueConflict<ModifierCondition>(
terms,
(t) => (t.kind === 'state' && t.type === 'modifier' ? t : null),
(t) => t.attribute,
(t) => t.value,
)
) {
return true;
}
// @root scope (single :root element):
// `@root(schema=dark) & @root(schema=light)` cannot match anything because
// there is only one document root.
if (hasNestedModifierConflict(terms, 'root')) return true;
// @own scope (single sub-element / styled element under `&`):
// `@own(schema=dark) & @own(schema=light)` is impossible for the same
// reason — both refer to the same element.
if (hasNestedModifierConflict(terms, 'own')) return true;
// NOTE: @parent is intentionally NOT checked. Different ancestor elements
// can hold different attribute values, so two `@parent(schema=...)` calls
// can both match (different ancestors), even when the values differ.
return false;
}
/**
* Collect modifier conditions inside non-negated state wrappers of `kind`
* and check for the same value-conflict pattern as the top-level pass.
*
* Modifiers from multiple sibling wrappers are combined — both wrappers
* scope to the same element (one :root, one own scope), so an attribute
* conflict across wrappers is still impossible.
*/
function hasNestedModifierConflict(
terms: ConditionNode[],
wrapperType: 'root' | 'own',
): boolean {
const innerTerms: ConditionNode[] = [];
for (const term of terms) {
if (term.kind === 'state' && term.type === wrapperType && !term.negated) {
flattenAndIntoArray(
(term as RootCondition | OwnCondition).innerCondition,
innerTerms,
);
}
}
if (innerTerms.length < 2) return false;
return hasGroupedValueConflict<ModifierCondition>(
innerTerms,
(t) => (t.kind === 'state' && t.type === 'modifier' ? t : null),
(t) => t.attribute,
(t) => t.value,
);
}
/**
* Flatten a top-level AND tree into a flat list of conjuncts. Non-AND nodes
* are pushed as-is.
*/
function flattenAndIntoArray(node: ConditionNode, into: ConditionNode[]): void {
if (node.kind === 'compound' && node.operator === 'AND') {
for (const child of node.children) flattenAndIntoArray(child, into);
} else {
into.push(node);
}
}
function hasContainerStyleConflict(terms: ConditionNode[]): boolean {
return hasGroupedValueConflict<ContainerCondition>(
terms,
(t) =>
t.kind === 'state' && t.type === 'container' && t.subtype === 'style'
? t
: null,
(t) => `${t.containerName || '_'}:${t.property}`,
(t) => t.propertyValue,
);
}
// ============================================================================
// Implied Negation Removal
// ============================================================================
/**
* Remove negations that are implied by positive terms.
*
* Key optimizations:
* 1. style(--variant: danger) implies NOT style(--variant: success)
* → If we have style(--variant: danger) & not style(--variant: success),
* the negation is redundant and can be removed.
*
* 2. [data-theme="dark"] implies NOT [data-theme="light"]
* → Same logic for attribute selectors.
*
* This produces cleaner CSS:
* Before: @container style(--variant: danger) and (not style(--variant: success))
* After: @container style(--variant: danger)
*/
/**
* Collect positive values from terms and build a "is this negation implied?" check.
*
* A negation is implied (redundant) when a positive term for the same group
* already pins a specific value, making "NOT other-value" obvious.
* e.g. style(--variant: danger) implies NOT style(--variant: success).
*/
function buildImpliedNegationCheck(
terms: ConditionNode[],
): (term: ConditionNode) => boolean {
const positiveValues = new Map<string, string>();
const negatedBooleanAttrs = new Set<string>();
for (const term of terms) {
if (term.kind !== 'state') continue;
if (!term.negated) {
if (term.type === 'container' && term.subtype === 'style') {
if (term.propertyValue !== undefined) {
positiveValues.set(
`c:${term.containerName || '_'}:${term.property}`,
term.propertyValue,
);
}
} else if (term.type === 'modifier' && term.value !== undefined) {
positiveValues.set(`m:${term.attribute}`, term.value);
}
} else {
// NOT [data-attr] (boolean negation) implies NOT [data-attr="val"]
if (term.type === 'modifier' && term.value === undefined) {
negatedBooleanAttrs.add(term.attribute);
}
}
}
return (term: ConditionNode): boolean => {
if (term.kind !== 'state' || !term.negated) return false;
if (term.type === 'container' && term.subtype === 'style') {
if (term.propertyValue === undefined) return false;
const pos = positiveValues.get(
`c:${term.containerName || '_'}:${term.property}`,
);
return pos !== undefined && term.propertyValue !== pos;
}
if (term.type === 'modifier' && term.value !== undefined) {
// :not([data-attr]) already present → :not([data-attr="val"]) is redundant
if (negatedBooleanAttrs.has(term.attribute)) return true;
const pos = positiveValues.get(`m:${term.attribute}`);
return pos !== undefined && term.value !== pos;
}
return false;
};
}
function removeImpliedNegations(terms: ConditionNode[]): ConditionNode[] {
const isImplied = buildImpliedNegationCheck(terms);
return terms.filter((t) => !isImplied(t));
}
// ============================================================================
// Deduplication
// ============================================================================
function deduplicateTerms(terms: ConditionNode[]): ConditionNode[] {
const seen = new Set<string>();
const result: ConditionNode[] = [];
for (const term of terms) {
const id = getConditionUniqueId(term);
if (!seen.has(id)) {
seen.add(id);
result.push(term);
}
}
return result;
}
// ============================================================================
// Range Merging
// ============================================================================
/**
* Merge compatible range conditions
* e.g., @media(w >= 400px) & @media(w <= 800px) → @media(400px <= w <= 800px)
*/
function mergeRanges(terms: ConditionNode[]): ConditionNode[] {
// Group media conditions by dimension
const mediaByDim = new Map<
string,
{ conditions: MediaCondition[]; indices: number[] }
>();
const containerByDim = new Map<
string,
{ conditions: ContainerCondition[]; indices: number[] }
>();
terms.forEach((term, index) => {
if (term.kind !== 'state') return;
if (
term.type === 'media' &&
term.subtype === 'dimension' &&
!term.negated
) {
const key = term.dimension || 'width';
if (!mediaByDim.has(key)) {
mediaByDim.set(key, { conditions: [], indices: [] });
}
const group = mediaByDim.get(key)!;
group.conditions.push(term);
group.indices.push(index);
}
if (
term.type === 'container' &&
term.subtype === 'dimension' &&
!term.negated
) {
const key = `${term.containerName || '_'}:${term.dimension || 'width'}`;
if (!containerByDim.has(key)) {
containerByDim.set(key, { conditions: [], indices: [] });
}
const group = containerByDim.get(key)!;
group.conditions.push(term);
group.indices.push(index);
}
});
// Track indices to remove
const indicesToRemove = new Set<number>();
const mergedTerms: ConditionNode[] = [];
// Merge media conditions
for (const [_dim, group] of mediaByDim) {
if (group.conditions.length > 1) {
const merged = mergeMediaRanges(group.conditions);
if (merged) {
group.indices.forEach((i) => indicesToRemove.add(i));
mergedTerms.push(merged);
}
}
}
// Merge container conditions
for (const [, group] of containerByDim) {
if (group.conditions.length > 1) {
const merged = mergeContainerRanges(group.conditions);
if (merged) {
group.indices.forEach((i) => indicesToRemove.add(i));
mergedTerms.push(merged);
}
}
}
// Build result
const result: ConditionNode[] = [];
terms.forEach((term, index) => {
if (!indicesToRemove.has(index)) {
result.push(term);
}
});
result.push(...mergedTerms);
return result;
}
/**
* Tighten bounds by picking the most restrictive lower and upper bounds
* from a set of conditions that have lowerBound/upperBound fields.
*/
function tightenBounds(
conditions: { lowerBound?: NumericBound; upperBound?: NumericBound }[],
): { lowerBound?: NumericBound; upperBound?: NumericBound } {
let lowerBound: NumericBound | undefined;
let upperBound: NumericBound | undefined;
for (const cond of conditions) {
if (cond.lowerBound) {
if (
!lowerBound ||
(cond.lowerBound.valueNumeric ?? -Infinity) >
(lowerBound.valueNumeric ?? -Infinity)
) {
lowerBound = cond.lowerBound;
}
}
if (cond.upperBound) {
if (
!upperBound ||
(cond.upperBound.valueNumeric ?? Infinity) <
(upperBound.valueNumeric ?? Infinity)
) {
upperBound = cond.upperBound;
}
}
}
return { lowerBound, upperBound };
}
function appendBoundsToUniqueId(
parts: string[],
lowerBound?: NumericBound,
upperBound?: NumericBound,
): void {
if (lowerBound) {
parts.push(lowerBound.inclusive ? '>=' : '>');
parts.push(lowerBound.value);
}
if (upperBound) {
parts.push(upperBound.inclusive ? '<=' : '<');
parts.push(upperBound.value);
}
}
function mergeDimensionRanges<T extends MediaCondition | ContainerCondition>(
conditions: T[],
idPrefix: string[],
): T | null {
if (conditions.length === 0) return null;
const { lowerBound, upperBound } = tightenBounds(conditions);
const base = conditions[0];
const parts = [...idPrefix];
appendBoundsToUniqueId(parts, lowerBound, upperBound);