🖌️ fix: Apply Controlled Themes Before Paint and Theme Prose Links, Inline Code and QR Backdrops (#16480)

* fix: Apply controlled themes before paint and give prose links, inline code and QR backdrops theme roles

ThemeProvider folds a controlled theme prop change into state during the
render that delivers it and applies the theme in a layout effect, so a
deployment theme, a shared link's theme and the viewer's own theme reach
the root before the commit paints. Storage writes stay after the commit.

Adds rgb-link-prose (link in light, primary text in dark, following a
theme's own link) and registers rgb-surface-qr, and paints inline prose
code with the surface-active-alt and surface-hover-alt roles.

* test: Record the frames a controlled theme paints and the prose and QR roles
This commit is contained in:
Marco Beretta 2026-09-29 16:50:00 +02:00 • committed by GitHub
parent f546dc2bee
commit 364bf27210
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 690 additions and 114 deletions

View file

@ -138,7 +138,7 @@ const DeploymentThemeOverrideContext = createContext<(override: ThemeOverride) =
* absent theme included, until the route unmounts. A route whose theme source
* failed passes `ready` with no theme, so the viewer's theme does not stand in
* for the link's. Registered in a layout effect so the wrapper re-renders in the
* same commit; `ThemeProvider` still applies the change in its own effects.
* same commit, and `ThemeProvider` applies the change before that commit paints.
*/
export function useDeploymentThemeOverride(ready: boolean, theme: DeploymentThemeValue) {
const setOverride = useContext(DeploymentThemeOverrideContext);

View file

@ -231,6 +231,7 @@ html {
--link: var(--blue-600);
--link-hover: var(--blue-700);
--link-visited: 147 51 234;
--link-prose: var(--link);
--accent-primary: 18 110 107;
--accent-primary-hover: 10 79 83;
--ring-primary: var(--gray-500);
@ -397,6 +398,7 @@ html {
--link: var(--blue-400);
--link-hover: var(--blue-300);
--link-visited: 192 132 252;
--link-prose: var(--text-primary);
--accent-primary: 65 167 157;
--accent-primary-hover: 109 200 185;
--header-primary: var(--gray-700);
@ -1094,12 +1096,12 @@ p > small {
color: var(--tw-prose-code);
font-size: 0.875em;
font-weight: 600;
background-color: rgb(var(--gray-200));
background-color: rgb(var(--surface-active-alt));
padding: 0.125rem 0.25rem;
border-radius: 0.35rem;
}
.dark .prose :where(code):not(:where([class~='not-prose'] *)):not(:where(pre *)) {
background-color: rgb(var(--gray-600));
background-color: rgb(var(--surface-hover-alt));
}
.prose :where(a code):not(:where([class~='not-prose'] *)) {
color: inherit;
@ -1192,13 +1194,13 @@ p > small {
}
/* Prose colours read the theme roles, so a theme definition repaints message
* content. Each variable takes the role that reproduces the default palette
* (body is `text-secondary`, #424242 in light); dark links stay on
* `text-primary` because the default dark set renders them white. */
* (body is `text-secondary`, #424242 in light). Links read `link-prose`, which is
* `link` in light and `text-primary` in dark, where the default set renders them white. */
.prose {
--tw-prose-body: rgb(var(--text-secondary));
--tw-prose-headings: rgb(var(--text-primary));
--tw-prose-lead: rgb(var(--text-secondary));
--tw-prose-links: rgb(var(--link));
--tw-prose-links: rgb(var(--link-prose));
--tw-prose-bold: rgb(var(--text-primary));
--tw-prose-counters: rgb(var(--text-tertiary));
--tw-prose-bullets: rgb(var(--border-medium));
@ -1214,7 +1216,7 @@ p > small {
--tw-prose-invert-body: rgb(var(--text-secondary));
--tw-prose-invert-headings: rgb(var(--text-primary));
--tw-prose-invert-lead: rgb(var(--text-tertiary));
--tw-prose-invert-links: rgb(var(--text-primary));
--tw-prose-invert-links: rgb(var(--link-prose));
--tw-prose-invert-bold: rgb(var(--text-primary));
--tw-prose-invert-counters: rgb(var(--text-tertiary));
--tw-prose-invert-bullets: rgb(var(--border-medium));

View file

@ -0,0 +1,251 @@
import { expect, test } from '@playwright/test';
import type { Page } from '@playwright/test';
import type { IThemeRGB } from '../../../../packages/client/src/theme/types';
import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse';
import { defaultTheme } from '../../../../packages/client/src/theme/themes/default';
import { darkTheme } from '../../../../packages/client/src/theme/themes/dark';
import {
sendMessageAndWaitForCompletion,
selectMockEndpoint,
getAccessToken,
MOCK_ENDPOINTS,
NEW_CHAT_PATH,
} from '../helpers';
import { getE2EUser } from '../../../setup/user';
import { themeValue } from './style.helpers';
/**
* What the browser paints while a controlled theme arrives, and the roles that
* Markdown and the share dialog read. `/api/config` carries the viewer tenant's
* theme and `/api/share/:shareId/config` the link tenant's, layered over the real
* server response. Frames are sampled in `requestAnimationFrame`, which runs just
* before each paint, so a sample is what the next frame shows.
*/
type Mode = 'light' | 'dark';
/** `null` serves a payload with no `interface.theme`. */
type ConfigTheme = string | Record<string, unknown> | null;
type Frame = { marker: boolean; theme: string | null; surface: string };
const VIEWER_THEME = {
version: 1,
name: 'viewer',
modes: {
light: { colors: { 'rgb-surface-primary': '240 244 255' } },
dark: { colors: { 'rgb-surface-primary': '12 16 32' } },
},
};
/** Names a link and a QR backdrop and leaves the prose link role to its fallback. */
const LINK_THEME = {
version: 1,
name: 'link-reference',
modes: {
light: { colors: { 'rgb-link': '160 40 120', 'rgb-surface-qr': '250 246 230' } },
dark: { colors: { 'rgb-link': '250 200 90', 'rgb-surface-qr': '250 246 230' } },
},
};
const withTheme = (payload: { interface?: Record<string, unknown> }, theme: ConfigTheme) => {
const served = { ...payload.interface };
delete served.theme;
if (theme !== null) {
served.theme = theme;
}
return { ...payload, interface: served };
};
async function serveThemes(page: Page, viewer: ConfigTheme, link: ConfigTheme = viewer) {
await page.route(
(url) => url.pathname === '/api/config',
async (route) => {
const response = await route.fetch();
await route.fulfill({ response, json: withTheme(await response.json(), viewer) });
},
);
await page.route(
(url) => /^\/api\/share\/[^/]+\/config$/.test(url.pathname),
async (route) => {
const response = await route.fetch();
await route.fulfill({ response, json: withTheme(await response.json(), link) });
},
);
}
/** Records every frame from the first one that shows `selector`, before any app script runs. */
async function recordFrames(page: Page, selector: string) {
await page.addInitScript((marker) => {
const frames: Array<{ marker: boolean; theme: string | null; surface: string }> = [];
(window as unknown as { __themeFrames: typeof frames }).__themeFrames = frames;
const sample = () => {
const root = document.documentElement;
frames.push({
marker: document.querySelector(marker) != null,
theme: root.getAttribute('data-theme'),
surface: getComputedStyle(root).getPropertyValue('--surface-primary').trim(),
});
requestAnimationFrame(sample);
};
requestAnimationFrame(sample);
}, selector);
}
const shownFrames = async (page: Page): Promise<Frame[]> =>
(
await page.evaluate(() => (window as unknown as { __themeFrames: Frame[] }).__themeFrames ?? [])
).filter((frame) => frame.marker);
async function resolvedMode(page: Page): Promise<Mode> {
const dark = await page.evaluate(() => document.documentElement.classList.contains('dark'));
return dark ? 'dark' : 'light';
}
async function createSharedLink(page: Page): Promise<string> {
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
await sendMessageAndWaitForCompletion(page, `Theme paint ${Date.now()}`);
await expect(page).toHaveURL(/\/c\/(?!new)[0-9a-fA-F-]{36}$/);
const conversationId = new URL(page.url()).pathname.split('/').pop();
const token = await getAccessToken(page);
const response = await page.request.post(`/api/share/${conversationId}`, {
headers: { Authorization: `Bearer ${token}` },
data: {},
});
expect(response.ok()).toBeTruthy();
const { shareId } = (await response.json()) as { shareId?: string };
if (!shareId) {
throw new Error('Expected create-share response to include a shareId');
}
return shareId;
}
/** Colors of a Markdown link, inline code and the QR backdrop, as the shipped CSS paints them. */
function paintRoles(page: Page) {
return page.evaluate(() => {
const host = document.createElement('section');
const prose = document.createElement('div');
prose.className = 'prose dark:prose-invert markdown';
const paragraph = document.createElement('p');
const link = document.createElement('a');
link.href = '#probe';
link.textContent = 'link';
const code = document.createElement('code');
code.textContent = 'code';
paragraph.append(link, ' ', code);
prose.append(paragraph);
const qr = document.createElement('div');
qr.className = 'bg-surface-qr';
host.append(prose, qr);
document.body.append(host);
const read = (node: Element, property: string) =>
getComputedStyle(node).getPropertyValue(property).trim();
const roles = {
link: read(link, 'color'),
codeFill: read(code, 'background-color'),
qr: read(qr, 'background-color'),
};
host.remove();
return roles;
});
}
const rgb = (channels: string | undefined) => `rgb(${(channels ?? '').split(' ').join(', ')})`;
test.describe('controlled theme paint', () => {
test("a shared link's first frame of the conversation already wears the link tenant's theme @scenario:shared-link-first-frame-wears-link-theme", async ({
page,
}) => {
test.setTimeout(120000);
await serveThemes(page, VIEWER_THEME, 'clickhouse');
const shareId = await createSharedLink(page);
await recordFrames(page, '[data-testid="messages-view"]');
await page.goto(`/share/${shareId}`, { timeout: 10000 });
await expect(page.getByTestId('messages-view')).toBeVisible({ timeout: 20000 });
await expect.poll(async () => (await shownFrames(page)).length).toBeGreaterThan(2);
const surface =
clickHouseTheme.modes[await resolvedMode(page)]?.colors?.['rgb-surface-primary'];
const frames = await shownFrames(page);
expect(frames.filter((frame) => frame.theme !== 'clickhouse')).toEqual([]);
expect(frames.filter((frame) => frame.surface !== surface)).toEqual([]);
});
test.describe('signed out', () => {
test.use({ storageState: { cookies: [], origins: [] } });
test('the login form first paints in the deployment theme @scenario:login-first-frame-wears-deployment-theme', async ({
page,
}) => {
test.setTimeout(60000);
await serveThemes(page, 'clickhouse');
await recordFrames(page, '[data-testid="login-button"]');
await page.goto('/login');
await expect(page.getByTestId('login-button')).toBeVisible({ timeout: 20000 });
await expect.poll(async () => (await shownFrames(page)).length).toBeGreaterThan(2);
const frames = await shownFrames(page);
expect(frames.filter((frame) => frame.theme !== 'clickhouse')).toEqual([]);
const user = getE2EUser();
await page.getByLabel('Email').fill(user.email);
await page.getByLabel('Password').fill(user.password);
await page.getByTestId('login-button').click();
await page.waitForURL(/\/c\/new/, { timeout: 20000 });
await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
});
});
test('Markdown links, inline code and the QR backdrop keep the default look @scenario:prose-and-qr-roles-keep-default-look', async ({
page,
}) => {
test.setTimeout(60000);
await serveThemes(page, null);
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({
timeout: 20000,
});
const dark = (await resolvedMode(page)) === 'dark';
const roles = await paintRoles(page);
expect(roles.link).toBe(rgb(dark ? darkTheme['rgb-text-primary'] : defaultTheme['rgb-link']));
expect(roles.codeFill).toBe(
rgb(dark ? darkTheme['rgb-surface-hover-alt'] : defaultTheme['rgb-surface-active-alt']),
);
expect(roles.qr).toBe('rgb(255, 255, 255)');
});
test('the ClickHouse theme paints its own link, code fill and QR backdrop @scenario:clickhouse-prose-and-qr-roles', async ({
page,
}) => {
test.setTimeout(60000);
await serveThemes(page, 'clickhouse');
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
const dark = (await resolvedMode(page)) === 'dark';
const colors: IThemeRGB = clickHouseTheme.modes[dark ? 'dark' : 'light']?.colors ?? {};
const roles = await paintRoles(page);
expect(roles.link).toBe(rgb(colors['rgb-link-prose']));
expect(roles.codeFill).toBe(
rgb(dark ? colors['rgb-surface-hover-alt'] : colors['rgb-surface-active-alt']),
);
expect(roles.qr).toBe(rgb(colors['rgb-surface-qr']));
});
test('a theme that names only its link colours Markdown links in both modes and can recolour the QR backdrop @scenario:theme-link-reaches-prose-links', async ({
page,
}) => {
test.setTimeout(60000);
await serveThemes(page, LINK_THEME);
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
await expect(page.locator('html')).toHaveAttribute('data-theme', 'link-reference');
const mode = await resolvedMode(page);
const roles = await paintRoles(page);
expect(roles.link).toBe(rgb(LINK_THEME.modes[mode].colors['rgb-link']));
expect(roles.qr).toBe(rgb(LINK_THEME.modes[mode].colors['rgb-surface-qr']));
expect(await themeValue(page, '--surface-qr')).toBe('250 246 230');
});
});

View file

@ -264,6 +264,7 @@ function MyComponent() {
- `text-text-warning` - Warning text color
- `text-text-destructive` - Destructive/error text color
- `text-text-on-status` - Text color for strong status surfaces
- `text-link-prose` - Links in rendered Markdown (`link` in light, primary text in dark by default)
### Surface Colors
@ -277,6 +278,7 @@ function MyComponent() {
- `bg-surface-chat` - Chat interface background
- `bg-surface-code` - Code block chrome: toolbar, output and result switcher
- `bg-surface-code-body` - Code block pane behind the highlighted code
- `bg-surface-qr` - Backdrop behind a QR code, kept light in every mode so it scans
### Border Colors

View file

@ -1,4 +1,5 @@
import '@testing-library/jest-dom';
import { useLayoutEffect } from 'react';
import { act, render, screen, waitFor } from '@testing-library/react';
import {
ThemeProvider,
@ -195,6 +196,128 @@ describe('ThemeProvider', () => {
expect(document.documentElement.style.getPropertyValue('--accent-primary')).toBe('1 2 3');
});
/** The probe wraps the provider, so its layout effect runs after the provider's in the same
* commit and before the browser paints it: what it reads is what the first frame shows. */
describe('a controlled theme change reaches the root before the commit paints', () => {
type Painted = { accent: string; name?: string; dark: boolean };
const deployment = (name: string, accent: string) => ({
version: 1 as const,
name,
modes: {
light: { colors: { 'rgb-accent-primary': accent } },
dark: { colors: { 'rgb-accent-primary': accent } },
},
});
function PaintProbe({ children, frames }: { children: React.ReactNode; frames: Painted[] }) {
useLayoutEffect(() => {
const root = document.documentElement;
frames.push({
accent: root.style.getPropertyValue('--accent-primary'),
name: root.dataset.theme,
dark: root.classList.contains('dark'),
});
});
return <>{children}</>;
}
const lastFrame = (frames: Painted[]) => frames[frames.length - 1];
it('on first load, on a replaced definition and when the definition is withdrawn', () => {
const frames: Painted[] = [];
const { rerender } = render(
<PaintProbe frames={frames}>
<ThemeProvider
initialTheme="light"
persistThemeDefinition={false}
themeDefinition={deployment('viewer', '1 2 3')}
>
<Controls />
</ThemeProvider>
</PaintProbe>,
);
expect(frames[0]).toEqual({ accent: '1 2 3', name: 'viewer', dark: false });
rerender(
<PaintProbe frames={frames}>
<ThemeProvider
initialTheme="light"
persistThemeDefinition={false}
themeDefinition={deployment('shared-link', '4 5 6')}
>
<Controls />
</ThemeProvider>
</PaintProbe>,
);
expect(frames[1]).toEqual({ accent: '4 5 6', name: 'shared-link', dark: false });
rerender(
<PaintProbe frames={frames}>
<ThemeProvider initialTheme="light" persistThemeDefinition={false}>
<Controls />
</ThemeProvider>
</PaintProbe>,
);
expect(frames[2]).toEqual({ accent: '', name: undefined, dark: false });
});
it('on legacy colors and on a controlled switch to dark', () => {
const frames: Painted[] = [];
const { rerender } = render(
<PaintProbe frames={frames}>
<ThemeProvider initialTheme="light" persistThemeDefinition={false}>
<Controls />
</ThemeProvider>
</PaintProbe>,
);
expect(lastFrame(frames)).toEqual({ accent: '', name: undefined, dark: false });
rerender(
<PaintProbe frames={frames}>
<ThemeProvider
initialTheme="dark"
persistThemeDefinition={false}
themeRGB={{ 'rgb-accent-primary': '7 8 9' }}
themeName="environment"
>
<Controls />
</ThemeProvider>
</PaintProbe>,
);
expect(lastFrame(frames)).toEqual({ accent: '7 8 9', name: 'environment', dark: true });
});
it('persists a controlled change once, after its commit', () => {
const setItem = jest.spyOn(Storage.prototype, 'setItem');
const { rerender } = render(
<ThemeProvider initialTheme="light" themeDefinition={deployment('first', '1 2 3')}>
<Controls />
</ThemeProvider>,
);
setItem.mockClear();
rerender(
<ThemeProvider initialTheme="light" themeDefinition={deployment('second', '4 5 6')}>
<Controls />
</ThemeProvider>,
);
rerender(
<ThemeProvider
initialTheme="light"
persistThemeDefinition={false}
themeDefinition={deployment('second', '4 5 6')}
>
<Controls />
</ThemeProvider>,
);
const definitionWrites = setItem.mock.calls.filter(([key]) => key === 'theme-definition');
expect(definitionWrites).toHaveLength(1);
expect(JSON.parse(definitionWrites[0][1]).name).toBe('second');
setItem.mockRestore();
});
});
it('keeps valid legacy overrides when another token is malformed', async () => {
render(
<ThemeProvider

View file

@ -3,6 +3,7 @@ import React, {
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
@ -66,6 +67,27 @@ type ThemePropSnapshot = Pick<
'initialTheme' | 'themeDefinition' | 'themeName' | 'themeRGB'
>;
type ThemeState = {
definition?: ThemeDefinition;
legacyColors?: IThemeRGB;
name?: string;
};
type StorageWrite = readonly [key: string, value?: string];
type ThemeTransition = {
state: ThemeState;
writes: StorageWrite[];
};
/** A controlled prop change resolved during render; its storage writes wait for the commit. */
type ControlledThemeSync = {
props: ThemePropSnapshot;
controlled: boolean;
writes: StorageWrite[];
appearance?: AppearanceMode;
};
type ThemeContextType = {
theme: AppearanceMode;
setTheme: (theme: string) => void;
@ -272,6 +294,119 @@ const getStoredThemeState = (): InitialThemeState => {
const getInitialThemeName = (): string | undefined => readStorage(THEME_NAME_KEY) ?? undefined;
/**
* Layout effects run before the browser paints the commit that scheduled them,
* which is what keeps a theme change from showing a frame of the previous one.
* The server has no paint and warns on layout effects, so it takes the passive form.
*/
const useBeforePaintEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
const defineTheme = (definition?: ThemeDefinition): ThemeTransition => ({
state: { definition, legacyColors: undefined, name: definition?.name },
writes: [
[THEME_DEFINITION_KEY, definition ? JSON.stringify(definition) : undefined],
[THEME_COLORS_KEY],
[THEME_SOURCE_KEY, definition ? 'definition' : undefined],
[THEME_NAME_KEY, definition?.name],
],
});
const applyLegacyColors = (current: ThemeState, colors?: IThemeRGB): ThemeTransition => {
const definition = colors
? fromLegacyTheme(colors, current.definition?.name ?? current.name)
: undefined;
const legacyColors = definition?.modes.light?.colors;
return {
state: { definition, legacyColors, name: definition?.name },
writes: [
[THEME_DEFINITION_KEY, definition ? JSON.stringify(definition) : undefined],
[THEME_NAME_KEY, definition?.name],
[THEME_COLORS_KEY, legacyColors ? JSON.stringify(legacyColors) : undefined],
[THEME_SOURCE_KEY, definition ? 'legacy' : undefined],
],
};
};
const renameTheme = (current: ThemeState, name?: string): ThemeTransition => {
const nextName = name?.trim() || (current.definition ? 'custom' : undefined);
if (!nextName || !current.definition) {
return { state: { ...current, name: nextName }, writes: [[THEME_NAME_KEY, nextName]] };
}
const definition = { ...current.definition, name: nextName };
return {
state: { ...current, definition, name: nextName },
writes: [
[THEME_NAME_KEY, nextName],
[THEME_DEFINITION_KEY, JSON.stringify(definition)],
[THEME_SOURCE_KEY, current.legacyColors ? 'legacy' : 'definition'],
],
};
};
const sameThemeProps = (a: ThemePropSnapshot, b: ThemePropSnapshot): boolean =>
a.initialTheme === b.initialTheme &&
a.themeDefinition === b.themeDefinition &&
a.themeName === b.themeName &&
a.themeRGB === b.themeRGB;
/**
* Folds a change of the controlled props into the theme state, in the order the
* props take precedence: a valid definition, then legacy colors, then clearing a
* theme the props installed, then the name. Pure, so it can run during render.
*/
const syncControlledTheme = (
previous: ThemePropSnapshot,
next: ThemePropSnapshot,
current: ThemeState,
controlled: boolean,
): ThemeTransition & Omit<ControlledThemeSync, 'props' | 'writes'> => {
const definitionChanged = next.themeDefinition !== previous.themeDefinition;
const legacyColorsChanged = next.themeRGB !== previous.themeRGB;
const switchedToLegacyColors =
definitionChanged && !next.themeDefinition && next.themeRGB !== undefined;
let state = current;
let writes: StorageWrite[] = [];
let nextControlled = controlled;
let clearedControlledDefinition = false;
const apply = (transition: ThemeTransition) => {
state = transition.state;
writes = [...writes, ...transition.writes];
};
if (definitionChanged || legacyColorsChanged) {
if (next.themeDefinition) {
if (isValidThemeDefinition(next.themeDefinition)) {
apply(defineTheme(next.themeDefinition));
nextControlled = true;
}
} else if (next.themeRGB) {
apply(applyLegacyColors(state, next.themeRGB));
nextControlled = true;
} else if (controlled) {
apply(defineTheme(undefined));
nextControlled = false;
clearedControlledDefinition = true;
}
}
if (
!next.themeDefinition &&
(next.themeName !== previous.themeName || switchedToLegacyColors || clearedControlledDefinition)
) {
apply(renameTheme(state, next.themeName));
}
const appearance =
next.initialTheme !== previous.initialTheme &&
next.initialTheme &&
isAppearanceMode(next.initialTheme)
? next.initialTheme
: undefined;
return { state, writes, controlled: nextControlled, appearance };
};
const captureThemeDOM = (root: HTMLElement): ThemeDOMSnapshot => ({
properties: new Map(
themeOwnedProperties.map((property) => [
@ -383,19 +518,48 @@ export function ThemeProvider({
const themeNameRef = useRef(themeName);
themeNameRef.current = themeName;
const persistedInitialProps = useRef(false);
const previousThemeProps = useRef<ThemePropSnapshot>({
const themeProps: ThemePropSnapshot = {
initialTheme,
themeDefinition: propThemeDefinition,
themeName: propThemeName,
themeRGB: propThemeRGB,
});
const controlledThemeActive = useRef(
Boolean(
};
const [controlledSync, setControlledSync] = useState<ControlledThemeSync>(() => ({
props: themeProps,
controlled: Boolean(
(propThemeDefinition && isValidThemeDefinition(propThemeDefinition)) ||
(!propThemeDefinition && propThemeRGB),
),
);
const synchronizedThemeProps = useRef(false);
writes: [],
}));
const persistedControlledSync = useRef(controlledSync);
/**
* A controlled theme change is folded into state during the render that
* delivers it (React re-renders before committing), so the layout effect that
* applies the theme sees it in the same commit and nothing paints in between.
*/
if (!sameThemeProps(controlledSync.props, themeProps)) {
const sync = syncControlledTheme(
controlledSync.props,
themeProps,
{ definition: themeDefinition, legacyColors: legacyThemeRGB, name: themeName },
controlledSync.controlled,
);
setControlledSync({
props: themeProps,
controlled: sync.controlled,
writes: sync.writes,
appearance: sync.appearance,
});
setThemeDefinitionState(sync.state.definition);
setLegacyThemeRGB(sync.state.legacyColors);
setThemeNameState(sync.state.name);
if (sync.appearance) {
setThemeState(sync.appearance);
}
}
const themeDOMSnapshot = useRef<ThemeDOMSnapshot | undefined>(undefined);
const themeClassSnapshot = useRef<ThemeClassSnapshot | undefined>(undefined);
@ -486,124 +650,61 @@ export function ThemeProvider({
writeStorage(THEME_KEY, newTheme);
}, []);
const commitThemeTransition = useCallback(
({ state, writes }: ThemeTransition) => {
themeDefinitionRef.current = state.definition;
setThemeDefinitionState(state.definition);
legacyThemeRGBRef.current = state.legacyColors;
setLegacyThemeRGB(state.legacyColors);
themeNameRef.current = state.name;
setThemeNameState(state.name);
writes.forEach(([key, value]) => writeThemeStorage(key, value));
},
[writeThemeStorage],
);
const currentThemeState = useCallback(
(): ThemeState => ({
definition: themeDefinitionRef.current,
legacyColors: legacyThemeRGBRef.current,
name: themeNameRef.current,
}),
[],
);
const setThemeDefinition = useCallback(
(definition?: ThemeDefinition) => {
const errors = definition ? validateThemeDefinition(definition) : [];
if (errors.length > 0) {
throw new TypeError(errors.join('\n'));
}
themeDefinitionRef.current = definition;
setThemeDefinitionState(definition);
legacyThemeRGBRef.current = undefined;
setLegacyThemeRGB(undefined);
writeThemeStorage(THEME_DEFINITION_KEY, definition ? JSON.stringify(definition) : undefined);
writeThemeStorage(THEME_COLORS_KEY);
writeThemeStorage(THEME_SOURCE_KEY, definition ? 'definition' : undefined);
setThemeNameState(definition?.name);
themeNameRef.current = definition?.name;
writeThemeStorage(THEME_NAME_KEY, definition?.name);
commitThemeTransition(defineTheme(definition));
},
[writeThemeStorage],
[commitThemeTransition],
);
const setThemeRGB = useCallback(
(colors?: IThemeRGB) => {
const definition = colors
? fromLegacyTheme(colors, themeDefinitionRef.current?.name ?? themeNameRef.current)
: undefined;
const legacyColors = definition?.modes.light?.colors;
themeDefinitionRef.current = definition;
setThemeDefinitionState(definition);
legacyThemeRGBRef.current = legacyColors;
setLegacyThemeRGB(legacyColors);
setThemeNameState(definition?.name);
themeNameRef.current = definition?.name;
writeThemeStorage(THEME_DEFINITION_KEY, definition ? JSON.stringify(definition) : undefined);
writeThemeStorage(THEME_NAME_KEY, definition?.name);
writeThemeStorage(THEME_COLORS_KEY, legacyColors ? JSON.stringify(legacyColors) : undefined);
writeThemeStorage(THEME_SOURCE_KEY, definition ? 'legacy' : undefined);
},
[writeThemeStorage],
(colors?: IThemeRGB) => commitThemeTransition(applyLegacyColors(currentThemeState(), colors)),
[commitThemeTransition, currentThemeState],
);
const setThemeName = useCallback(
(name?: string) => {
const currentDefinition = themeDefinitionRef.current;
const nextName = name?.trim() || (currentDefinition ? 'custom' : undefined);
setThemeNameState(nextName);
themeNameRef.current = nextName;
writeThemeStorage(THEME_NAME_KEY, nextName);
if (!nextName || !currentDefinition) {
return;
}
const renamedDefinition = { ...currentDefinition, name: nextName };
themeDefinitionRef.current = renamedDefinition;
setThemeDefinitionState(renamedDefinition);
writeThemeStorage(THEME_DEFINITION_KEY, JSON.stringify(renamedDefinition));
writeThemeStorage(THEME_SOURCE_KEY, legacyThemeRGBRef.current ? 'legacy' : 'definition');
},
[writeThemeStorage],
(name?: string) => commitThemeTransition(renameTheme(currentThemeState(), name)),
[commitThemeTransition, currentThemeState],
);
/** Storage is not paint, so a controlled change persists after its commit, under the
* gating of the render that made it; each sync is written once. */
useEffect(() => {
if (!synchronizedThemeProps.current) {
synchronizedThemeProps.current = true;
if (persistedControlledSync.current === controlledSync) {
return;
}
const previous = previousThemeProps.current;
const definitionChanged = propThemeDefinition !== previous.themeDefinition;
const legacyColorsChanged = propThemeRGB !== previous.themeRGB;
const switchedToLegacyColors =
definitionChanged && !propThemeDefinition && propThemeRGB !== undefined;
let clearedControlledDefinition = false;
if (definitionChanged || legacyColorsChanged) {
if (propThemeDefinition) {
if (isValidThemeDefinition(propThemeDefinition)) {
setThemeDefinition(propThemeDefinition);
controlledThemeActive.current = true;
}
} else if (propThemeRGB) {
setThemeRGB(propThemeRGB);
controlledThemeActive.current = true;
} else if (controlledThemeActive.current) {
setThemeDefinition(undefined);
controlledThemeActive.current = false;
clearedControlledDefinition = true;
}
persistedControlledSync.current = controlledSync;
controlledSync.writes.forEach(([key, value]) => writeThemeStorage(key, value));
if (controlledSync.appearance) {
writeStorage(THEME_KEY, controlledSync.appearance);
}
if (
!propThemeDefinition &&
(propThemeName !== previous.themeName ||
switchedToLegacyColors ||
clearedControlledDefinition)
) {
setThemeName(propThemeName);
}
if (initialTheme !== previous.initialTheme && initialTheme && isAppearanceMode(initialTheme)) {
setTheme(initialTheme);
}
previousThemeProps.current = {
initialTheme,
themeDefinition: propThemeDefinition,
themeName: propThemeName,
themeRGB: propThemeRGB,
};
}, [
initialTheme,
propThemeDefinition,
propThemeName,
propThemeRGB,
setTheme,
setThemeDefinition,
setThemeName,
setThemeRGB,
]);
}, [controlledSync, writeThemeStorage]);
/** Stored, controlled and deployment definitions all arrive here, so each is reported once. */
useEffect(() => {
@ -665,7 +766,7 @@ export function ThemeProvider({
[legacyThemeRGB, prepareThemeDOM, restoreAppliedTheme, themeDefinition],
);
useEffect(() => {
useBeforePaintEffect(() => {
applyThemeMode(theme);
}, [applyThemeMode, theme]);

View file

@ -209,6 +209,53 @@ describe('theme registry', () => {
expect(resolved.colors['rgb-text-muted']).toBe('90 91 92');
});
it('keeps prose links on the link role in light and on primary text in dark', () => {
expect(resolveTheme(libreChatTheme, 'light').colors['rgb-link-prose']).toBe(
defaultTheme['rgb-link'],
);
expect(resolveTheme(libreChatTheme, 'dark').colors['rgb-link-prose']).toBe(
darkTheme['rgb-text-primary'],
);
});
it('derives omitted prose links from the link a theme names, in either mode', () => {
const colors = { 'rgb-link': '250 255 105', 'rgb-text-primary': '240 240 240' };
const theme: ThemeDefinition = {
version: 1,
name: 'prose-link-reference',
modes: { light: { colors }, dark: { colors } },
};
expect(resolveTheme(theme, 'light').colors['rgb-link-prose']).toBe('250 255 105');
expect(resolveTheme(theme, 'dark').colors['rgb-link-prose']).toBe('250 255 105');
});
it('keeps dark prose links on the primary text of a theme that names no link', () => {
const resolved = resolveTheme(
{
version: 1,
name: 'prose-text-reference',
modes: { dark: { colors: { 'rgb-text-primary': '240 240 240' } } },
},
'dark',
);
expect(resolved.colors['rgb-link-prose']).toBe('240 240 240');
});
it('preserves an explicit prose link color', () => {
const resolved = resolveTheme(
{
version: 1,
name: 'explicit-prose-link-reference',
modes: { dark: { colors: { 'rgb-link': '1 2 3', 'rgb-link-prose': '4 5 6' } } },
},
'dark',
);
expect(resolved.colors['rgb-link-prose']).toBe('4 5 6');
});
it('derives omitted chart widget colors from the previous panel roles', () => {
const resolved = resolveTheme(
{

View file

@ -418,6 +418,18 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT
customColors?.['rgb-text-tertiary'] !== undefined
? { 'rgb-text-muted': customColors['rgb-text-tertiary'] }
: {};
/**
* Markdown links read `link` in light and `text-primary` in dark before they
* had a role, so a theme that names neither prose role keeps whichever of
* those it painted, its own link colour first.
*/
const proseLinkSource =
customColors?.['rgb-link'] ??
(mode === 'dark' ? customColors?.['rgb-text-primary'] : undefined);
const proseLinkFallback =
customColors?.['rgb-link-prose'] === undefined && proseLinkSource !== undefined
? { 'rgb-link-prose': proseLinkSource }
: {};
const chartWidgetSurfaceFallback =
customColors?.['rgb-chart-widget-surface'] === undefined &&
customColors?.['rgb-surface-primary'] !== undefined
@ -491,6 +503,7 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT
...composerHoverFallback,
...shimmerBaseFallback,
...textMutedFallback,
...proseLinkFallback,
...chartWidgetSurfaceFallback,
...chartWidgetStrokeFallback,
...borderControlFallback,

View file

@ -72,6 +72,7 @@ const accentTokens: Array<keyof IThemeRGB> = [
'rgb-link',
'rgb-link-hover',
'rgb-link-visited',
'rgb-link-prose',
'rgb-brand-purple',
];

View file

@ -45,6 +45,7 @@ export const clickHouseLightTheme: IThemeRGB = {
'rgb-link': '29 100 236', // #1d64ec (palette.info.500, one step past text.link.default #437eef (3.84:1 on white))
'rgb-link-hover': '16 78 198', // #104ec6 (text.link.hover)
'rgb-link-visited': '136 0 204', // #8800cc (palette.violet.600)
'rgb-link-prose': '29 100 236', // #1d64ec (palette.info.500, matching link)
'rgb-accent-primary': '21 21 21', // #151515 (accent.default)
'rgb-accent-primary-hover': '50 50 50', // #323232 (palette.neutral.712)
@ -83,6 +84,7 @@ export const clickHouseLightTheme: IThemeRGB = {
'rgb-surface-chat': '255 255 255', // #ffffff (background.default)
'rgb-surface-code': '246 247 250', // #f6f7fa (codeblock.lightMode.color.background.default)
'rgb-surface-code-body': '246 247 250', // #f6f7fa (codeblock.lightMode.color.background.default)
'rgb-surface-qr': '255 255 255', // #ffffff (palette.neutral.0)
'rgb-surface-inverted': '21 21 21', // #151515 (palette.neutral.900)
'rgb-surface-inverted-hover': '50 50 50', // #323232 (palette.neutral.712)
'rgb-surface-inverted-pressed': '22 21 23', // #161517 (button.basic.color.primary.background.active)
@ -172,6 +174,7 @@ export const clickHouseDarkTheme: IThemeRGB = {
'rgb-link': '250 255 105', // #faff69 (text.link.default)
'rgb-link-hover': '254 255 194', // #feffc2 (text.link.hover)
'rgb-link-visited': '204 102 255', // #cc66ff (palette.violet.300)
'rgb-link-prose': '250 255 105', // #faff69 (text.link.default)
'rgb-accent-primary': '250 255 105', // #faff69 (accent.default)
'rgb-accent-primary-hover': '253 255 163', // #fdffa3 (palette.brand.200)
@ -213,6 +216,7 @@ export const clickHouseDarkTheme: IThemeRGB = {
'rgb-surface-chat': '31 31 28', // #1f1f1c (background.default)
'rgb-surface-code': '40 40 40', // #282828 (codeblock.darkMode.color.background.default)
'rgb-surface-code-body': '40 40 40', // #282828 (codeblock.darkMode.color.background.default)
'rgb-surface-qr': '255 255 255', // #ffffff (palette.neutral.0)
'rgb-surface-inverted': '250 255 105', // #faff69 (button.basic.color.primary.background.default)
'rgb-surface-inverted-hover': '252 255 150', // #fcff96 (button.basic.color.primary.background.hover)
'rgb-surface-inverted-pressed': '231 236 97', // #e7ec61 (button.basic.color.primary.background.active)

View file

@ -33,6 +33,7 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>
'rgb-link': 'palette.info.500',
'rgb-link-hover': 'global.color.text.link.hover',
'rgb-link-visited': 'palette.violet.600',
'rgb-link-prose': 'palette.info.500',
'rgb-accent-primary': 'global.color.accent.default',
'rgb-accent-primary-hover': 'palette.neutral.712',
'rgb-ring-primary': 'global.color.outline.default',
@ -65,6 +66,7 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>
'rgb-surface-chat': 'global.color.background.default',
'rgb-surface-code': 'click.codeblock.lightMode.color.background.default',
'rgb-surface-code-body': 'click.codeblock.lightMode.color.background.default',
'rgb-surface-qr': 'palette.neutral.0',
'rgb-surface-inverted': 'palette.neutral.900',
'rgb-surface-inverted-hover': 'palette.neutral.712',
'rgb-surface-inverted-pressed': 'click.button.basic.color.primary.background.active',
@ -136,6 +138,7 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>
'rgb-link': 'global.color.text.link.default',
'rgb-link-hover': 'global.color.text.link.hover',
'rgb-link-visited': 'palette.violet.300',
'rgb-link-prose': 'global.color.text.link.default',
'rgb-accent-primary': 'global.color.accent.default',
'rgb-accent-primary-hover': 'palette.brand.200',
'rgb-ring-primary': 'global.color.outline.default',
@ -167,6 +170,7 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>
'rgb-surface-chat': 'global.color.background.default',
'rgb-surface-code': 'click.codeblock.darkMode.color.background.default',
'rgb-surface-code-body': 'click.codeblock.darkMode.color.background.default',
'rgb-surface-qr': 'palette.neutral.0',
'rgb-surface-inverted': 'click.button.basic.color.primary.background.default',
'rgb-surface-inverted-hover': 'click.button.basic.color.primary.background.hover',
'rgb-surface-inverted-pressed': 'click.button.basic.color.primary.background.active',

View file

@ -20,6 +20,7 @@ export const darkTheme: IThemeRGB = {
'rgb-link': '96 165 250', // #60a5fa (blue-400)
'rgb-link-hover': '147 197 253', // #93c5fd (blue-300)
'rgb-link-visited': '192 132 252', // #c084fc (purple-400)
'rgb-link-prose': '236 236 236', // #ececec (gray-100, matching text-primary)
'rgb-accent-primary': '65 167 157', // #41a79d
'rgb-accent-primary-hover': '109 200 185', // #6dc8b9
@ -58,6 +59,7 @@ export const darkTheme: IThemeRGB = {
'rgb-surface-chat': '47 47 47', // #2f2f2f (gray-700)
'rgb-surface-code': '33 33 33', // #212121 (gray-800)
'rgb-surface-code-body': '23 23 23', // #171717 (gray-850)
'rgb-surface-qr': '255 255 255', // #fff (white, so the code stays scannable)
'rgb-surface-inverted': '255 255 255', // #fff (white)
'rgb-surface-inverted-hover': '236 236 236', // #ececec (gray-100)
'rgb-surface-inverted-pressed': '236 236 236', // #ececec (gray-100), the hover fill

View file

@ -20,6 +20,7 @@ export const defaultTheme: IThemeRGB = {
'rgb-link': '37 99 235', // #2563eb (blue-600)
'rgb-link-hover': '29 78 216', // #1d4ed8 (blue-700)
'rgb-link-visited': '147 51 234', // #9333ea (purple-600)
'rgb-link-prose': '37 99 235', // #2563eb (blue-600, matching link)
'rgb-accent-primary': '18 110 107', // #126e6b
'rgb-accent-primary-hover': '10 79 83', // #0a4f53
@ -58,6 +59,7 @@ export const defaultTheme: IThemeRGB = {
'rgb-surface-chat': '255 255 255', // #fff (white)
'rgb-surface-code': '247 247 248', // #f7f7f8 (gray-50)
'rgb-surface-code-body': '255 255 255', // #fff (white)
'rgb-surface-qr': '255 255 255', // #fff (white)
'rgb-surface-inverted': '23 23 23', // #171717 (gray-850)
'rgb-surface-inverted-hover': '47 47 47', // #2f2f2f (gray-700)
'rgb-surface-inverted-pressed': '47 47 47', // #2f2f2f (gray-700), the hover fill

View file

@ -117,6 +117,7 @@ const accentTokens: Array<keyof IThemeRGB> = [
'rgb-link',
'rgb-link-hover',
'rgb-link-visited',
'rgb-link-prose',
'rgb-brand-purple',
];

View file

@ -46,6 +46,7 @@ export const highContrastLightTheme: IThemeRGB = {
'rgb-link': '0 0 204', // #0000cc
'rgb-link-hover': '0 0 128', // #000080
'rgb-link-visited': '107 0 179', // #6b00b3
'rgb-link-prose': '0 0 204', // #0000cc, matching link
'rgb-accent-primary': '0 80 77', // #00504d
'rgb-accent-primary-hover': '0 51 48', // #003330
@ -94,6 +95,7 @@ export const highContrastLightTheme: IThemeRGB = {
'rgb-surface-chat': '255 255 255', // #ffffff
'rgb-surface-code': '255 255 255', // #ffffff, matching surface-primary-alt
'rgb-surface-code-body': '255 255 255', // #ffffff, matching surface-chat
'rgb-surface-qr': '255 255 255', // #ffffff
'rgb-surface-inverted': '0 0 0', // #000000
'rgb-surface-inverted-hover': '51 51 51', // #333333
'rgb-surface-inverted-pressed': '51 51 51', // #333333, the hover fill
@ -199,6 +201,7 @@ export const highContrastDarkTheme: IThemeRGB = {
'rgb-link': '140 200 255', // #8cc8ff
'rgb-link-hover': '194 224 255', // #c2e0ff
'rgb-link-visited': '224 179 255', // #e0b3ff
'rgb-link-prose': '140 200 255', // #8cc8ff, matching link
'rgb-accent-primary': '92 230 219', // #5ce6db
'rgb-accent-primary-hover': '163 242 236', // #a3f2ec
@ -243,6 +246,7 @@ export const highContrastDarkTheme: IThemeRGB = {
'rgb-surface-chat': '0 0 0', // #000000
'rgb-surface-code': '0 0 0', // #000000, matching presentation
'rgb-surface-code-body': '0 0 0', // #000000, matching surface-primary-alt
'rgb-surface-qr': '255 255 255', // #ffffff, so the code stays scannable
'rgb-surface-inverted': '255 255 255', // #ffffff
'rgb-surface-inverted-hover': '212 212 212', // #d4d4d4
'rgb-surface-inverted-pressed': '212 212 212', // #d4d4d4, the hover fill

View file

@ -79,6 +79,7 @@
--color-link: rgb(var(--link));
--color-link-hover: rgb(var(--link-hover));
--color-link-visited: rgb(var(--link-visited));
--color-link-prose: rgb(var(--link-prose));
/* borders */
--color-border-light: rgb(var(--border-light) / var(--border-light-alpha, 1));

View file

@ -68,6 +68,13 @@ describe('theme color tokens', () => {
expect(missing).toEqual([]);
});
it('lets a theme set every color token the stylesheet declares', () => {
const registered = new Set(Object.keys(defaultTheme).map((key) => key.replace(/^rgb-/, '')));
const unowned = [...declared].filter((token) => !registered.has(token));
expect(unowned).toEqual([]);
});
it('resolves a token to the custom property the theme rewrites at runtime', async () => {
const css = await generate(['bg-surface-primary', 'text-text-secondary', 'bg-series-1']);

View file

@ -21,6 +21,9 @@ export interface IThemeRGB {
'rgb-link'?: string;
'rgb-link-hover'?: string;
'rgb-link-visited'?: string;
/** Links inside rendered Markdown. Falls back to the mode's `rgb-link`, or in dark to
* `rgb-text-primary`, when a theme names that and not this. */
'rgb-link-prose'?: string;
'rgb-accent-primary'?: string;
'rgb-accent-primary-hover'?: string;
@ -60,6 +63,8 @@ export interface IThemeRGB {
'rgb-surface-chat'?: string;
'rgb-surface-code'?: string;
'rgb-surface-code-body'?: string;
/** The backdrop a QR code is scanned against; keep it light in every mode. */
'rgb-surface-qr'?: string;
'rgb-surface-inverted'?: string;
'rgb-surface-inverted-hover'?: string;
/** Fill of an inverted control while pressed; follows `rgb-surface-inverted-hover` when omitted. */
@ -179,6 +184,7 @@ export interface IThemeVariables {
'--link': string;
'--link-hover': string;
'--link-visited': string;
'--link-prose': string;
'--accent-primary': string;
'--accent-primary-hover': string;
'--ring-primary': string;
@ -211,6 +217,7 @@ export interface IThemeVariables {
'--surface-chat': string;
'--surface-code': string;
'--surface-code-body': string;
'--surface-qr': string;
'--surface-inverted': string;
'--surface-inverted-hover': string;
'--surface-inverted-pressed': string;
@ -292,6 +299,7 @@ export interface IThemeColors {
link?: string;
'link-hover'?: string;
'link-visited'?: string;
'link-prose'?: string;
'accent-primary'?: string;
'accent-primary-hover'?: string;
'ring-primary'?: string;
@ -324,6 +332,7 @@ export interface IThemeColors {
'surface-chat'?: string;
'surface-code'?: string;
'surface-code-body'?: string;
'surface-qr'?: string;
'surface-inverted'?: string;
'surface-inverted-hover'?: string;
'surface-inverted-pressed'?: string;

View file

@ -2252,7 +2252,7 @@ const themeModeSchema = z
/**
* Shape of an inline deployment theme. Token names and value ranges are checked
* by the client registry (`validateThemeDefinition`), which owns the token list.
* by `collectThemeIssues` in `theme.ts`, which owns the token list.
*/
export const themeDefinitionSchema = z
.object({

View file

@ -26,6 +26,7 @@ export const themeColorTokens = Object.freeze([
'rgb-link',
'rgb-link-hover',
'rgb-link-visited',
'rgb-link-prose',
'rgb-accent-primary',
'rgb-accent-primary-hover',
'rgb-ring-primary',
@ -58,6 +59,7 @@ export const themeColorTokens = Object.freeze([
'rgb-surface-chat',
'rgb-surface-code',
'rgb-surface-code-body',
'rgb-surface-qr',
'rgb-surface-inverted',
'rgb-surface-inverted-hover',
'rgb-surface-inverted-pressed',