From 2443095fcc6dc6bb38ccfd1c3b4d2aa87a5c0b9e Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Fri, 25 Sep 2026 01:22:42 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BF=20fix:=20Keep=20Identity=20Badge=20La?= =?UTF-8?q?bels=20at=20Text=20Contrast=20(#16337)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: keep identity badge labels on a text role and move the series hue to a dot Action method and principal type badges painted 11-12px labels in a categorical series slot over its own tint. The series scale is contracted at the 3:1 mark floor, so that text fell below 4.5:1 in every palette. The label now uses text-secondary and the hue rides on a decorative leading dot, and semanticTokens.spec.ts floors both halves of the pairing on the surfaces these badges sit on. * test: cover identity badge label contrast across palettes and modes * refactor: share the identity label treatment as a SeriesLabel primitive Both badges composed the same neutral label and series dot by hand. The treatment now lives in @librechat/client so a later contrast or appearance change lands once. It renders the caller's text, so it joins the text primitives whose typography belongs to the caller. The principal scenario also waits for each query's own option before reading paint, since the picker keeps the previous result on screen while the debounced search is in flight. --- .../PeoplePicker/PeoplePickerSearchItem.tsx | 22 +- .../SidePanel/Agents/ActionsTable/Columns.tsx | 37 +-- .../scenarios/action-method-labels.spec.ts | 229 +++++++++++++ .../scenarios/principal-type-labels.spec.ts | 307 ++++++++++++++++++ eslint.config.mjs | 2 +- .../src/components/SeriesLabel.spec.tsx | 30 ++ .../client/src/components/SeriesLabel.tsx | 51 +++ packages/client/src/components/index.ts | 1 + .../client/src/theme/semanticTokens.spec.ts | 22 ++ 9 files changed, 666 insertions(+), 35 deletions(-) create mode 100644 e2e/specs/mock/scenarios/action-method-labels.spec.ts create mode 100644 e2e/specs/mock/scenarios/principal-type-labels.spec.ts create mode 100644 packages/client/src/components/SeriesLabel.spec.tsx create mode 100644 packages/client/src/components/SeriesLabel.tsx diff --git a/client/src/components/Sharing/PeoplePicker/PeoplePickerSearchItem.tsx b/client/src/components/Sharing/PeoplePicker/PeoplePickerSearchItem.tsx index d0ed5b08a8..9317a1d514 100644 --- a/client/src/components/Sharing/PeoplePicker/PeoplePickerSearchItem.tsx +++ b/client/src/components/Sharing/PeoplePicker/PeoplePickerSearchItem.tsx @@ -1,4 +1,5 @@ import React, { forwardRef } from 'react'; +import { SeriesLabel } from '@librechat/client'; import { PrincipalType } from 'librechat-data-provider'; import type { TPrincipal } from 'librechat-data-provider'; import PrincipalAvatar from '~/components/Sharing/PrincipalAvatar'; @@ -20,29 +21,27 @@ const PeoplePickerSearchItem = forwardRef { switch (type) { case PrincipalType.USER: return { - className: 'bg-series-1/10 text-series-1', + hue: 1 as const, label: localize('com_ui_user'), }; case PrincipalType.GROUP: return { - className: 'bg-series-7/10 text-series-7', + hue: 7 as const, label: localize('com_ui_group'), }; case PrincipalType.ROLE: return { - className: 'bg-series-6/10 text-series-6', + hue: 6 as const, label: localize('com_ui_role'), }; default: return { - className: 'bg-surface-tertiary text-text-secondary', + hue: undefined, label: type, }; } @@ -68,14 +67,9 @@ const PeoplePickerSearchItem = forwardRef
- + {badgeConfig.label} - +
); diff --git a/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx b/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx index e4d82fce1a..6b594e466d 100644 --- a/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx +++ b/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx @@ -1,7 +1,8 @@ +import { SeriesLabel } from '@librechat/client'; +import type { SeriesLabelHue } from '@librechat/client'; import type { ColumnDef } from '@tanstack/react-table'; import type { TranslationKeys } from '~/hooks'; import { useLocalize } from '~/hooks'; -import { cn } from '~/utils'; export type Spec = { name: string; @@ -12,18 +13,16 @@ export type Spec = { /** * Color-codes the HTTP verb the way API docs do, so the method reads at a - * glance. The hues come from the categorical series ramp, which is what that - * scale is for: identity rather than status, contrast-checked per mode, and - * separable under simulated deuteranopia. Slots are chosen to stay close to the - * conventional verb colours. `delete` is the one exception, taking the error - * role, because destructive really is a status. + * glance. The hues come from the categorical series ramp (identity rather than + * status), chosen to stay close to the conventional verb colours. `delete` + * takes the error role, because destructive really is a status. */ -const METHOD_STYLES: Record = { - get: 'bg-series-1/10 text-series-1', - post: 'bg-series-7/10 text-series-7', - put: 'bg-series-4/10 text-series-4', - patch: 'bg-series-6/10 text-series-6', - delete: 'bg-status-error-subtle text-status-error', +const METHOD_HUES: Record = { + get: 1, + post: 7, + put: 4, + patch: 6, + delete: 'error', }; function HeaderCell({ labelKey }: { labelKey: TranslationKeys }) { @@ -33,14 +32,12 @@ function HeaderCell({ labelKey }: { labelKey: TranslationKeys }) { function MethodBadge({ method }: { method: string }) { return ( - {method} - + ); } @@ -48,7 +45,7 @@ export const columns: ColumnDef[] = [ { accessorKey: 'name', header: () => , - cell: ({ row }) => {row.original.name}, + cell: ({ row }) => {row.original.name}, }, { accessorKey: 'method', @@ -59,7 +56,7 @@ export const columns: ColumnDef[] = [ accessorKey: 'path', header: () => , cell: ({ row }) => ( - {row.original.path} + {row.original.path} ), }, ]; diff --git a/e2e/specs/mock/scenarios/action-method-labels.spec.ts b/e2e/specs/mock/scenarios/action-method-labels.spec.ts new file mode 100644 index 0000000000..0564c36234 --- /dev/null +++ b/e2e/specs/mock/scenarios/action-method-labels.spec.ts @@ -0,0 +1,229 @@ +import { expect, test } from '@playwright/test'; +import type { Locator, Page } from '@playwright/test'; +import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse'; +import { openAgentBuilder, uniqueAgentName, cleanupAgent } from '../agents.helpers'; +import { MOCK_ENDPOINTS, NEW_CHAT_PATH, getAccessToken, requestJson } from '../helpers'; + +/** + * The HTTP method badge in the agent builder's action table used to paint its + * label text in a categorical series color (`text-series-N` over `bg-series-N/10`), + * which fails WCAG 4.5:1 for text this small. The label now stays on + * `text-text-secondary` and the series hue rides on a leading decorative dot + * held to the 3:1 mark floor instead (`ActionsTable/Columns.tsx`). These + * scenarios drive the real parsed-actions table and read what the browser + * actually paints, rather than the classes under test, in light, dark, and the + * ClickHouse reference theme (the theme the original report measured failing). + */ + +type Mode = 'light' | 'dark'; +type ThemeVariant = 'default' | 'clickhouse'; +type Rgb = [number, number, number]; + +const MODES: Mode[] = ['light', 'dark']; +const VARIANTS: ThemeVariant[] = ['default', 'clickhouse']; +const MODE_PARAM = 'e2eThemeMode'; +const VARIANT_PARAM = 'e2eThemeVariant'; +const WCAG_AA_NORMAL = 4.5; +/** WCAG 1.4.11: a graphical object (the dot) owes 3:1 against what it sits on. */ +const WCAG_MARK_MIN = 3; + +const METHOD_OPERATIONS: ReadonlyArray<{ method: string; operationId: string }> = [ + { method: 'get', operationId: 'e2eListWidgets' }, + { method: 'post', operationId: 'e2eCreateWidget' }, + { method: 'put', operationId: 'e2eReplaceWidget' }, + { method: 'patch', operationId: 'e2ePatchWidget' }, + { method: 'delete', operationId: 'e2eDeleteWidget' }, +]; + +const OPENAPI_SPEC = JSON.stringify({ + openapi: '3.0.0', + info: { title: 'E2E Badge Contrast API', version: '1.0.0' }, + servers: [{ url: 'https://e2e-badge-contrast.example.com' }], + paths: { + '/widgets': { + get: { operationId: 'e2eListWidgets', responses: { '200': { description: 'ok' } } }, + post: { operationId: 'e2eCreateWidget', responses: { '200': { description: 'ok' } } }, + put: { operationId: 'e2eReplaceWidget', responses: { '200': { description: 'ok' } } }, + patch: { operationId: 'e2ePatchWidget', responses: { '200': { description: 'ok' } } }, + delete: { operationId: 'e2eDeleteWidget', responses: { '200': { description: 'ok' } } }, + }, + }, +}); + +/** + * Mirrors `clickhouse-theme.spec.ts`'s URL-param bridge, extended with a second + * param for whether the ClickHouse definition is installed. The mode key is + * only written when the param is present, and the theme keys only change on an + * explicit `default`/`clickhouse` value: a bare re-navigation (as + * `openAgentBuilder`'s own internal `page.goto` performs) carries neither param + * and leaves whatever the test's own prior navigation chose in place. + */ +async function installThemeBridge(page: Page, clickHouseDefinition: unknown) { + await page.addInitScript( + ([stored, modeParam, variantParam]) => { + const params = new URL(location.href).searchParams; + const mode = params.get(modeParam as string); + if (mode) { + localStorage.setItem('color-theme', mode); + } + localStorage.setItem('navVisible', 'true'); + localStorage.removeItem('theme-colors'); + localStorage.removeItem('theme-name'); + const variant = params.get(variantParam as string); + if (variant === 'clickhouse') { + localStorage.setItem('theme-definition', JSON.stringify(stored)); + localStorage.setItem('theme-source', 'definition'); + } else if (variant === 'default') { + localStorage.removeItem('theme-definition'); + localStorage.removeItem('theme-source'); + } + }, + [clickHouseDefinition, MODE_PARAM, VARIANT_PARAM] as [unknown, string, string], + ); +} + +function parseRgb(value: string): Rgb { + const channels = value.match(/\d+(\.\d+)?/g)?.map(Number) ?? []; + return [channels[0], channels[1], channels[2]]; +} + +function channel(value: number): number { + const c = value / 255; + return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); +} + +function contrast(a: Rgb, b: Rgb): number { + const luminance = ([r, g, b]: Rgb) => + 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); + const [lighter, darker] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (lighter + 0.05) / (darker + 0.05); +} + +type BadgePaint = { + labelColor: string; + dotColor: string; + dotAriaHidden: boolean; + background: string; +}; + +/** + * Reads what the browser actually painted for a badge inside `container`: the + * dot is found by its `aria-hidden` attribute (not by the color classes under + * test), the label is the dot's own parent span, and the background is the + * first non-transparent ancestor of that label, walking up from it. + */ +async function readBadgePaint(container: Locator): Promise { + return container.evaluate((node) => { + const dot = node.querySelector('span[aria-hidden="true"]') as HTMLElement | null; + const label = dot?.parentElement ?? null; + if (!dot || !label) { + throw new Error('Expected a label span holding an aria-hidden leading dot'); + } + let background = ''; + for (let el: Element | null = label; el; el = el.parentElement) { + const bg = getComputedStyle(el).backgroundColor; + if (bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent') { + background = bg; + break; + } + } + return { + labelColor: getComputedStyle(label).color, + dotColor: getComputedStyle(dot).backgroundColor, + dotAriaHidden: dot.getAttribute('aria-hidden') === 'true', + background, + }; + }); +} + +async function createAgent(page: Page, name: string): Promise { + const token = await getAccessToken(page); + const agent = await requestJson<{ id: string }>(page, { + path: '/api/agents', + token, + method: 'POST', + body: { + name, + provider: MOCK_ENDPOINTS[0].label, + model: MOCK_ENDPOINTS[0].model, + }, + }); + return agent.id; +} + +async function selectAgentInBuilder(page: Page, name: string): Promise { + const form = await openAgentBuilder(page); + await form.getByRole('combobox', { name: 'Agent', exact: true }).click(); + await page.getByRole('option', { name, exact: true }).click(); + await expect(form.getByLabel('Agent name')).toHaveValue(name); + return form; +} + +/** Opens the parsed-actions table for a brand new action on the given agent. */ +async function openNewActionTable(page: Page, agentName: string): Promise { + const form = await selectAgentInBuilder(page, agentName); + await form.getByRole('button', { name: 'Add tools' }).click(); + const toolLibrary = page.getByRole('dialog', { name: 'Tool Library' }); + await expect(toolLibrary).toBeVisible(); + + await toolLibrary.getByRole('button', { name: 'Create new…' }).click(); + await page.getByRole('menuitem', { name: 'Actions' }).click(); + + const actionDialog = page.getByRole('dialog', { name: 'New action' }); + await expect(actionDialog).toBeVisible(); + + await actionDialog.getByRole('textbox', { name: 'Schema' }).fill(OPENAPI_SPEC); + await expect(actionDialog.getByRole('table')).toBeVisible({ timeout: 20000 }); + return actionDialog; +} + +test.describe('agent action method badges', () => { + test('@scenario:action-method-labels-meet-text-contrast HTTP method labels stay text-secondary while the series hue rides the leading dot', async ({ + page, + }) => { + test.setTimeout(180000); + const agentName = uniqueAgentName('E2E Method Badge Contrast'); + let agentId: string | undefined; + + await installThemeBridge(page, clickHouseTheme); + + try { + await page.goto(NEW_CHAT_PATH, { timeout: 10000 }); + agentId = await createAgent(page, agentName); + + for (const variant of VARIANTS) { + for (const mode of MODES) { + await page.goto(`${NEW_CHAT_PATH}?${MODE_PARAM}=${mode}&${VARIANT_PARAM}=${variant}`, { + timeout: 10000, + }); + const actionDialog = await openNewActionTable(page, agentName); + + for (const { method, operationId } of METHOD_OPERATIONS) { + const row = actionDialog.getByRole('row').filter({ hasText: operationId }); + await expect(row).toBeVisible({ timeout: 20000 }); + + const paint = await readBadgePaint(row); + const context = `method=${method} variant=${variant} mode=${mode}`; + + expect(paint.dotAriaHidden, `dot should be aria-hidden (${context})`).toBe(true); + expect(paint.labelColor, `label should not reuse the dot color (${context})`).not.toBe( + paint.dotColor, + ); + + const background = parseRgb(paint.background); + expect( + contrast(parseRgb(paint.labelColor), background), + `label contrast (${context})`, + ).toBeGreaterThanOrEqual(WCAG_AA_NORMAL); + expect( + contrast(parseRgb(paint.dotColor), background), + `dot contrast (${context})`, + ).toBeGreaterThanOrEqual(WCAG_MARK_MIN); + } + } + } + } finally { + await cleanupAgent(page, agentId); + } + }); +}); diff --git a/e2e/specs/mock/scenarios/principal-type-labels.spec.ts b/e2e/specs/mock/scenarios/principal-type-labels.spec.ts new file mode 100644 index 0000000000..486584c497 --- /dev/null +++ b/e2e/specs/mock/scenarios/principal-type-labels.spec.ts @@ -0,0 +1,307 @@ +import { ObjectId } from 'mongodb'; +import { expect, test } from '@playwright/test'; +import type { Locator, Page } from '@playwright/test'; +import { clickHouseTheme } from '../../../../packages/client/src/theme/themes/clickhouse'; +import { getSecondaryE2EUser } from '../../../setup/users.mock'; +import { openAgentBuilder, uniqueAgentName, cleanupAgent } from '../agents.helpers'; +import { MOCK_ENDPOINTS, NEW_CHAT_PATH, getAccessToken, requestJson, uniqueName } from '../helpers'; +import { getE2EUser } from '../../../setup/user'; +import { withMongo } from '../db'; + +/** + * The principal type badge (User / Group / Role) on each people-search result + * inside the agent share dialog used to paint its label text in a categorical + * series color (`text-series-N` over `bg-series-N/10`), which fails WCAG + * 4.5:1 for text this small. The label now stays on `text-text-secondary` and + * the series hue rides on a leading decorative dot held to the 3:1 mark floor + * instead (`PeoplePickerSearchItem.tsx`). These scenarios drive a real search + * through `UnifiedPeopleSearch` -> `SearchPicker` and read what the browser + * actually paints, at rest (popover `bg-surface-secondary`) and while the + * option is active (`bg-surface-tertiary`), in light, dark, and the ClickHouse + * reference theme (the theme the original report measured failing). + * + * The primary e2e user is the first user ever registered in this run's fresh + * database (`e2e/setup/global-setup.ts` -> `authenticate`), so + * `AuthService.js` auto-promotes it to ADMIN. The default ADMIN role already + * grants `PEOPLE_PICKER` view access and bypasses the agent `SHARE` + * permission check (`roleDefaults` in `packages/data-provider/src/roles.ts`, + * the admin shortcut in `packages/api/src/acl/search.ts`, and the `isAdmin` + * clauses in `AgentFooter.tsx`), so no role permissions need seeding here. + */ + +type Mode = 'light' | 'dark'; +type ThemeVariant = 'default' | 'clickhouse'; +type Rgb = [number, number, number]; + +const MODES: Mode[] = ['light', 'dark']; +const VARIANTS: ThemeVariant[] = ['default', 'clickhouse']; +const MODE_PARAM = 'e2eThemeMode'; +const VARIANT_PARAM = 'e2eThemeVariant'; +const WCAG_AA_NORMAL = 4.5; +/** WCAG 1.4.11: a graphical object (the dot) owes 3:1 against what it sits on. */ +const WCAG_MARK_MIN = 3; +const SEARCH_LABEL = 'Search for people or groups by name or email'; + +/** + * Mirrors `clickhouse-theme.spec.ts`'s URL-param bridge, extended with a second + * param for whether the ClickHouse definition is installed. The mode key is + * only written when the param is present, and the theme keys only change on an + * explicit `default`/`clickhouse` value: a bare re-navigation (as + * `openAgentBuilder`'s own internal `page.goto` performs) carries neither param + * and leaves whatever the test's own prior navigation chose in place. + */ +async function installThemeBridge(page: Page, clickHouseDefinition: unknown) { + await page.addInitScript( + ([stored, modeParam, variantParam]) => { + const params = new URL(location.href).searchParams; + const mode = params.get(modeParam as string); + if (mode) { + localStorage.setItem('color-theme', mode); + } + localStorage.setItem('navVisible', 'true'); + localStorage.removeItem('theme-colors'); + localStorage.removeItem('theme-name'); + const variant = params.get(variantParam as string); + if (variant === 'clickhouse') { + localStorage.setItem('theme-definition', JSON.stringify(stored)); + localStorage.setItem('theme-source', 'definition'); + } else if (variant === 'default') { + localStorage.removeItem('theme-definition'); + localStorage.removeItem('theme-source'); + } + }, + [clickHouseDefinition, MODE_PARAM, VARIANT_PARAM] as [unknown, string, string], + ); +} + +function parseRgb(value: string): Rgb { + const channels = value.match(/\d+(\.\d+)?/g)?.map(Number) ?? []; + return [channels[0], channels[1], channels[2]]; +} + +function channel(value: number): number { + const c = value / 255; + return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); +} + +function contrast(a: Rgb, b: Rgb): number { + const luminance = ([r, g, b]: Rgb) => + 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); + const [lighter, darker] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (lighter + 0.05) / (darker + 0.05); +} + +type BadgePaint = { + labelColor: string; + dotColor: string; + dotAriaHidden: boolean; + background: string; +}; + +/** + * Reads what the browser actually painted for a badge inside `container`: the + * dot is found by its `aria-hidden` attribute (not by the color classes under + * test), the label is the dot's own parent span, and the background is the + * first non-transparent ancestor of that label, walking up from it. + */ +async function readBadgePaint(container: Locator): Promise { + return container.evaluate((node) => { + const dot = node.querySelector('span[aria-hidden="true"]') as HTMLElement | null; + const label = dot?.parentElement ?? null; + if (!dot || !label) { + throw new Error('Expected a label span holding an aria-hidden leading dot'); + } + let background = ''; + for (let el: Element | null = label; el; el = el.parentElement) { + const bg = getComputedStyle(el).backgroundColor; + if (bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent') { + background = bg; + break; + } + } + return { + labelColor: getComputedStyle(label).color, + dotColor: getComputedStyle(dot).backgroundColor, + dotAriaHidden: dot.getAttribute('aria-hidden') === 'true', + background, + }; + }); +} + +function assertBadgePaint(paint: BadgePaint, context: string) { + expect(paint.dotAriaHidden, `dot should be aria-hidden (${context})`).toBe(true); + expect(paint.labelColor, `label should not reuse the dot color (${context})`).not.toBe( + paint.dotColor, + ); + const background = parseRgb(paint.background); + expect( + contrast(parseRgb(paint.labelColor), background), + `label contrast (${context})`, + ).toBeGreaterThanOrEqual(WCAG_AA_NORMAL); + expect( + contrast(parseRgb(paint.dotColor), background), + `dot contrast (${context})`, + ).toBeGreaterThanOrEqual(WCAG_MARK_MIN); +} + +async function createAgent(page: Page, name: string): Promise { + const token = await getAccessToken(page); + const agent = await requestJson<{ id: string }>(page, { + path: '/api/agents', + token, + method: 'POST', + body: { + name, + provider: MOCK_ENDPOINTS[0].label, + model: MOCK_ENDPOINTS[0].model, + }, + }); + return agent.id; +} + +async function selectAgentInBuilder(page: Page, name: string): Promise { + const form = await openAgentBuilder(page); + await form.getByRole('combobox', { name: 'Agent', exact: true }).click(); + await page.getByRole('option', { name, exact: true }).click(); + await expect(form.getByLabel('Agent name')).toHaveValue(name); + return form; +} + +async function openShareDialog(page: Page, agentName: string): Promise { + await selectAgentInBuilder(page, agentName); + await page.getByRole('button', { name: `Share ${agentName}` }).click(); + const dialog = page.getByRole('dialog', { name: `Share ${agentName}` }); + await expect(dialog).toBeVisible(); + return dialog; +} + +/** A minimal local group: `source: 'local'` needs no `idOnTheSource` + * (`packages/data-schemas/src/schema/group.ts`), and the search matches on + * `name` alone (`findGroupsByNamePattern`). */ +async function seedGroup(name: string): Promise { + await withMongo(async (db) => { + await db.collection('groups').insertOne({ + name, + source: 'local', + memberIds: [], + createdAt: new Date(), + updatedAt: new Date(), + }); + }); +} + +async function deleteGroup(name: string): Promise { + await withMongo(async (db) => { + await db.collection('groups').deleteOne({ name }); + }); +} + +/** The primary e2e user is registered by global setup, but the secondary one + * is not guaranteed to exist yet in this run's database: mirrors the same + * defensive insert `marketplace-mine.spec.ts` uses so the principal search + * has a "user" result to find regardless of spec run order. Left in place + * afterward, as that spec does, since it is a shared fixture. */ +async function ensureSecondaryUser(): Promise<{ name: string; email: string }> { + const secondary = getSecondaryE2EUser(); + await withMongo(async (db) => { + const users = db.collection('users'); + const existing = await users.findOne({ email: secondary.email }); + if (existing) { + return; + } + const primaryUser = await users.findOne({ email: getE2EUser().email }); + const now = new Date(); + await users.insertOne({ + _id: new ObjectId(), + email: secondary.email, + name: secondary.name, + tenantId: primaryUser?.tenantId, + role: primaryUser?.role, + createdAt: now, + updatedAt: now, + }); + }); + return secondary; +} + +/** Makes the sole rendered option the active descendant (`data-active-item`), + * the same roving-focus mechanism `model-selector-search.spec.ts` drives with + * repeated `ArrowDown` presses from the search box. */ +async function activateOnlyOption(search: Locator, option: Locator): Promise { + for (let attempt = 0; attempt < 3; attempt++) { + if ((await option.getAttribute('data-active-item')) !== null) { + return; + } + await search.press('ArrowDown'); + } +} + +test.describe('people picker principal type badges', () => { + test('@scenario:principal-type-labels-meet-text-contrast principal type labels (User/Group/Role) stay text-secondary while the series hue rides the leading dot', async ({ + page, + }) => { + test.setTimeout(180000); + const agentName = uniqueAgentName('E2E Principal Badge Contrast'); + const groupName = uniqueName('E2E Principal Badge Group'); + let agentId: string | undefined; + let groupSeeded = false; + + await installThemeBridge(page, clickHouseTheme); + + try { + await page.goto(NEW_CHAT_PATH, { timeout: 10000 }); + agentId = await createAgent(page, agentName); + await seedGroup(groupName); + groupSeeded = true; + + const secondaryUser = await ensureSecondaryUser(); + /** Each query isolates exactly one result: the secondary user's full + * name, the unique seeded group's name, and "admin", which matches only + * the ADMIN system role (no seeded user, group, or email contains it). */ + const queries: ReadonlyArray<{ type: string; label: string; query: string }> = [ + { type: 'user', label: 'User', query: secondaryUser.name }, + { type: 'group', label: 'Group', query: groupName }, + { type: 'role', label: 'Role', query: 'admin' }, + ]; + + for (const variant of VARIANTS) { + for (const mode of MODES) { + await page.goto(`${NEW_CHAT_PATH}?${MODE_PARAM}=${mode}&${VARIANT_PARAM}=${variant}`, { + timeout: 10000, + }); + const dialog = await openShareDialog(page, agentName); + const search = dialog.getByRole('combobox', { name: SEARCH_LABEL }); + await expect(search).toBeVisible(); + + for (const { type, label, query } of queries) { + await search.fill(query); + /** The picker debounces the query and keeps the previous result on + * screen until the new one lands, so wait for this query's own + * option (its name and its type label) before reading any paint. */ + const option = dialog + .getByRole('option') + .filter({ hasText: query }) + .filter({ hasText: label }); + await expect(option).toBeVisible({ timeout: 10000 }); + await expect(dialog.getByRole('option')).toHaveCount(1); + + const context = `type=${type} variant=${variant} mode=${mode}`; + assertBadgePaint(await readBadgePaint(option), `resting, ${context}`); + + await activateOnlyOption(search, option); + await expect( + option, + `option should become the active descendant (${context})`, + ).toHaveAttribute('data-active-item', /.*/); + assertBadgePaint(await readBadgePaint(option), `active, ${context}`); + } + } + } + } finally { + await cleanupAgent(page, agentId); + if (groupSeeded) { + await deleteGroup(groupName); + } + } + }); +}); diff --git a/eslint.config.mjs b/eslint.config.mjs index bd200b4963..fdc76ee151 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -222,7 +222,7 @@ export default [ // A text primitive renders the caller's text, so the caller owns its size, weight // and leading. Color is still the theme's: it stays reported here. { - pattern: '^(Label|Description|DialogTitle|DialogDescription)$', + pattern: '^(Label|Description|DialogTitle|DialogDescription|SeriesLabel)$', allow: ['layout', 'icon-*', 'typography'], }, // A skeleton stands in for the caller's content, so it takes that content's diff --git a/packages/client/src/components/SeriesLabel.spec.tsx b/packages/client/src/components/SeriesLabel.spec.tsx new file mode 100644 index 0000000000..9eec213d7d --- /dev/null +++ b/packages/client/src/components/SeriesLabel.spec.tsx @@ -0,0 +1,30 @@ +import '@testing-library/jest-dom'; +import { render, screen } from '@testing-library/react'; +import { SeriesLabel } from './SeriesLabel'; + +describe('SeriesLabel', () => { + it('keeps the label on the neutral text role and the hue on a hidden dot', () => { + render(POST); + + const label = screen.getByText('POST'); + const dot = label.querySelector('[aria-hidden="true"]'); + + expect(label).toHaveClass('text-text-secondary'); + expect(label.className).not.toMatch(/text-series-/); + expect(dot).toHaveClass('bg-series-7'); + }); + + it('maps the error hue to the status error role', () => { + render(DELETE); + + expect(screen.getByText('DELETE').querySelector('[aria-hidden="true"]')).toHaveClass( + 'bg-status-error', + ); + }); + + it('renders the label alone when no hue applies', () => { + render(OPTIONS); + + expect(screen.getByText('OPTIONS').querySelector('[aria-hidden="true"]')).toBeNull(); + }); +}); diff --git a/packages/client/src/components/SeriesLabel.tsx b/packages/client/src/components/SeriesLabel.tsx new file mode 100644 index 0000000000..013e7c2799 --- /dev/null +++ b/packages/client/src/components/SeriesLabel.tsx @@ -0,0 +1,51 @@ +import * as React from 'react'; +import { cn } from '~/utils'; + +/** A categorical series slot, or the error role for an identity that is destructive by nature. */ +export type SeriesLabelHue = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 'error'; + +const dotClassNames: Record = { + 1: 'bg-series-1', + 2: 'bg-series-2', + 3: 'bg-series-3', + 4: 'bg-series-4', + 5: 'bg-series-5', + 6: 'bg-series-6', + 7: 'bg-series-7', + 8: 'bg-series-8', + error: 'bg-status-error', +}; + +export interface SeriesLabelProps extends React.HTMLAttributes { + hue?: SeriesLabelHue; +} + +/** + * Small identity text (an HTTP verb, a principal type) keyed to a categorical + * hue. The series slots are contracted as marks at 3:1, so the hue rides on a + * decorative leading dot and the label stays on `text-secondary` at 4.5:1. + * Typography belongs to the caller. + */ +const SeriesLabel: React.ForwardRefExoticComponent< + SeriesLabelProps & React.RefAttributes +> = React.forwardRef( + ({ hue, className, children, ...props }, ref) => ( + + {hue != null && ( + + ), +); + +SeriesLabel.displayName = 'SeriesLabel'; + +export { SeriesLabel }; diff --git a/packages/client/src/components/index.ts b/packages/client/src/components/index.ts index f7bf5fbfe0..fbe6c4c163 100644 --- a/packages/client/src/components/index.ts +++ b/packages/client/src/components/index.ts @@ -5,6 +5,7 @@ export * from './AlertDialog'; export * from './Breadcrumb'; export * from './Button'; export * from './Chip'; +export * from './SeriesLabel'; export * from './Checkbox'; export * from './DisclosureChevron'; export * from './Dialog'; diff --git a/packages/client/src/theme/semanticTokens.spec.ts b/packages/client/src/theme/semanticTokens.spec.ts index d2e7ec2f19..c4c53d673a 100644 --- a/packages/client/src/theme/semanticTokens.spec.ts +++ b/packages/client/src/theme/semanticTokens.spec.ts @@ -357,6 +357,28 @@ describe.each([ expect(failures).toEqual([]); }); + + /** Identity labels (`SeriesLabel`: action methods, principal types) are small text, so the + * series hue never paints the glyphs: the label takes `text-secondary` at AA + * and the hue rides on a leading dot at the 3:1 mark floor, both on the rows + * and popover options that host them, at rest and while hovered or active. */ + it('keeps identity labels at AA and their hue dots at the 3:1 mark floor', () => { + const hosts: Array = [ + 'rgb-surface-primary', + 'rgb-surface-secondary', + 'rgb-surface-tertiary', + 'rgb-surface-dialog', + ]; + const dots: Array = [...seriesTokens, 'rgb-status-error']; + const dotFailures = dots.flatMap((token) => + hosts.flatMap((surface) => { + const ratio = contrast(toRgb(theme, token), toRgb(theme, surface)); + return ratio < WCAG_MARK_MIN ? [`${token} dot on ${surface}: ${ratio.toFixed(2)}:1`] : []; + }), + ); + + expect([...dotFailures, ...belowAA(theme, ['rgb-text-secondary'], hosts)]).toEqual([]); + }); }); describe.each([