diff --git a/packages/runtime/src/themeRuntime.ts b/packages/runtime/src/themeRuntime.ts index 8f07975..ce7c927 100644 --- a/packages/runtime/src/themeRuntime.ts +++ b/packages/runtime/src/themeRuntime.ts @@ -21,18 +21,62 @@ export function resolvedFonts(font: FontSpec, siteStack: string): ResolvedFonts })) as ResolvedFonts; } -/** Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s. */ +type RuleNode = { selectorText?: string; style?: RuleLike['style']; cssRules?: ArrayLike; conditionText?: string; type?: number; constructor?: { name?: string } }; +const isSupports = (rule: RuleNode) => rule.type === 12 || rule.constructor?.name === 'CSSSupportsRule'; + +/** + * A style rule as it takes effect. Tailwind 4 writes an opacity utility as a fallback plus the real + * value in a nested `@supports`: + * `.bg-white\/15 { background-color: var(--white); @supports (color: color-mix(in lab, red, red)) { background-color: color-mix(in oklab, var(--white) 15%, transparent) } }`. + * Read alone, the outer declaration is a solid white fill; where the browser passes the condition the + * nested one is what paints, so it answers for the rule. + */ +function effectiveRule(rule: RuleNode, supported: (condition: string) => boolean): RuleLike { + const overrides: Array = []; + for (const child of Array.from(rule.cssRules ?? [])) { + if (!isSupports(child) || !supported(child.conditionText ?? '')) continue; + for (const inner of Array.from(child.cssRules ?? [])) { + // Bare declarations inside the group: a CSSNestedDeclarations, or `& { }` in older engines. + if (inner.style && (inner.selectorText === undefined || inner.selectorText === '&')) overrides.push(inner.style); + } + } + if (!overrides.length) return rule as RuleLike; + const outer = rule.style!; + return { + selectorText: rule.selectorText!, + style: { + getPropertyValue(name) { + for (let i = overrides.length - 1; i >= 0; i--) { const value = overrides[i]!.getPropertyValue(name); if (value) return value; } + return outer.getPropertyValue(name); + }, + length: outer.length, + }, + }; +} + +/** + * Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s, each as + * it takes effect (`effectiveRule`). A `@supports` group the browser does not pass is left out. + */ export function collectRules(doc: Document, own: HTMLStyleElement | null): RuleLike[] { const rules: RuleLike[] = []; - const walk = (list: CSSRuleList) => { + const css = (doc.defaultView as (Window & typeof globalThis) | null)?.CSS; + const verdicts = new Map(); + const supported = (condition: string) => { + if (!condition || !css?.supports) return true; + let verdict = verdicts.get(condition); + if (verdict === undefined) { try { verdict = css.supports(condition); } catch { verdict = true; } verdicts.set(condition, verdict); } + return verdict; + }; + const walk = (list: ArrayLike) => { for (const rule of Array.from(list)) { - if ('selectorText' in rule && 'style' in rule) rules.push(rule as unknown as RuleLike); - else if ('cssRules' in rule && !('selectorText' in rule)) walk((rule as CSSGroupingRule).cssRules); + if (rule.selectorText !== undefined && rule.style) rules.push(effectiveRule(rule, supported)); + else if (rule.cssRules && rule.selectorText === undefined && (!isSupports(rule) || supported(rule.conditionText ?? ''))) walk(rule.cssRules); } }; for (const sheet of Array.from(doc.styleSheets)) { if (own && sheet.ownerNode === own) continue; - try { walk(sheet.cssRules); } catch { /* Cross-origin sheet. */ } + try { walk(sheet.cssRules as unknown as ArrayLike); } catch { /* Cross-origin sheet. */ } } return rules; } diff --git a/packages/runtime/src/themeSpec.ts b/packages/runtime/src/themeSpec.ts index cd31e7a..b17c400 100644 --- a/packages/runtime/src/themeSpec.ts +++ b/packages/runtime/src/themeSpec.ts @@ -132,7 +132,7 @@ export const isHex = (value: unknown): value is string => typeof value === 'stri export const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${+alpha.toFixed(3)})`; /** Moves `color` toward black or white until it reaches `ratio` against every surface. */ -function reach(color: string, surfaces: string[], ratio: number): string { +export function reach(color: string, surfaces: string[], ratio: number): string { const worst = (c: string) => Math.min(...surfaces.map(s => contrastRatio(c, s))); if (worst(color) >= ratio) return color; const lightSurfaces = surfaces.reduce((sum, s) => sum + relativeLuminance(s), 0) / surfaces.length > 0.18; diff --git a/packages/runtime/tests/themeEngine.test.ts b/packages/runtime/tests/themeEngine.test.ts index cce6e35..adb12ab 100644 --- a/packages/runtime/tests/themeEngine.test.ts +++ b/packages/runtime/tests/themeEngine.test.ts @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { FONT_ROLE_NAMES, MONO_FONT, contrastRatio } from '../src/themeApi.ts'; import { choiceForId, createThemeCatalog, serializeChoice, MAX_USER_THEMES } from '../src/themeChoice.ts'; -import { SNAPSHOT_LOCAL_MAX, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts'; +import { SNAPSHOT_LOCAL_MAX, collectRules, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts'; import { BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, FONT_CHOICES, ROLE_LIMITS, applyOverrides, backgroundLayers, ensureContrast, fontChoiceOf, fontStack, isNeutral, pageBackgroundCss, parseThemeJson, resolveFontRoles, sanitizeSpec, withFamily, withRoles, type ThemeSpec, @@ -197,3 +197,58 @@ test('garbage in storage is no snapshot', () => { stores.local!.setItem('wb:theme-snapshot', JSON.stringify({ key: 1, css: 'a{}' })); assert.equal(readSnapshot(stores), null); }); + +// collectRules: the site's rules as they take effect + +type FakeRule = { selectorText?: string; style?: { getPropertyValue(name: string): string; length: number }; cssRules?: FakeRule[]; conditionText?: string; type?: number }; +const decl = (values: Record) => ({ getPropertyValue: (name: string) => values[name] ?? '', length: Object.keys(values).length }); +const styleRule = (selectorText: string, values: Record, cssRules: FakeRule[] = []): FakeRule => ({ selectorText, style: decl(values), cssRules }); +const supportsRule = (conditionText: string, cssRules: FakeRule[]): FakeRule => ({ type: 12, conditionText, cssRules }); +const mediaRule = (conditionText: string, cssRules: FakeRule[]): FakeRule => ({ type: 4, conditionText, cssRules }); +const fakeDoc = (rules: FakeRule[], supports = (_condition: string) => true) => ({ styleSheets: [{ ownerNode: null, cssRules: rules }], defaultView: { CSS: { supports } } }) as unknown as Document; +const MIX = '(color: color-mix(in lab, red, red))'; + +test('collectRules reads a Tailwind opacity utility as its nested @supports value, not its solid fallback', () => { + const rules = collectRules(fakeDoc([ + styleRule('.dark\:bg-white\/15', { 'background-color': 'var(--x-white)', 'border-radius': '9999px' }, [ + supportsRule(MIX, [{ style: decl({ 'background-color': 'color-mix(in oklab, var(--x-white) 15%, transparent)' }) }]), + ]), + styleRule('.plain', { color: 'rgb(1, 2, 3)' }), + ]), null); + assert.equal(rules.length, 2, 'one rule per selector, the nested declarations are not a rule of their own'); + assert.equal(rules[0]!.selectorText, '.dark\:bg-white\/15'); + assert.equal(rules[0]!.style.getPropertyValue('background-color'), 'color-mix(in oklab, var(--x-white) 15%, transparent)'); + assert.equal(rules[0]!.style.getPropertyValue('border-radius'), '9999px', 'what the group does not re-declare stays the rule\'s own'); + assert.equal(rules[0]!.style.length, 2); + assert.equal(rules[1]!.style.getPropertyValue('color'), 'rgb(1, 2, 3)'); +}); + +test('collectRules: the `& { }` form of nested declarations counts, a nested rule with its own selector does not', () => { + const [rule] = collectRules(fakeDoc([ + styleRule('.border-accent\/50', { 'border-color': 'hsl(var(--accent))' }, [ + supportsRule(MIX, [styleRule('&', { 'border-color': 'color-mix(in oklab, hsl(var(--accent)) 50%, transparent)' }), styleRule('&:hover', { 'border-color': 'red' })]), + mediaRule('(hover: hover)', [{ style: decl({ 'border-color': 'blue' }) }]), + ]), + ]), null); + assert.equal(rule!.style.getPropertyValue('border-color'), 'color-mix(in oklab, hsl(var(--accent)) 50%, transparent)'); +}); + +test('collectRules keeps the fallback where the browser fails the @supports condition, and skips such top-level groups', () => { + const rules = collectRules(fakeDoc([ + styleRule('.bg-white\/15', { 'background-color': 'var(--x-white)' }, [supportsRule(MIX, [{ style: decl({ 'background-color': 'color-mix(in oklab, var(--x-white) 15%, transparent)' }) }])]), + supportsRule(MIX, [styleRule('.hover\:bg-white\/10:hover', { 'background-color': 'color-mix(in oklab, var(--x-white) 10%, transparent)' })]), + mediaRule('(hover: hover)', [styleRule('.in-media', { color: 'red' })]), + ], () => false), null); + assert.deepEqual(rules.map(rule => rule.selectorText), ['.bg-white\/15', '.in-media']); + assert.equal(rules[0]!.style.getPropertyValue('background-color'), 'var(--x-white)'); +}); + +test('collectRules leaves the engine\'s own sheet out and survives a cross-origin sheet', () => { + const own = { id: 'own' } as unknown as HTMLStyleElement; + const doc = { styleSheets: [ + { ownerNode: own, cssRules: [styleRule('.ours', { color: 'red' })] }, + { ownerNode: null, get cssRules(): FakeRule[] { throw new Error('SecurityError'); } }, + { ownerNode: null, cssRules: [supportsRule(MIX, [mediaRule('(hover: hover)', [styleRule('.deep', { color: 'red' })])])] }, + ], defaultView: null } as unknown as Document; + assert.deepEqual(collectRules(doc, own).map(rule => rule.selectorText), ['.deep']); +});