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

themeCss.ts

117 lines4.8 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.
18function pendingLonghands(style: CSSStyleDeclaration): string[] {
19 return Array.from(style).filter(
20 (property) => !property.startsWith("--") && style.getPropertyValue(property) === "",
21 );
23​
24/** Every declaration block the browser finds in `text`, parsed apart from the theme sheet. */
25function parsedStyles(text: string): CSSStyleDeclaration[] {
26 const styles: CSSStyleDeclaration[] = [];
27 const collect = (rules: CSSRuleList) => {
28 for (const rule of rules) {
29 if ("style" in rule && rule.style instanceof CSSStyleDeclaration) styles.push(rule.style);
30 if ("cssRules" in rule && rule.cssRules instanceof CSSRuleList) collect(rule.cssRules);
31 }
32 };
33 const sheet = new CSSStyleSheet();
34 sheet.replaceSync(text);
35 collect(sheet.cssRules);
36 return styles;
38​
39/**
40 * Whether a shorthand that `style` leaves pending can fetch. cssText shows its text until a later
41 * declaration overrides one of its longhands; `hiddenFetches` says what to make of one that then
42 * does not come back from parsing cssText.
43 */
44function pendingShorthandFetches(style: CSSStyleDeclaration, hiddenFetches: boolean): boolean {
45 const pending = pendingLonghands(style);
46 if (pending.length === 0) return false;
47 const text = style.cssText;
48 if (themeCssValueFetches(text)) return true;
49 if (!hiddenFetches) return false;
50 const shown = new Set(parsedStyles(`x{${text}}`).flatMap(pendingLonghands));
51 return pending.some((longhand) => !shown.has(longhand));
53​
54/**
55 * The theme's source without the var() shorthands that can fetch, so that none is left for a later
56 * declaration to hide. The browser parses each candidate alone, as rules and as a block, so
57 * escapes resolve as they will.
58 */
59function withoutFetchingShorthands(css: string): string {
60 return themeCssWithoutDeclarations(css, (candidate) =>
61 [...parsedStyles(candidate), ...parsedStyles(`x{${candidate}}`)].some((style) =>
62 pendingShorthandFetches(style, true),
63 ),
64 );
66​
67function stripDeclarations(rule: CSSRule): boolean {
68 if (!("style" in rule) || !(rule.style instanceof CSSStyleDeclaration)) return false;
69 for (let item = rule.style.length - 1; item >= 0; item--) {
70 const property = rule.style.item(item);
71 if (themeCssValueFetches(rule.style.getPropertyValue(property))) {
72 rule.style.removeProperty(property);
73 }
74 }
75 if (pendingShorthandFetches(rule.style, false)) {
76 for (const longhand of pendingLonghands(rule.style)) rule.style.removeProperty(longhand);
77 }
78 return true;
80​
81/** Keeps only rule shapes it can check, so a new at-rule that fetches is dropped by default. */
82function stripFetches(parent: RuleParent): void {
83 for (let index = parent.cssRules.length - 1; index >= 0; index--) {
84 const rule = parent.cssRules[index];
85 if (!rule) continue;
86 const hasStyle = stripDeclarations(rule);
87 if (rule instanceof CSSKeyframesRule) {
88 for (const frame of rule.cssRules) stripDeclarations(frame);
89 } else if (isRuleParent(rule)) {
90 stripFetches(rule);
91 } else if (rule instanceof CSSPropertyRule) {
92 // A registered property's initial value is used wherever var() reads it.
93 if (themeCssValueFetches(rule.initialValue ?? "")) parent.deleteRule(index);
94 } else if (
95 !hasStyle &&
96 !(rule instanceof CSSLayerStatementRule) &&
97 // Names a namespace without loading it. CSSOM refuses to delete one while style rules remain.
98 !(rule instanceof CSSNamespaceRule)
99 ) {
100 parent.deleteRule(index);
101 }
102 }
104​
105export function applyThemeCss(css: string | undefined): void {
106 if (typeof document === "undefined" || typeof CSSStyleSheet === "undefined") return;
107 const next = css ?? "";
108 if (next === appliedCss) return;
109 appliedCss = next;
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 themeSheet.replaceSync(withoutFetchingShorthands(next));
116 stripFetches(themeSheet);