From 50ff19829aa5774f37cd3a33cd86e035b081c6a4 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:34:29 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=90=20feat:=20Radius=20and=20Font=20Sc?= =?UTF-8?q?ales=20Follow=20the=20Theme=20(#16340)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Radius and Font Scales Follow the Theme Map Tailwind's radius scale (sm through 3xl, plus bare `rounded`) and the sans and mono families to theme-owned appearance properties in the app's `@theme inline` block, so a theme definition reshapes the existing plain utilities instead of only the `theme-*` roles. Defaults reproduce the values those utilities resolved to before, and the JS config entries and the bare `--radius` they replace are removed. * fix: Keep the Pixel Offsets in the Small Radius Defaults The old `rounded-sm` and `rounded-md` were `calc(var(--radius) - 4px)` and `calc(var(--radius) - 2px)`. Rem-only defaults matched them only at a 16px root, so keep the calc form and match at every root font size. * test: Resolve Custom Properties Before Comparing the Code Font `code` and `.font-mono` now both reach the mono stack through custom properties, so compare the resolved stacks rather than the raw declarations. * fix: Leave Bare rounded on Its Fixed Radius Bare `rounded` was a fixed 0.25rem, which the `sm` default only equals at a 16px root now that it keeps its px offset, so it no longer follows the `sm` step. * fix: Accept the calc() Radius Defaults the Registry Exports * test: Cover the Theme Radius and Font Scales in the Browser * fix: Require Units on Both Operands of a calc() Radius --- client/src/style.css | 35 ++++- client/src/style.spec.ts | 41 ++++- client/tailwind.config.cjs | 38 +---- .../scenarios/theme-radius-font-scale.spec.ts | 141 ++++++++++++++++++ packages/client/src/theme/README.md | 12 +- packages/client/src/theme/registry.spec.ts | 31 ++++ packages/client/src/theme/registry.ts | 34 ++++- packages/client/src/theme/tailwind.spec.js | 104 ++++++++++++- packages/client/src/theme/types/index.ts | 7 + .../client/src/theme/utils/applyTheme.spec.ts | 44 +++++- 10 files changed, 437 insertions(+), 50 deletions(-) create mode 100644 e2e/specs/mock/scenarios/theme-radius-font-scale.spec.ts diff --git a/client/src/style.css b/client/src/style.css index f3abda65e1..4a5da50456 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -11,6 +11,23 @@ --color-green-*: initial; } +/* The plain radius and font utilities read theme-owned properties, so a theme definition reshapes + * the 900-odd `rounded-*`, `font-sans` and `font-mono` call sites without a migration. The + * defaults in the `html` block reproduce the scale these utilities resolved to before. Bare + * `rounded` stays Tailwind's fixed 0.25rem: `sm` keeps its px offset, so the two part at a + * non-16px root. App-only: the published preset keeps its own `sm`, which differs from this + * scale, so consumers' corners do not move. */ +@theme inline { + --radius-sm: var(--theme-radius-sm); + --radius-md: var(--theme-radius-md); + --radius-lg: var(--theme-radius-lg); + --radius-xl: var(--theme-radius-xl); + --radius-2xl: var(--theme-radius-2xl); + --radius-3xl: var(--theme-radius-3xl); + --font-sans: var(--theme-font-family); + --font-mono: var(--theme-mono-font-family); +} + /* Tailwind v4 changed two preflight defaults this app was built against. Each rule below * restores the v3 default rather than adopting the new one, so the upgrade carries no visual * change; drop one only as a deliberate design decision. @@ -280,15 +297,29 @@ html { --surface-fixed: var(--white); --surface-fixed-hover: var(--gray-100); --text-fixed: var(--gray-800); - --radius: 0.5rem; --theme-control-radius: 0.75rem; --theme-round-control-radius: 9999px; --theme-surface-radius: 1rem; --theme-large-surface-radius: 1.5rem; + --theme-radius-sm: calc(0.5rem - 4px); + --theme-radius-md: calc(0.5rem - 2px); + --theme-radius-lg: 0.5rem; + --theme-radius-xl: 0.75rem; + --theme-radius-2xl: 1rem; + --theme-radius-3xl: 1.5rem; --theme-control-height: 2.25rem; --theme-space-compact: 0.375rem; --theme-space-normal: 0.75rem; --theme-font-family: Inter, sans-serif; + /* Roboto Mono is self-hosted (the `@font-face` block below), so code renders the same on every + * platform with real bold and italic faces. The tail is reached while the font loads, if it + * fails, and per glyph for what the bundled latin subset omits (box drawing in terminal output + * most visibly), ordered so those glyphs keep Roboto Mono's advance width: `ui-monospace` is SF + * Mono on macOS, Cascadia Mono ships with Windows Terminal, and Consolas is last because it is + * narrower than the rest. */ + --theme-mono-font-family: + 'Roboto Mono', ui-monospace, SFMono-Regular, Menlo, 'Cascadia Mono', 'Liberation Mono', + Consolas, monospace; --theme-elevation-surface: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --theme-motion-fast: 150ms; --theme-motion-normal: 200ms; @@ -1245,7 +1276,7 @@ p > small { } /* `code`, `kbd`, `samp` and `pre` take their font from Tailwind's preflight, which - reads `theme.fontFamily.mono` — see `tailwind.config.cjs`. Do not restate it here: + reads `--font-mono`, mapped to `--theme-mono-font-family` above. Do not restate it here: this file used to, with `!important`, which silently beat every `font-mono` class in the app and pinned code to faces the repository does not ship. */ code.language-text, diff --git a/client/src/style.spec.ts b/client/src/style.spec.ts index d8c6747972..3f3244914d 100644 --- a/client/src/style.spec.ts +++ b/client/src/style.spec.ts @@ -21,17 +21,43 @@ const selectorOf = (parent: Container | undefined): string => { const collapse = (value: string): string => value.replace(/\s+/g, ' ').trim(); +/** Replaces each `var(--name, fallback)` with the declared value of `--name`, or else its + * fallback, until none remain. A reference with neither is an error, not an empty string. */ +const resolveVars = (value: string, properties: Map, depth = 0): string => { + const start = value.indexOf('var('); + if (start === -1 || depth > 10) { + return collapse(value); + } + let end = start + 4; + for (let open = 1; open > 0; end++) { + if (value[end] === '(') { + open++; + } else if (value[end] === ')') { + open--; + } + } + const inner = value.slice(start + 4, end - 1); + const comma = inner.indexOf(','); + const name = (comma === -1 ? inner : inner.slice(0, comma)).trim(); + const replacement = properties.get(name) ?? (comma === -1 ? undefined : inner.slice(comma + 1)); + if (replacement === undefined) { + throw new Error(`${name} is referenced but never declared`); + } + return resolveVars(value.slice(0, start) + replacement + value.slice(end), properties, depth + 1); +}; + const firstFamily = (value: string): string => collapse(value.split(',')[0]).replace(/^['"]/, '').replace(/['"]$/, ''); /** - * The code font is one decision: `theme.fontFamily.mono` in `tailwind.config.cjs`, which - * Tailwind's preflight applies to `code`, `kbd`, `samp` and `pre`, and which the - * `font-mono` utility carries. + * The code font is one decision: `--theme-mono-font-family` in `style.css`, mapped to + * `--font-mono`, which Tailwind's preflight applies to `code`, `kbd`, `samp` and `pre`, and + * which the `font-mono` utility carries. Both reach it through custom properties, so the + * declarations are compared after resolving them. * * `style.css` used to restate that decision with `!important`. Because `!important` beats * specificity, one stylesheet rule outranked every `font-mono` class in the app and pinned - * code to `Consolas, Söhne Mono, Monaco, …` — faces this repository does not ship, so code + * code to `Consolas, Söhne Mono, Monaco, …`: faces this repository does not ship, so code * rendered in Consolas on Windows and in Monaco on macOS, the latter carrying neither an * italic nor a bold face for the browser to use, hence synthesized ones. */ @@ -55,11 +81,16 @@ describe('code typography', () => { from: file, }); + const properties = new Map(); + compiled.root.walkDecls(/^--/, (declaration) => { + properties.set(declaration.prop, declaration.value); + }); + fontFamilies = []; compiled.root.walkDecls('font-family', (declaration) => { fontFamilies.push({ selector: collapse(selectorOf(declaration.parent)), - value: collapse(declaration.value), + value: resolveVars(declaration.value, properties), important: declaration.important === true, }); }); diff --git a/client/tailwind.config.cjs b/client/tailwind.config.cjs index 0c0178f882..c2671416bc 100644 --- a/client/tailwind.config.cjs +++ b/client/tailwind.config.cjs @@ -1,6 +1,6 @@ -// const { fontFamily } = require('tailwindcss/defaultTheme'); // Semantic colors are declared in -// packages/client/src/theme/tokens.css, which src/style.css imports. +// packages/client/src/theme/tokens.css, which src/style.css imports. The radius scale and the +// sans and mono families are theme-owned properties mapped in src/style.css. const libreChatTailwindPreset = require('../packages/client/tailwind.preset.cjs'); const compatibilityColors = require('../packages/client/tailwind.compat.cjs'); @@ -15,35 +15,6 @@ module.exports = { darkMode: ['class'], presets: [libreChatTailwindPreset], theme: { - fontFamily: { - sans: ['Inter', 'sans-serif'], - /** - * Roboto Mono is self-hosted (the `@font-face` block in `style.css`), so code - * renders the same on every platform and carries real bold and italic faces - * rather than ones the browser synthesizes by smearing and shearing. - * - * The tail is reached while the font loads, if it fails, and per glyph for the - * characters the bundled latin subset omits — box drawing in terminal output - * most visibly. It is ordered so those glyphs come from a face whose advance - * width matches Roboto Mono's and keeps its columns: `ui-monospace` resolves - * to SF Mono on macOS, and Cascadia Mono ships with Windows Terminal. - * Consolas is last of the named faces because it is narrower than the rest. - */ - mono: [ - 'Roboto Mono', - 'ui-monospace', - 'SFMono-Regular', - 'Menlo', - 'Cascadia Mono', - 'Liberation Mono', - 'Consolas', - 'monospace', - ], - }, - // fontFamily: { - // sans: ['Söhne', 'sans-serif'], - // mono: ['Söhne Mono', 'monospace'], - // }, extend: { colors: compatibilityColors, width: { @@ -120,11 +91,6 @@ module.exports = { 'refresh-link-spin': 'refresh-link-spin 650ms cubic-bezier(0.42, 0, 0.58, 1)', 'reset-spin': 'reset-spin 500ms cubic-bezier(0.22, 1, 0.36, 1)', }, - borderRadius: { - lg: 'var(--radius)', - md: 'calc(var(--radius) - 2px)', - sm: 'calc(var(--radius) - 4px)', - }, }, }, plugins: [ diff --git a/e2e/specs/mock/scenarios/theme-radius-font-scale.spec.ts b/e2e/specs/mock/scenarios/theme-radius-font-scale.spec.ts new file mode 100644 index 0000000000..c4593bcc5a --- /dev/null +++ b/e2e/specs/mock/scenarios/theme-radius-font-scale.spec.ts @@ -0,0 +1,141 @@ +import { expect, test } from '@playwright/test'; +import type { Locator, Page } from '@playwright/test'; +import { NEW_CHAT_PATH } from '../helpers'; +import { probeStyle } from './style.helpers'; + +/** + * The plain `rounded-*`, `font-sans` and `font-mono` utilities read `--theme-radius-*` and the + * theme font families, so a theme's appearance reshapes existing call sites. The mention menu + * carries `rounded-2xl` and opens from the composer, which makes it the shortest path to a real + * element on the radius scale. Every theme here pins light mode so the desktop-dark project + * cannot pick a mode the definition does not carry. + */ +test.describe.configure({ timeout: 120_000 }); + +async function storeTheme(page: Page, definition: Record) { + await page.addInitScript((theme) => { + localStorage.setItem('color-theme', 'light'); + localStorage.setItem('theme-definition', JSON.stringify(theme)); + localStorage.setItem('theme-source', 'definition'); + localStorage.removeItem('theme-colors'); + localStorage.removeItem('theme-name'); + }, definition); +} + +async function openComposer(page: Page): Promise { + await page.goto(NEW_CHAT_PATH, { timeout: 15000 }); + const composer = page.getByRole('textbox', { name: 'Message input' }); + await expect(composer).toBeVisible({ timeout: 30000 }); + return composer; +} + +async function openMentionMenu(page: Page): Promise { + const composer = await openComposer(page); + await composer.click(); + await composer.pressSequentially('@'); + const search = page.getByPlaceholder('Mention an endpoint'); + await expect(search).toBeVisible({ timeout: 15000 }); + const menu = page.locator('div.popover').filter({ has: search }); + await expect(menu).toBeVisible(); + return menu; +} + +const radius = (element: Locator) => + element.evaluate((node) => getComputedStyle(node).borderTopLeftRadius); + +test.describe('theme radius and font scales', () => { + test('without a theme the radius scale keeps its previous values @scenario:default-radius-scale-unchanged', async ({ + page, + }) => { + const menu = await openMentionMenu(page); + + expect(await radius(menu)).toBe('16px'); + expect(await probeStyle(page, 'rounded-sm', 'border-top-left-radius')).toBe('4px'); + expect(await probeStyle(page, 'rounded-md', 'border-top-left-radius')).toBe('6px'); + expect(await probeStyle(page, 'rounded', 'border-top-left-radius')).toBe('4px'); + }); + + test('a theme radius step reshapes the mention menu @scenario:theme-radius-step-reshapes-mention-menu', async ({ + page, + }) => { + const theme = { + version: 1, + name: 'e2e-square', + modes: { light: { appearance: { radius2xl: '3px' } } }, + }; + await storeTheme(page, theme); + + const menu = await openMentionMenu(page); + await expect(page.locator('html')).toHaveAttribute('data-theme', theme.name); + + await expect.poll(() => radius(menu)).toBe('3px'); + }); + + test('theme font families reach the interface and code text @scenario:theme-font-families-reach-ui-and-code', async ({ + page, + }) => { + const theme = { + version: 1, + name: 'e2e-typefaces', + modes: { + light: { + appearance: { fontFamily: 'Georgia, serif', monoFontFamily: "'Courier New', monospace" }, + }, + }, + }; + await storeTheme(page, theme); + + const composer = await openComposer(page); + await expect(page.locator('html')).toHaveAttribute('data-theme', theme.name); + + await expect + .poll(() => composer.evaluate((node) => getComputedStyle(node).fontFamily)) + .toContain('Georgia'); + expect(await probeStyle(page, 'font-mono', 'font-family')).toContain('Courier New'); + expect(await probeStyle(page, '', 'font-family', 'code')).toContain('Courier New'); + }); + + test('the small radii keep their pixel offset at a larger root font size @scenario:small-radii-keep-px-offset-at-larger-root-font', async ({ + page, + }) => { + await openComposer(page); + /** Stands in for a browser whose default font size is 20px. */ + await page.addStyleTag({ content: 'html { font-size: 20px !important; }' }); + + expect(await probeStyle(page, 'rounded-sm', 'border-top-left-radius')).toBe('6px'); + expect(await probeStyle(page, 'rounded-md', 'border-top-left-radius')).toBe('8px'); + expect(await probeStyle(page, 'rounded', 'border-top-left-radius')).toBe('5px'); + }); + + test('a theme with calc() radii like the shipped defaults applies @scenario:calc-radius-theme-applies', async ({ + page, + }) => { + const theme = { + version: 1, + name: 'e2e-offset-radii', + modes: { light: { appearance: { radiusSm: 'calc(1rem - 4px)' } } }, + }; + await storeTheme(page, theme); + + await openComposer(page); + await expect(page.locator('html')).toHaveAttribute('data-theme', theme.name); + + expect(await probeStyle(page, 'rounded-sm', 'border-top-left-radius')).toBe('12px'); + }); + + test('a theme with a malformed radius is rejected and the default radius stays @scenario:malformed-radius-theme-keeps-default', async ({ + page, + }) => { + const theme = { + version: 1, + name: 'e2e-malformed-radius', + modes: { light: { appearance: { radius2xl: 'calc(1rem - var(--x))' } } }, + }; + await storeTheme(page, theme); + + const menu = await openMentionMenu(page); + + await expect(page.locator('html')).not.toHaveAttribute('data-theme', theme.name); + expect(await radius(menu)).toBe('16px'); + }); +}); diff --git a/packages/client/src/theme/README.md b/packages/client/src/theme/README.md index 16c98470f3..0fb4a799dd 100644 --- a/packages/client/src/theme/README.md +++ b/packages/client/src/theme/README.md @@ -26,8 +26,16 @@ const compactTheme: ThemeDefinition = { {children}; ``` -The initial appearance registry intentionally covers only shared control shape, surface shape, -control height, compact/normal spacing, UI typography, surface elevation, and fast/normal motion. +The appearance registry covers shared control shape, surface shape, control height, compact/normal +spacing, UI and code typography, surface elevation, fast/normal motion, and the radius scale. + +In the LibreChat app the plain Tailwind utilities read theme-owned properties, so a theme reshapes +existing call sites without a migration: `rounded-sm` through `rounded-3xl` read `radiusSm` +through `radius3xl` (`--theme-radius-*`), `font-sans` reads `fontFamily` (`--theme-font-family`), +and `font-mono` reads `monoFontFamily` (`--theme-mono-font-family`). The defaults reproduce the +scale those utilities had before, so a theme that names none of them changes nothing. The mapping lives in the app stylesheet +(`client/src/style.css`), not the published `theme.css`, whose preset keeps its own `rounded-sm`. + `themeRGB`, `REACT_APP_THEME_*`, and the existing localStorage keys remain supported through legacy adapters. Theme application removes only variables owned by the theme module when a theme is reset. diff --git a/packages/client/src/theme/registry.spec.ts b/packages/client/src/theme/registry.spec.ts index c13deaf70f..05f4792596 100644 --- a/packages/client/src/theme/registry.spec.ts +++ b/packages/client/src/theme/registry.spec.ts @@ -503,6 +503,37 @@ describe('theme registry', () => { expect(() => resolveTheme(invalidTheme, 'light')).toThrow(TypeError); }); + /** A caller may seed a theme from the exported defaults or round-trip a resolved theme. */ + it('accepts its own appearance defaults, calc() radii included', () => { + const roundTrip = resolveTheme( + { version: 1, name: 'seeded', modes: { light: { appearance: { ...defaultAppearance } } } }, + 'light', + ); + + expect(roundTrip.appearance).toEqual(defaultAppearance); + expect( + validateThemeDefinition({ + version: 1, + name: 'offsets', + modes: { + light: { appearance: { radiusSm: 'calc(1rem + 2px)', radiusMd: 'calc(4px - 0px)' } }, + }, + }), + ).toEqual([]); + expect( + validateThemeDefinition({ + version: 1, + name: 'nested', + modes: { + light: { appearance: { radiusSm: 'calc(1rem - var(--x))', radiusMd: 'calc(4px - 0)' } }, + }, + }), + ).toEqual([ + 'Invalid appearance value for radiusSm: calc(1rem - var(--x))', + 'Invalid appearance value for radiusMd: calc(4px - 0)', + ]); + }); + it('sanitizes malformed legacy colors without weakening definition validation', () => { const legacyTheme = fromLegacyTheme( { diff --git a/packages/client/src/theme/registry.ts b/packages/client/src/theme/registry.ts index bef9a29e8f..5d8f8e9c01 100644 --- a/packages/client/src/theme/registry.ts +++ b/packages/client/src/theme/registry.ts @@ -53,10 +53,17 @@ export const themeAppearanceProperties: Readonly< roundControlRadius: '--theme-round-control-radius', surfaceRadius: '--theme-surface-radius', largeSurfaceRadius: '--theme-large-surface-radius', + radiusSm: '--theme-radius-sm', + radiusMd: '--theme-radius-md', + radiusLg: '--theme-radius-lg', + radiusXl: '--theme-radius-xl', + radius2xl: '--theme-radius-2xl', + radius3xl: '--theme-radius-3xl', controlHeight: '--theme-control-height', spaceCompact: '--theme-space-compact', spaceNormal: '--theme-space-normal', fontFamily: '--theme-font-family', + monoFontFamily: '--theme-mono-font-family', elevationSurface: '--theme-elevation-surface', motionFast: '--theme-motion-fast', motionNormal: '--theme-motion-normal', @@ -67,10 +74,18 @@ export const defaultAppearance: IThemeAppearance = Object.freeze({ roundControlRadius: '9999px', surfaceRadius: '1rem', largeSurfaceRadius: '1.5rem', + radiusSm: 'calc(0.5rem - 4px)', + radiusMd: 'calc(0.5rem - 2px)', + radiusLg: '0.5rem', + radiusXl: '0.75rem', + radius2xl: '1rem', + radius3xl: '1.5rem', controlHeight: '2.25rem', spaceCompact: '0.375rem', spaceNormal: '0.75rem', fontFamily: 'Inter, sans-serif', + monoFontFamily: + "'Roboto Mono', ui-monospace, SFMono-Regular, Menlo, 'Cascadia Mono', 'Liberation Mono', Consolas, monospace", elevationSurface: '0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)', motionFast: '150ms', motionNormal: '200ms', @@ -153,6 +168,8 @@ export const highContrastTheme: ThemeDefinition = Object.freeze({ const rgbPattern = /^(\d{1,3})\s+(\d{1,3})\s+(\d{1,3})$/; const cssLengthPattern = /^(0|\d*\.?\d+(px|rem|em))$/; +const cssLengthDifferencePattern = + /^calc\(\s*\d*\.?\d+(px|rem|em)\s+[-+]\s+\d*\.?\d+(px|rem|em)\s*\)$/; const cssDurationPattern = /^\d*\.?\d+(ms|s)$/; const hexColorPattern = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/; @@ -186,8 +203,13 @@ const isRGB = (value: unknown): value is string => { return match !== null && match.slice(1).every((channel) => Number(channel) <= 255); }; +/** The bare form, or one `calc()` of two unit-bearing lengths (a bare `0` is a number there): + * the small radius defaults keep a px offset. */ const isLength = (value: unknown): value is string => - typeof value === 'string' && cssLengthPattern.test(value); + typeof value === 'string' && + (cssLengthPattern.test(value) || cssLengthDifferencePattern.test(value)); +const isFontFamily = (value: unknown): value is string => + typeof value === 'string' && value.trim().length > 0 && !/[;{}]/.test(value); const isDuration = (value: unknown): value is string => typeof value === 'string' && cssDurationPattern.test(value); @@ -208,11 +230,17 @@ const appearanceValidators: Record b roundControlRadius: isLength, surfaceRadius: isLength, largeSurfaceRadius: isLength, + radiusSm: isLength, + radiusMd: isLength, + radiusLg: isLength, + radiusXl: isLength, + radius2xl: isLength, + radius3xl: isLength, controlHeight: isLength, spaceCompact: isLength, spaceNormal: isLength, - fontFamily: (value) => - typeof value === 'string' && value.trim().length > 0 && !/[;{}]/.test(value), + fontFamily: isFontFamily, + monoFontFamily: isFontFamily, elevationSurface: (value) => typeof value === 'string' && value.trim().length > 0 && !/[;{}]|url\s*\(/i.test(value), motionFast: isDuration, diff --git a/packages/client/src/theme/tailwind.spec.js b/packages/client/src/theme/tailwind.spec.js index 091bd36bfa..26e0573a3b 100644 --- a/packages/client/src/theme/tailwind.spec.js +++ b/packages/client/src/theme/tailwind.spec.js @@ -47,6 +47,45 @@ async function generate(candidates) { return compiler.build(candidates); } +const tailwindRoot = path.dirname(require.resolve('tailwindcss/package.json')); +const applicationRoot = path.resolve(packageRoot, '../../client'); + +/** The application stylesheet, compiled the way the SPA's build compiles it. */ +async function generateApplication(candidates) { + const stylesheet = path.join(applicationRoot, 'src/style.css'); + const compiler = await compile(await fsp.readFile(stylesheet, 'utf8'), { + base: path.dirname(stylesheet), + async loadModule(id, base) { + const modulePath = id.startsWith('.') ? path.resolve(base, id) : require.resolve(id); + const loaded = require(modulePath); + return { base: path.dirname(modulePath), module: loaded.default ?? loaded, path: modulePath }; + }, + async loadStylesheet(id, base) { + const resolved = + id === 'tailwindcss' ? path.join(tailwindRoot, 'index.css') : path.resolve(base, id); + return { + base: path.dirname(resolved), + content: await fsp.readFile(resolved, 'utf8'), + path: resolved, + }; + }, + }); + + return compiler.build(candidates); +} + +/** The declarations of `.candidate`, whitespace collapsed. */ +function rule(css, candidate) { + const match = css.match(new RegExp(`\\.${candidate}\\s*\\{([^}]*)\\}`)); + return match ? match[1].replace(/\s+/g, ' ').trim() : undefined; +} + +/** Tailwind's own default for a theme variable, read from the installed package. */ +function tailwindDefault(variable) { + const theme = fs.readFileSync(path.join(tailwindRoot, 'theme.css'), 'utf8'); + return theme.match(new RegExp(`\\s${variable}:\\s*([^;]+);`))?.[1].trim(); +} + describe('LibreChat Tailwind preset', () => { it('generates every component animation and its keyframes together', async () => { const names = ['loading-dot', 'accordion-down', 'accordion-up', 'caret-blink']; @@ -145,8 +184,71 @@ describe('LibreChat Tailwind preset', () => { 'utf8', ); + /** Prettier wraps a long font stack, so declarations compare with whitespace collapsed. */ + const collapsed = applicationStyles.replace(/\s+/g, ' '); Object.entries(themeAppearanceProperties).forEach(([key, property]) => { - expect(applicationStyles).toContain(`${property}: ${defaultAppearance[key]};`); + expect(collapsed).toContain(`${property}: ${defaultAppearance[key]};`); }); }); }); + +describe('application radius and font scales', () => { + const scale = [ + ['rounded-sm', '--theme-radius-sm', 'radiusSm'], + ['rounded-md', '--theme-radius-md', 'radiusMd'], + ['rounded-lg', '--theme-radius-lg', 'radiusLg'], + ['rounded-xl', '--theme-radius-xl', 'radiusXl'], + ['rounded-2xl', '--theme-radius-2xl', 'radius2xl'], + ['rounded-3xl', '--theme-radius-3xl', 'radius3xl'], + ]; + + it('routes the plain radius and font utilities through theme-owned properties', async () => { + const css = await generateApplication([ + 'rounded', + ...scale.map(([candidate]) => candidate), + 'font-sans', + 'font-mono', + 'rounded-theme-control', + 'font-theme-ui', + ]); + + scale.forEach(([candidate, property]) => { + expect(rule(css, candidate)).toBe(`border-radius: var(${property});`); + }); + /** Bare `rounded` was a fixed 0.25rem, which `sm`'s `calc(0.5rem - 4px)` only equals at a + * 16px root, so it keeps Tailwind's value rather than following `sm`. */ + expect(rule(css, 'rounded')).toBe('border-radius: 0.25rem;'); + expect(rule(css, 'font-sans')).toBe('font-family: var(--theme-font-family);'); + expect(rule(css, 'font-mono')).toBe('font-family: var(--theme-mono-font-family);'); + + /** Preflight gives `html` and `code` the same families the utilities do. */ + expect(css).toContain('--default-font-family: var(--theme-font-family);'); + expect(css).toContain('--default-mono-font-family: var(--theme-mono-font-family);'); + + /** The existing appearance roles are untouched. */ + expect(rule(css, 'rounded-theme-control')).toBe( + `border-radius: var(--theme-control-radius, ${defaultAppearance.controlRadius});`, + ); + expect(rule(css, 'font-theme-ui')).toBe( + `font-family: var(--theme-font-family, ${defaultAppearance.fontFamily});`, + ); + }); + + it('defaults to the values the utilities resolved to before the remap', () => { + /** `sm`, `md` and `lg` were `calc(var(--radius) - 4px)`, `calc(var(--radius) - 2px)` and + * `var(--radius)` over `--radius: 0.5rem`. The px offsets stay, so the corners match at + * every root font size, not only at 16px; a theme still supplies plain lengths. */ + expect(defaultAppearance.radiusSm).toBe('calc(0.5rem - 4px)'); + expect(defaultAppearance.radiusMd).toBe('calc(0.5rem - 2px)'); + expect(defaultAppearance.radiusLg).toBe('0.5rem'); + /** The rest were Tailwind's own steps, read from the installed package. */ + expect(defaultAppearance.radiusXl).toBe(tailwindDefault('--radius-xl')); + expect(defaultAppearance.radius2xl).toBe(tailwindDefault('--radius-2xl')); + expect(defaultAppearance.radius3xl).toBe(tailwindDefault('--radius-3xl')); + + expect(defaultAppearance.fontFamily).toBe('Inter, sans-serif'); + expect(defaultAppearance.monoFontFamily).toBe( + "'Roboto Mono', ui-monospace, SFMono-Regular, Menlo, 'Cascadia Mono', 'Liberation Mono', Consolas, monospace", + ); + }); +}); diff --git a/packages/client/src/theme/types/index.ts b/packages/client/src/theme/types/index.ts index d53c68175e..caed5ad901 100644 --- a/packages/client/src/theme/types/index.ts +++ b/packages/client/src/theme/types/index.ts @@ -364,10 +364,17 @@ export interface IThemeAppearance { roundControlRadius: string; surfaceRadius: string; largeSurfaceRadius: string; + radiusSm: string; + radiusMd: string; + radiusLg: string; + radiusXl: string; + radius2xl: string; + radius3xl: string; controlHeight: string; spaceCompact: string; spaceNormal: string; fontFamily: string; + monoFontFamily: string; elevationSurface: string; motionFast: string; motionNormal: string; diff --git a/packages/client/src/theme/utils/applyTheme.spec.ts b/packages/client/src/theme/utils/applyTheme.spec.ts index dec4725436..8fd038fbe2 100644 --- a/packages/client/src/theme/utils/applyTheme.spec.ts +++ b/packages/client/src/theme/utils/applyTheme.spec.ts @@ -4,7 +4,7 @@ import applyTheme, { clearAppliedTheme, themeOwnedProperties, } from './applyTheme'; -import { highContrastTheme, resolveTheme } from '../registry'; +import { defaultAppearance, highContrastTheme, resolveTheme } from '../registry'; import { defaultTheme } from '../themes/default'; const semanticProperties = [ @@ -137,6 +137,48 @@ describe('applyTheme', () => { expect(root.style.getPropertyValue('--theme-motion-fast')).toBe('80ms'); }); + /** The plain `rounded-*`, `font-sans` and `font-mono` utilities read these properties, so a + * theme reaches every call site only if the adapter writes them and a reset removes them. */ + it('applies and clears the radius scale and the mono family', () => { + const root = document.documentElement; + const scale = { + radiusSm: ['--theme-radius-sm', '0px'], + radiusMd: ['--theme-radius-md', '0.125rem'], + radiusLg: ['--theme-radius-lg', '0.25rem'], + radiusXl: ['--theme-radius-xl', '0.5rem'], + radius2xl: ['--theme-radius-2xl', '0.75rem'], + radius3xl: ['--theme-radius-3xl', '1rem'], + monoFontFamily: ['--theme-mono-font-family', 'Inconsolata, monospace'], + } as const; + const appearance = Object.fromEntries( + Object.entries(scale).map(([key, [, value]]) => [key, value]), + ); + + applyResolvedTheme( + resolveTheme( + { version: 1, name: 'shape-reference', modes: { light: { appearance } } }, + 'light', + ), + root, + ); + + Object.values(scale).forEach(([property, value]) => { + expect(root.style.getPropertyValue(property)).toBe(value); + expect(themeOwnedProperties).toContain(property); + }); + + applyResolvedTheme(resolveTheme({ version: 1, name: 'defaults', modes: {} }, 'light'), root); + expect(root.style.getPropertyValue('--theme-radius-lg')).toBe(defaultAppearance.radiusLg); + expect(root.style.getPropertyValue('--theme-mono-font-family')).toBe( + defaultAppearance.monoFontFamily, + ); + + clearAppliedTheme(root); + Object.values(scale).forEach(([property]) => { + expect(root.style.getPropertyValue(property)).toBe(''); + }); + }); + it('applies the resolved high-contrast code surface instead of the stock grey', () => { const root = document.documentElement;