🧱 feat: Add Flush, Embedded and Nav Primitive Variants (#16862)

This commit is contained in:
Marco Beretta 2026-10-08 12:26:28 +02:00 • committed by GitHub
parent 248dae1059
commit 2c2288d634
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 951 additions and 44 deletions

View file

@ -0,0 +1,644 @@
import { createElement as h } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from '@playwright/test';
import type { Page } from '@playwright/test';
import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse';
import { NEW_CHAT_PATH } from '../helpers';
import { probeStyle } from './style.helpers';
/**
* The field and nav variants are rendered from the built primitives (server-side markup, the
* classes the components really emit) into the running app, so its stylesheet and active theme
* decide what is painted. Each expectation is read back from the browser, either off the call site
* the variant replaces or off a probe carrying the role.
*/
test.describe.configure({ timeout: 120_000 });
test.use({ viewport: { width: 1280, height: 800 } });
const THEME_PARAM = 'e2eTheme';
const THEMES = ['default', 'clickhouse'] as const;
type ThemeChoice = (typeof THEMES)[number];
type Primitives = {
Input: React.ElementType;
Textarea: React.ElementType;
TextareaAutosize: React.ElementType;
SecretInput: React.ElementType;
Button: React.ElementType;
};
async function primitives(): Promise<Primitives> {
return (await import('../../../../packages/client/dist/index.mjs')) as Primitives;
}
/** Same bridge as the other theme specs: the URL picks the stored definition. */
async function installThemeBridge(page: Page) {
await page.addInitScript(
([param, definition]) => {
const wanted = new URL(location.href).searchParams.get(param);
if (wanted === null) {
return;
}
localStorage.removeItem('theme-colors');
localStorage.removeItem('theme-name');
if (wanted === 'clickhouse') {
localStorage.setItem('theme-definition', JSON.stringify(definition));
localStorage.setItem('theme-source', 'definition');
} else {
localStorage.removeItem('theme-definition');
localStorage.removeItem('theme-source');
}
},
[THEME_PARAM, clickHouseTheme] as const,
);
}
async function openWithMarkup(page: Page, theme: ThemeChoice, markup: string) {
await installThemeBridge(page);
await page.goto(`${NEW_CHAT_PATH}?${THEME_PARAM}=${theme}`, { timeout: 15000 });
await page.getByTestId('nav-user').waitFor({ timeout: 15000 });
await page.evaluate((html) => {
const host = document.createElement('div');
host.id = 'variant-host';
host.className = 'bg-surface-primary text-text-primary fixed top-0 left-0 z-[9999] p-4';
host.innerHTML = html;
document.body.append(host);
}, markup);
}
const render = (node: React.ReactElement) => renderToStaticMarkup(node);
const styleOf = (page: Page, selector: string, properties: string[], focus = false) =>
page.evaluate(
async ([sel, names, focused]) => {
const node = document.querySelector<HTMLElement>(sel);
if (node == null) {
throw new Error(`no element for ${sel}`);
}
if (focused) {
node.focus();
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
}
const style = getComputedStyle(node);
return Object.fromEntries(names.map((name) => [name, style.getPropertyValue(name).trim()]));
},
[selector, properties, focus] as [string, string[], boolean],
);
const FIELD_PROPS = [
'border-top-width',
'border-top-left-radius',
'padding-top',
'padding-left',
'font-size',
'background-color',
'box-shadow',
];
for (const theme of THEMES) {
test.describe(`field and nav variants (${theme} theme)`, () => {
test(`a flush field draws no border and no focus ring, and keeps its other metrics @scenario:field-flush-draws-no-edge`, async ({
page,
}) => {
const { Input, Textarea, TextareaAutosize } = await primitives();
await openWithMarkup(
page,
theme,
render(
h(
'div',
null,
h(Input, { 'aria-label': 'flush', id: 'flush', variant: 'flush' }),
h(Input, {
'aria-label': 'legacy',
id: 'legacy',
className: 'border-0 focus-visible:ring-0',
}),
h(Input, { 'aria-label': 'bordered', id: 'bordered' }),
h(Textarea, { 'aria-label': 'tflush', id: 'tflush', variant: 'flush' }),
h(TextareaAutosize, { 'aria-label': 'aflush', id: 'aflush', variant: 'flush' }),
),
),
);
for (const id of ['flush', 'tflush', 'aflush']) {
const resting = await styleOf(page, `#${id}`, ['border-top-width']);
expect(resting['border-top-width']).toBe('0px');
const focused = await styleOf(page, `#${id}`, ['box-shadow', 'border-top-width'], true);
expect(focused['border-top-width']).toBe('0px');
expect(focused['box-shadow']).toBe('none');
}
const bordered = await styleOf(page, '#bordered', ['border-top-width']);
expect(bordered['border-top-width']).not.toBe('0px');
if (theme === 'default') {
expect(await styleOf(page, '#flush', FIELD_PROPS, true)).toEqual(
await styleOf(page, '#legacy', FIELD_PROPS, true),
);
}
});
test(`an embedded field fills its row edge to edge from the tertiary fill @scenario:field-embedded-fills-row`, async ({
page,
}) => {
const { Input, TextareaAutosize } = await primitives();
await openWithMarkup(
page,
theme,
render(
h(
'div',
null,
h(Input, { 'aria-label': 'embedded', id: 'embedded', variant: 'embedded' }),
h(Input, {
'aria-label': 'legacy',
id: 'legacy',
className: 'bg-surface-tertiary-alt h-auto w-full rounded-none border-0 p-2 text-sm',
}),
h(TextareaAutosize, { 'aria-label': 'auto', id: 'auto', variant: 'embedded' }),
),
),
);
const embedded = await styleOf(page, '#embedded', FIELD_PROPS);
expect(embedded['border-top-width']).toBe('0px');
expect(embedded['border-top-left-radius']).toBe('0px');
expect(embedded['padding-top']).toBe('8px');
expect(embedded['padding-left']).toBe('8px');
expect(embedded['font-size']).toBe('14px');
if (theme === 'default') {
expect(embedded['background-color']).toBe(
await probeStyle(page, 'bg-surface-tertiary-alt', 'background-color'),
);
const metrics = [
...FIELD_PROPS.filter((name) => name !== 'background-color'),
'height',
'width',
];
expect(await styleOf(page, '#embedded', metrics)).toEqual(
await styleOf(page, '#legacy', metrics),
);
}
const auto = await styleOf(page, '#auto', ['border-top-width', 'border-top-left-radius']);
expect(auto).toEqual({ 'border-top-width': '0px', 'border-top-left-radius': '0px' });
});
test(`a framed editor draws the medium border, the rounded box and the focus-control ring @scenario:field-framed-matches-editor-box`, async ({
page,
}) => {
const { TextareaAutosize } = await primitives();
await openWithMarkup(
page,
theme,
render(
h(
'div',
null,
h(TextareaAutosize, { 'aria-label': 'framed', id: 'framed', variant: 'framed' }),
h(TextareaAutosize, {
'aria-label': 'legacy',
id: 'legacy',
className:
'rounded-xl border border-border-medium bg-transparent focus-visible:ring-2 focus-visible:ring-focus-control text-text-primary placeholder:text-text-secondary',
}),
),
),
);
await page.evaluate(() =>
document.documentElement.setAttribute('data-input-modality', 'keyboard'),
);
const props = [...FIELD_PROPS, 'border-top-color', 'color'];
expect(await styleOf(page, '#framed', props, true)).toEqual(
await styleOf(page, '#legacy', props, true),
);
const framed = await styleOf(
page,
'#framed',
['border-top-color', 'box-shadow', 'color', 'outline-style'],
true,
);
expect(framed['outline-style']).toBe('none');
expect(framed['border-top-color']).toBe(
await probeStyle(page, 'border-border-medium', 'border-top-color'),
);
expect(framed['color']).toBe(await probeStyle(page, 'text-text-primary', 'color'));
expect(framed['box-shadow']).not.toBe('none');
});
test(`an invalid Input or Textarea draws the destructive border @scenario:field-invalid-destructive-border`, async ({
page,
}) => {
const { Input, Textarea } = await primitives();
await openWithMarkup(
page,
theme,
render(
h(
'div',
null,
h(Input, { 'aria-label': 'ok', id: 'ok' }),
h(Input, { 'aria-label': 'bad', id: 'bad', 'aria-invalid': true }),
h(Textarea, { 'aria-label': 'tbad', id: 'tbad', 'aria-invalid': true }),
),
),
);
const destructive = await probeStyle(page, 'border-border-destructive', 'border-top-color');
const ok = await styleOf(page, '#ok', ['border-top-color']);
expect(ok['border-top-color']).not.toBe(destructive);
for (const id of ['bad', 'tbad']) {
expect((await styleOf(page, `#${id}`, ['border-top-color']))['border-top-color']).toBe(
destructive,
);
}
await page.evaluate(() =>
document.documentElement.setAttribute('data-input-modality', 'pointer'),
);
for (const id of ['bad', 'tbad']) {
const focused = await styleOf(
page,
`#${id}`,
['border-top-color', 'box-shadow', 'outline-style'],
true,
);
expect(focused['border-top-color']).toBe(destructive);
expect(focused['box-shadow']).toBe('none');
expect(focused['outline-style']).toBe('none');
}
const okFocused = await styleOf(page, '#ok', ['border-top-color'], true);
expect(okFocused['border-top-color']).not.toBe(destructive);
});
test(`a nav button rests secondary, hovers on the nav fill and marks the current item with aria-pressed @scenario:button-nav-roles`, async ({
page,
}) => {
const { Button } = await primitives();
await openWithMarkup(
page,
theme,
render(
h(
'div',
{ className: 'flex gap-2' },
h(Button, { id: 'rest', variant: 'nav', size: 'icon', 'aria-pressed': false }, 'a'),
h(Button, { id: 'current', variant: 'nav', size: 'icon', 'aria-pressed': true }, 'b'),
),
),
);
const secondary = await probeStyle(page, 'text-text-secondary', 'color');
const primary = await probeStyle(page, 'text-text-primary', 'color');
const navHover = await probeStyle(page, 'bg-surface-nav-hover', 'background-color');
const navSelected = await probeStyle(page, 'bg-surface-nav-selected', 'background-color');
const rest = await styleOf(page, '#rest', ['color', 'background-color']);
expect(rest['color']).toBe(secondary);
expect(rest['background-color']).toBe('rgba(0, 0, 0, 0)');
const current = await styleOf(page, '#current', ['color', 'background-color']);
expect(current['color']).toBe(primary);
expect(current['background-color']).toBe(navSelected);
await page.locator('#rest').hover();
await expect
.poll(async () => (await styleOf(page, '#rest', ['background-color']))['background-color'])
.toBe(navHover);
await page.mouse.move(0, 400);
await page.locator('#current').hover();
expect((await styleOf(page, '#current', ['background-color']))['background-color']).toBe(
navSelected,
);
await page.mouse.move(0, 400);
await page.evaluate(() => document.documentElement.classList.add('high-contrast'));
const perimeter = ['outline-style', 'outline-width', 'outline-offset'];
expect(await styleOf(page, '#current', perimeter)).toEqual({
'outline-style': 'solid',
'outline-width': '3px',
'outline-offset': '-3px',
});
expect((await styleOf(page, '#rest', ['outline-style']))['outline-style']).toBe('none');
});
test(`the floating label chip paints the field fill when the theme fills fields @scenario:floating-label-chip-field-fill`, async ({
page,
}) => {
const { SecretInput } = await primitives();
await openWithMarkup(
page,
theme,
render(h(SecretInput, { id: 'secret', variant: 'floating', label: 'Password', value: '' })),
);
const chip = await page.evaluate(
() => getComputedStyle(document.querySelector('label[for="secret"]')!).backgroundColor,
);
const expectedRole =
theme === 'clickhouse' ? 'theme-field-fill:bg-field-fill' : 'bg-surface-primary';
expect(chip).toBe(await probeStyle(page, expectedRole, 'background-color'));
});
test(`every field primitive and variant resolves its fill, edge, ring and outline the same way in each state @scenario:field-variant-matrix`, async ({
page,
}) => {
const { Input, Textarea, TextareaAutosize, SecretInput } = await primitives();
type Fill = 'field' | 'secondary' | 'transparent' | 'embedded';
type Cell = {
id: string;
node: (props: Record<string, unknown>) => React.ReactElement;
fill: Fill;
bordered: boolean;
ring: boolean;
keyboardOutline: boolean;
pointerEdge: 'reset' | 'keep' | 'none';
};
const lcField = (
id: string,
node: Cell['node'],
fill: Fill,
variant: 'edged' | 'flush' | 'embedded',
): Cell => ({
id,
node,
fill,
bordered: variant === 'edged',
ring: variant !== 'flush',
keyboardOutline: false,
pointerEdge: variant === 'edged' ? 'reset' : 'none',
});
const input = (variant: string) => (p: Record<string, unknown>) =>
h(Input, { ...p, variant });
const secret = (variant: string) => (p: Record<string, unknown>) =>
h(SecretInput, { ...p, variant });
const area = (variant: string) => (p: Record<string, unknown>) =>
h(Textarea, { ...p, variant });
const auto = (variant: string) => (p: Record<string, unknown>) =>
h(TextareaAutosize, { ...p, variant });
const cells: Cell[] = [
lcField('input-default', input('default'), 'field', 'edged'),
lcField('input-floating', input('floating'), 'field', 'edged'),
lcField('input-flush', input('flush'), 'transparent', 'flush'),
lcField('input-embedded', input('embedded'), 'embedded', 'embedded'),
lcField('secret-default', secret('default'), 'field', 'edged'),
lcField('secret-flush', secret('flush'), 'transparent', 'flush'),
lcField('secret-embedded', secret('embedded'), 'embedded', 'embedded'),
lcField('textarea-default', area('default'), 'secondary', 'edged'),
lcField('textarea-transparent', area('transparent'), 'transparent', 'edged'),
lcField('textarea-document', area('document'), 'transparent', 'edged'),
lcField('textarea-flush', area('flush'), 'transparent', 'flush'),
lcField('textarea-embedded', area('embedded'), 'embedded', 'embedded'),
{
id: 'auto-default',
node: auto('default'),
fill: 'transparent',
bordered: false,
ring: false,
keyboardOutline: true,
pointerEdge: 'none',
},
{
id: 'auto-framed',
node: auto('framed'),
fill: 'transparent',
bordered: true,
ring: true,
keyboardOutline: false,
pointerEdge: 'keep',
},
{
id: 'auto-flush',
node: auto('flush'),
fill: 'transparent',
bordered: false,
ring: false,
keyboardOutline: false,
pointerEdge: 'none',
},
{
id: 'auto-embedded',
node: auto('embedded'),
fill: 'embedded',
bordered: false,
ring: false,
keyboardOutline: true,
pointerEdge: 'none',
},
];
await openWithMarkup(
page,
theme,
render(
h(
'div',
null,
...cells.flatMap((cell) => [
h(
'div',
{ key: cell.id },
cell.node({ id: cell.id, 'aria-label': cell.id, value: '', onChange: () => null }),
),
h(
'div',
{ key: `${cell.id}-bad` },
cell.node({
id: `${cell.id}-bad`,
'aria-label': `${cell.id}-bad`,
'aria-invalid': true,
value: '',
onChange: () => null,
}),
),
]),
),
),
);
const transparent = 'rgba(0, 0, 0, 0)';
const fills: Record<Fill, string> = {
field:
theme === 'clickhouse'
? await probeStyle(page, 'theme-field-fill:bg-field-fill', 'background-color')
: transparent,
secondary:
theme === 'clickhouse'
? await probeStyle(page, 'theme-field-fill:bg-field-fill', 'background-color')
: await probeStyle(page, 'bg-surface-secondary', 'background-color'),
transparent,
embedded: await probeStyle(page, 'bg-surface-tertiary-alt', 'background-color'),
};
const destructive = await probeStyle(page, 'border-border-destructive', 'border-top-color');
const primaryInk = await probeStyle(page, 'text-text-primary', 'color');
const resetEdge =
theme === 'clickhouse'
? await page.evaluate(() => {
const probe = document.createElement('div');
probe.style.cssText =
'border:1px solid rgb(var(--border-field-focus, var(--focus-control)))';
document.body.append(probe);
const color = getComputedStyle(probe).borderTopColor;
probe.remove();
return color;
})
: await probeStyle(page, 'border-border-light', 'border-top-color');
const read = (id: string, modality: 'keyboard' | 'pointer' | null) =>
page.evaluate(
async ([target, mode]) => {
const node = document.getElementById(target) as HTMLElement;
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
if (mode === null) {
document.documentElement.removeAttribute('data-input-modality');
} else {
document.documentElement.setAttribute('data-input-modality', mode);
node.focus();
}
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
await Promise.all(node.getAnimations().map((animation) => animation.finished));
const style = getComputedStyle(node);
const rings = style.boxShadow
.split(/,(?![^(]*\))/)
.map((shadow) => shadow.trim())
.filter((shadow) => shadow !== 'none' && !shadow.includes('inset'))
.filter((shadow) =>
/(^|\s)[1-9]\d*(\.\d+)?px/.test(shadow.replace(/rgba?\([^)]*\)/, '')),
);
return {
fill: style.backgroundColor,
width: style.borderTopWidth,
edge: style.borderTopColor,
ring: rings.length > 0,
outline: style.outlineStyle !== 'none' && style.outlineColor !== 'rgba(0, 0, 0, 0)',
ink: style.color,
outlineWidth: style.outlineWidth,
};
},
[id, modality] as const,
);
for (const cell of cells) {
const label = `${theme} ${cell.id}`;
const rest = await read(cell.id, null);
if (cell.fill === 'embedded') {
expect.soft(rest.ink, `${label} ink`).toBe(primaryInk);
}
expect.soft(rest.fill, `${label} fill`).toBe(fills[cell.fill]);
expect.soft(rest.width !== '0px', `${label} draws an edge`).toBe(cell.bordered);
const keyboard = await read(cell.id, 'keyboard');
expect.soft(keyboard.fill, `${label} fill on keyboard focus`).toBe(fills[cell.fill]);
expect.soft(keyboard.ring, `${label} ring on keyboard focus`).toBe(cell.ring);
expect
.soft(keyboard.outline, `${label} outline on keyboard focus`)
.toBe(cell.keyboardOutline);
const pointer = await read(cell.id, 'pointer');
expect.soft(pointer.ring, `${label} ring on pointer focus`).toBe(false);
expect.soft(pointer.outline, `${label} outline on pointer focus`).toBe(false);
if (cell.pointerEdge === 'reset') {
expect.soft(pointer.edge, `${label} edge on pointer focus`).toBe(resetEdge);
}
if (cell.pointerEdge === 'keep') {
expect.soft(pointer.edge, `${label} edge on pointer focus`).toBe(rest.edge);
}
await page.evaluate(() => document.documentElement.classList.add('high-contrast'));
const contrastKeyboard = await read(cell.id, 'keyboard');
expect
.soft(
[contrastKeyboard.outline, contrastKeyboard.outlineWidth],
`${label} high-contrast keyboard outline`,
)
.toEqual([true, '3px']);
const contrastPointer = await read(cell.id, 'pointer');
expect.soft(contrastPointer.outline, `${label} high-contrast pointer outline`).toBe(false);
await page.evaluate(() => document.documentElement.classList.remove('high-contrast'));
if (!cell.bordered) {
continue;
}
for (const mode of [null, 'keyboard', 'pointer'] as const) {
const bad = await read(`${cell.id}-bad`, mode);
expect.soft(bad.edge, `${label} invalid edge (${mode ?? 'rest'})`).toBe(destructive);
if (mode === 'pointer') {
expect.soft(bad.ring, `${label} invalid ring on pointer focus`).toBe(false);
expect.soft(bad.outline, `${label} invalid outline on pointer focus`).toBe(false);
}
}
}
});
test(`flush and framed editors keep the outline as the only indicator under forced colors @scenario:field-variant-matrix`, async ({
page,
}) => {
const { TextareaAutosize } = await primitives();
await openWithMarkup(
page,
theme,
render(
h(
'div',
null,
h(TextareaAutosize, { 'aria-label': 'flush', id: 'flush', variant: 'flush' }),
h(TextareaAutosize, { 'aria-label': 'framed', id: 'framed', variant: 'framed' }),
),
),
);
await page.emulateMedia({ forcedColors: 'active' });
for (const id of ['flush', 'framed']) {
const outline = await page.evaluate(async (target) => {
document.documentElement.setAttribute('data-input-modality', 'keyboard');
const node = document.getElementById(target) as HTMLElement;
node.focus();
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
return getComputedStyle(node).outlineStyle;
}, id);
expect(outline, `${theme} ${id} outline under forced colors`).not.toBe('none');
}
});
test(`the framed and flush editors clear their ring on pointer focus with only the package stylesheet @scenario:field-variant-matrix`, async ({
page,
}) => {
const { TextareaAutosize } = await primitives();
await page.goto('about:blank');
await page.setContent(
`<!doctype html><html><body>${render(
h(
'div',
null,
h(TextareaAutosize, { 'aria-label': 'framed', id: 'framed', variant: 'framed' }),
h(TextareaAutosize, { 'aria-label': 'plain', id: 'plain', variant: 'default' }),
),
)}</body></html>`,
);
await page.addStyleTag({ path: 'packages/client/dist/style.css' });
// The published stylesheet carries no Tailwind utilities, so a stand-in rule at the weight of
// `focus-visible:ring-2` draws the ring that the package's pointer reset has to clear.
await page.addStyleTag({
content: '.lc-own-focus:focus-visible { box-shadow: 0 0 0 2px rgb(0 0 255); }',
});
const ring = (id: string, modality: string) =>
page.evaluate(
async ([target, mode]) => {
document.documentElement.setAttribute('data-input-modality', mode);
(document.getElementById(target) as HTMLElement).focus();
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
const style = getComputedStyle(document.getElementById(target) as HTMLElement);
return [
style.boxShadow !== 'none' && !/0px 0px 0px 0px/.test(style.boxShadow),
style.outlineStyle,
];
},
[id, modality] as const,
);
expect((await ring('framed', 'keyboard'))[0]).toBe(true);
expect(await ring('framed', 'pointer')).toEqual([false, 'none']);
});
});
}

