Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🎚️ feat: Give the Switch Theme Roles for Its Size and Knob (#16486)

Marco Berettaf51b1a823b17
diff --git a/e2e/specs/mock/scenarios/clickhouse-switch.spec.ts b/e2e/specs/mock/scenarios/clickhouse-switch.spec.ts
new file mode 100644
index 0000000000..4333ae1c26
--- /dev/null
+++ b/e2e/specs/mock/scenarios/clickhouse-switch.spec.ts
@@ -0,0 +1,118 @@
+import { expect, test } from '@playwright/test';
+import type { Locator, Page } from '@playwright/test';
+import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse';
+import { NEW_CHAT_PATH } from '../helpers';
+
+/**
+ * The shared switch reads its track size and its knob from theme roles. Click UI draws a 32x16
+ * track with a 12px knob that is white in light mode and `#151515` in dark; LibreChat's own switch
+ * is 44x24 with a 20px knob on `surface-primary`, and stays that way without a theme.
+ */
+test.describe.configure({ timeout: 120_000 });
+test.use({ viewport: { width: 1280, height: 800 } });
+
+type Mode = 'light' | 'dark';
+
+type ThemeChoice = 'clickhouse' | 'default';
+
+/**
+ * One init script per page: Playwright does not order several, so the theme and mode a
+ * navigation wants ride in its URL and the script stores or clears the definition.
+ */
+async function installThemeBridge(page: Page) {
+ await page.addInitScript((definition) => {
+ const params = new URL(location.href).searchParams;
+ const theme = params.get('e2eTheme');
+ const mode = params.get('e2eThemeMode');
+ if (theme === null || mode === null) {
+ return;
+ }
+ localStorage.setItem('color-theme', mode);
+ localStorage.removeItem('theme-colors');
+ localStorage.removeItem('theme-name');
+ if (theme === 'clickhouse') {
+ localStorage.setItem('theme-definition', JSON.stringify(definition));
+ localStorage.setItem('theme-source', 'definition');
+ } else {
+ localStorage.removeItem('theme-definition');
+ localStorage.removeItem('theme-source');
+ }
+ }, clickHouseTheme);
+}
+
+async function settingsSwitch(page: Page, theme: ThemeChoice, mode: Mode): Promise<Locator> {
+ await page.goto(`${NEW_CHAT_PATH}?e2eTheme=${theme}&e2eThemeMode=${mode}`, { timeout: 15000 });
+ await page.getByTestId('nav-user').click();
+ await page.getByRole('menuitem', { name: 'Settings' }).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog.getByRole('heading', { name: 'Settings', exact: true })).toBeVisible({
+ timeout: 15000,
+ });
+ await dialog.getByRole('tab', { name: 'General' }).click();
+ const control = dialog.getByRole('switch').first();
+ await expect(control).toBeVisible();
+ return control;
+}
+
+/** What takes a tap: the track's own box together with the invisible layer centered on it. */
+const hitArea = (control: Locator) =>
+ control.evaluate((node: HTMLElement) => {
+ const layer = getComputedStyle(node, '::before');
+ return {
+ width: Math.max(node.offsetWidth, parseFloat(layer.width)),
+ height: Math.max(node.offsetHeight, parseFloat(layer.height)),
+ coarse: matchMedia('(any-pointer: coarse)').matches,
+ };
+ });
+
+async function measure(control: Locator) {
+ /** Layout sizes, not client rects: the dialog is still zooming in when this reads. */
+ return control.evaluate((node: HTMLElement) => {
+ const thumb = node.firstElementChild as HTMLElement;
+ return {
+ track: [node.offsetWidth, node.offsetHeight],
+ thumb: thumb.offsetWidth,
+ thumbColor: getComputedStyle(thumb).backgroundColor,
+ };
+ });
+}
+
+const rgb = (triplet: string | undefined) => `rgb(${(triplet ?? '').split(' ').join(', ')})`;
+
+test.describe('theme switch', () => {
+ test('the switch takes Click UI geometry and knob color under the ClickHouse theme @scenario:clickhouse-switch-follows-click-ui', async ({
+ page,
+ }) => {
+ await installThemeBridge(page);
+ for (const mode of ['light', 'dark'] as Mode[]) {
+ const control = await settingsSwitch(page, 'clickhouse', mode);
+ await expect(page.locator('html')).toHaveAttribute('data-theme', 'clickhouse');
+ await expect(page.locator('html')).toHaveClass(new RegExp(`\\b${mode}\\b`));
+
+ const knob = clickHouseTheme.modes[mode]?.colors?.['rgb-switch-thumb'];
+ expect(await measure(control)).toEqual({
+ track: [32, 16],
+ thumb: 12,
+ thumbColor: rgb(knob),
+ });
+ const hit = await hitArea(control);
+ const floor = hit.coarse ? 44 : 24;
+ expect(hit.height).toBeGreaterThanOrEqual(floor);
+ expect(hit.width).toBeGreaterThanOrEqual(floor);
+ }
+ });
+
+ test('the default theme keeps its switch @scenario:default-theme-switch-unchanged', async ({
+ page,
+ }) => {
+ await installThemeBridge(page);
+ for (const [mode, surface] of [
+ ['light', 'rgb(255, 255, 255)'],
+ ['dark', 'rgb(13, 13, 13)'],
+ ] as Array<[Mode, string]>) {
+ const control = await settingsSwitch(page, 'default', mode);
+
+ expect(await measure(control)).toEqual({ track: [44, 24], thumb: 20, thumbColor: surface });
+ }
+ });
+});
diff --git a/e2e/specs/mock/scenarios/theme-unknown-appearance.spec.ts b/e2e/specs/mock/scenarios/theme-unknown-appearance.spec.ts
index 67663c4ce4..00901ad230 100644
--- a/e2e/specs/mock/scenarios/theme-unknown-appearance.spec.ts
+++ b/e2e/specs/mock/scenarios/theme-unknown-appearance.spec.ts
@@ -116,3 +116,38 @@ test.describe('appearance tokens this build does not know', () => {
await expect(page.locator('body')).toBeVisible();
});
});
+
+/**
+ * The same holds for a color role added after this build: a well-formed `rgb-` name with a valid
+ * triplet is dropped with a warning, so a newer definition keeps every color this build paints.
+ */
+test.describe('color tokens this build does not know', () => {
+ const NEWER_COLORS = {
+ version: 1,
+ name: 'e2e-newer-colors',
+ modes: {
+ light: { colors: { 'rgb-surface-primary': '240 244 255', 'rgb-future-role': '1 2 3' } },
+ dark: { colors: { 'rgb-surface-primary': '12 16 32', 'rgb-future-role': '1 2 3' } },
+ },
+ };
+
+ test('a stored theme with an unknown color role keeps the colors this build paints @scenario:stored-theme-unknown-color-token-applies-rest', async ({
+ page,
+ }) => {
+ const warnings: string[] = [];
+ page.on('console', (message) => {
+ if (message.type() === 'warning') {
+ warnings.push(message.text());
+ }
+ });
+ await storeTheme(page, NEWER_COLORS);
+
+ await openChat(page);
+
+ await expect(page.locator('html')).toHaveAttribute('data-theme', NEWER_COLORS.name);
+ const dark = await page.evaluate(() => document.documentElement.classList.contains('dark'));
+ expect(await themeValue(page, '--surface-primary')).toBe(dark ? '12 16 32' : '240 244 255');
+ expect(await themeValue(page, '--future-role')).toBe('');
+ expect(warnings.join('\n')).toContain('color token ignored: rgb-future-role');
+ });
+});
diff --git a/packages/client/src/components/Switch.tsx b/packages/client/src/components/Switch.tsx
index 9556a3688e..9a2f7a0dd8 100644
--- a/packages/client/src/components/Switch.tsx
+++ b/packages/client/src/components/Switch.tsx
@@ -23,7 +23,11 @@ const Switch: React.ForwardRefExoticComponent<
({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
- 'peer focus-visible:ring-focus-control focus-visible:ring-offset-surface-primary data-[state=checked]:bg-surface-inverted data-[state=unchecked]:bg-switch-unchecked inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
+ /** A compact theme track can be smaller than a usable target, so an invisible layer
+ * centered on it keeps the hit area at least 24px tall, and 44px each way on a coarse
+ * pointer; a track larger than that still takes taps on its own box. */
+ 'touch:before:h-theme-control-touch touch:before:w-theme-control-touch relative before:absolute before:top-1/2 before:left-1/2 before:h-6 before:w-full before:-translate-x-1/2 before:-translate-y-1/2',
+ 'peer focus-visible:ring-focus-control focus-visible:ring-offset-surface-primary data-[state=checked]:bg-surface-inverted data-[state=unchecked]:bg-switch-unchecked h-theme-switch w-theme-switch inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
disabledFillClasses,
className,
)}
@@ -32,7 +36,7 @@ const Switch: React.ForwardRefExoticComponent<
>
<SwitchPrimitives.Thumb
className={cn(
- 'bg-surface-primary pointer-events-none block h-5 w-5 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0',
+ 'bg-switch-thumb size-theme-switch-thumb data-[state=checked]:translate-x-theme-switch-travel pointer-events-none block rounded-full shadow-lg ring-0 transition-transform data-[state=unchecked]:translate-x-0',
)}
/>
</SwitchPrimitives.Root>
diff --git a/packages/client/src/theme/defaults.css b/packages/client/src/theme/defaults.css
index e4edb13a48..ee891b2489 100644
--- a/packages/client/src/theme/defaults.css
+++ b/packages/client/src/theme/defaults.css
@@ -197,6 +197,8 @@ html {
--theme-radius-2xl: 1rem;
--theme-radius-3xl: 1.5rem;
--theme-control-height: 2.25rem;
+ --theme-switch-width: 2.75rem;
+ --theme-switch-height: 1.5rem;
--theme-space-compact: 0.375rem;
--theme-space-normal: 0.75rem;
--theme-disabled-style: dim;
@@ -237,6 +239,7 @@ html {
--theme-motion-fast: 150ms;
--theme-motion-normal: 200ms;
--switch-unchecked: 148 148 148;
+ --switch-thumb: 255 255 255;
--provider-openai: #19c37d;
--provider-openai-gpt4: #ab68ff;
--provider-openai-reasoning: #000000;
@@ -357,6 +360,7 @@ html {
--surface-fixed-hover: var(--gray-100);
--text-fixed: var(--gray-800);
--switch-unchecked: 102 102 102;
+ --switch-thumb: 13 13 13;
--provider-openai: #19c37d;
--provider-openai-gpt4: #ab68ff;
--provider-openai-reasoning: #000000;
diff --git a/packages/client/src/theme/defaults.spec.ts b/packages/client/src/theme/defaults.spec.ts
index c946d6af3c..5f2ec9d9ef 100644
--- a/packages/client/src/theme/defaults.spec.ts
+++ b/packages/client/src/theme/defaults.spec.ts
@@ -63,7 +63,7 @@ describe.each([
const tokens = Object.keys(theme) as Array<keyof IThemeRGB>;
it('covers every registry color', () => {
- expect(tokens).toHaveLength(103);
+ expect(tokens).toHaveLength(104);
});
it('resolves every registry color to the runtime theme value', () => {
diff --git a/packages/client/src/theme/registry.spec.ts b/packages/client/src/theme/registry.spec.ts
index 188635a580..f55a4a2f20 100644
--- a/packages/client/src/theme/registry.spec.ts
+++ b/packages/client/src/theme/registry.spec.ts
@@ -300,6 +300,92 @@ describe('theme registry', () => {
expect(resolved.colors['rgb-chart-widget-stroke']).toBe('50 51 52');
});
+ describe('switch size pair', () => {
+ const withSwitch = (switchWidth: string, switchHeight: string) =>
+ ({
+ version: 1,
+ name: 'switch',
+ modes: { light: { appearance: { switchWidth, switchHeight } } },
+ }) as ThemeDefinition;
+
+ it('checks one named dimension against the default it is drawn with', () => {
+ const widthOnly = {
+ version: 1,
+ name: 'switch-width',
+ modes: { light: { appearance: { switchWidth: '1rem' } } },
+ } as ThemeDefinition;
+
+ expect(validateThemeDefinition(widthOnly)).toEqual([
+ 'switchWidth must exceed switchHeight so the knob can travel: 1rem, 1.5rem',
+ ]);
+ });
+
+ it('accepts a pair in one unit that leaves a knob and a forward travel', () => {
+ expect(validateThemeDefinition(withSwitch('2rem', '1rem'))).toEqual([]);
+ expect(validateThemeDefinition(withSwitch('40px', '20px'))).toEqual([]);
+ });
+
+ it('rejects a mixed-unit pair, which only holds at one root size', () => {
+ expect(validateThemeDefinition(withSwitch('40px', '2rem'))).toEqual([
+ 'switchWidth and switchHeight must share a unit (the default is rem): 40px, 2rem',
+ ]);
+ });
+
+ it('rejects em, zero, a track too short for its border and a width not above the height', () => {
+ expect(validateThemeDefinition(withSwitch('2em', '1rem'))).toEqual([
+ 'Invalid appearance value for switchWidth: 2em',
+ ]);
+ expect(validateThemeDefinition(withSwitch('0', '1rem'))).toEqual([
+ 'Invalid appearance value for switchWidth: 0',
+ ]);
+ expect(validateThemeDefinition(withSwitch('32px', '4px'))).toEqual([
+ 'switchHeight must exceed the 4px track border: 4px',
+ ]);
+ expect(validateThemeDefinition(withSwitch('2rem', '0.25rem'))).toEqual([
+ 'switchHeight must be at least 0.5rem to clear the 4px track border: 0.25rem',
+ ]);
+ expect(validateThemeDefinition(withSwitch('1rem', '2rem'))).toEqual([
+ 'switchWidth must exceed switchHeight so the knob can travel: 1rem, 2rem',
+ ]);
+ expect(validateThemeDefinition(withSwitch('1.5rem', '1.5rem'))).toEqual([
+ 'switchWidth must exceed switchHeight so the knob can travel: 1.5rem, 1.5rem',
+ ]);
+ });
+ });
+
+ it('keeps the switch thumb on the surface a theme repainted before the role existed', () => {
+ const resolved = resolveTheme(
+ {
+ version: 1,
+ name: 'legacy-switch-thumb',
+ modes: { dark: { colors: { 'rgb-surface-primary': '20 21 22' } } },
+ },
+ 'dark',
+ );
+
+ expect(resolved.colors['rgb-switch-thumb']).toBe('20 21 22');
+ });
+
+ it('preserves an explicit switch thumb and falls back to the bundled one otherwise', () => {
+ const explicit = resolveTheme(
+ {
+ version: 1,
+ name: 'explicit-switch-thumb',
+ modes: {
+ dark: { colors: { 'rgb-surface-primary': '20 21 22', 'rgb-switch-thumb': '1 2 3' } },
+ },
+ },
+ 'dark',
+ );
+ const untouched = resolveTheme(
+ { version: 1, name: 'no-surface', modes: { dark: { colors: {} } } },
+ 'dark',
+ );
+
+ expect(explicit.colors['rgb-switch-thumb']).toBe('1 2 3');
+ expect(untouched.colors['rgb-switch-thumb']).toBe(darkTheme['rgb-switch-thumb']);
+ });
+
it('keeps the light border a legacy theme drew its controls with', () => {
const resolved = resolveTheme(
{
diff --git a/packages/client/src/theme/registry.ts b/packages/client/src/theme/registry.ts
index b2d5a781f9..0923708ce6 100644
--- a/packages/client/src/theme/registry.ts
+++ b/packages/client/src/theme/registry.ts
@@ -4,6 +4,7 @@ import {
collectThemeIssues,
isThemeAppearanceToken,
collectThemeWarningIssues,
+ defaultSwitchSize,
themeColorTokens as sharedColorTokens,
themeBrandTokens as sharedBrandTokens,
} from 'librechat-data-provider';
@@ -134,6 +135,8 @@ export const themeAppearanceProperties: Readonly<
radius2xl: '--theme-radius-2xl',
radius3xl: '--theme-radius-3xl',
controlHeight: '--theme-control-height',
+ switchWidth: '--theme-switch-width',
+ switchHeight: '--theme-switch-height',
spaceCompact: '--theme-space-compact',
spaceNormal: '--theme-space-normal',
disabledStyle: '--theme-disabled-style',
@@ -179,6 +182,7 @@ export const defaultAppearance: IThemeAppearance = Object.freeze({
radius2xl: '1rem',
radius3xl: '1.5rem',
controlHeight: '2.25rem',
+ ...defaultSwitchSize,
spaceCompact: '0.375rem',
spaceNormal: '0.75rem',
disabledStyle: 'dim',
@@ -435,6 +439,15 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT
customColors?.['rgb-surface-primary'] !== undefined
? { 'rgb-chart-widget-surface': customColors['rgb-surface-primary'] }
: {};
+ /**
+ * The thumb was painted `surface-primary` before it had a role, so a theme that repaints that
+ * surface keeps the knob it drew against its tracks.
+ */
+ const switchThumbFallback =
+ customColors?.['rgb-switch-thumb'] === undefined &&
+ customColors?.['rgb-surface-primary'] !== undefined
+ ? { 'rgb-switch-thumb': customColors['rgb-surface-primary'] }
+ : {};
const chartWidgetStrokeFallback =
customColors?.['rgb-chart-widget-stroke'] === undefined &&
customColors?.['rgb-border-light'] !== undefined
@@ -506,6 +519,7 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT
...proseLinkFallback,
...chartWidgetSurfaceFallback,
...chartWidgetStrokeFallback,
+ ...switchThumbFallback,
...borderControlFallback,
...focusFallback,
...pressedFallback,
diff --git a/packages/client/src/theme/semanticTokens.spec.ts b/packages/client/src/theme/semanticTokens.spec.ts
index 14d8d6c664..6a4e742b79 100644
--- a/packages/client/src/theme/semanticTokens.spec.ts
+++ b/packages/client/src/theme/semanticTokens.spec.ts
@@ -507,7 +507,7 @@ describe('verified fill defaults', () => {
/** The shared `Switch` paints this track, so it travels with the package rather
* than the app stylesheet. It is a UI component boundary under WCAG 1.4.11 and
- * has to stay distinct from the `surface-primary` thumb on it and from the
+ * has to stay distinct from the `switch-thumb` knob on it and from the
* `surface-inverted` fill it swaps with when checked. */
describe.each([
['default', defaultTheme],
@@ -519,14 +519,12 @@ describe.each([
])('%s switch track', (_name, theme: IThemeRGB) => {
it('keeps the unchecked track at the 3:1 mark floor against thumb and checked fill', () => {
const track = toRgb(theme, 'rgb-switch-unchecked');
- (['rgb-surface-primary', 'rgb-surface-inverted'] as Array<keyof IThemeRGB>).forEach(
- (surface) => {
- expect({ surface, ok: contrast(track, toRgb(theme, surface)) >= WCAG_MARK_MIN }).toEqual({
- surface,
- ok: true,
- });
- },
- );
+ (['rgb-switch-thumb', 'rgb-surface-inverted'] as Array<keyof IThemeRGB>).forEach((surface) => {
+ expect({ surface, ok: contrast(track, toRgb(theme, surface)) >= WCAG_MARK_MIN }).toEqual({
+ surface,
+ ok: true,
+ });
+ });
});
});
@@ -546,6 +544,16 @@ describe('switch track defaults', () => {
darkTheme['rgb-switch-unchecked'],
]);
});
+
+ it('declares the stock thumb the registry paints', () => {
+ const stockStyles = readFileSync(join(__dirname, 'defaults.css'), 'utf8');
+
+ const declared = [...stockStyles.matchAll(/--switch-thumb:\s*([^;]+);/g)].map((match) =>
+ match[1].trim(),
+ );
+
+ expect(declared).toEqual([defaultTheme['rgb-switch-thumb'], darkTheme['rgb-switch-thumb']]);
+ });
});
/** The syntax palette used to live as raw hex in `style.css`, which meant a
diff --git a/packages/client/src/theme/tailwind.spec.js b/packages/client/src/theme/tailwind.spec.js
index dea1604ab1..3208c172b2 100644
--- a/packages/client/src/theme/tailwind.spec.js
+++ b/packages/client/src/theme/tailwind.spec.js
@@ -103,6 +103,10 @@ describe('LibreChat Tailwind preset', () => {
const roles = [
['font-theme-ui', '--theme-font-family', defaultAppearance.fontFamily],
['h-theme-control', '--theme-control-height', defaultAppearance.controlHeight],
+ ['h-theme-switch', '--theme-switch-height', defaultAppearance.switchHeight],
+ ['w-theme-switch', '--theme-switch-width', defaultAppearance.switchWidth],
+ ['size-theme-switch-thumb', '--theme-switch-height', defaultAppearance.switchHeight],
+ ['translate-x-theme-switch-travel', '--theme-switch-width', defaultAppearance.switchWidth],
['p-theme-compact', '--theme-space-compact', defaultAppearance.spaceCompact],
['p-theme-normal', '--theme-space-normal', defaultAppearance.spaceNormal],
['p-theme-control-touch', '--theme-control-height', defaultAppearance.controlHeight],
diff --git a/packages/client/src/theme/themes/clickhouse.ts b/packages/client/src/theme/themes/clickhouse.ts
index 3f39d788e8..6564bb2a37 100644
--- a/packages/client/src/theme/themes/clickhouse.ts
+++ b/packages/client/src/theme/themes/clickhouse.ts
@@ -153,6 +153,7 @@ export const clickHouseLightTheme: IThemeRGB = {
// Switch
'rgb-switch-unchecked': '128 134 145', // #808691 (palette.slate.500)
+ 'rgb-switch-thumb': '255 255 255', // #ffffff (switch.color.indicator.default)
// Presentation
'rgb-presentation': '255 255 255', // #ffffff (background.default)
@@ -285,6 +286,7 @@ export const clickHouseDarkTheme: IThemeRGB = {
// Switch
'rgb-switch-unchecked': '128 128 128', // #808080 (palette.neutral.500)
+ 'rgb-switch-thumb': '21 21 21', // #151515 (switch.color.indicator.default)
// Presentation
'rgb-presentation': '31 31 28', // #1f1f1c (background.default)
@@ -353,6 +355,8 @@ const clickHouseShape = {
modalScrimOpacity: '0.75', // dialog.color.opaqueBackground alpha
/** Click UI paints disabled controls in fixed fills (`#dfdfdf` / `#414141`) rather than fading them. */
disabledStyle: 'fill' as const,
+ switchWidth: '2rem', // switch.size.width
+ switchHeight: '1rem', // switch.size.height
motionFast: '100ms', // transition.duration.medium, the step transition.default runs at
motionNormal: '150ms', // transition.duration.smooth
};
diff --git a/packages/client/src/theme/themes/clickui.json b/packages/client/src/theme/themes/clickui.json
index a70285b835..1fe2f68ba4 100644
--- a/packages/client/src/theme/themes/clickui.json
+++ b/packages/client/src/theme/themes/clickui.json
@@ -39,6 +39,8 @@
"click.switch.color.background.default": "#cccfd3",
"click.switch.color.indicator.default": "#ffffff",
"click.switch.radii.all": "9999px",
+ "click.switch.size.height": "1rem",
+ "click.switch.size.width": "2rem",
"click.table.header.color.background.default": "#f6f7fa",
"click.table.header.color.title.default": "#161517",
"click.table.radii.all": "0.25rem",
@@ -141,6 +143,8 @@
"click.switch.color.background.default": "#606060",
"click.switch.color.indicator.default": "#151515",
"click.switch.radii.all": "9999px",
+ "click.switch.size.height": "1rem",
+ "click.switch.size.width": "2rem",
"click.table.header.color.background.default": "#282828",
"click.table.header.color.title.default": "rgb(97.5% 97.5% 97.5%)",
"click.table.radii.all": "0.25rem",
diff --git a/packages/client/src/theme/themes/clickui.spec.ts b/packages/client/src/theme/themes/clickui.spec.ts
index ee63ac5773..0c7821054e 100644
--- a/packages/client/src/theme/themes/clickui.spec.ts
+++ b/packages/client/src/theme/themes/clickui.spec.ts
@@ -145,6 +145,7 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>
'rgb-series-7': 'palette.babyblue.600',
'rgb-series-8': 'global.color.chart.default.teal',
'rgb-switch-unchecked': 'palette.slate.500',
+ 'rgb-switch-thumb': 'click.switch.color.indicator.default',
'rgb-presentation': 'global.color.background.default',
},
dark: {
@@ -249,6 +250,7 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>
'rgb-series-7': 'global.color.chart.default.babyblue',
'rgb-series-8': 'global.color.chart.default.teal',
'rgb-switch-unchecked': 'palette.neutral.500',
+ 'rgb-switch-thumb': 'click.switch.color.indicator.default',
'rgb-presentation': 'global.color.background.default',
},
};
@@ -311,6 +313,8 @@ const appearanceSources: Partial<Record<keyof IThemeAppearance, string>> = {
scrimOpacity: 'click.dialog.color.opaqueBackground.default',
alertScrimOpacity: 'click.dialog.color.opaqueBackground.default',
modalScrimOpacity: 'click.dialog.color.opaqueBackground.default',
+ switchWidth: 'click.switch.size.width',
+ switchHeight: 'click.switch.size.height',
motionFast: 'transition.duration.medium',
motionNormal: 'transition.duration.smooth',
};
@@ -438,7 +442,7 @@ function comparable(key: keyof IThemeAppearance, raw: string | number): string {
* every decision; the floors below only move up.
*/
type ParityKind = 'color' | 'shape';
-type Utility = 'bg' | 'text' | 'border' | 'rounded';
+type Utility = 'bg' | 'text' | 'border' | 'rounded' | 'w' | 'h';
interface ParityProbe {
/** The Click UI component token the primitive should reproduce. */
@@ -627,6 +631,18 @@ const parityProbes: Record<string, ParityProbe> = {
utility: 'bg',
element: () => switchProbe(false)().firstElementChild ?? document.body,
},
+ 'Switch width': {
+ token: 'click.switch.size.width',
+ kind: 'shape',
+ utility: 'w',
+ element: switchProbe(false),
+ },
+ 'Switch height': {
+ token: 'click.switch.size.height',
+ kind: 'shape',
+ utility: 'h',
+ element: switchProbe(false),
+ },
'Switch corner': {
token: 'click.switch.radii.all',
kind: 'shape',
@@ -685,8 +701,8 @@ const parityProbes: Record<string, ParityProbe> = {
/** The fewest decisions per mode that must match; raise a floor when a change closes a gap. */
const parityFloors: Record<ThemeMode, Record<ParityKind, number>> = {
- light: { color: 6, shape: 6 },
- dark: { color: 6, shape: 6 },
+ light: { color: 6, shape: 8 },
+ dark: { color: 7, shape: 8 },
};
const radiusRoles: Record<string, keyof IThemeAppearance> = {
@@ -704,12 +720,26 @@ const radiusRoles: Record<string, keyof IThemeAppearance> = {
const fixedRadii: Record<string, string> = { full: '9999px', none: '0px' };
+const sizeRoles: Record<'w' | 'h', Record<string, keyof IThemeAppearance>> = {
+ w: { 'theme-switch': 'switchWidth' },
+ h: { 'theme-switch': 'switchHeight', 'theme-control': 'controlHeight' },
+};
+
/** A `border`, `border-2` or one-sided `border-b` class, the width a border color needs to show. */
const drawsBorder = (classes: string[]) =>
classes.some((name) => /^border(-[0-9]+|-[xytblrse](-[0-9]+)?)?$/.test(name));
type Resolved = ReturnType<typeof resolveTheme>;
+/** A `w-*` or `h-*` step: a theme role, or Tailwind's 0.25rem spacing scale. */
+function sizeValue(utility: 'w' | 'h', name: string, resolved: Resolved): string | undefined {
+ const role = sizeRoles[utility][name];
+ if (role !== undefined) {
+ return resolved.appearance[role];
+ }
+ return /^[0-9.]+$/.test(name) ? `${Number(name) / 4}rem` : undefined;
+}
+
function roleColor(resolved: Resolved, name: string): Rgba | undefined {
const [role, alpha] = name.split('/');
if (role === 'transparent') {
@@ -733,6 +763,10 @@ function paintedRole(element: Element, probe: ParityProbe, resolved: Resolved):
if (probe.utility === 'rounded') {
return names.find((name) => name in radiusRoles || name in fixedRadii);
}
+ if (probe.utility === 'w' || probe.utility === 'h') {
+ const utility = probe.utility;
+ return names.find((name) => sizeValue(utility, name, resolved) !== undefined);
+ }
if (probe.utility === 'border' && !drawsBorder(classes)) {
return undefined;
}
@@ -757,6 +791,16 @@ const sameColor = (a: Rgba, b: Rgba) =>
(a.slice(0, 3).every((value, index) => Math.abs(value - b[index]) < 1) &&
Math.abs(a[3] - b[3]) < 0.01);
+function shapeValue(utility: Utility, role: string | undefined, resolved: Resolved): string {
+ if (role === undefined) {
+ return utility === 'rounded' ? '0px' : 'auto';
+ }
+ if (utility === 'w' || utility === 'h') {
+ return sizeValue(utility, role, resolved) ?? 'auto';
+ }
+ return fixedRadii[role] ?? resolved.appearance[radiusRoles[role]];
+}
+
interface ParityResult {
decision: string;
kind: ParityKind;
@@ -777,8 +821,7 @@ function measure(mode: ThemeMode, decision: string, probe: ParityProbe): ParityR
cleanup();
const base = { decision, kind: probe.kind, clickUi: source, deviation: probe.deviation };
if (probe.kind === 'shape') {
- const theme =
- role === undefined ? '0px' : (fixedRadii[role] ?? resolved.appearance[radiusRoles[role]]);
+ const theme = shapeValue(probe.utility, role, resolved);
const painted = role === undefined ? 'unpainted' : `${probe.utility}-${role}`;
return { ...base, theme: `${painted} = ${theme}`, match: theme === source };
}
diff --git a/packages/client/src/theme/themes/dark.ts b/packages/client/src/theme/themes/dark.ts
index 59a1e195d1..a4df843d78 100644
--- a/packages/client/src/theme/themes/dark.ts
+++ b/packages/client/src/theme/themes/dark.ts
@@ -150,6 +150,7 @@ export const darkTheme: IThemeRGB = {
/** Unchecked switch track. 3.38:1 against the page and the `surface-primary`
* thumb, 5.74:1 against the checked `surface-inverted` track. */
'rgb-switch-unchecked': '102 102 102', // #666666
+ 'rgb-switch-thumb': '13 13 13', // #0d0d0d (gray-900, matching surface-primary)
// Presentation
'rgb-presentation': '33 33 33', // #212121 (gray-800)
diff --git a/packages/client/src/theme/themes/default.ts b/packages/client/src/theme/themes/default.ts
index add4e13323..cd91c854d1 100644
--- a/packages/client/src/theme/themes/default.ts
+++ b/packages/client/src/theme/themes/default.ts
@@ -137,6 +137,7 @@ export const defaultTheme: IThemeRGB = {
* `surface-primary` thumb, 5.91:1 against the checked `surface-inverted`
* track, so the control reads in either state. */
'rgb-switch-unchecked': '148 148 148', // #949494
+ 'rgb-switch-thumb': '255 255 255', // #fff (white, matching surface-primary)
// Presentation
'rgb-presentation': '255 255 255', // #fff (white)
diff --git a/packages/client/src/theme/themes/highContrast.spec.ts b/packages/client/src/theme/themes/highContrast.spec.ts
index 22ba59f934..136166e459 100644
--- a/packages/client/src/theme/themes/highContrast.spec.ts
+++ b/packages/client/src/theme/themes/highContrast.spec.ts
@@ -289,7 +289,7 @@ describe.each([
theme,
WCAG_NON_TEXT,
['rgb-switch-unchecked'],
- ['rgb-surface-primary', 'rgb-surface-inverted'],
+ ['rgb-surface-primary', 'rgb-switch-thumb', 'rgb-surface-inverted'],
),
).toEqual([]);
});
diff --git a/packages/client/src/theme/themes/highContrast.ts b/packages/client/src/theme/themes/highContrast.ts
index 0e7e78a15b..0fe04e56af 100644
--- a/packages/client/src/theme/themes/highContrast.ts
+++ b/packages/client/src/theme/themes/highContrast.ts
@@ -175,6 +175,7 @@ export const highContrastLightTheme: IThemeRGB = {
* the page and the `surface-primary` thumb, 3.66:1 against the checked
* `surface-inverted` track. */
'rgb-switch-unchecked': '102 102 102', // #666666
+ 'rgb-switch-thumb': '255 255 255', // #ffffff (matching surface-primary)
// Presentation
'rgb-presentation': '255 255 255', // #ffffff
@@ -323,6 +324,7 @@ export const highContrastDarkTheme: IThemeRGB = {
/** Unchecked switch track: 5.32:1 against the page and the `surface-primary`
* thumb, 3.95:1 against the checked `surface-inverted` track. */
'rgb-switch-unchecked': '128 128 128', // #808080
+ 'rgb-switch-thumb': '0 0 0', // #000000 (matching surface-primary)
// Presentation
'rgb-presentation': '0 0 0', // #000000
diff --git a/packages/client/src/theme/tokens.css b/packages/client/src/theme/tokens.css
index 5073d2614b..d633d2c722 100644
--- a/packages/client/src/theme/tokens.css
+++ b/packages/client/src/theme/tokens.css
@@ -132,6 +132,8 @@
--color-chart-widget-surface: rgb(var(--chart-widget-surface));
--color-chart-widget-stroke: rgb(var(--chart-widget-stroke));
--color-switch-unchecked: rgb(var(--switch-unchecked));
+ /* Falls back to the surface it was painted before the role, for a stylesheet that predates it. */
+ --color-switch-thumb: rgb(var(--switch-thumb, var(--surface-primary)));
}
/* The plain radius, font, type scale and shadow utilities read theme-owned properties, so a theme
diff --git a/packages/client/src/theme/tokens.spec.ts b/packages/client/src/theme/tokens.spec.ts
index 5741d8a39c..b3e901e1a1 100644
--- a/packages/client/src/theme/tokens.spec.ts
+++ b/packages/client/src/theme/tokens.spec.ts
@@ -82,11 +82,17 @@ describe('theme color tokens', () => {
});
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']);
+ const css = await generate([
+ 'bg-surface-primary',
+ 'text-text-secondary',
+ 'bg-series-1',
+ 'bg-switch-thumb',
+ ]);
expect(css).toContain('rgb(var(--surface-primary))');
expect(css).toContain('rgb(var(--text-secondary))');
expect(css).toContain('rgb(var(--series-1))');
+ expect(css).toContain('rgb(var(--switch-thumb, var(--surface-primary)))');
});
it('keeps a border token on its intrinsic alpha and still takes an opacity modifier', async () => {
diff --git a/packages/client/src/theme/types/index.ts b/packages/client/src/theme/types/index.ts
index 07fda4fbae..919e886d2d 100644
--- a/packages/client/src/theme/types/index.ts
+++ b/packages/client/src/theme/types/index.ts
@@ -163,6 +163,8 @@ export interface IThemeRGB {
* got a switch with no track at all.
*/
'rgb-switch-unchecked'?: string;
+ /** The switch's knob in both states, painted over the unchecked track and the checked fill. */
+ 'rgb-switch-thumb'?: string;
// Presentation
'rgb-presentation'?: string;
@@ -281,6 +283,7 @@ export interface IThemeVariables {
'--series-8': string;
'--switch-unchecked': string;
+ '--switch-thumb': string;
'--presentation': string;
}
@@ -381,6 +384,7 @@ export interface IThemeColors {
'series-6'?: string;
'series-7'?: string;
'switch-unchecked'?: string;
+ 'switch-thumb'?: string;
'series-8'?: string;
presentation?: string;
@@ -410,6 +414,8 @@ export interface IThemeAppearance {
radius2xl: string;
radius3xl: string;
controlHeight: string;
+ switchWidth: string;
+ switchHeight: string;
spaceCompact: string;
spaceNormal: string;
/** `dim` fades a disabled control to half opacity; `fill` paints it in the disabled roles. */
diff --git a/packages/client/src/theme/utils/applyTheme.spec.ts b/packages/client/src/theme/utils/applyTheme.spec.ts
index 2c6ef97a7f..eda4667612 100644
--- a/packages/client/src/theme/utils/applyTheme.spec.ts
+++ b/packages/client/src/theme/utils/applyTheme.spec.ts
@@ -18,6 +18,7 @@ const semanticProperties = [
'--text-muted',
'--chart-widget-surface',
'--chart-widget-stroke',
+ '--switch-thumb',
'--border-destructive',
'--border-control',
'--status-success',
@@ -365,6 +366,22 @@ describe('applyTheme', () => {
expect(root.hasAttribute(THEME_DISABLED_ATTRIBUTE)).toBe(false);
});
+ it('keeps the switch knob of a legacy theme on the surface it repainted', () => {
+ const root = document.documentElement;
+
+ applyTheme({ 'rgb-surface-primary': '20 21 22' }, root);
+
+ expect(root.style.getPropertyValue('--switch-thumb')).toBe('20 21 22');
+ });
+
+ it('leaves an explicit switch knob alone', () => {
+ const root = document.documentElement;
+
+ applyTheme({ 'rgb-surface-primary': '20 21 22', 'rgb-switch-thumb': '1 2 3' }, root);
+
+ expect(root.style.getPropertyValue('--switch-thumb')).toBe('1 2 3');
+ });
+
it('carries a legacy light border onto the control outline', () => {
const root = document.documentElement;
diff --git a/packages/client/src/theme/utils/applyTheme.ts b/packages/client/src/theme/utils/applyTheme.ts
index a5e6c24c53..cee27214c8 100644
--- a/packages/client/src/theme/utils/applyTheme.ts
+++ b/packages/client/src/theme/utils/applyTheme.ts
@@ -69,6 +69,11 @@ function mapColors(colors: IThemeRGB, base?: IThemeRGB): Array<[string, string]>
variables.push(['--chart-widget-surface', colors['rgb-surface-primary']]);
}
+ /** The switch knob was painted `surface-primary` before it had a role, as in `resolveTheme`. */
+ if (colors['rgb-switch-thumb'] === undefined && colors['rgb-surface-primary'] !== undefined) {
+ variables.push(['--switch-thumb', colors['rgb-surface-primary']]);
+ }
+
if (colors['rgb-chart-widget-stroke'] === undefined && colors['rgb-border-light'] !== undefined) {
variables.push(['--chart-widget-stroke', colors['rgb-border-light']]);
}
diff --git a/packages/client/tailwind.preset.cjs b/packages/client/tailwind.preset.cjs
index 903bbbd716..c7d2c97bf4 100644
--- a/packages/client/tailwind.preset.cjs
+++ b/packages/client/tailwind.preset.cjs
@@ -7,6 +7,11 @@ module.exports = {
},
height: {
'theme-control': 'var(--theme-control-height, 2.25rem)',
+ 'theme-switch': 'var(--theme-switch-height, 1.5rem)',
+ },
+ width: {
+ /** Never narrower than the track is tall, so the knob always has somewhere to travel. */
+ 'theme-switch': 'max(var(--theme-switch-width, 2.75rem), var(--theme-switch-height, 1.5rem))',
},
spacing: {
'theme-compact': 'var(--theme-space-compact, 0.375rem)',
@@ -18,6 +23,11 @@ module.exports = {
* controls is never shrunk on a phone. Pair it with `touch:`.
*/
'theme-control-touch': 'max(var(--theme-control-height, 2.25rem), 2.75rem)',
+ /** The switch knob inside the track's 2px border, in px so it holds at any root size,
+ * and how far it travels when checked (the borders cancel out of the travel). */
+ 'theme-switch-thumb': 'max(0px, calc(var(--theme-switch-height, 1.5rem) - 4px))',
+ 'theme-switch-travel':
+ 'max(0px, calc(var(--theme-switch-width, 2.75rem) - var(--theme-switch-height, 1.5rem)))',
},
keyframes: {
/** Discord-style "connecting" dots: each dot lifts and brightens in
diff --git a/packages/data-provider/src/theme.ts b/packages/data-provider/src/theme.ts
index 3f8f6e9364..fb78e8d083 100644
--- a/packages/data-provider/src/theme.ts
+++ b/packages/data-provider/src/theme.ts
@@ -116,6 +116,7 @@ export const themeColorTokens = Object.freeze([
'rgb-series-7',
'rgb-series-8',
'rgb-switch-unchecked',
+ 'rgb-switch-thumb',
'rgb-presentation',
] as const);
@@ -185,6 +186,12 @@ export const isThemeRGB = (value: unknown): value is string => {
const isLength = (value: unknown): value is string =>
typeof value === 'string' &&
(cssLengthPattern.test(value) || cssLengthDifferencePattern.test(value));
+/**
+ * A switch dimension is a positive px or rem length: `em` would follow the component's own font
+ * size, and the pair is only comparable when both sides share one unit.
+ */
+const isSwitchLength = (value: unknown): value is string =>
+ typeof value === 'string' && /^\d*\.?\d+(px|rem)$/.test(value) && parseFloat(value) > 0;
const isFontFamily = (value: unknown): value is string =>
typeof value === 'string' && value.trim().length > 0 && !/[;{}]/.test(value);
@@ -293,6 +300,8 @@ const appearanceValidators = {
radius2xl: isLength,
radius3xl: isLength,
controlHeight: isLength,
+ switchWidth: isSwitchLength,
+ switchHeight: isSwitchLength,
spaceCompact: isLength,
spaceNormal: isLength,
/** `dim` fades a disabled control to half opacity; `fill` paints it in the disabled roles. */
@@ -371,6 +380,64 @@ export interface ThemeReadOptions {
ignoreFutureColors?: boolean;
}
+/** LibreChat's own switch, which a theme naming only one of the two dimensions keeps for the other. */
+export const defaultSwitchSize = Object.freeze({ switchWidth: '2.75rem', switchHeight: '1.5rem' });
+
+const switchLength = (value: unknown): [number, 'px' | 'rem'] | undefined => {
+ const match = typeof value === 'string' ? /^(\d*\.?\d+)(px|rem)$/.exec(value) : null;
+ return match ? [Number(match[1]), match[2] as 'px' | 'rem'] : undefined;
+};
+
+/**
+ * The switch knob is the height less the track's 4px of border, and it travels the width less the
+ * height, so the pair the switch will draw (a missing side taken from the default) has to leave a
+ * knob and a forward travel at any root size. That only holds when both sides share a unit, so a
+ * pair is compared in its own unit and a mixed pair is rejected. A rem height of at least 0.5rem
+ * clears the border at any root above 8px; below that the preset clamps the knob at zero.
+ */
+function collectSwitchIssues(appearance: Record<string, unknown>, base: string[]): ThemeIssue[] {
+ if (appearance.switchWidth === undefined && appearance.switchHeight === undefined) {
+ return [];
+ }
+ const widthValue = appearance.switchWidth ?? defaultSwitchSize.switchWidth;
+ const heightValue = appearance.switchHeight ?? defaultSwitchSize.switchHeight;
+ const width = switchLength(widthValue);
+ const height = switchLength(heightValue);
+ if (!width || !height) {
+ return [];
+ }
+ if (width[1] !== height[1]) {
+ return [
+ issue(
+ [...base, 'switchWidth'],
+ `switchWidth and switchHeight must share a unit (the default is rem): ${widthValue}, ${heightValue}`,
+ ),
+ ];
+ }
+ const issues: ThemeIssue[] = [];
+ const minimumHeight = height[1] === 'px' ? 4 : 0.5;
+ const tooShort = height[1] === 'px' ? height[0] <= minimumHeight : height[0] < minimumHeight;
+ if (tooShort) {
+ issues.push(
+ issue(
+ [...base, 'switchHeight'],
+ height[1] === 'px'
+ ? `switchHeight must exceed the 4px track border: ${heightValue}`
+ : `switchHeight must be at least 0.5rem to clear the 4px track border: ${heightValue}`,
+ ),
+ );
+ }
+ if (width[0] <= height[0]) {
+ issues.push(
+ issue(
+ [...base, 'switchWidth'],
+ `switchWidth must exceed switchHeight so the knob can travel: ${widthValue}, ${heightValue}`,
+ ),
+ );
+ }
+ return issues;
+}
+
/** The color and appearance tokens this reader does not know, which a resolved theme leaves out. */
export function collectThemeWarningIssues(
theme: unknown,
@@ -479,6 +546,9 @@ function collectModeIssues(
);
}
});
+ if (isPlainThemeRecord(appearance)) {
+ issues.push(...collectSwitchIssues(appearance, [...base, 'appearance']));
+ }
}
if (brands !== undefined && !isPlainThemeRecord(brands)) {