From 7a99b5cef7405634268cec42e2b36f2c3c3531dd Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Tue, 29 Sep 2026 16:11:53 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=AF=20feat:=20Give=20Keyboard=20Focus?= =?UTF-8?q?=20Its=20Own=20Theme=20Roles=20(#16478)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Give Keyboard Focus Its Own Theme Roles Add rgb-focus-outline for the app-wide keyboard focus outline and rgb-focus-control for the shared primitives' focus ring. The defaults reproduce the default theme exactly: a black and white outline, and primitive rings in the primary text ink. A theme that names only rgb-ring-primary keeps drawing its outline in that ring, and one that names only rgb-text-primary keeps ringing its controls in that ink, so the data-theme-ring marker is no longer needed. ClickHouse sets both roles to Click UI outline.default, cited in the drift guard. Every bundled palette holds both roles at 3:1 on its canvases. Button keeps its ring until the open PR that owns it lands. * test: Read the Opaque Ring Layer in the Focus Ring Probe * fix: Draw the Popover Focus Outline in the Control Focus Role --- client/src/style.css | 33 ++--- .../mock/scenarios/focus-outline.spec.ts | 130 +++++++++++++++++- .../client/src/components/AlertDialog.tsx | 4 +- .../src/components/AnimatedSearchInput.tsx | 2 +- packages/client/src/components/Checkbox.tsx | 2 +- packages/client/src/components/Combobox.tsx | 2 +- .../DataTable/DataTableErrorBoundary.tsx | 2 +- packages/client/src/components/Dialog.tsx | 8 +- packages/client/src/components/Dropdown.css | 2 +- packages/client/src/components/Field.ts | 2 +- packages/client/src/components/IconButton.tsx | 2 +- .../client/src/components/InfoHoverCard.tsx | 2 +- packages/client/src/components/InputOTP.tsx | 2 +- .../client/src/components/MultiSelect.tsx | 4 +- .../client/src/components/OriginalDialog.tsx | 2 +- packages/client/src/components/Radio.tsx | 2 +- packages/client/src/components/Resizable.tsx | 4 +- .../client/src/components/SelectDropDown.tsx | 2 +- packages/client/src/components/Slider.tsx | 2 +- packages/client/src/components/Switch.tsx | 2 +- packages/client/src/theme/README.md | 9 +- .../src/theme/context/ThemeProvider.spec.tsx | 20 +-- .../src/theme/context/ThemeProvider.tsx | 14 +- packages/client/src/theme/controls.css | 14 +- packages/client/src/theme/registry.spec.ts | 63 +++++++++ packages/client/src/theme/registry.ts | 18 +++ .../client/src/theme/semanticTokens.spec.ts | 53 ++++++- .../client/src/theme/themes/clickhouse.ts | 4 + .../client/src/theme/themes/clickui.spec.ts | 4 + packages/client/src/theme/themes/dark.ts | 2 + packages/client/src/theme/themes/default.ts | 2 + .../client/src/theme/themes/highContrast.ts | 4 + packages/client/src/theme/tokens.css | 2 + packages/client/src/theme/types/index.ts | 6 + packages/client/src/theme/utils/applyTheme.ts | 17 +-- packages/data-provider/src/theme.ts | 2 + 36 files changed, 358 insertions(+), 87 deletions(-) diff --git a/client/src/style.css b/client/src/style.css index c5e51201fb..b02463a00e 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -222,6 +222,7 @@ html { --accent-primary: 18 110 107; --accent-primary-hover: 10 79 83; --ring-primary: var(--gray-500); + --focus-outline: 0 0 0; --header-primary: var(--white); --header-hover: var(--gray-50); --header-button-hover: var(--gray-50); @@ -353,6 +354,7 @@ html { --brand-purple: 171 104 255; --presentation: var(--gray-800); --text-primary: var(--gray-100); + --focus-outline: 255 255 255; --text-secondary: var(--gray-300); --text-secondary-alt: var(--gray-400); --text-tertiary: var(--gray-400); @@ -551,11 +553,10 @@ html.high-contrast ::selection { color: rgb(var(--surface-primary)); } /* WCAG 2.4.13 wants a 2px perimeter as the floor; a contrast mode should exceed - * it. The global pair below hard-codes #000/#fff instead of reading the ink - * token, and the keyboard-modality rule for text fields sits at 2px. */ + * it. The global rule and the keyboard-modality rule for text fields sit at 2px. */ html.high-contrast :focus-visible, html.high-contrast.dark :focus-visible { - outline: 3px solid rgb(var(--text-primary)); + outline: 3px solid rgb(var(--focus-outline)); outline-offset: 2px; } /* Selection perimeters and placeholder ink used to live here, but they complete @@ -583,7 +584,7 @@ html[data-input-modality='keyboard'].high-contrast ), textarea ):not(.lc-field):focus-visible { - outline: 3px solid rgb(var(--text-primary)) !important; + outline: 3px solid rgb(var(--focus-control)) !important; outline-offset: 2px !important; } /* The WCAG 1.4.1 link treatment moved to @@ -2461,35 +2462,25 @@ html[data-input-modality='keyboard'] ), textarea ):not(.lc-field):focus-visible { - outline: 2px solid rgb(var(--text-primary)) !important; + outline: 2px solid rgb(var(--focus-control)) !important; outline-offset: 2px !important; } -/* Black and white are the default theme's focus outline. A theme that names its - * own `ring-primary` (`data-theme-ring` on the root) draws the outline in it, - * at the same specificity and layer as the rule it recolours, so every utility - * that beat the outline before still does. A theme that leaves the ring to the - * default keeps black and white, and the contrast modes keep their own rule. */ +/* The focus outline is the theme's `focus-outline` role: black and white in the + * default theme, and whatever a theme names, or its `ring-primary` when it names + * only that (see `resolveTheme`). The contrast modes keep their own 3px rule. */ @layer base { :focus-visible { - outline: 2px solid #000; + outline: 2px solid rgb(var(--focus-outline)); outline-offset: 2px; } - - :where(html[data-theme-ring]:not(.high-contrast)) :focus-visible { - outline-color: rgb(var(--ring-primary)); - } } .dark :focus-visible { - outline: 2px solid #fff; + outline: 2px solid rgb(var(--focus-outline)); outline-offset: 2px; } -.dark:where([data-theme-ring]:not(.high-contrast)) :focus-visible { - outline-color: rgb(var(--ring-primary)); -} - .popover-ui { display: flex; max-height: min(var(--popover-available-height, 1700px), 1700px); @@ -2530,7 +2521,7 @@ html[data-input-modality='keyboard'] .popover-ui:focus-visible, .popover-ui[data-focus-visible] { - outline: 2px solid rgb(var(--text-primary)); + outline: 2px solid rgb(var(--focus-control)); outline-offset: -1px; } diff --git a/e2e/specs/mock/scenarios/focus-outline.spec.ts b/e2e/specs/mock/scenarios/focus-outline.spec.ts index 31c448c7be..3bf1b5085f 100644 --- a/e2e/specs/mock/scenarios/focus-outline.spec.ts +++ b/e2e/specs/mock/scenarios/focus-outline.spec.ts @@ -4,11 +4,13 @@ import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/cl import { NEW_CHAT_PATH } from '../helpers'; /** - * The app-wide keyboard focus outline. The default light and dark themes draw it in black and - * white, a theme definition that names its own `ring-primary` draws it in that ring, one that - * leaves the ring to the default keeps black and white, and the contrast modes keep their heavier - * text-colored outline. The probe is a bare button reached with Tab, so nothing but the - * global rule styles its outline. + * The app-wide keyboard focus outline and the shared primitives' focus ring, the `focus-outline` + * and `focus-control` theme roles. The default light and dark themes draw the outline in black and + * white and the ring in their primary ink, a theme definition that names only its own + * `ring-primary` draws the outline in that ring, one that leaves the ring to the default keeps + * black and white, one that names the roles draws both in them, and the contrast modes keep their + * heavier outline. The probes are bare buttons reached with Tab, so nothing but the global rule + * and the primitives' ring classes styles them. */ type Appearance = 'light' | 'dark' | 'high-contrast-light' | 'high-contrast-dark'; @@ -25,6 +27,28 @@ const CUSTOM_RING_THEME = { }, } as const; +/** Names the roles apart from its ring and ink, so an outline or ring that followed either shows. */ +const FOCUS_ROLE_THEME = { + version: 1, + name: 'e2e-focus-roles', + modes: { + light: { + colors: { + 'rgb-ring-primary': '10 20 30', + 'rgb-focus-outline': '180 0 110', + 'rgb-focus-control': '0 90 160', + }, + }, + dark: { + colors: { + 'rgb-ring-primary': '200 210 220', + 'rgb-focus-outline': '255 140 200', + 'rgb-focus-control': '120 200 255', + }, + }, + }, +} as const; + /** Leaves `rgb-ring-primary` to the default, which resolves to a gray too dim for a dark surface. */ const RINGLESS_THEME = { version: 1, @@ -84,6 +108,36 @@ async function keyboardFocusOutline(page: Page): Promise { }); } +/** The ring classes `Checkbox`, `Switch` and `IconButton` draw keyboard focus with. */ +const CONTROL_RING_CLASSES = + 'focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control'; + +/** Tabs onto a bare button carrying the primitives' ring classes and reads the ring's color. */ +async function keyboardFocusRing(page: Page): Promise { + const id = `${PROBE}-ring`; + await page.evaluate( + ([probeId, classes]) => { + const sentinel = document.createElement('span'); + sentinel.tabIndex = -1; + const probe = document.createElement('button'); + probe.id = probeId; + probe.className = classes; + probe.textContent = 'Ring probe'; + document.body.prepend(sentinel, probe); + sentinel.focus(); + }, + [id, CONTROL_RING_CLASSES], + ); + await page.keyboard.press('Tab'); + + const probe = page.locator(`#${id}`); + await expect(probe).toBeFocused(); + const shadow = await probe.evaluate((node) => getComputedStyle(node).boxShadow); + /** Tailwind lists transparent offset and shadow layers beside the ring; the ring is the opaque one. */ + const layers = shadow.match(/rgba?\([^)]*\)/g) ?? []; + return layers.find((color) => !/,\s*0\)$/.test(color)) ?? shadow; +} + async function openChat(page: Page, appearance: Appearance, definition?: { name: string }) { await installAppearance(page, appearance, definition); await page.goto(NEW_CHAT_PATH, { timeout: 15000 }); @@ -173,6 +227,72 @@ test.describe('keyboard focus outline', () => { }); } + test('a theme that names the focus roles draws the outline and the control ring in them @scenario:focus-roles-follow-reference-theme', async ({ + page, + }) => { + const expected: Record<'light' | 'dark', { outline: string; ring: string }> = { + light: { outline: 'rgb(180, 0, 110)', ring: 'rgb(0, 90, 160)' }, + dark: { outline: 'rgb(255, 140, 200)', ring: 'rgb(120, 200, 255)' }, + }; + for (const mode of ['light', 'dark'] as const) { + const modePage = mode === 'light' ? page : await page.context().newPage(); + await openChat(modePage, mode, FOCUS_ROLE_THEME); + + expect(await keyboardFocusOutline(modePage)).toEqual(outline(expected[mode].outline)); + expect(await keyboardFocusRing(modePage)).toBe(expected[mode].ring); + } + }); + + /** Each tag is written out whole: the runner finds a scenario by its literal tag. */ + const RING_CASES: Array<{ + title: string; + appearance: Appearance; + definition?: { name: string }; + ring: string; + }> = [ + { + title: + 'the default light theme keeps its primitives ring in the primary ink @scenario:focus-control-default-light-unchanged', + appearance: 'light', + ring: 'rgb(33, 33, 33)', + }, + { + title: + 'the default dark theme keeps its primitives ring in the primary ink @scenario:focus-control-default-dark-unchanged', + appearance: 'dark', + ring: 'rgb(236, 236, 236)', + }, + { + title: + 'the ClickHouse light theme rings its primitives in the Click UI outline @scenario:focus-control-clickhouse-light', + appearance: 'light', + definition: clickHouseTheme, + ring: 'rgb(67, 126, 239)', + }, + { + title: + 'the ClickHouse dark theme rings its primitives in the Click UI outline @scenario:focus-control-clickhouse-dark', + appearance: 'dark', + definition: clickHouseTheme, + ring: 'rgb(250, 255, 105)', + }, + { + title: + 'high contrast dark rings its primitives in its white ink @scenario:focus-control-high-contrast-dark', + appearance: 'high-contrast-dark', + definition: clickHouseTheme, + ring: 'rgb(255, 255, 255)', + }, + ]; + + for (const { title, appearance, definition, ring } of RING_CASES) { + test(title, async ({ page }) => { + await openChat(page, appearance, definition); + + expect(await keyboardFocusRing(page)).toBe(ring); + }); + } + test('a custom theme draws focus in the ring it defines, in both modes @scenario:focus-outline-follows-custom-theme-ring', async ({ page, }) => { diff --git a/packages/client/src/components/AlertDialog.tsx b/packages/client/src/components/AlertDialog.tsx index 4b957750fd..6e6bbee22c 100644 --- a/packages/client/src/components/AlertDialog.tsx +++ b/packages/client/src/components/AlertDialog.tsx @@ -147,7 +147,7 @@ const AlertDialogAction: React.ForwardRefExoticComponent< {/* Gradient overlay */} diff --git a/packages/client/src/components/Checkbox.tsx b/packages/client/src/components/Checkbox.tsx index b70a6f81ff..ff0dcfc225 100644 --- a/packages/client/src/components/Checkbox.tsx +++ b/packages/client/src/components/Checkbox.tsx @@ -27,7 +27,7 @@ const Checkbox: React.ForwardRefExoticComponent< span]:w-auto [&>svg]:hidden' : '', - 'bg-surface-secondary text-text-primary hover:bg-surface-hover focus-visible:ring-text-primary focus-visible:ring-2', + 'bg-surface-secondary text-text-primary hover:bg-surface-hover focus-visible:ring-focus-control focus-visible:ring-2', )} > diff --git a/packages/client/src/components/DataTable/DataTableErrorBoundary.tsx b/packages/client/src/components/DataTable/DataTableErrorBoundary.tsx index a75b76243b..009e8debba 100644 --- a/packages/client/src/components/DataTable/DataTableErrorBoundary.tsx +++ b/packages/client/src/components/DataTable/DataTableErrorBoundary.tsx @@ -73,7 +73,7 @@ class DataTableErrorBoundaryInner extends Component< aria-labelledby="datatable-error-title" aria-describedby="datatable-error-desc" tabIndex={-1} - className="border-border-light bg-surface-primary-alt before:bg-surface-destructive/80 focus:ring-text-primary relative w-full max-w-md overflow-hidden rounded-lg border p-6 shadow-xs outline-hidden before:absolute before:top-0 before:left-0 before:h-full before:w-1 focus:ring-2 focus:ring-offset-2" + className="border-border-light bg-surface-primary-alt before:bg-surface-destructive/80 focus:ring-focus-control relative w-full max-w-md overflow-hidden rounded-lg border p-6 shadow-xs outline-hidden before:absolute before:top-0 before:left-0 before:h-full before:w-1 focus:ring-2 focus:ring-offset-2" >
diff --git a/packages/client/src/components/Dialog.tsx b/packages/client/src/components/Dialog.tsx index b8ce440457..49fb1fa2a2 100644 --- a/packages/client/src/components/Dialog.tsx +++ b/packages/client/src/components/Dialog.tsx @@ -73,7 +73,7 @@ const DialogContent: React.ForwardRefExoticComponent< > {children} {showCloseButton && ( - + @@ -147,7 +147,7 @@ const DialogClose: React.ForwardRefExoticComponent< 'border-border-light text-text-primary hover:bg-surface-hover mt-2 inline-flex h-10 items-center justify-center rounded-lg border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', className ?? '', /* Important: for accessibility */ - 'focus:ring-text-primary focus:ring-2 focus:ring-offset-2', + 'focus:ring-focus-control focus:ring-2 focus:ring-offset-2', )} {...props} /> @@ -165,10 +165,10 @@ const DialogButton: React.ForwardRefExoticComponent< ref={ref} variant="outline" className={cn( - 'border-border-light text-text-primary hover:bg-surface-hover focus:ring-text-primary mt-2 inline-flex h-10 items-center justify-center rounded-lg border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', + 'border-border-light text-text-primary hover:bg-surface-hover focus:ring-focus-control mt-2 inline-flex h-10 items-center justify-center rounded-lg border bg-transparent px-4 py-2 text-sm font-semibold transition-colors focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 sm:mt-0', className ?? '', /* Important: for accessibility */ - 'focus:ring-text-primary focus:ring-2 focus:ring-offset-2', + 'focus:ring-focus-control focus:ring-2 focus:ring-offset-2', )} {...props} /> diff --git a/packages/client/src/components/Dropdown.css b/packages/client/src/components/Dropdown.css index 8f43d01df5..62d1d2af7a 100644 --- a/packages/client/src/components/Dropdown.css +++ b/packages/client/src/components/Dropdown.css @@ -46,7 +46,7 @@ html.high-contrast .popover-ui { .popover-ui:focus-visible, .popover-ui[data-focus-visible] { - outline: 2px solid rgb(var(--text-primary)); + outline: 2px solid rgb(var(--focus-control)); outline-offset: -1px; } diff --git a/packages/client/src/components/Field.ts b/packages/client/src/components/Field.ts index de83c9d3c8..c2177e8ffd 100644 --- a/packages/client/src/components/Field.ts +++ b/packages/client/src/components/Field.ts @@ -7,7 +7,7 @@ * palette can raise it to the 3:1 non-text floor without touching separators. */ export const fieldBase: string = - 'lc-field flex w-full rounded-lg border border-border-control px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-text-primary disabled:cursor-not-allowed disabled:opacity-50'; + 'lc-field flex w-full rounded-lg border border-border-control px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control disabled:cursor-not-allowed disabled:opacity-50'; /** A single-line control sized to sit in a form row, matching `Input`. */ export const fieldControl: string = `${fieldBase} h-10 bg-transparent`; diff --git a/packages/client/src/components/IconButton.tsx b/packages/client/src/components/IconButton.tsx index f1910c47b3..b3c2fc8af0 100644 --- a/packages/client/src/components/IconButton.tsx +++ b/packages/client/src/components/IconButton.tsx @@ -19,7 +19,7 @@ type IconButtonVariantProps = { }; const iconButtonVariants: (props?: IconButtonVariantProps & ClassProp) => string = cva( - 'inline-flex shrink-0 items-center justify-center text-text-primary transition-colors duration-theme-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary disabled:pointer-events-none disabled:opacity-50', + 'inline-flex shrink-0 items-center justify-center text-text-primary transition-colors duration-theme-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control focus-visible:ring-offset-2 focus-visible:ring-offset-surface-primary disabled:pointer-events-none disabled:opacity-50', { variants: { variant: { diff --git a/packages/client/src/components/InfoHoverCard.tsx b/packages/client/src/components/InfoHoverCard.tsx index 4666d09e11..b4536ca3e0 100644 --- a/packages/client/src/components/InfoHoverCard.tsx +++ b/packages/client/src/components/InfoHoverCard.tsx @@ -28,7 +28,7 @@ const InfoHoverCard = ({
)} diff --git a/packages/client/src/components/OriginalDialog.tsx b/packages/client/src/components/OriginalDialog.tsx index f8080df1c2..12b66cc65b 100644 --- a/packages/client/src/components/OriginalDialog.tsx +++ b/packages/client/src/components/OriginalDialog.tsx @@ -370,7 +370,7 @@ const DialogContent: React.ForwardRefExoticComponent< aria-hidden="true" /> {showCloseButton && ( - + diff --git a/packages/client/src/components/Radio.tsx b/packages/client/src/components/Radio.tsx index 908c28a157..86070ff093 100644 --- a/packages/client/src/components/Radio.tsx +++ b/packages/client/src/components/Radio.tsx @@ -188,7 +188,7 @@ const Radio: React.NamedExoticComponent = memo(function Radio({ onClick={() => handleChange(option.value)} onKeyDown={(event) => handleKeyDown(event, index)} disabled={disabled} - className={`focus-visible:ring-text-primary relative z-10 flex h-[34px] items-center justify-center gap-2 rounded-md px-4 text-sm font-medium transition-colors duration-150 focus-visible:ring-2 focus-visible:outline-hidden ${ + className={`focus-visible:ring-focus-control relative z-10 flex h-[34px] items-center justify-center gap-2 rounded-md px-4 text-sm font-medium transition-colors duration-150 focus-visible:ring-2 focus-visible:outline-hidden ${ currentValue === option.value ? 'text-text-primary' : 'text-text-secondary' } ${disabled ? 'cursor-not-allowed opacity-50' : ''} ${fullWidth ? 'flex-1' : ''} ${buttonClassName}`} > diff --git a/packages/client/src/components/Resizable.tsx b/packages/client/src/components/Resizable.tsx index 097228b45e..deef6c61ad 100644 --- a/packages/client/src/components/Resizable.tsx +++ b/packages/client/src/components/Resizable.tsx @@ -22,7 +22,7 @@ const ResizableHandle = ({ }): JSX.Element => ( ( diff --git a/packages/client/src/components/Slider.tsx b/packages/client/src/components/Slider.tsx index dbdf2fe97b..4ae8afba7e 100644 --- a/packages/client/src/components/Slider.tsx +++ b/packages/client/src/components/Slider.tsx @@ -48,7 +48,7 @@ const Slider: React.ForwardRefExoticComponent ( ({ @@ -71,7 +72,6 @@ beforeEach(() => { document.documentElement.removeAttribute('class'); document.documentElement.removeAttribute('style'); document.documentElement.removeAttribute('data-theme'); - document.documentElement.removeAttribute('data-theme-ring'); window.matchMedia = jest.fn(() => matchMedia(false)); }); @@ -1138,8 +1138,10 @@ describe('ThemeProvider', () => { expect(screen.getByTestId('resolved-mode')).toHaveTextContent('dark'); expect(matchMediaSpy).toHaveBeenCalled(); }); - describe('the ring mark the global focus outline follows', () => { - it('marks only the modes whose definition names its ring, and clears it on unmount', async () => { + describe('the focus outline a theme paints', () => { + const focusOutline = () => document.documentElement.style.getPropertyValue('--focus-outline'); + + it('follows the ring of the mode that names one, and clears on unmount', async () => { const { unmount } = render( { ); await waitFor(() => { - expect(document.documentElement).toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe('10 20 30'); }); act(() => screen.getByRole('button', { name: 'Dark' }).click()); @@ -1166,14 +1168,14 @@ describe('ThemeProvider', () => { expect(document.documentElement).toHaveClass('dark'); }); expect(document.documentElement.dataset.theme).toBe('ringed'); - expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe(darkTheme['rgb-focus-outline']); unmount(); - expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe(''); }); - it('marks legacy RGB props only when they carry a ring', async () => { + it('follows a legacy RGB ring only when the props carry one', async () => { const { rerender } = render( { ); await waitFor(() => { - expect(document.documentElement).toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe('1 2 3'); }); rerender( @@ -1199,7 +1201,7 @@ describe('ThemeProvider', () => { ); await waitFor(() => { - expect(document.documentElement).not.toHaveAttribute('data-theme-ring'); + expect(focusOutline()).toBe(''); }); expect(document.documentElement.dataset.theme).toBe('legacy'); }); diff --git a/packages/client/src/theme/context/ThemeProvider.tsx b/packages/client/src/theme/context/ThemeProvider.tsx index 2fca707987..82467fbe21 100644 --- a/packages/client/src/theme/context/ThemeProvider.tsx +++ b/packages/client/src/theme/context/ThemeProvider.tsx @@ -16,11 +16,7 @@ import { resolveTheme, validateThemeDefinition, } from '../registry'; -import applyTheme, { - applyResolvedTheme, - themeOwnedProperties, - THEME_RING_ATTRIBUTE, -} from '../utils/applyTheme'; +import applyTheme, { applyResolvedTheme, themeOwnedProperties } from '../utils/applyTheme'; import { defaultTheme } from '../themes/default'; import { darkTheme } from '../themes/dark'; import '../highContrast.css'; @@ -52,7 +48,6 @@ type ThemeDOMSnapshot = { properties: Map; colorScheme: { value: string; priority: string }; dataTheme: string | null; - themeRing: boolean; }; type ThemeClassSnapshot = { @@ -287,7 +282,6 @@ const captureThemeDOM = (root: HTMLElement): ThemeDOMSnapshot => ({ priority: root.style.getPropertyPriority('color-scheme'), }, dataTheme: root.getAttribute('data-theme'), - themeRing: root.hasAttribute(THEME_RING_ATTRIBUTE), }); const restoreThemeDOM = (snapshot: ThemeDOMSnapshot, root: HTMLElement): void => { @@ -314,7 +308,6 @@ const restoreThemeDOM = (snapshot: ThemeDOMSnapshot, root: HTMLElement): void => } else { root.setAttribute('data-theme', snapshot.dataTheme); } - root.toggleAttribute(THEME_RING_ATTRIBUTE, snapshot.themeRing); }; export function ThemeProvider({ @@ -648,16 +641,11 @@ export function ThemeProvider({ if (!highContrast && legacyThemeRGB) { applyTheme(legacyThemeRGB, root, mode === 'dark' ? darkTheme : defaultTheme); root.dataset.theme = definition.name; - root.toggleAttribute(THEME_RING_ATTRIBUTE, legacyThemeRGB['rgb-ring-primary'] != null); return; } try { applyResolvedTheme(resolveTheme(definition, mode), root); - root.toggleAttribute( - THEME_RING_ATTRIBUTE, - definition.modes[mode]?.colors?.['rgb-ring-primary'] != null, - ); } catch (error) { restoreAppliedTheme(root); console.error('Unable to apply theme definition', error); diff --git a/packages/client/src/theme/controls.css b/packages/client/src/theme/controls.css index a2f562e7ff..b1dbd7041b 100644 --- a/packages/client/src/theme/controls.css +++ b/packages/client/src/theme/controls.css @@ -1,9 +1,13 @@ /** - * Stylesheet defaults for `--border-control`, the form-control boundary role. + * Stylesheet defaults for the roles the package's own primitives paint: + * `--border-control`, the form-control boundary, and `--focus-control`, the + * keyboard focus ring of `Checkbox`, `Switch`, `Field` and their siblings. * - * Every other color role is declared by the app stylesheet, but this one ships - * with the package so a consumer rendering `Input`, `Select` or `InputOTP` gets - * an outline without restating it. The stock values match `border-light`. + * Every other color role is declared by the app stylesheet, but these ship + * with the package so a consumer rendering `Input`, `Select` or `Checkbox` gets + * an outline and a focus ring without restating them. The stock boundary + * matches `border-light`, and the stock ring matches `text-primary`, the ink + * the primitives drew their ring in before the role existed. * `ThemeProvider` paints the registry value inline whenever a theme is active, * which outranks these; they only cover the stock palette before and without a * theme definition, and `semanticTokens.spec.ts` keeps them in step with @@ -11,8 +15,10 @@ */ html { --border-control: 227 227 227; + --focus-control: 33 33 33; } .dark { --border-control: 33 33 33; + --focus-control: 236 236 236; } diff --git a/packages/client/src/theme/registry.spec.ts b/packages/client/src/theme/registry.spec.ts index 2dd7e3c5b1..431ec8f89b 100644 --- a/packages/client/src/theme/registry.spec.ts +++ b/packages/client/src/theme/registry.spec.ts @@ -291,6 +291,69 @@ describe('theme registry', () => { expect(resolved.colors['rgb-border-control']).toBe(darkTheme['rgb-border-control']); }); + it('draws the focus outline in the ring of a theme that predates the role', () => { + const resolved = resolveTheme( + { + version: 1, + name: 'ring-only-reference', + modes: { dark: { colors: { 'rgb-ring-primary': '200 210 220' } } }, + }, + 'dark', + ); + + expect(resolved.colors['rgb-focus-outline']).toBe('200 210 220'); + }); + + it('draws the control focus ring in the ink of a theme that predates the role', () => { + const resolved = resolveTheme( + { + version: 1, + name: 'ink-only-reference', + modes: { light: { colors: { 'rgb-text-primary': '20 30 40' } } }, + }, + 'light', + ); + + expect(resolved.colors['rgb-focus-control']).toBe('20 30 40'); + }); + + it('gives a theme that names neither the bundled focus roles', () => { + const light = resolveTheme( + { + version: 1, + name: 'focusless-reference', + modes: { light: { colors: { 'rgb-accent-primary': '1 2 3' } } }, + }, + 'light', + ); + + expect(light.colors['rgb-focus-outline']).toBe('0 0 0'); + expect(light.colors['rgb-focus-control']).toBe(defaultTheme['rgb-text-primary']); + }); + + it('preserves explicit focus roles over the ring and ink they would follow', () => { + const resolved = resolveTheme( + { + version: 1, + name: 'focus-reference', + modes: { + light: { + colors: { + 'rgb-ring-primary': '10 20 30', + 'rgb-text-primary': '40 50 60', + 'rgb-focus-outline': '200 0 120', + 'rgb-focus-control': '0 120 200', + }, + }, + }, + }, + 'light', + ); + + expect(resolved.colors['rgb-focus-outline']).toBe('200 0 120'); + expect(resolved.colors['rgb-focus-control']).toBe('0 120 200'); + }); + it('preserves an explicit control outline', () => { const resolved = resolveTheme( { diff --git a/packages/client/src/theme/registry.ts b/packages/client/src/theme/registry.ts index 5a45609723..78e1a39cdd 100644 --- a/packages/client/src/theme/registry.ts +++ b/packages/client/src/theme/registry.ts @@ -88,6 +88,22 @@ export function controlBorderFallback(colors: IThemeRGB): string | undefined { return colors['rgb-border-light'] ?? colors['rgb-border-medium']; } +/** + * The focus roles for a stored or environment theme that predates them. The + * global outline followed a theme's `rgb-ring-primary` whenever it named one, + * and the shared primitives drew their ring in `rgb-text-primary`, so a theme + * that painted either keeps that focus color. A theme that painted neither + * keeps the bundled roles, and one that names a role keeps it as written. + */ +export function focusFallbacks(colors: IThemeRGB): IThemeRGB { + const outline = colors['rgb-focus-outline'] ?? colors['rgb-ring-primary']; + const control = colors['rgb-focus-control'] ?? colors['rgb-text-primary']; + return { + ...(outline !== undefined ? { 'rgb-focus-outline': outline } : {}), + ...(control !== undefined ? { 'rgb-focus-control': control } : {}), + }; +} + export const themeAppearanceProperties: Readonly< Record > = Object.freeze({ @@ -339,6 +355,7 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT customColors != null ? controlBorderFallback(customColors) : undefined; const borderControlFallback = borderControlSource !== undefined ? { 'rgb-border-control': borderControlSource } : {}; + const focusFallback = customColors != null ? focusFallbacks(customColors) : {}; /** * Slot 8 arrived after the seven-slot scale shipped, so a stored or * environment theme that paints its own scale cannot name it. Filling the @@ -399,6 +416,7 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedT ...chartWidgetSurfaceFallback, ...chartWidgetStrokeFallback, ...borderControlFallback, + ...focusFallback, ...seriesEightFallback, ...verifiedFallback, } as Required, diff --git a/packages/client/src/theme/semanticTokens.spec.ts b/packages/client/src/theme/semanticTokens.spec.ts index c2ede2be94..a85356bf56 100644 --- a/packages/client/src/theme/semanticTokens.spec.ts +++ b/packages/client/src/theme/semanticTokens.spec.ts @@ -136,7 +136,7 @@ describe('shared field and dropdown interaction styles', () => { expect(field).toMatch(/\bborder-border-control\b/); expect(field).not.toMatch(/\bborder-border-(?:light|medium)\b/); expect(field).toMatch(/focus-visible:ring-2/); - expect(field).toMatch(/focus-visible:ring-text-primary/); + expect(field).toMatch(/focus-visible:ring-focus-control/); const composers: Array<[string, RegExp]> = [ ['Input.tsx', /\bfieldControl\b/], @@ -161,7 +161,7 @@ describe('shared field and dropdown interaction styles', () => { ); expect(appStyles).toMatch(/html\[data-input-modality='pointer'\]/); expect(appStyles).toMatch(/html\[data-input-modality='keyboard'\]/); - expect(appStyles).toMatch(/outline:\s*2px solid rgb\(var\(--text-primary\)\) !important;/); + expect(appStyles).toMatch(/outline:\s*2px solid rgb\(var\(--focus-control\)\) !important;/); expect(appStyles).not.toMatch(/textarea\s*\n\):hover,/); }); @@ -652,3 +652,52 @@ describe('control border defaults', () => { expect(declared).toEqual([defaultTheme['rgb-border-control'], darkTheme['rgb-border-control']]); }); }); + +/** WCAG 2.4.13 holds a focus indicator to 3:1 against what it is drawn on. The + * global outline and the primitives' ring are theme roles, so every bundled + * palette carries both at that floor on its canvases. */ +describe.each([ + ['default light', defaultTheme], + ['default dark', darkTheme], + ['high contrast light', highContrastLightTheme], + ['high contrast dark', highContrastDarkTheme], + ['clickhouse light', clickHouseLightTheme], + ['clickhouse dark', clickHouseDarkTheme], +])('%s focus roles', (_name, theme: IThemeRGB) => { + it.each(['rgb-focus-outline', 'rgb-focus-control'] as const)( + 'keeps %s at the 3:1 floor on every canvas', + (role) => { + const focus = toRgb(theme, role); + const failures = canvasSurfaces.flatMap((surface) => { + const ratio = contrast(focus, toRgb(theme, surface)); + return ratio < WCAG_MARK_MIN ? [`${surface}: ${ratio.toFixed(2)}:1`] : []; + }); + + expect(failures).toEqual([]); + }, + ); +}); + +describe('focus role defaults', () => { + /** The default theme's outline was literal black and white and its primitives + * drew their ring in the primary ink; the roles reproduce both. */ + it('reproduces the outline and ring the default theme drew before the roles', () => { + expect([defaultTheme['rgb-focus-outline'], darkTheme['rgb-focus-outline']]).toEqual([ + '0 0 0', + '255 255 255', + ]); + expect([defaultTheme['rgb-focus-control'], darkTheme['rgb-focus-control']]).toEqual([ + defaultTheme['rgb-text-primary'], + darkTheme['rgb-text-primary'], + ]); + }); + + it('keeps the package CSS in step with the runtime themes', () => { + const controls = readFileSync(join(__dirname, 'controls.css'), 'utf8'); + const declared = [...controls.matchAll(/--focus-control:\s*([^;]+);/g)].map((match) => + match[1].trim(), + ); + + expect(declared).toEqual([defaultTheme['rgb-focus-control'], darkTheme['rgb-focus-control']]); + }); +}); diff --git a/packages/client/src/theme/themes/clickhouse.ts b/packages/client/src/theme/themes/clickhouse.ts index e9819fc62e..704e336213 100644 --- a/packages/client/src/theme/themes/clickhouse.ts +++ b/packages/client/src/theme/themes/clickhouse.ts @@ -50,6 +50,8 @@ export const clickHouseLightTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '67 126 239', // #437eef (outline.default) + 'rgb-focus-outline': '67 126 239', // #437eef (outline.default) + 'rgb-focus-control': '67 126 239', // #437eef (outline.default) // Header colors 'rgb-header-primary': '255 255 255', // #ffffff (background.default) @@ -170,6 +172,8 @@ export const clickHouseDarkTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '250 255 105', // #faff69 (outline.default) + 'rgb-focus-outline': '250 255 105', // #faff69 (outline.default) + 'rgb-focus-control': '250 255 105', // #faff69 (outline.default) // Header colors 'rgb-header-primary': '31 31 28', // #1f1f1c (background.default) diff --git a/packages/client/src/theme/themes/clickui.spec.ts b/packages/client/src/theme/themes/clickui.spec.ts index 47bed8cfc8..4debd99d6d 100644 --- a/packages/client/src/theme/themes/clickui.spec.ts +++ b/packages/client/src/theme/themes/clickui.spec.ts @@ -35,6 +35,8 @@ const colorSources: Record>> 'rgb-accent-primary': 'global.color.accent.default', 'rgb-accent-primary-hover': 'palette.neutral.712', 'rgb-ring-primary': 'global.color.outline.default', + 'rgb-focus-outline': 'global.color.outline.default', + 'rgb-focus-control': 'global.color.outline.default', 'rgb-header-primary': 'global.color.background.default', 'rgb-header-hover': 'global.color.background.muted', 'rgb-header-button-hover': 'global.color.background.muted', @@ -131,6 +133,8 @@ const colorSources: Record>> 'rgb-accent-primary': 'global.color.accent.default', 'rgb-accent-primary-hover': 'palette.brand.200', 'rgb-ring-primary': 'global.color.outline.default', + 'rgb-focus-outline': 'global.color.outline.default', + 'rgb-focus-control': 'global.color.outline.default', 'rgb-header-primary': 'global.color.background.default', 'rgb-header-hover': 'global.color.background.muted', 'rgb-header-button-hover': 'global.color.background.muted', diff --git a/packages/client/src/theme/themes/dark.ts b/packages/client/src/theme/themes/dark.ts index 1365fba855..56469f4548 100644 --- a/packages/client/src/theme/themes/dark.ts +++ b/packages/client/src/theme/themes/dark.ts @@ -25,6 +25,8 @@ export const darkTheme: IThemeRGB = { // Ring colors (not defined in dark mode, using default) 'rgb-ring-primary': '89 89 89', // #595959 (gray-500) + 'rgb-focus-outline': '255 255 255', // #ffffff + 'rgb-focus-control': '236 236 236', // #ececec (gray-100) // Header colors 'rgb-header-primary': '47 47 47', // #2f2f2f (gray-700) diff --git a/packages/client/src/theme/themes/default.ts b/packages/client/src/theme/themes/default.ts index 29659facff..410a282ca5 100644 --- a/packages/client/src/theme/themes/default.ts +++ b/packages/client/src/theme/themes/default.ts @@ -25,6 +25,8 @@ export const defaultTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '89 89 89', // #595959 (gray-500) + 'rgb-focus-outline': '0 0 0', // #000000 + 'rgb-focus-control': '33 33 33', // #212121 (gray-800) // Header colors 'rgb-header-primary': '255 255 255', // #fff (white) diff --git a/packages/client/src/theme/themes/highContrast.ts b/packages/client/src/theme/themes/highContrast.ts index 93d220caab..2893b71863 100644 --- a/packages/client/src/theme/themes/highContrast.ts +++ b/packages/client/src/theme/themes/highContrast.ts @@ -51,6 +51,8 @@ export const highContrastLightTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '0 0 0', // #000000 + 'rgb-focus-outline': '0 0 0', // #000000 + 'rgb-focus-control': '0 0 0', // #000000 // Header colors 'rgb-header-primary': '255 255 255', // #ffffff @@ -197,6 +199,8 @@ export const highContrastDarkTheme: IThemeRGB = { // Ring colors 'rgb-ring-primary': '255 255 255', // #ffffff + 'rgb-focus-outline': '255 255 255', // #ffffff + 'rgb-focus-control': '255 255 255', // #ffffff // Header colors 'rgb-header-primary': '0 0 0', // #000000 diff --git a/packages/client/src/theme/tokens.css b/packages/client/src/theme/tokens.css index 5df3b7129a..f4b46d75aa 100644 --- a/packages/client/src/theme/tokens.css +++ b/packages/client/src/theme/tokens.css @@ -21,6 +21,8 @@ --color-accent-primary: rgb(var(--accent-primary)); --color-accent-primary-hover: rgb(var(--accent-primary-hover)); --color-ring-primary: rgb(var(--ring-primary)); + --color-focus-outline: rgb(var(--focus-outline)); + --color-focus-control: rgb(var(--focus-control)); --color-header-primary: rgb(var(--header-primary)); --color-header-hover: rgb(var(--header-hover)); --color-header-button-hover: rgb(var(--header-button-hover)); diff --git a/packages/client/src/theme/types/index.ts b/packages/client/src/theme/types/index.ts index 7ba250a8fa..b782f3dc16 100644 --- a/packages/client/src/theme/types/index.ts +++ b/packages/client/src/theme/types/index.ts @@ -26,6 +26,8 @@ export interface IThemeRGB { // Ring colors 'rgb-ring-primary'?: string; + 'rgb-focus-outline'?: string; + 'rgb-focus-control'?: string; // Header colors 'rgb-header-primary'?: string; @@ -172,6 +174,8 @@ export interface IThemeVariables { '--accent-primary': string; '--accent-primary-hover': string; '--ring-primary': string; + '--focus-outline': string; + '--focus-control': string; '--header-primary': string; '--header-hover': string; '--header-button-hover': string; @@ -278,6 +282,8 @@ export interface IThemeColors { 'accent-primary'?: string; 'accent-primary-hover'?: string; 'ring-primary'?: string; + 'focus-outline'?: string; + 'focus-control'?: string; 'header-primary'?: string; 'header-hover'?: string; 'header-button-hover'?: string; diff --git a/packages/client/src/theme/utils/applyTheme.ts b/packages/client/src/theme/utils/applyTheme.ts index dacbd0a84a..8eed809fc4 100644 --- a/packages/client/src/theme/utils/applyTheme.ts +++ b/packages/client/src/theme/utils/applyTheme.ts @@ -1,6 +1,7 @@ import type { IThemeAppearance, IThemeBrands, IThemeRGB, ResolvedThemeDefinition } from '../types'; import { controlBorderFallback, + focusFallbacks, MARK_NEIGHBOURHOOD, themeAppearanceProperties, themeBrandTokens, @@ -76,6 +77,14 @@ function mapColors(colors: IThemeRGB, base?: IThemeRGB): Array<[string, string]> variables.push(['--border-control', legacyControlBorder]); } + const focus = focusFallbacks(colors); + if (colors['rgb-focus-outline'] === undefined && focus['rgb-focus-outline'] !== undefined) { + variables.push(['--focus-outline', focus['rgb-focus-outline']]); + } + if (colors['rgb-focus-control'] === undefined && focus['rgb-focus-control'] !== undefined) { + variables.push(['--focus-control', focus['rgb-focus-control']]); + } + /** * Same rule as `resolveTheme`: a theme that paints what the mark is measured * against coordinated the `status-success-strong` the mark wore before it had @@ -104,17 +113,9 @@ function mapAppearance(appearance: IThemeAppearance): Array<[string, string]> { ]); } -/** - * Marks a root whose applied theme names its own `rgb-ring-primary`. The app's global focus - * outline follows the ring only then: a theme that leaves the ring to the default resolves it to a - * mid gray that a dark surface cannot carry at 3:1, so it keeps the default outline instead. - */ -export const THEME_RING_ATTRIBUTE = 'data-theme-ring'; - export function clearAppliedTheme(root: HTMLElement = document.documentElement): void { themeOwnedProperties.forEach((property) => root.style.removeProperty(property)); root.removeAttribute('data-theme'); - root.removeAttribute(THEME_RING_ATTRIBUTE); } export function applyResolvedTheme( diff --git a/packages/data-provider/src/theme.ts b/packages/data-provider/src/theme.ts index e1b321dea5..46ea02e755 100644 --- a/packages/data-provider/src/theme.ts +++ b/packages/data-provider/src/theme.ts @@ -29,6 +29,8 @@ export const themeColorTokens = Object.freeze([ 'rgb-accent-primary', 'rgb-accent-primary-hover', 'rgb-ring-primary', + 'rgb-focus-outline', + 'rgb-focus-control', 'rgb-header-primary', 'rgb-header-hover', 'rgb-header-button-hover',