Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

themeCss.ts

125 lines5.1 KB

1import { themeCssValueFetches, themeCssWithoutDeclarations } from "@t3tools/shared/themeCss";
2​
3// Theme CSS comes from imported files and from agents, so it must not fetch: a
4// url() on an attribute selector can send what is on screen to another host.
5// The browser parses the text first, so the checks see normalized values and
6// CSS escapes in a function name cannot dodge them.
7​
8let themeSheet: CSSStyleSheet | null = null;
9let appliedCss = "";
10​
11type RuleParent = Pick<CSSStyleSheet, "cssRules" | "deleteRule">;
12​
13// @keyframes also has both members, but its deleteRule takes a keyframe selector.
14const isRuleParent = (rule: CSSRule): rule is CSSRule & RuleParent =>
15 "cssRules" in rule && "deleteRule" in rule && !(rule instanceof CSSKeyframesRule);
16​
17// A shorthand holding var() leaves its longhands reading "" until substitution.
18// item(), not indexing: Chromium's CSSPositionTryDescriptors returns undefined by index.
19function pendingLonghands(style: CSSStyleDeclaration): string[] {
20 return Array.from({ length: style.length }, (_, index) => style.item(index)).filter(
21 (property) => !property.startsWith("--") && style.getPropertyValue(property) === "",
22 );
24​
25/** Every declaration block the browser finds in `text`, parsed apart from the theme sheet. */
26function parsedStyles(text: string): CSSStyleDeclaration[] {
27 const styles: CSSStyleDeclaration[] = [];
28 const collect = (rules: CSSRuleList) => {
29 for (const rule of rules) {
30 if ("style" in rule && rule.style instanceof CSSStyleDeclaration) styles.push(rule.style);
31 if ("cssRules" in rule && rule.cssRules instanceof CSSRuleList) collect(rule.cssRules);
32 }
33 };
34 const sheet = new CSSStyleSheet();
35 sheet.replaceSync(text);
36 collect(sheet.cssRules);
37 return styles;
39​
40/**
41 * Whether a shorthand that `style` leaves pending can fetch. cssText shows its text until a later
42 * declaration overrides one of its longhands; `hiddenFetches` says what to make of one that then
43 * does not come back from parsing cssText.
44 */
45function pendingShorthandFetches(style: CSSStyleDeclaration, hiddenFetches: boolean): boolean {
46 const pending = pendingLonghands(style);
47 if (pending.length === 0) return false;
48 const text = style.cssText;
49 if (themeCssValueFetches(text)) return true;
50 if (!hiddenFetches) return false;
51 const shown = new Set(parsedStyles(`x{${text}}`).flatMap(pendingLonghands));
52 return pending.some((longhand) => !shown.has(longhand));
54​
55/**
56 * The theme's source without the var() shorthands that can fetch, so that none is left for a later
57 * declaration to hide. The browser parses each candidate alone, as rules and as a block, so
58 * escapes resolve as they will.
59 */
60function withoutFetchingShorthands(css: string): string {
61 return themeCssWithoutDeclarations(css, (candidate) =>
62 [...parsedStyles(candidate), ...parsedStyles(`x{${candidate}}`)].some((style) =>
63 pendingShorthandFetches(style, true),
64 ),
65 );
67​
68function stripDeclarations(rule: CSSRule): boolean {
69 if (!("style" in rule) || !(rule.style instanceof CSSStyleDeclaration)) return false;
70 for (let item = rule.style.length - 1; item >= 0; item--) {
71 const property = rule.style.item(item);
72 if (themeCssValueFetches(rule.style.getPropertyValue(property))) {
73 rule.style.removeProperty(property);
74 }
75 }
76 if (pendingShorthandFetches(rule.style, false)) {
77 for (const longhand of pendingLonghands(rule.style)) rule.style.removeProperty(longhand);
78 }
79 return true;
81​
82/** Keeps only rule shapes it can check, so a new at-rule that fetches is dropped by default. */
83function stripFetches(parent: RuleParent): void {
84 for (let index = parent.cssRules.length - 1; index >= 0; index--) {
85 const rule = parent.cssRules[index];
86 if (!rule) continue;
87 const hasStyle = stripDeclarations(rule);
88 if (rule instanceof CSSKeyframesRule) {
89 for (const frame of rule.cssRules) stripDeclarations(frame);
90 } else if (isRuleParent(rule)) {
91 stripFetches(rule);
92 } else if (rule instanceof CSSPropertyRule) {
93 // A registered property's initial value is used wherever var() reads it.
94 if (themeCssValueFetches(rule.initialValue ?? "")) parent.deleteRule(index);
95 } else if (
96 !hasStyle &&
97 !(rule instanceof CSSLayerStatementRule) &&
98 // Names a namespace without loading it. CSSOM refuses to delete one while style rules remain.
99 !(rule instanceof CSSNamespaceRule)
100 ) {
101 parent.deleteRule(index);
102 }
103 }
105​
106export function applyThemeCss(css: string | undefined): void {
107 if (typeof document === "undefined" || typeof CSSStyleSheet === "undefined") return;
108 const next = css ?? "";
109 if (next === appliedCss) return;
110 if (!themeSheet) {
111 // Adopted sheets order after the document's own, and they cannot hold @import.
112 themeSheet = new CSSStyleSheet();
113 document.adoptedStyleSheets = [...document.adoptedStyleSheets, themeSheet];
114 }
115 try {
116 themeSheet.replaceSync(withoutFetchingShorthands(next));
117 stripFetches(themeSheet);
118 } catch (error) {
119 // A half-cleaned sheet can still fetch; leave none applied so the next call retries.
120 themeSheet.replaceSync("");
121 appliedCss = "";
122 throw error;
123 }
124 appliedCss = next;