View file

@ -40,6 +40,22 @@ describe('Button', () => {
expect(ghost).not.toContain('text-text-secondary');
});
it('marks the current nav destination with aria-pressed and the theme navigation roles', () => {
const nav = cn(buttonVariants({ variant: 'nav', size: 'icon' }));
expect(nav).toContain('text-text-secondary');
expect(nav).toContain('hover:bg-surface-nav-hover');
expect(nav).toContain('aria-pressed:bg-surface-nav-selected');
expect(nav).toContain('aria-pressed:text-text-primary');
expect(nav).toContain('size-theme-button');
});
it('presses the message action to the pressed fill like ghost and keeps the carousel arrows on the fixed surface', () => {
expect(cn(buttonVariants({ variant: 'message-action' }))).toContain(
'hover:active:bg-surface-pressed',
);
expect(cn(buttonVariants({ variant: 'carousel-nav' }))).not.toContain('bg-surface-pressed');
});
it('offers the message, link, carousel and toolbar roles as variants', () => {
expect(cn(buttonVariants({ variant: 'message-action' }))).toContain('text-text-secondary-alt');
expect(cn(buttonVariants({ variant: 'message-action' }))).toContain('p-1.5');

View file

@ -27,6 +27,7 @@ type ButtonVariantOptions =
| 'inline-link'
| 'carousel-nav'
| 'toolbar'
| 'nav'
| 'media'
| 'row-action'
| 'row-action-reveal'
@ -114,7 +115,7 @@ const buttonVariantRecipe = cva(
'text-text-secondary hover:bg-surface-hover hover:active:bg-surface-pressed hover:text-text-primary',
/** An icon action under a message: a small padded square that rests in the alt secondary ink. */
'message-action':
'size-auto rounded-lg p-1.5 text-text-secondary-alt hover:bg-surface-hover hover:text-text-primary',
'size-auto rounded-lg p-1.5 text-text-secondary-alt hover:bg-surface-hover hover:active:bg-surface-pressed hover:text-text-primary',
/** A text action that reads as a link in a list or footer: no fill at rest or under the pointer,
* and a ring flush against the control. */
'inline-link':
@ -125,6 +126,9 @@ const buttonVariantRecipe = cva(
/** A compact text action in a toolbar, quiet until hovered. */
toolbar:
'rounded-sm bg-transparent px-2 py-1 text-xs font-normal text-text-secondary hover:bg-surface-hover',
/** A destination in a navigation rail. The fills are the theme's navigation roles, and the
* current destination is marked with `aria-pressed`, so a caller sets no class for it. */
nav: 'text-text-secondary hover:bg-surface-nav-hover hover:text-text-primary hover:active:bg-surface-pressed aria-pressed:bg-surface-nav-selected aria-pressed:text-text-primary aria-pressed:hover:bg-surface-nav-selected',
/**
* A control drawn over the user's own media (a lightbox toolbar, an image preview's close):
* ghost-shaped, with the media ink and a tint of it on hover, so it stays legible on the

View file

@ -7,46 +7,75 @@
keeps that edge on pointer focus too, so it puts the edge back over the
reset. The style is read from the `--theme-field-focus-style` property of the
nearest themed root, so a field under a ring root nested in a border root is
reset again, and a browser without style queries keeps the default reset. */
html[data-input-modality='pointer'] .lc-field:focus,
html[data-input-modality='pointer'] .lc-field:focus-visible {
border-color: rgb(var(--border-light) / var(--border-light-alpha, 1));
reset again, and a browser without style queries keeps the default reset. A field marked
`aria-invalid` keeps its destructive edge through both border resets but still
loses the ring and outline on pointer focus. The framed and flush editors
(`lc-own-focus`) take the same ring and outline reset, so they behave alike
without the SPA's global textarea rules. */
html[data-input-modality='pointer'] :is(.lc-field, .lc-own-focus):focus,
html[data-input-modality='pointer'] :is(.lc-field, .lc-own-focus):focus-visible {
box-shadow: none;
outline: none;
}
html[data-input-modality='pointer'] .lc-field:not([aria-invalid='true']):focus,
html[data-input-modality='pointer'] .lc-field:not([aria-invalid='true']):focus-visible {
border-color: rgb(var(--border-light) / var(--border-light-alpha, 1));
}
@container style(--theme-field-focus-style: border) {
html[data-input-modality='pointer'] .lc-field:is(:root *):focus,
html[data-input-modality='pointer'] .lc-field:is(:root *):focus-visible {
html[data-input-modality='pointer'] .lc-field:not([aria-invalid='true']):is(:root *):focus,
html[data-input-modality='pointer']
.lc-field:not([aria-invalid='true']):is(:root *):focus-visible {
border-color: rgb(var(--border-field-focus, var(--focus-control)));
}
}
/* A field focused by its edge draws no outline either. The app's dark-mode
`:focus-visible` outline is unlayered, so it outranks the field's own
`focus-visible:outline-hidden` utility and would add a second indicator
around the swapped edge; `:is(:root *)` keeps this rule's weight above it.
Forced colors drop the edge color and the ring, so there the outline stays
as the only indicator. */
/* A field draws its own indicator (the ring, or the swapped edge), so it draws no outline too.
The app's dark-mode `:focus-visible` outline is unlayered, so it outranks the field's own
`focus-visible:outline-hidden` utility and would add a second indicator; `:is(:root *)` keeps
this rule's weight above it. Forced colors drop the edge color and the ring, so there the
outline stays as the only indicator, and the contrast modes enlarge the outline to 3px on
purpose, so `html.high-contrast` keeps it. */
@media not (forced-colors: active) {
@container style(--theme-field-focus-style: border) {
.lc-field:is(:root *):focus-visible {
outline: none;
}
html:not(.high-contrast) .lc-field:focus-visible {
outline: none;
}
}
/* The floating-label field (`floatingField`) paints its own fill over the browser's autofill, so
an autofilled sign-in field keeps the theme's field color instead of the UA's yellow. */
an autofilled sign-in field keeps the theme's field color instead of the UA's yellow. The mask
is one entry of the box-shadow list, followed by the ring and shadow layers Tailwind composes,
so the field's keyboard ring still paints over it. */
.webkit-dark-styles {
--lc-autofill-mask: 0 0 0 50vh rgb(var(--field-fill, var(--surface-primary))) inset;
}
.webkit-dark-styles,
.webkit-dark-styles:focus {
background-clip: content-box;
-webkit-box-shadow: 0 0 0 50vh rgb(var(--field-fill, var(--surface-primary))) inset;
box-shadow:
var(--lc-autofill-mask), var(--tw-ring-offset-shadow, 0 0 transparent),
var(--tw-ring-shadow, 0 0 transparent), var(--tw-shadow, 0 0 transparent);
}
html[data-input-modality='pointer'] .lc-field.webkit-dark-styles:focus,
html[data-input-modality='pointer'] .lc-field.webkit-dark-styles:focus-visible {
box-shadow: var(--lc-autofill-mask);
}
.dark .webkit-dark-styles,
.dark .webkit-dark-styles:focus {
-webkit-text-fill-color: rgb(var(--field-text, var(--text-primary)));
background-clip: content-box;
-webkit-box-shadow: 0 0 0 50vh rgb(var(--field-fill, var(--surface-primary))) inset;
}
/* A control outside `.lc-field` that carries `lc-own-focus` (the framed and flush editors) has
its own ring, or a frame that owns the indicator, so the app's global focus outline for
non-`.lc-field` textareas would add a second one. `:root` lifts this above that rule's
weight; forced colors keep the outline as the only indicator, and the contrast modes keep
their enlarged outline. */
@media not (forced-colors: active) {
html:root:not(.high-contrast) textarea.lc-own-focus:focus-visible {
outline: none !important;
}
}

View file

@ -0,0 +1,152 @@
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import { TextareaAutosize } from './TextareaAutosize';
import { SecretInput } from './SecretInput';
import { floatingLabel } from './floating';
import { fieldInvalid } from './Field';
import { Textarea } from './Textarea';
import { Input } from './Input';
import { cn } from '~/utils';
const FLUSH = ['border-0', 'focus-visible:ring-0', 'theme-field-fill:bg-transparent'];
const EMBEDDED = [
'bg-surface-tertiary-alt',
'h-auto',
'w-full',
'border-0',
'p-2',
'rounded-none',
'text-sm',
'text-text-primary',
'theme-field-fill:bg-surface-tertiary-alt',
];
const FRAMED = [
'lc-own-focus',
'rounded-xl',
'border',
'border-border-medium',
'bg-transparent',
'text-text-primary',
'placeholder:text-text-secondary',
'focus-visible:ring-2',
'focus-visible:ring-focus-control',
];
describe('field variants', () => {
it('Input keeps its bordered default and draws the destructive border when invalid', () => {
render(<Input aria-label="name" />);
const input = screen.getByLabelText('name');
expect(input).toHaveClass(
'border',
'border-border-control',
'aria-invalid:border-border-destructive',
);
expect(input).not.toHaveClass('border-0');
});
it('Input flush drops the border and the focus ring', () => {
render(<Input aria-label="name" variant="flush" />);
const input = screen.getByLabelText('name');
expect(input).toHaveClass(...FLUSH);
['border', 'focus-visible:ring-2'].forEach((name) => expect(input).not.toHaveClass(name));
});
it('Input embedded merges to the same classes as the call site it replaces', () => {
render(<Input aria-label="name" variant="embedded" />);
const input = screen.getByLabelText('name');
expect(input).toHaveClass(...EMBEDDED);
['rounded-lg', 'border', 'px-3', 'bg-transparent'].forEach((name) =>
expect(input).not.toHaveClass(name),
);
});
it('Textarea flush is transparent with no border or ring, and embedded fills the row', () => {
render(
<>
<Textarea aria-label="flush" variant="flush" />
<Textarea aria-label="embedded" variant="embedded" />
</>,
);
expect(screen.getByLabelText('flush')).toHaveClass('bg-transparent', ...FLUSH);
expect(screen.getByLabelText('flush')).not.toHaveClass('bg-surface-secondary');
expect(screen.getByLabelText('embedded')).toHaveClass(...EMBEDDED);
});
it('Textarea default keeps the secondary fill and draws the destructive border when invalid', () => {
render(<Textarea aria-label="notes" />);
expect(screen.getByLabelText('notes')).toHaveClass(
'bg-surface-secondary',
'border',
'aria-invalid:border-border-destructive',
);
});
it('TextareaAutosize adds nothing by default', () => {
render(<TextareaAutosize aria-label="draft" className="resize-none" />);
const field = screen.getByLabelText('draft');
expect(field.className).toBe(cn(fieldInvalid, 'resize-none'));
});
it('TextareaAutosize framed carries the bordered editor box exactly', () => {
render(<TextareaAutosize aria-label="draft" variant="framed" className="min-h-20" />);
const field = screen.getByLabelText('draft');
expect(field).toHaveClass(...FRAMED, 'min-h-20');
});
it('TextareaAutosize framed lets a caller override a role', () => {
render(
<TextareaAutosize aria-label="draft" variant="framed" className="border-border-light" />,
);
const field = screen.getByLabelText('draft');
expect(field).toHaveClass('border-border-light');
expect(field).not.toHaveClass('border-border-medium');
});
it('TextareaAutosize flush and embedded match their Input counterparts', () => {
render(
<>
<TextareaAutosize aria-label="flush" variant="flush" />
<TextareaAutosize aria-label="embedded" variant="embedded" />
</>,
);
expect(screen.getByLabelText('flush')).toHaveClass(...FLUSH);
expect(screen.getByLabelText('embedded')).toHaveClass(...EMBEDDED);
});
it('SecretInput follows the Input variants', () => {
render(<SecretInput aria-label="key" variant="flush" />);
expect(screen.getByLabelText('key')).toHaveClass(...FLUSH);
});
it('paints the floating label chip in the field fill when the theme fills fields', () => {
expect(floatingLabel).toContain('bg-surface-primary');
expect(floatingLabel).toContain('theme-field-fill:bg-field-fill');
});
it('flush and embedded variants drop the base field fill in every control that carries it', () => {
render(
<div>
<Input aria-label="if" variant="flush" />
<Input aria-label="ie" variant="embedded" />
<Textarea aria-label="tf" variant="flush" />
<Textarea aria-label="te" variant="embedded" />
<Textarea aria-label="tt" variant="transparent" />
<Textarea aria-label="td" variant="document" />
</div>,
);
for (const label of ['if', 'ie', 'tf', 'te', 'tt', 'td']) {
expect(screen.getByLabelText(label).className).not.toContain('bg-field-fill');
}
});
it('TextareaAutosize flush and framed keep the global textarea outline off', () => {
render(
<div>
<TextareaAutosize aria-label="f" variant="flush" />
<TextareaAutosize aria-label="r" variant="framed" />
</div>,
);
expect(screen.getByLabelText('f')).toHaveClass('lc-own-focus');
expect(screen.getByLabelText('r')).toHaveClass('lc-own-focus');
});
});

View file

@ -17,3 +17,25 @@ export const fieldBase: string = `lc-field flex w-full rounded-lg border border-
/** A single-line control sized to sit in a form row, matching `Input`. */
export const fieldControl: string = `${fieldBase} h-theme-field bg-transparent`;
/**
* A variant that owns its fill restates it under `theme-field-fill:` too, because that variant's
* `bg-field-fill` (and its disabled-hover twin) would otherwise outrank the variant's own `bg-*`
* in a theme that fills fields.
*/
export const fieldFillTransparent: string =
'bg-transparent theme-field-fill:bg-transparent theme-field-fill:disabled:hover:bg-transparent';
/** A field that sits inside a frame which owns the fill, the border and the focus indicator, so it draws none of them. */
export const fieldFlush: string = `${fieldFillTransparent} border-0 focus-visible:ring-0 theme-field-border:focus-visible:ring-0`;
/** Marks a control outside `.lc-field` whose own ring, or surrounding frame, is its focus indicator, so the app's global textarea outline stays off it. */
export const FIELD_OWN_FOCUS: string = 'lc-own-focus';
/** A field marked `aria-invalid` draws its border in the destructive role, over the caller's border colour. */
export const fieldInvalid: string =
'aria-invalid:border-border-destructive theme-field-border:focus:aria-invalid:border-border-destructive';
/** A field set into a list or popover edge to edge, filling its row and leaving the frame to the host. */
export const fieldEmbedded: string =
'bg-surface-tertiary-alt theme-field-fill:bg-surface-tertiary-alt theme-field-fill:disabled:hover:bg-surface-tertiary-alt h-auto w-full border-0 p-2 rounded-none text-sm text-text-primary';

View file

@ -1,19 +1,25 @@
import * as React from 'react';
import { fieldControl, fieldEmbedded, fieldFlush, fieldInvalid } from './Field';
import { floatingField } from './floating';
import { fieldControl } from './Field';
import { cn } from '~/utils';
import './Field.css';
/** `title` edits a heading in place, so the field takes the heading's type scale. `inline` shares
* a row with icon Buttons, so it takes their height role and the row stays one height when a
* theme sizes fields and buttons apart. `floating` is the sign-in form field whose label rests
* inside it and lifts on focus. */
const INPUT_VARIANTS: Record<'default' | 'inline' | 'title' | 'title-sm' | 'floating', string> = {
* inside it and lifts on focus. `flush` draws no border or ring because the surrounding frame owns
* the indicator, and `embedded` fills a list or popover row edge to edge. */
export const INPUT_VARIANTS: Record<
'default' | 'inline' | 'title' | 'title-sm' | 'floating' | 'flush' | 'embedded',
string
> = {
default: '',
inline: 'h-theme-button',
title: 'h-theme-field-lg text-2xl font-semibold tracking-tight',
'title-sm': 'text-base font-semibold tracking-tight',
floating: floatingField,
flush: fieldFlush,
embedded: fieldEmbedded,
};
export type InputProps = React.InputHTMLAttributes<HTMLInputElement> & {
@ -29,6 +35,7 @@ const Input: React.ForwardRefExoticComponent<InputProps & React.RefAttributes<HT
className={cn(
fieldControl,
'ring-offset-surface-primary',
fieldInvalid,
INPUT_VARIANTS[variant],
colorTransition && 'transition-colors',
className ?? '',

View file

@ -1,17 +1,18 @@
import * as React from 'react';
import { useState, useCallback } from 'react';
import { Eye, EyeOff, Copy, Check } from 'lucide';
import { floatingField, floatingLabel, floatingSecretButton } from './floating';
import { floatingLabel, floatingSecretButton } from './floating';
import { cn, disabledInkClasses } from '~/utils';
import { MorphIcon } from './MorphIcon';
import './Field.css';
import { fieldControl } from './Field';
import { fieldControl, fieldInvalid } from './Field';
import { INPUT_VARIANTS } from './Input';
export interface SecretInputProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type'> {
colorTransition?: boolean;
/** `floating` is the sign-in form field whose label rests inside it and lifts on focus. */
variant?: 'default' | 'floating';
/** Follows the `Input` variants; `floating` is the sign-in form field whose label rests inside it. */
variant?: keyof typeof INPUT_VARIANTS;
/** Show the built-in copy button */
showCopy?: boolean;
/** Custom copy control rendered inside the input, in place of the built-in one */
@ -92,7 +93,8 @@ const SecretInput: React.ForwardRefExoticComponent<
className={cn(
fieldControl,
colorTransition && 'transition-colors',
isFloating && floatingField,
fieldInvalid,
INPUT_VARIANTS[variant],
className ?? '',
copyButton != null || showCopy ? 'pr-20' : 'pr-11',
)}

View file

@ -1,14 +1,21 @@
import * as React from 'react';
import { fieldBase } from './Field';
import { fieldBase, fieldEmbedded, fieldFlush, fieldInvalid, fieldFillTransparent } from './Field';
import { cn } from '~/utils';
import './Field.css';
/** `document` is a long-form editor that reads like the text it will become. */
const TEXTAREA_VARIANTS = {
/** `document` is a long-form editor that reads like the text it will become. `flush` draws no
* border or ring because the surrounding frame owns the indicator, and `embedded` fills a row
* edge to edge. */
const TEXTAREA_VARIANTS: Record<
'default' | 'transparent' | 'document' | 'flush' | 'embedded',
string
> = {
default: 'bg-surface-secondary',
transparent: 'bg-transparent',
document: 'bg-transparent text-base leading-relaxed',
} as const;
transparent: fieldFillTransparent,
document: `${fieldFillTransparent} text-base leading-relaxed`,
flush: fieldFlush,
embedded: fieldEmbedded,
};
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement> & {
variant?: keyof typeof TEXTAREA_VARIANTS;
@ -20,7 +27,13 @@ const Textarea: React.ForwardRefExoticComponent<
({ className = '', variant = 'default', ...props }, ref) => {
return (
<textarea
className={cn(fieldBase, TEXTAREA_VARIANTS[variant], 'min-h-20 resize-none', className)}
className={cn(
fieldBase,
fieldInvalid,
TEXTAREA_VARIANTS[variant],
'min-h-20 resize-none',
className,
)}
ref={ref}
{...props}
/>

View file

@ -6,20 +6,32 @@ import {
useState,
} from 'react';
import { useAtomValue } from 'jotai';
import { cx } from 'class-variance-authority';
import ReactTextareaAutosize from 'react-textarea-autosize';
import type { TextareaAutosizeProps } from 'react-textarea-autosize';
import type { FocusOutline } from './Focus';
import { FIELD_OWN_FOCUS, fieldEmbedded, fieldFlush, fieldInvalid } from './Field';
import { focusOutlineVariants } from './Focus';
import { chatDirectionAtom } from '~/store';
import { cn } from '~/utils';
/** A rounded editor box of its own, such as a prompt or message editor. */
const framed = `${FIELD_OWN_FOCUS} rounded-xl border border-border-medium bg-transparent text-text-primary placeholder:text-text-secondary focus-visible:ring-2 focus-visible:ring-focus-control`;
/** The control is bare by default and the caller draws it. `framed` is the bordered, rounded
* editor box, `flush` draws no border or ring because the surrounding frame owns the indicator,
* and `embedded` fills a list or popover row edge to edge. */
const AUTOSIZE_VARIANTS: Record<'default' | 'framed' | 'flush' | 'embedded', string> = {
default: '',
framed,
flush: `${FIELD_OWN_FOCUS} ${fieldFlush}`,
embedded: fieldEmbedded,
};
type BaseTextareaAutosizeProps = Omit<TextareaAutosizeProps, 'aria-label' | 'aria-labelledby'> & {
focusOutline?: FocusOutline;
variant?: keyof typeof AUTOSIZE_VARIANTS;
};
/** A field marked `aria-invalid` draws its border in the destructive role, over the caller's border colour. */
const invalidBorder = 'aria-invalid:border-border-destructive';
export type TextareaAutosizePropsWithAria =
| (BaseTextareaAutosizeProps & {
'aria-label': string;
@ -33,7 +45,7 @@ export type TextareaAutosizePropsWithAria =
export const TextareaAutosize: ForwardRefExoticComponent<
TextareaAutosizePropsWithAria & RefAttributes<HTMLTextAreaElement>
> = forwardRef<HTMLTextAreaElement, TextareaAutosizePropsWithAria>(
({ focusOutline, className, ...props }, ref) => {
({ focusOutline, variant = 'default', className, ...props }, ref) => {
const [, setIsRerendered] = useState(false);
const chatDirection = useAtomValue(chatDirectionAtom).toLowerCase();
useLayoutEffect(() => setIsRerendered(true), []);
@ -42,7 +54,12 @@ export const TextareaAutosize: ForwardRefExoticComponent<
dir={chatDirection}
{...props}
className={
cx(focusOutlineVariants({ focusOutline }), invalidBorder, className) || undefined
cn(
focusOutlineVariants({ focusOutline }),
fieldInvalid,
AUTOSIZE_VARIANTS[variant],
className,
) || undefined
}
ref={ref}
/>

View file

@ -8,7 +8,7 @@ export const floatingField: string =
'webkit-dark-styles peer h-auto w-full rounded-2xl border px-3.5 pb-2.5 pt-3 text-text-primary duration-200 motion-reduce:transition-none focus:border-accent-primary focus-visible:border-accent-primary';
export const floatingLabel: string =
'absolute start-3 top-1.5 z-10 origin-[0] -translate-y-4 scale-75 transform bg-surface-primary px-2 text-sm text-text-secondary-alt duration-200 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-1.5 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 peer-focus:text-accent-primary motion-reduce:transition-none rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4';
'absolute start-3 top-1.5 z-10 origin-[0] -translate-y-4 scale-75 transform bg-surface-primary px-2 theme-field-fill:bg-field-fill text-sm text-text-secondary-alt duration-200 peer-placeholder-shown:top-1/2 peer-placeholder-shown:-translate-y-1/2 peer-placeholder-shown:scale-100 peer-focus:top-1.5 peer-focus:-translate-y-4 peer-focus:scale-75 peer-focus:px-2 peer-focus:text-accent-primary motion-reduce:transition-none rtl:peer-focus:left-auto rtl:peer-focus:translate-x-1/4';
export const floatingSecretButton: string =
'size-9 rounded-xl text-text-secondary-alt hover:bg-transparent hover:text-text-primary';

View file

@ -40,7 +40,8 @@ html.high-contrast [data-active-item],
html.high-contrast .select-item:focus-visible,
html.high-contrast [data-state='selected'],
html.high-contrast
:is(.bg-surface-active, .bg-surface-active-alt, .bg-surface-nav-selected):not(span) {
:is(.bg-surface-active, .bg-surface-active-alt, .bg-surface-nav-selected):not(span),
html.high-contrast [aria-pressed='true'][class*='aria-pressed:bg-surface-nav-selected']:not(span) {
outline: 3px solid rgb(var(--text-primary)) !important;
outline-offset: -3px;
}