generated from oddbird/polyfill-template
-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathparse.ts
975 lines (892 loc) · 31 KB
/
parse.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
import * as csstree from 'css-tree';
import { nanoid } from 'nanoid/non-secure';
import { StyleData } from './fetch.js';
import { validatedForPositioning } from './validate.js';
interface DeclarationWithValue extends csstree.Declaration {
value: csstree.Value;
}
interface AtRuleRaw extends csstree.Atrule {
prelude: csstree.Raw | null;
}
interface AnchorNames {
// `key` is the `anchor-name` value
// `value` is an array of all element selectors with that anchor name
[key: string]: string[];
}
export type InsetProperty =
| 'top'
| 'left'
| 'right'
| 'bottom'
| 'inset-block-start'
| 'inset-block-end'
| 'inset-inline-start'
| 'inset-inline-end'
| 'inset-block'
| 'inset-inline'
| 'inset';
const INSET_PROPS: InsetProperty[] = [
'left',
'right',
'top',
'bottom',
'inset-block-start',
'inset-block-end',
'inset-inline-start',
'inset-inline-end',
'inset-block',
'inset-inline',
'inset',
];
export type SizingProperty =
| 'width'
| 'height'
| 'min-width'
| 'min-height'
| 'max-width'
| 'max-height';
const SIZING_PROPS: SizingProperty[] = [
'width',
'height',
'min-width',
'min-height',
'max-width',
'max-height',
];
export type BoxAlignmentProperty =
| 'justify-content'
| 'align-content'
| 'justify-self'
| 'align-self'
| 'justify-items'
| 'align-items';
const BOX_ALIGNMENT_PROPS: BoxAlignmentProperty[] = [
'justify-content',
'align-content',
'justify-self',
'align-self',
'justify-items',
'align-items',
];
type AnchorSideKeyword =
| 'top'
| 'left'
| 'right'
| 'bottom'
| 'start'
| 'end'
| 'self-start'
| 'self-end'
| 'center';
const ANCHOR_SIDES: AnchorSideKeyword[] = [
'top',
'left',
'right',
'bottom',
'start',
'end',
'self-start',
'self-end',
'center',
];
export type AnchorSide = AnchorSideKeyword | number;
export type AnchorSize =
| 'width'
| 'height'
| 'block'
| 'inline'
| 'self-block'
| 'self-inline';
const ANCHOR_SIZES: AnchorSize[] = [
'width',
'height',
'block',
'inline',
'self-block',
'self-inline',
];
export interface AnchorFunction {
targetEl?: HTMLElement | null;
anchorEl?: HTMLElement | null;
anchorName?: string;
anchorSide?: AnchorSide;
anchorSize?: AnchorSize;
fallbackValue: string;
customPropName?: string;
uuid: string;
}
// `key` is the property being declared
// `value` is the anchor-positioning data for that property
export type AnchorFunctionDeclaration = Partial<
Record<InsetProperty | SizingProperty, AnchorFunction[]>
>;
interface AnchorFunctionDeclarations {
// `key` is the target element selector
// `value` is an object with all anchor-function declarations on that element
[key: string]: AnchorFunctionDeclaration;
}
interface AnchorPosition {
declarations?: AnchorFunctionDeclaration;
fallbacks?: TryBlock[];
}
export interface AnchorPositions {
// `key` is the target element selector
// `value` is an object with all anchor-positioning data for that element
[key: string]: AnchorPosition;
}
export interface TryBlock {
uuid: string;
// `key` is the property being declared
// `value` is the property value
declarations: Partial<
Record<InsetProperty | SizingProperty | BoxAlignmentProperty, string>
>;
}
interface FallbackTargets {
// `key` is the `@try` block uuid
// `value` is the target element selector
[key: string]: string;
}
interface Fallbacks {
// `key` is the `position-fallback` value (name)
[key: string]: {
// `targets` is an array of selectors where this `position-fallback` is used
targets: string[];
// `blocks` is an array of `@try` block declarations (in order)
blocks: TryBlock[];
};
}
function isDeclaration(node: csstree.CssNode): node is DeclarationWithValue {
return node.type === 'Declaration';
}
function isAnchorNameDeclaration(
node: csstree.CssNode,
): node is DeclarationWithValue {
return node.type === 'Declaration' && node.property === 'anchor-name';
}
function isAnchorFunction(
node: csstree.CssNode | null,
): node is csstree.FunctionNode {
return Boolean(node && node.type === 'Function' && node.name === 'anchor');
}
function isAnchorSizeFunction(
node: csstree.CssNode | null,
): node is csstree.FunctionNode {
return Boolean(
node && node.type === 'Function' && node.name === 'anchor-size',
);
}
function isVarFunction(
node: csstree.CssNode | null,
): node is csstree.FunctionNode {
return Boolean(node && node.type === 'Function' && node.name === 'var');
}
function isFallbackDeclaration(
node: csstree.CssNode,
): node is DeclarationWithValue {
return node.type === 'Declaration' && node.property === 'position-fallback';
}
function isFallbackAtRule(node: csstree.CssNode): node is AtRuleRaw {
return node.type === 'Atrule' && node.name === 'position-fallback';
}
function isTryAtRule(node: csstree.CssNode): node is AtRuleRaw {
return node.type === 'Atrule' && node.name === 'try';
}
function isIdentifier(node: csstree.CssNode): node is csstree.Identifier {
return Boolean(node.type === 'Identifier' && node.name);
}
function isPercentage(node: csstree.CssNode): node is csstree.Percentage {
return Boolean(node.type === 'Percentage' && node.value);
}
export function isInsetProp(
property: string | AnchorSide,
): property is InsetProperty {
return INSET_PROPS.includes(property as InsetProperty);
}
function isAnchorSide(property: string): property is AnchorSideKeyword {
return ANCHOR_SIDES.includes(property as AnchorSideKeyword);
}
export function isSizingProp(property: string): property is SizingProperty {
return SIZING_PROPS.includes(property as SizingProperty);
}
function isAnchorSize(property: string): property is AnchorSize {
return ANCHOR_SIZES.includes(property as AnchorSize);
}
export function isBoxAlignmentProp(
property: string,
): property is BoxAlignmentProperty {
return BOX_ALIGNMENT_PROPS.includes(property as BoxAlignmentProperty);
}
function parseAnchorFn(
node: csstree.FunctionNode,
replaceCss?: boolean,
): AnchorFunction {
let anchorName: string | undefined,
anchorSide: AnchorSide | undefined,
anchorSize: AnchorSize | undefined,
fallbackValue = '',
foundComma = false,
customPropName: string | undefined;
const args: csstree.CssNode[] = [];
node.children.toArray().forEach((child) => {
if (foundComma) {
fallbackValue = `${fallbackValue}${csstree.generate(child)}`;
return;
}
if (child.type === 'Operator' && child.value === ',') {
foundComma = true;
return;
}
args.push(child);
});
let [name, sideOrSize]: (csstree.CssNode | undefined)[] = args;
if (!sideOrSize) {
// If we only have one argument assume it is the (required) anchor-side/size
sideOrSize = name;
name = undefined;
}
if (name) {
if (isIdentifier(name)) {
if (name.name === 'implicit') {
name = undefined;
} else if (name.name.startsWith('--')) {
// Store anchor name
anchorName = name.name;
}
} else if (isVarFunction(name) && name.children.first) {
// Store CSS custom prop for anchor name
customPropName = (name.children.first as csstree.Identifier).name;
}
}
if (sideOrSize) {
if (isAnchorFunction(node)) {
if (isIdentifier(sideOrSize) && isAnchorSide(sideOrSize.name)) {
anchorSide = sideOrSize.name;
} else if (isPercentage(sideOrSize)) {
const number = Number(sideOrSize.value);
anchorSide = Number.isNaN(number) ? undefined : number;
}
} else if (
isAnchorSizeFunction(node) &&
isIdentifier(sideOrSize) &&
isAnchorSize(sideOrSize.name)
) {
anchorSize = sideOrSize.name;
}
}
const uuid = `--anchor-${nanoid(12)}`;
if (replaceCss) {
// Replace anchor function with unique CSS custom property.
// This allows us to update the value of the new custom property
// every time the position changes.
Object.assign(node, {
type: 'Raw',
value: `var(${uuid})`,
children: null,
});
Reflect.deleteProperty(node, 'name');
}
return {
anchorName,
anchorSide,
anchorSize,
fallbackValue: fallbackValue || '0px',
customPropName,
uuid,
};
}
function getAnchorNameData(node: csstree.CssNode, rule?: csstree.Raw) {
if (
isAnchorNameDeclaration(node) &&
node.value.children.first &&
rule?.value
) {
const name = (node.value.children.first as csstree.Identifier).name;
return { name, selector: rule.value };
}
return {};
}
let anchorNames: AnchorNames = {};
// Mapping of custom property names, to anchor function data objects referenced
// in their values
let customPropAssignments: Record<string, AnchorFunction[]> = {};
// Mapping of custom property names, to the original values that have been
// replaced in the CSS
let customPropOriginals: Record<string, string> = {};
// Top-level key (`uuid`) is the original uuid to find in the updated CSS
// - `key` (`propUuid`) is the new property-specific uuid to append to the
// original custom property name
// - `value` is the new property-specific custom property value to use
let customPropReplacements: Record<string, Record<string, string>> = {};
// Objects are declared at top-level to keep code cleaner,
// but we reset them on every `parseCSS()` call
// to prevent data leaking from one call to another.
function resetStores() {
anchorNames = {};
customPropAssignments = {};
customPropOriginals = {};
customPropReplacements = {};
}
function getAnchorFunctionData(
node: csstree.CssNode,
declaration: csstree.Declaration | null,
) {
if ((isAnchorFunction(node) || isAnchorSizeFunction(node)) && declaration) {
if (declaration.property.startsWith('--')) {
const original = csstree.generate(declaration.value);
const data = parseAnchorFn(node, true);
// Store the original anchor function so that we can restore it later
customPropOriginals[data.uuid] = original;
customPropAssignments[declaration.property] = [
...(customPropAssignments[declaration.property] ?? []),
data,
];
return { changed: true };
}
if (
isInsetProp(declaration.property) ||
isSizingProp(declaration.property)
) {
const data = parseAnchorFn(node, true);
return { prop: declaration.property, data, changed: true };
}
}
return {};
}
function getPositionFallbackDeclaration(
node: csstree.Declaration,
rule?: csstree.Raw,
) {
if (isFallbackDeclaration(node) && node.value.children.first && rule?.value) {
const name = (node.value.children.first as csstree.Identifier).name;
return { name, selector: rule.value };
}
return {};
}
function getPositionFallbackRules(node: csstree.Atrule) {
if (isFallbackAtRule(node) && node.prelude?.value && node.block?.children) {
const name = node.prelude.value;
const tryBlocks: TryBlock[] = [];
const tryAtRules = node.block.children.filter(isTryAtRule);
tryAtRules.forEach((atRule) => {
if (atRule.block?.children) {
// Only declarations are allowed inside a `@try` block
const declarations = atRule.block.children.filter(
(d): d is DeclarationWithValue =>
isDeclaration(d) &&
(isInsetProp(d.property) ||
isSizingProp(d.property) ||
isBoxAlignmentProp(d.property)),
);
const tryBlock: TryBlock = {
uuid: `${name}-try-${nanoid(12)}`,
declarations: Object.fromEntries(
declarations.map((d) => [d.property, csstree.generate(d.value)]),
),
};
tryBlocks.push(tryBlock);
}
});
return { name, blocks: tryBlocks };
}
return {};
}
export function getCSSPropertyValue(el: HTMLElement, prop: string) {
return getComputedStyle(el).getPropertyValue(prop).trim();
}
async function getAnchorEl(
targetEl: HTMLElement | null,
anchorObj: AnchorFunction,
) {
let anchorName = anchorObj.anchorName;
const customPropName = anchorObj.customPropName;
if (targetEl && !anchorName) {
const anchorAttr = targetEl.getAttribute('anchor');
if (customPropName) {
anchorName = getCSSPropertyValue(targetEl, customPropName);
} else if (anchorAttr) {
return await validatedForPositioning(targetEl, [`#${anchorAttr}`]);
}
}
const anchorSelectors = anchorName ? anchorNames[anchorName] ?? [] : [];
return await validatedForPositioning(targetEl, anchorSelectors);
}
function getAST(cssText: string) {
const ast = csstree.parse(cssText, {
parseAtrulePrelude: false,
parseRulePrelude: false,
parseCustomProperty: true,
});
return ast;
}
export async function parseCSS(styleData: StyleData[]) {
const anchorFunctions: AnchorFunctionDeclarations = {};
const fallbackTargets: FallbackTargets = {};
const fallbacks: Fallbacks = {};
// Final data merged together under target-element selector key
const validPositions: AnchorPositions = {};
resetStores();
// First, find all uses of `@position-fallback`
for (const styleObj of styleData) {
const ast = getAST(styleObj.css);
csstree.walk(ast, {
visit: 'Atrule',
enter(node) {
// Parse `@position-fallback` rules
const { name, blocks } = getPositionFallbackRules(node);
if (name && blocks?.length) {
// This will override earlier `@position-fallback` lists
// with the same name:
// (e.g. multiple `@position-fallback --my-fallback {...}` uses
// with the same `--my-fallback` name)
fallbacks[name] = {
targets: [],
blocks: blocks,
};
}
},
});
}
// Then, find all `position-fallback` declarations,
// and add in `@try` block contents (scoped to unique data-attrs)
for (const styleObj of styleData) {
let changed = false;
const ast = getAST(styleObj.css);
csstree.walk(ast, {
visit: 'Declaration',
enter(node) {
const rule = this.rule?.prelude as csstree.Raw | undefined;
// Parse `position-fallback` declaration
const { name, selector } = getPositionFallbackDeclaration(node, rule);
if (name && selector && fallbacks[name]) {
validPositions[selector] = { fallbacks: fallbacks[name].blocks };
if (!fallbacks[name].targets.includes(selector)) {
fallbacks[name].targets.push(selector);
}
// Add each `@try` block, scoped to a unique data-attr
for (const block of fallbacks[name].blocks) {
const dataAttr = `[data-anchor-polyfill="${block.uuid}"]`;
this.stylesheet?.children.prependData({
type: 'Rule',
prelude: {
type: 'Raw',
value: dataAttr,
},
block: {
type: 'Block',
children: new csstree.List<csstree.CssNode>().fromArray(
Object.entries(block.declarations).map(([prop, val]) => ({
type: 'Declaration',
important: true,
property: prop,
value: {
type: 'Raw',
value: val,
},
})),
),
},
});
// Store mapping of data-attr to target selector
fallbackTargets[dataAttr] = selector;
}
changed = true;
}
},
});
if (changed) {
// Update CSS
styleObj.css = csstree.generate(ast);
styleObj.changed = true;
}
}
for (const styleObj of styleData) {
let changed = false;
const ast = getAST(styleObj.css);
csstree.walk(ast, function (node) {
const rule = this.rule?.prelude as csstree.Raw | undefined;
// Parse `anchor-name` declaration
const { name: anchorName, selector: anchorSelector } = getAnchorNameData(
node,
rule,
);
if (anchorName && anchorSelector) {
if (anchorNames[anchorName]) {
anchorNames[anchorName].push(anchorSelector);
} else {
anchorNames[anchorName] = [anchorSelector];
}
}
// Parse `anchor()` function
const {
prop,
data,
changed: updated,
} = getAnchorFunctionData(node, this.declaration);
if (prop && data && rule?.value) {
// This will override earlier declarations
// with the same exact rule selector
// *and* the same exact declaration property:
// (e.g. multiple `top: anchor(...)` declarations
// for the same `.foo {...}` selector)
anchorFunctions[rule.value] = {
...anchorFunctions[rule.value],
[prop]: [...(anchorFunctions[rule.value]?.[prop] ?? []), data],
};
}
if (updated) {
changed = true;
}
});
if (changed) {
// Update CSS
styleObj.css = csstree.generate(ast);
styleObj.changed = true;
}
}
// List of CSS custom properties that include anchor fns
const customPropsToCheck = new Set(Object.keys(customPropAssignments));
// Mapping of a custom property name, to the name(s) and uuid(s) of other
// custom properties "up" the chain that contain (eventually) a reference to
// an anchor function
const customPropsMapping: Record<
// custom property name
string,
// other custom property name(s) and uuid(s) referenced by this custom prop
{ names: string[]; uuids: string[] }
> = {};
// Find (recursively) anchor data assigned to another custom property, and
// that custom property is referenced by (i.e. passed through) the given
// custom property
const getReferencedFns = (prop: string) => {
const referencedFns: AnchorFunction[] = [];
const ancestorProps = new Set(customPropsMapping[prop]?.names ?? []);
while (ancestorProps.size > 0) {
for (const prop of ancestorProps) {
referencedFns.push(...(customPropAssignments[prop] ?? []));
ancestorProps.delete(prop);
if (customPropsMapping[prop]?.names?.length) {
// Continue checking recursively "up" the chain of custom properties
customPropsMapping[prop].names.forEach((n) => ancestorProps.add(n));
}
}
}
return referencedFns;
};
// First find where CSS custom properties are used in other custom properties
while (customPropsToCheck.size > 0) {
const toCheckAgain: string[] = [];
for (const styleObj of styleData) {
let changed = false;
const ast = getAST(styleObj.css);
csstree.walk(ast, {
visit: 'Function',
enter(node) {
const rule = this.rule?.prelude as csstree.Raw | undefined;
const declaration = this.declaration;
const prop = declaration?.property;
if (
rule?.value &&
isVarFunction(node) &&
declaration &&
prop &&
node.children.first &&
customPropsToCheck.has(
(node.children.first as csstree.Identifier).name,
) &&
// For now, we only want assignments to other CSS custom properties
prop.startsWith('--')
) {
const child = node.children.first as csstree.Identifier;
// Find anchor data assigned to this custom property
const anchorFns = customPropAssignments[child.name] ?? [];
// Find anchor data assigned to another custom property referenced
// by this custom property (recursively)
const referencedFns = getReferencedFns(child.name);
// Return if there are no anchor fns related to this custom property
if (!(anchorFns.length || referencedFns.length)) {
return;
}
// An anchor fn was assigned to a custom property, which is
// now being re-assigned to another custom property...
const uuid = `${child.name}-anchor-${nanoid(12)}`;
// Store the original declaration so that we can restore it later
const original = csstree.generate(declaration.value);
customPropOriginals[uuid] = original;
// Store a mapping of the new property to the original property
// name, as well as the unique uuid(s) temporarily used to replace
// the original property value.
if (!customPropsMapping[prop]) {
customPropsMapping[prop] = { names: [], uuids: [] };
}
const mapping = customPropsMapping[prop];
if (!mapping.names.includes(child.name)) {
mapping.names.push(child.name);
}
mapping.uuids.push(uuid);
// Note that we need to do another pass of the CSS looking for
// usage of the new property name:
toCheckAgain.push(prop);
// Temporarily replace the original property with a new unique key
child.name = uuid;
changed = true;
}
},
});
if (changed) {
// Update CSS
styleObj.css = csstree.generate(ast);
styleObj.changed = true;
}
}
customPropsToCheck.clear();
toCheckAgain.forEach((s) => customPropsToCheck.add(s));
}
// Then find where CSS custom properties are used in inset/sizing properties:
for (const styleObj of styleData) {
let changed = false;
const ast = getAST(styleObj.css);
csstree.walk(ast, {
visit: 'Function',
enter(node) {
const rule = this.rule?.prelude as csstree.Raw | undefined;
const declaration = this.declaration;
const prop = declaration?.property;
if (
rule?.value &&
isVarFunction(node) &&
declaration &&
prop &&
node.children.first &&
// Now we only want assignments to inset/sizing properties
(isInsetProp(prop) || isSizingProp(prop))
) {
const child = node.children.first as csstree.Identifier;
// Find anchor data assigned to this custom property
const anchorFns = customPropAssignments[child.name] ?? [];
// Find anchor data assigned to another custom property referenced
// by this custom property (recursively)
const referencedFns = getReferencedFns(child.name);
// Return if there are no anchor fns related to this custom property
if (!(anchorFns.length || referencedFns.length)) {
return;
}
/*
An anchor (or anchor-size) fn was assigned to an inset (or sizing)
property.
It's possible that there are multiple uses of the same CSS
custom property name, with different anchor function calls
assigned to them. Instead of trying to figure out which one has
cascaded to the given location, we iterate over all anchor
functions that were assigned to the given CSS custom property
name. For each one, we add a new custom prop with the value
for that target and inset/sizing property, and let CSS determine
which one cascades down to where it's used.
For example, this:
.one {
--center: anchor(--anchor-name 50%);
}
.two {
--center: anchor(--anchor-name 100%);
}
#target {
top: var(--center);
}
Becomes this:
.one {
--center-top-EnmDEkZ5mBLp: var(--anchor-aPyy7qLK9f38-top);
--center: anchor(--anchor-name 50%);
}
.two {
--center-top-EnmDEkZ5mBLp: var(--anchor-SgrF5vARDf6H-top);
--center: anchor(--anchor-name 100%);
}
#target {
top: var(--center-top-EnmDEkZ5mBLp);
}
*/
const propUuid = `${prop}-${nanoid(12)}`;
// If this is a custom property which was assigned a value from
// another custom property (and not a direct reference to an anchor
// fn), we want to replace the reference to its "parent" property with
// a direct reference to the resolved value of the parent property for
// this given inset/sizing property (e.g. top or width). We do this
// recursively back up the chain of references...
if (referencedFns.length) {
const ancestorProps = new Set([child.name]);
while (ancestorProps.size > 0) {
for (const propToCheck of ancestorProps) {
const mapping = customPropsMapping[propToCheck];
if (mapping?.names?.length && mapping?.uuids?.length) {
for (const name of mapping.names) {
for (const uuid of mapping.uuids) {
// Top-level key (`uuid`) is the original uuid to find in
// the updated CSS
customPropReplacements[uuid] = {
...customPropReplacements[uuid],
// - `key` (`propUuid`) is the property-specific
// uuid to append to the new custom property name
// - `value` is the new property-specific custom
// property value to use
[propUuid]: `${name}-${propUuid}`,
};
}
}
}
ancestorProps.delete(propToCheck);
// Check (recursively) for custom properties up the chain...
if (mapping?.names?.length) {
mapping.names.forEach((n) => ancestorProps.add(n));
}
}
}
}
// When `anchor()` is used multiple times in different inset/sizing
// properties, the value will be different each time. So we append
// the property to the uuid, and update the CSS property to point
// to the new uuid...
for (const anchorFnData of [...anchorFns, ...referencedFns]) {
const data = { ...anchorFnData };
const uuidWithProp = `--anchor-${nanoid(12)}-${prop}`;
const uuid = data.uuid;
data.uuid = uuidWithProp;
anchorFunctions[rule.value] = {
...anchorFunctions[rule.value],
[prop]: [...(anchorFunctions[rule.value]?.[prop] ?? []), data],
};
// Store new name with declaration prop appended,
// so that we can go back and update the original custom
// property value...
// Top-level key (`uuid`) is the original uuid to find in
// the updated CSS:
customPropReplacements[uuid] = {
...customPropReplacements[uuid],
// - `key` (`propUuid`) is the property-specific
// uuid to append to the new custom property name
// - `value` is the new property-specific custom
// property value to use
[propUuid]: uuidWithProp,
};
}
// Update CSS property to new name with declaration prop added
child.name = `${child.name}-${propUuid}`;
changed = true;
}
},
});
if (changed) {
// Update CSS
styleObj.css = csstree.generate(ast);
styleObj.changed = true;
}
}
// Add new CSS custom properties, and restore original values of
// previously-replaced custom properties
if (Object.keys(customPropReplacements).length > 0) {
for (const styleObj of styleData) {
let changed = false;
const ast = getAST(styleObj.css);
csstree.walk(ast, {
visit: 'Function',
enter(node) {
if (
isVarFunction(node) &&
(node.children.first as csstree.Identifier)?.name?.startsWith(
'--',
) &&
this.declaration?.property?.startsWith('--') &&
this.block
) {
const child = node.children.first as csstree.Identifier;
const positions = customPropReplacements[child.name];
if (positions) {
for (const [propUuid, value] of Object.entries(positions)) {
// Add new property-specific declarations
this.block.children.appendData({
type: 'Declaration',
important: false,
property: `${this.declaration.property}-${propUuid}`,
value: {
type: 'Raw',
value: csstree
.generate(this.declaration.value)
.replace(`var(${child.name})`, `var(${value})`),
},
});
changed = true;
}
}
if (customPropOriginals[child.name]) {
// Restore original (now unused) CSS custom property value
this.declaration.value = {
type: 'Raw',
value: customPropOriginals[child.name],
};
changed = true;
}
}
},
});
if (changed) {
// Update CSS
styleObj.css = csstree.generate(ast);
styleObj.changed = true;
}
}
}
// Store inline style custom property mappings for each target element
const inlineStyles = new Map<HTMLElement, Record<string, string>>();
// Store any `anchor()` fns
for (const [targetSel, anchorFns] of Object.entries(anchorFunctions)) {
let targets: NodeListOf<HTMLElement>;
if (
targetSel.startsWith('[data-anchor-polyfill=') &&
fallbackTargets[targetSel]
) {
// If we're dealing with a `@position-fallback` `@try` block,
// then the targets are places where that `position-fallback` is used.
targets = document.querySelectorAll(fallbackTargets[targetSel]);
} else {
targets = document.querySelectorAll(targetSel);
}
for (const [targetProperty, anchorObjects] of Object.entries(anchorFns) as [
InsetProperty | SizingProperty,
AnchorFunction[],
][]) {
for (const anchorObj of anchorObjects) {
for (const targetEl of targets) {
// For every target element, find a valid anchor element
const anchorEl = await getAnchorEl(targetEl, anchorObj);
const uuid = `--anchor-${nanoid(12)}`;
// Store new mapping, in case inline styles have changed and will
// be overwritten -- in which case new mappings will be re-added
inlineStyles.set(targetEl, {
...(inlineStyles.get(targetEl) ?? {}),
[anchorObj.uuid]: uuid,
});
// Point original uuid to new uuid
targetEl.setAttribute(
'style',
`${anchorObj.uuid}: var(${uuid}); ${
targetEl.getAttribute('style') ?? ''
}`,
);
// Populate new data for each anchor/target combo
validPositions[targetSel] = {
...validPositions[targetSel],
declarations: {
...validPositions[targetSel]?.declarations,
[targetProperty]: [
...(validPositions[targetSel]?.declarations?.[
targetProperty as InsetProperty
] ?? []),
{ ...anchorObj, anchorEl, targetEl, uuid },
],
},
};
}
}
}
}
return { rules: validPositions, inlineStyles };
}