🎯 feat: Give Keyboard Focus Its Own Theme Roles (#16478)

* 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
This commit is contained in:
Marco Beretta 2026-09-29 16:11:53 +02:00 • committed by GitHub
parent 1d5062cd95
commit 7a99b5cef7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
36 changed files with 358 additions and 87 deletions

View file

@ -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;
}

View file

@ -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<Outline> {
});
}
/** 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<string> {
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,
}) => {

View file

@ -147,7 +147,7 @@ const AlertDialogAction: React.ForwardRefExoticComponent<
<AlertDialogPrimitive.Action
ref={ref}
className={cn(
'bg-surface-inverted text-text-inverted hover:bg-surface-inverted-hover focus:ring-text-primary inline-flex h-10 items-center justify-center rounded-md 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',
'bg-surface-inverted text-text-inverted hover:bg-surface-inverted-hover focus:ring-focus-control inline-flex h-10 items-center justify-center rounded-md 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',
className,
)}
{...props}
@ -168,7 +168,7 @@ const AlertDialogCancel: React.ForwardRefExoticComponent<
<AlertDialogPrimitive.Cancel
ref={ref}
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-md 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-md 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,
)}
{...props}

View file

@ -40,7 +40,7 @@ const AnimatedSearchInput = ({
onChange={onChange}
placeholder={placeholder}
aria-label={localize('com_ui_search')}
className={`peer bg-surface-secondary placeholder:text-text-secondary focus:ring-text-primary relative z-20 w-full rounded-lg py-2 pl-10 outline-hidden backdrop-blur-xs transition-all duration-500 ease-in-out`}
className={`peer bg-surface-secondary placeholder:text-text-secondary focus:ring-focus-control relative z-20 w-full rounded-lg py-2 pl-10 outline-hidden backdrop-blur-xs transition-all duration-500 ease-in-out`}
/>
{/* Gradient overlay */}

View file

@ -27,7 +27,7 @@ const Checkbox: React.ForwardRefExoticComponent<
<CheckboxPrimitive.Root
ref={ref}
className={cn(
'peer border-border-xheavy ring-offset-surface-primary focus-visible:ring-text-primary data-[state=checked]:bg-surface-inverted data-[state=checked]:text-text-inverted h-4 w-4 shrink-0 rounded-sm border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
'peer border-border-xheavy ring-offset-surface-primary focus-visible:ring-focus-control data-[state=checked]:bg-surface-inverted data-[state=checked]:text-text-inverted h-4 w-4 shrink-0 rounded-sm border focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
{...props}

View file

@ -84,7 +84,7 @@ export default function ComboboxComponent({
isCollapsed
? 'flex h-9 w-9 shrink-0 items-center justify-center p-0 [&>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',
)}
>
<SelectValue placeholder={selectPlaceholder}>

View file

@ -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"
>
<div className="flex items-center gap-2">
<RefreshCw className="text-surface-destructive h-4 w-4" />

View file

@ -73,7 +73,7 @@ const DialogContent: React.ForwardRefExoticComponent<
>
{children}
{showCloseButton && (
<DialogPrimitive.Close className="focus:ring-text-primary data-[state=open]:bg-surface-hover absolute top-[1.6rem] right-6 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<DialogPrimitive.Close className="focus:ring-focus-control data-[state=open]:bg-surface-hover absolute top-[1.6rem] right-6 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<X className="text-text-primary h-5 w-5" aria-hidden="true" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
@ -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}
/>

View file

@ -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;
}

View file

@ -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`;

View file

@ -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: {

View file

@ -28,7 +28,7 @@ const InfoHoverCard = ({
<HoverCardTrigger asChild>
<button
type="button"
className="focus-visible:ring-text-primary inline-flex cursor-help items-center justify-center rounded-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden"
className="focus-visible:ring-focus-control inline-flex cursor-help items-center justify-center rounded-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden"
onFocus={() => setIsOpen(true)}
onBlur={() => setIsOpen(false)}
aria-label={text}

View file

@ -110,7 +110,7 @@ const InputOTPSlot: React.ForwardRefExoticComponent<
ref={ref}
className={cn(
'border-border-control relative flex h-11 w-11 items-center justify-center border-y border-r text-base shadow-xs transition-all first:rounded-l-xl first:border-l last:rounded-r-xl',
isActive && 'ring-text-primary z-10 ring-1',
isActive && 'ring-focus-control z-10 ring-1',
className,
)}
{...props}

View file

@ -147,7 +147,7 @@ export default function MultiSelect<T extends string>({
'flex items-center justify-between gap-2 rounded-xl px-3 py-2 text-sm',
'bg-surface-tertiary text-text-primary hover:bg-surface-hover shadow-xs hover:cursor-pointer',
'disabled:hover:bg-surface-tertiary disabled:cursor-not-allowed disabled:opacity-60',
'focus-visible:ring-text-primary outline-hidden focus-visible:ring-2 focus-visible:outline-hidden',
'focus-visible:ring-focus-control outline-hidden focus-visible:ring-2 focus-visible:outline-hidden',
selectClassName,
selectedValues.length > 0 && selectItemsClassName != null && selectItemsClassName,
)}
@ -191,7 +191,7 @@ export default function MultiSelect<T extends string>({
placeholder={searchPlaceholder}
value={search}
onChange={(event) => setSearch(event.target.value)}
className="focus-visible:ring-text-primary min-w-0 flex-1 bg-transparent text-sm outline-hidden focus-visible:ring-2"
className="focus-visible:ring-focus-control min-w-0 flex-1 bg-transparent text-sm outline-hidden focus-visible:ring-2"
/>
</div>
)}

View file

@ -370,7 +370,7 @@ const DialogContent: React.ForwardRefExoticComponent<
aria-hidden="true"
/>
{showCloseButton && (
<DialogPrimitive.Close className="ring-ring-primary ring-offset-surface-dialog focus:ring-text-primary data-[state=open]:bg-surface-hover data-[state=open]:text-text-secondary absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<DialogPrimitive.Close className="ring-ring-primary ring-offset-surface-dialog focus:ring-focus-control data-[state=open]:bg-surface-hover data-[state=open]:text-text-secondary absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<X className="h-6 w-6" aria-hidden="true" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>

View file

@ -188,7 +188,7 @@ const Radio: React.NamedExoticComponent<RadioProps> = 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}`}
>

View file

@ -22,7 +22,7 @@ const ResizableHandle = ({
}): JSX.Element => (
<Separator
className={cn(
'bg-border-medium focus-visible:ring-text-primary relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden',
'bg-border-medium focus-visible:ring-focus-control relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden',
className,
)}
{...props}
@ -44,7 +44,7 @@ const ResizableHandleAlt = ({
}): JSX.Element => (
<Separator
className={cn(
'group bg-border-medium focus-visible:ring-text-primary relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden',
'group bg-border-medium focus-visible:ring-focus-control relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden',
className,
)}
{...props}

View file

@ -119,7 +119,7 @@ function SelectDropDown({
}
}}
className={cn(
'border-border-control bg-surface-secondary focus-visible:ring-text-primary disabled:bg-surface-secondary relative flex w-full cursor-default flex-col rounded-md border py-2 pr-10 pl-3 text-left focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden sm:text-sm',
'border-border-control bg-surface-secondary focus-visible:ring-focus-control disabled:bg-surface-secondary relative flex w-full cursor-default flex-col rounded-md border py-2 pr-10 pl-3 text-left focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden sm:text-sm',
className ?? '',
)}
>

View file

@ -48,7 +48,7 @@ const Slider: React.ForwardRefExoticComponent<SliderProps & React.RefAttributes<
<SliderPrimitive.Thumb
{...{
className:
'block h-5 w-5 rounded-full border-2 border-border-xheavy bg-surface-primary ring-offset-surface-primary transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
'block h-5 w-5 rounded-full border-2 border-border-xheavy bg-surface-primary ring-offset-surface-primary transition-colors focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-focus-control focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
'aria-labelledby': ariaLabelledBy,
'aria-label': ariaLabel,
'aria-describedby': ariaDescribedBy,

View file

@ -23,7 +23,7 @@ const Switch: React.ForwardRefExoticComponent<
({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
'peer focus-visible:ring-text-primary 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',
'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',
className,
)}
{...props}

View file

@ -305,7 +305,14 @@ Each status family has a foreground, a `-subtle` background, a `-border`, and a
- `bg-brand-purple` - Brand purple color
- `bg-presentation` - Presentation background
- `ring-ring-primary` - Focus ring color
- `ring-ring-primary` - Decorative ring color (selection and hover rings)
- `focus-outline` - The app-wide keyboard focus outline. Defaults to black in
light and white in dark; a theme that names only `rgb-ring-primary` draws its
outline in that ring.
- `ring-focus-control` - The keyboard focus ring of the shared primitives
(`Checkbox`, `Switch`, `Field`, `IconButton` and their siblings). Defaults to
the primary text ink; a theme that names only `rgb-text-primary` rings its
controls in that ink.
## Creating Custom Themes

View file

@ -8,6 +8,7 @@ import {
useTheme,
} from './ThemeProvider';
import { highContrastDarkTheme, highContrastLightTheme } from '../themes/highContrast';
import { darkTheme } from '../themes/dark';
const matchMedia = (matches: boolean): MediaQueryList =>
({
@ -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(
<ThemeProvider
initialTheme="light"
@ -1157,7 +1159,7 @@ describe('ThemeProvider', () => {
);
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(
<ThemeProvider
initialTheme="dark"
@ -1185,7 +1187,7 @@ describe('ThemeProvider', () => {
);
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');
});

View file

@ -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<string, { value: string; priority: string }>;
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);

View file

@ -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;
}

View file

@ -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(
{

View file

@ -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<keyof IThemeAppearance, `--theme-${string}`>
> = 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<IThemeRGB>,

View file

@ -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']]);
});
});

View file

@ -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)

View file

@ -35,6 +35,8 @@ const colorSources: Record<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>
'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<ThemeMode, Partial<Record<keyof IThemeRGB, string>>>
'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',

View file

@ -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)

View file

@ -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)

View file

@ -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

View file

@ -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));

View file

@ -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;

View file

@ -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(

View file

@ -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',