feat(ui): shared page-pattern layer (facts, rows, states, fields, choices)

The clue surface carried 31 hand-written fact rows, 14 list-row shells, 10
empty states, 14 error+retry blocks, 15 stacked fields, 6 choice groups, 11
status footers and 9 action bars — 968 lines of CSS in ten near-identical
families that had already drifted apart (four spellings of the retry row,
three different "selected" pictures).

These eight components own those shapes once, on the same token-only contract
as the global kit: flat fills, one 1px border language, no shadow, no resting
state painted, native keyboard semantics (a navigating title is a real
<button>, a choice is a real <input>), tabular figures, 44px touch targets.

patterns.module.css joins the theme guard and the host-token guard; the new
spec pins the contract structurally (default states unstyled, native controls
preserved) rather than cosmetically.
This commit is contained in:
Menghuan1918 committed 2026-11-24 16:43:26 +08:00
1 parent 5ee81fb073
commit 9056ea2c7c
5 files changed
+1134

No files matched your search

+6
View File
@@ -11,6 +11,12 @@ export { LoadingIndicator, type LoadingIndicatorProps } from './LoadingIndicator
export { WorkbenchSection, type WorkbenchSectionProps } from './WorkbenchSection.tsx'
export { SelectMenu, type SelectMenuProps, type SelectOption } from './SelectMenu.tsx'
export { TextInput, TextArea, NumberInput, Checkbox, ToggleSwitch, Tabs, SettingRow, type TabOption } from './controls.tsx'
export {
ActionFooter, ChoiceCard, EmptyState, ErrorBlock, FactList, FactRow, Field, ListRow, StatusLine,
type ActionFooterProps, type ChoiceCardProps, type ChoiceOption, type EmptyStateProps,
type ErrorBlockProps, type Fact, type FactListProps, type FactRowProps, type FieldProps,
type ListRowProps, type PatternTone, type StatusLineProps,
} from './patterns.tsx'
export { SourceSwitcher, type SourceSwitcherItem, type SourceSwitcherProps } from './SourceSwitcher.tsx'
export { SearchField, type SearchFieldProps } from './SearchField.tsx'
export { SidebarToolbar, type SidebarToolbarProps } from './SidebarToolbar.tsx'
+441
View File
@@ -0,0 +1,441 @@
/*
* Shared page patterns — the second half of the global kit.
*
* `kit.module.css` owns the ATOMS (a button, a badge, a state line); this sheet
* owns the SHAPES that pages kept rebuilding: a key-value fact, a list row, an
* empty page, an error with a retry, a labelled field, a mutually-exclusive
* choice, a status line and an action footer. Every rule here replaces 6-31
* hand-written copies that had drifted apart (different paddings, three
* different "selected" pictures, four spellings of the retry row).
*
* Contract, same as the kit: token-only paint (`tests/theme.spec.ts` scans this
* sheet), ONE border language (1px solid), no shadow, no gradient, no
* decoration. Numbers use tabular figures. Touch targets reach 44px under a
* coarse pointer.
*/
/* ── FactRow / FactList ─────────────────────────────────────────────────── */
.factList {
display: flex;
flex-direction: column;
min-width: 0;
margin: 0;
padding: 0;
}
.factRow {
display: flex;
align-items: baseline;
gap: var(--ds-sidebar-space-2);
min-width: 0;
padding: 3px 0;
font: var(--dsw-font-xxs-12);
}
.factLabel {
flex: none;
color: var(--dsw-alias-label-tertiary);
}
.factValue {
min-width: 0;
overflow-wrap: anywhere;
color: var(--dsw-alias-label-primary);
}
/* One ink rung per fact tone; a default fact stays secondary. */
.factRow[data-tone='error'] .factValue { color: var(--dsw-alias-state-error-primary); }
.factRow[data-tone='warn'] .factValue { color: var(--dsw-alias-state-warn-primary); }
.factRow[data-tone='success'] .factValue { color: var(--dsw-alias-state-success-primary); }
.factRow[data-tone='business'] .factValue { color: var(--dsw-alias-state-business-primary); }
/* The host defines no `--dsw-font-mono`; the fallback keeps the declaration
alive and resolves to the plugin's code family (the same pair every other
mono site in this repo uses). */
.mono {
font-family: var(--dsw-font-mono, var(--ds-font-family-code));
font-variant-numeric: tabular-nums;
}
/* ── ListRow ────────────────────────────────────────────────────────────── */
.listRow {
box-sizing: border-box;
display: flex;
align-items: center;
gap: var(--ds-sidebar-space-2);
min-width: 0;
min-height: 30px;
padding: 0 var(--ds-sidebar-space-3);
border-radius: var(--ds-sidebar-radius);
color: var(--dsw-alias-label-primary);
font: var(--dsw-font-xxs-12);
}
.listRow:hover { background: var(--dsw-alias-interactive-bg-hover); }
.listRow[data-selected='true'] {
background: var(--dsw-alias-interactive-bg-active);
color: var(--dsw-alias-label-primary);
}
.listRow[data-dimmed='true'] { color: var(--dsw-alias-label-tertiary); }
.listRowLeading {
display: inline-flex;
align-items: center;
flex: none;
color: var(--dsw-alias-label-tertiary);
}
.listRowMain {
display: flex;
flex-direction: column;
min-width: 0;
flex: 1 1 auto;
text-align: start;
gap: 1px;
}
/* The title is a real button when the row navigates: keyboard operation and a
visible focus ring come for free, and the row's own padding stays intact. */
.listRowTitle {
appearance: none;
display: block;
min-width: 0;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
text-align: start;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
}
.listRowTitle:focus-visible {
outline: 2px solid var(--dsw-alias-brand-primary);
outline-offset: 1px;
border-radius: var(--ds-sidebar-radius);
}
.listRowSubtitle {
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxxs-11);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.listRowMeta {
display: inline-flex;
align-items: center;
flex: none;
gap: var(--ds-sidebar-space-2);
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxxs-11);
font-variant-numeric: tabular-nums;
}
/* Row actions stay out of the way until the row is touched, but a coarse
pointer has no hover: there they are always present. */
.listRowActions {
display: inline-flex;
align-items: center;
flex: none;
gap: 2px;
opacity: 0;
}
.listRow:hover .listRowActions,
.listRow:focus-within .listRowActions,
.listRow[data-selected='true'] .listRowActions {
opacity: 1;
}
@media (pointer: coarse) {
.listRow { min-height: 44px; }
.listRowActions { opacity: 1; }
}
/* ── EmptyState ─────────────────────────────────────────────────────────── */
.empty {
box-sizing: border-box;
display: flex;
flex-direction: column;
align-items: center;
gap: var(--ds-sidebar-space-2);
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxs-12);
text-align: center;
}
.emptyPage { padding: var(--ds-sidebar-gutter); }
.emptyWell { padding: var(--ds-sidebar-space-2) var(--ds-sidebar-space-3) var(--ds-sidebar-space-3); }
.emptyIcon {
display: inline-flex;
color: var(--dsw-alias-label-tertiary);
}
.emptyTitle { color: var(--dsw-alias-label-secondary); }
.emptyDescription {
max-width: 34em;
overflow-wrap: anywhere;
}
.emptyActions {
display: inline-flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: var(--ds-sidebar-space-2);
margin-top: var(--ds-sidebar-space-1);
}
/* ── ErrorBlock ─────────────────────────────────────────────────────────── */
.errorBlock {
box-sizing: border-box;
display: flex;
align-items: flex-start;
gap: var(--ds-sidebar-space-2);
min-width: 0;
padding: var(--ds-sidebar-space-2) var(--ds-sidebar-space-3);
color: var(--dsw-alias-state-error-primary);
font: var(--dsw-font-xxs-12);
}
.errorBody {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
flex: 1 1 auto;
}
.errorMessage { overflow-wrap: anywhere; }
.errorDetail {
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxxs-11);
overflow-wrap: anywhere;
}
.errorAction { flex: none; }
/* ── Field ──────────────────────────────────────────────────────────────── */
.field {
display: flex;
flex-direction: column;
gap: var(--ds-sidebar-space-1);
min-width: 0;
padding: var(--ds-sidebar-space-2) 0;
}
.fieldLabel {
color: var(--dsw-alias-label-secondary);
font: var(--dsw-font-xxxs-strong-11);
}
.fieldDescription {
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxxs-11);
overflow-wrap: anywhere;
}
.fieldError {
color: var(--dsw-alias-state-error-primary);
font: var(--dsw-font-xxxs-11);
overflow-wrap: anywhere;
}
.fieldInline {
flex-direction: row;
align-items: center;
gap: var(--ds-sidebar-space-3);
}
.fieldInline .fieldControl { flex: 1 1 auto; min-width: 0; }
.fieldControl { min-width: 0; }
/* ── ChoiceCard ─────────────────────────────────────────────────────────── */
.choiceGrid {
display: flex;
flex-direction: column;
gap: var(--ds-sidebar-space-1);
min-width: 0;
}
.choice {
box-sizing: border-box;
position: relative;
display: flex;
align-items: flex-start;
gap: var(--ds-sidebar-space-2);
min-width: 0;
padding: var(--ds-sidebar-space-2);
border: 1px solid var(--dsw-alias-border-l2);
border-radius: var(--ds-sidebar-radius);
color: var(--dsw-alias-label-primary);
font: var(--dsw-font-xxs-12);
cursor: pointer;
}
.choice:hover { background: var(--dsw-alias-interactive-bg-hover); }
/* Selected is a border + tint, never a fill block: one accent surface per
screen is the budget, and the choice list lives beside other content. */
.choice:has(.choiceInput:checked) {
border-color: var(--dsw-alias-state-business-primary);
background: var(--dsw-alias-interactive-bg-hover-accent);
}
.choice:has(.choiceInput:focus-visible) {
outline: 2px solid var(--dsw-alias-brand-primary);
outline-offset: 1px;
}
.choice:has(.choiceInput:disabled) {
opacity: 0.5;
cursor: default;
}
/* The native control keeps form semantics and keyboard behavior; only its
picture is replaced. */
.choiceInput {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: inherit;
}
.choiceMark {
display: inline-flex;
align-items: center;
justify-content: center;
flex: none;
width: 14px;
height: 14px;
margin-top: 3px;
box-sizing: border-box;
border: 1px solid var(--dsw-alias-border-l3);
border-radius: 50%;
color: var(--dsw-alias-label-primary-foreground);
}
.choice[data-type='checkbox'] .choiceMark { border-radius: 3px; }
.choice:has(.choiceInput:checked) .choiceMark {
border-color: var(--dsw-alias-state-business-primary);
background: var(--dsw-alias-state-business-primary);
}
.choiceMarkGlyph { visibility: hidden; }
.choice:has(.choiceInput:checked) .choiceMarkGlyph { visibility: visible; }
.choiceBody {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
flex: 1 1 auto;
}
.choiceTitle { min-width: 0; overflow-wrap: anywhere; }
.choiceMeta {
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxxs-11);
overflow-wrap: anywhere;
}
.choiceIcon {
display: inline-flex;
flex: none;
color: var(--dsw-alias-label-tertiary);
}
@media (pointer: coarse) {
.choice { min-height: 44px; }
}
/* ── StatusLine ─────────────────────────────────────────────────────────── */
.statusLine {
box-sizing: border-box;
display: flex;
align-items: center;
gap: var(--ds-sidebar-space-2);
min-width: 0;
min-height: 24px;
padding: 0 var(--ds-sidebar-space-3);
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxxs-11);
font-variant-numeric: tabular-nums;
}
.statusLine[data-tone='error'] { color: var(--dsw-alias-state-error-primary); }
.statusLine[data-tone='warn'] { color: var(--dsw-alias-state-warn-primary); }
.statusLine[data-tone='success'] { color: var(--dsw-alias-state-success-primary); }
.statusLine[data-tone='business'] { color: var(--dsw-alias-state-business-primary); }
.statusLineIcon {
display: inline-flex;
flex: none;
}
.statusLineText {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.statusLineMeta { flex: none; }
.statusLineAction {
margin-left: auto;
display: inline-flex;
align-items: center;
flex: none;
}
.statusLinePlain { padding: 0; }
/* ── ActionFooter ───────────────────────────────────────────────────────── */
.actionFooter {
box-sizing: border-box;
display: flex;
align-items: center;
gap: var(--ds-sidebar-space-2);
min-height: var(--ds-sidebar-control-height);
padding: var(--ds-sidebar-space-2) var(--ds-sidebar-space-3);
border-top: 1px solid var(--dsw-alias-border-l1);
color: var(--dsw-alias-label-tertiary);
font: var(--dsw-font-xxxs-11);
}
.actionFooterEnd {
display: inline-flex;
align-items: center;
gap: var(--ds-sidebar-space-2);
margin-left: auto;
}
@media (pointer: coarse) {
.actionFooter { min-height: 44px; }
}
+384
View File
@@ -0,0 +1,384 @@
/**
* Shared page SHAPES — the second half of the global kit.
*
* `kit.tsx` owns the atoms (a button, a badge, a state line). This module owns
* the shapes every page kept rebuilding: a key-value fact, a list row, an empty
* page, an error with its retry, a labelled field, a mutually-exclusive choice,
* a status line and an action footer.
*
* Why it exists (measured before the rewrite): the clue surface alone carried
* 31 copies of the fact row, 14 list-row shells, 10 empty states, 14 error+
* retry blocks, 15 stacked fields, 6 choice groups, 11 status footers and 9
* action bars — 968 lines of CSS in 10 near-identical families, already drifted
* apart (four spellings of the retry row, three different "selected" pictures).
* A page that needs one of these shapes now passes props instead of re-cutting
* the picture.
*
* Rules these components keep, so callers do not have to think about them:
* - ONE border language (1px solid), flat fills only, no shadow, no gradient;
* - a default/resting state is NOT styled (a healthy row is quiet), so a page
* never repaints every row to say "fine";
* - keyboard operation is native: a navigating title is a real `<button>`, a
* choice is a real `<input>`, a status action is a real button;
* - a coarse pointer gets 44px targets;
* - every number is tabular.
*
* Skin contract: every paint resolves to a `--dsw-*` / `--ds-*` token
* (`tests/theme.spec.ts` scans `patterns.module.css`).
*/
import type { CSSProperties, ReactNode } from 'react'
import clsx from 'clsx'
import { ActionButton } from './kit.tsx'
import css from './patterns.module.css'
/** `data-*` passthrough used by every component here (e2e stable locators). */
type DataAttributes = { readonly [key: `data-${string}`]: string | number | boolean | undefined }
/** Ink rung of one fact / status; absent means the neutral secondary ink. */
export type PatternTone = 'error' | 'warn' | 'success' | 'business'
/** One row of a {@link FactList}. */
export interface Fact {
/** Stable React key and the row's data attribute. */
readonly key: string
/** Localized label; omitted renders the value alone (a bare fact). */
readonly label?: string
readonly value: ReactNode
/** Monospace + tabular figures: ids, paths, hashes, model names. */
readonly mono?: boolean
readonly tone?: PatternTone
}
/** Props of {@link FactRow}. */
export interface FactRowProps {
readonly label?: string
readonly value: ReactNode
readonly mono?: boolean
readonly tone?: PatternTone
readonly className?: string
}
/**
* One key-value fact: the label in the quiet rung, the value in the primary one.
*
* Deliberately not a `<dl>`: these rows are rendered inside lists, headers and
* definition tables whose markup the caller owns, and a nested definition list
* would fight the surrounding semantics. The label/value pair is readable in
* order either way.
*/
export function FactRow({ label, value, mono, tone, className }: FactRowProps): ReactNode {
return (
<div className={clsx(css.factRow, className)} {...(tone === undefined ? {} : { 'data-tone': tone })}>
{label !== undefined && <span className={css.factLabel}>{label}</span>}
<span className={clsx(css.factValue, mono === true && css.mono)}>{value}</span>
</div>
)
}
/** Props of {@link FactList}. */
export interface FactListProps {
readonly facts: readonly Fact[]
readonly className?: string
/** Accessible name of the group; the caller owns the localized string. */
readonly label?: string
}
/** A stack of {@link FactRow}s, skipping nothing and inventing nothing. */
export function FactList({ facts, className, label }: FactListProps): ReactNode {
if (facts.length === 0) return null
return (
<div className={clsx(css.factList, className)} {...(label === undefined ? {} : { role: 'group', 'aria-label': label })}>
{facts.map(fact => (
<FactRow
key={fact.key}
label={fact.label}
value={fact.value}
mono={fact.mono}
tone={fact.tone}
/>
))}
</div>
)
}
/** Props of {@link ListRow}. */
export interface ListRowProps extends DataAttributes {
/** Glyph or status dot at the leading edge. */
readonly leading?: ReactNode
readonly title: ReactNode
/** Secondary line under the title (a subtitle, not a second fact column). */
readonly subtitle?: ReactNode
/** Facts at the trailing edge, before the actions. */
readonly meta?: ReactNode
/** Row actions; hidden until the row is hovered or focused. */
readonly actions?: ReactNode
/**
* `button` makes the title the row's single navigation target — the shape a
* browse result uses. `plain` (default) leaves the title as text, for a row
* whose whole surface is a click target of the caller's own control.
*/
readonly titleAs?: 'plain' | 'button'
readonly onTitleClick?: () => void
readonly selected?: boolean
/** A row that exists but is not actionable yet (unresolved reference). */
readonly dimmed?: boolean
readonly onContextMenu?: (event: React.MouseEvent) => void
/** Roving tabindex: only one row of a list is in the tab order. */
readonly primaryTabIndex?: boolean
readonly className?: string
}
/**
* The one list-row shell: leading glyph, title (optionally a real button),
* subtitle, trailing facts, hover-revealed actions.
*
* Selected and dimmed are the only two visual states; everything else is the
* untouched surface, because a list of 25 rows must not repaint itself.
*/
export function ListRow(props: ListRowProps): ReactNode {
const {
leading, title, subtitle, meta, actions, titleAs = 'plain', onTitleClick,
selected, dimmed, onContextMenu, primaryTabIndex, className, ...dataProps
} = props
return (
<div
{...dataProps}
className={clsx(css.listRow, className)}
{...(selected === true ? { 'data-selected': 'true' } : {})}
{...(dimmed === true ? { 'data-dimmed': 'true' } : {})}
onContextMenu={onContextMenu}
>
{leading !== undefined && <span className={css.listRowLeading}>{leading}</span>}
<span className={css.listRowMain}>
{titleAs === 'button'
? (
<button
type="button"
className={css.listRowTitle}
tabIndex={primaryTabIndex === false ? -1 : undefined}
onClick={onTitleClick}
>{title}</button>
)
: <span className={css.listRowTitle} style={TITLE_TEXT as CSSProperties}>{title}</span>}
{subtitle !== undefined && <span className={css.listRowSubtitle}>{subtitle}</span>}
</span>
{meta !== undefined && <span className={css.listRowMeta}>{meta}</span>}
{actions !== undefined && <span className={css.listRowActions}>{actions}</span>}
</div>
)
}
/** A text title must not inherit the button's pointer cursor. */
const TITLE_TEXT = { cursor: 'inherit' } as const
/** Props of {@link EmptyState}. */
export interface EmptyStateProps {
readonly icon?: ReactNode
readonly title: ReactNode
readonly description?: ReactNode
readonly actions?: ReactNode
/** `page` centres in a whole pane; `well` is the compact block inside a list. */
readonly tone?: 'page' | 'well'
readonly className?: string
}
/** The one empty state: glyph, one-line title, optional description, actions. */
export function EmptyState({ icon, title, description, actions, tone = 'well', className }: EmptyStateProps): ReactNode {
return (
<div className={clsx(css.empty, tone === 'page' ? css.emptyPage : css.emptyWell, className)}>
{icon !== undefined && <span className={css.emptyIcon}>{icon}</span>}
<span className={css.emptyTitle}>{title}</span>
{description !== undefined && <span className={css.emptyDescription}>{description}</span>}
{actions !== undefined && <span className={css.emptyActions}>{actions}</span>}
</div>
)
}
/** Props of {@link ErrorBlock}. */
export interface ErrorBlockProps {
readonly message: ReactNode
/** A sanitized second line (a reason code, a dependency id) — never a secret. */
readonly detail?: ReactNode
readonly retryLabel?: string
readonly onRetry?: () => void
/** A retry already in flight: the button stays, disabled, and says so. */
readonly busy?: boolean
readonly className?: string
}
/**
* Error + its retry, as ONE block.
*
* The retry belongs to the message: separated, a reader can miss which line it
* belongs to, and the four hand-written spellings this replaces had already
* drifted in exactly that way (two put the button above, two below).
*/
export function ErrorBlock({ message, detail, retryLabel, onRetry, busy, className }: ErrorBlockProps): ReactNode {
return (
<div className={clsx(css.errorBlock, className)} role="alert">
<span className={css.errorBody}>
<span className={css.errorMessage}>{message}</span>
{detail !== undefined && <span className={css.errorDetail}>{detail}</span>}
</span>
{onRetry !== undefined && retryLabel !== undefined && (
<span className={css.errorAction}>
{/* The kit's own action recipe: a retry is a button, not a fifth
spelling of one. */}
<ActionButton size="sm" busy={busy === true} onClick={onRetry}>{retryLabel}</ActionButton>
</span>
)}
</div>
)
}
/** Props of {@link Field}. */
export interface FieldProps {
readonly label: ReactNode
readonly description?: ReactNode
readonly error?: ReactNode
readonly htmlFor?: string
/** `stacked` (default) puts the label above; `inline` puts it beside. */
readonly layout?: 'stacked' | 'inline'
readonly children: ReactNode
readonly className?: string
}
/**
* A labelled control with its description and its error.
*
* Replaces the 15 stacked label+control blocks that each re-declared the same
* three typographic rungs. The label is a real `<label>` when `htmlFor` is
* given, so clicking it focuses the control.
*/
export function Field({ label, description, error, htmlFor, layout = 'stacked', children, className }: FieldProps): ReactNode {
return (
<div className={clsx(css.field, layout === 'inline' && css.fieldInline, className)}>
{htmlFor === undefined
? <span className={css.fieldLabel}>{label}</span>
: <label className={css.fieldLabel} htmlFor={htmlFor}>{label}</label>}
<div className={css.fieldControl}>{children}</div>
{description !== undefined && <span className={css.fieldDescription}>{description}</span>}
{error !== undefined && <span className={css.fieldError} role="alert">{error}</span>}
</div>
)
}
/** One option of a {@link ChoiceCard} group. */
export interface ChoiceOption {
readonly value: string
readonly title: ReactNode
readonly meta?: ReactNode
readonly icon?: ReactNode
readonly disabled?: boolean
}
/** Props of {@link ChoiceCard}. */
export interface ChoiceCardProps {
readonly type: 'radio' | 'checkbox'
/** The form field name shared by the group. */
readonly name: string
readonly options: readonly ChoiceOption[]
/** Selected values; a radio group passes at most one. */
readonly selected: readonly string[]
readonly onChange: (value: string, checked: boolean) => void
readonly label?: string
readonly className?: string
}
/**
* Mutually-exclusive (or multiple) choices that need a title AND a line of
* explanation — the shape a plain segmented control cannot carry.
*
* The native `<input>` stays in the DOM: form semantics, keyboard operation,
* screen-reader announcements and `:checked` styling all come for free, and
* only its picture is replaced by {@link ChoiceCard}'s own mark.
*/
export function ChoiceCard({ type, name, options, selected, onChange, label, className }: ChoiceCardProps): ReactNode {
return (
<div className={clsx(css.choiceGrid, className)} role={type === 'radio' ? 'radiogroup' : 'group'}
{...(label === undefined ? {} : { 'aria-label': label })}>
{options.map(option => {
const checked = selected.includes(option.value)
return (
<label className={css.choice} data-type={type} data-value={option.value} key={option.value}>
<input
type={type}
className={css.choiceInput}
name={name}
value={option.value}
checked={checked}
disabled={option.disabled}
onChange={event => { onChange(option.value, event.target.checked) }}
/>
<span className={css.choiceMark} aria-hidden="true">
<svg className={css.choiceMarkGlyph} viewBox="0 0 12 12" width="9" height="9">
{type === 'radio'
? <circle cx="6" cy="6" r="2.5" fill="currentColor" />
: <path d="m2 6 2.5 2.5L10 3.5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />}
</svg>
</span>
{option.icon !== undefined && <span className={css.choiceIcon}>{option.icon}</span>}
<span className={css.choiceBody}>
<span className={css.choiceTitle}>{option.title}</span>
{option.meta !== undefined && <span className={css.choiceMeta}>{option.meta}</span>}
</span>
</label>
)
})}
</div>
)
}
/** Props of {@link StatusLine}. */
export interface StatusLineProps {
readonly text: ReactNode
readonly tone?: PatternTone
readonly icon?: ReactNode
readonly meta?: ReactNode
readonly action?: ReactNode
/** `status` announces changes politely; omit for a purely static footnote. */
readonly role?: 'status'
/** Drop the horizontal padding when the caller's container already has it. */
readonly plain?: boolean
readonly className?: string
}
/** The one footer/status line: text, optional meta, one trailing action. */
export function StatusLine({ text, tone, icon, meta, action, role, plain, className }: StatusLineProps): ReactNode {
return (
<div
className={clsx(css.statusLine, plain === true && css.statusLinePlain, className)}
{...(tone === undefined ? {} : { 'data-tone': tone })}
{...(role === undefined ? {} : { role })}
>
{icon !== undefined && <span className={css.statusLineIcon}>{icon}</span>}
<span className={css.statusLineText} title={typeof text === 'string' ? text : undefined}>{text}</span>
{meta !== undefined && <span className={css.statusLineMeta}>{meta}</span>}
{action !== undefined && <span className={css.statusLineAction}>{action}</span>}
</div>
)
}
/** Props of {@link ActionFooter}. */
export interface ActionFooterProps {
/** Leading content: a count, a hint, the progress copy. */
readonly start?: ReactNode
/** Trailing actions, in reading order. */
readonly end?: ReactNode
readonly className?: string
}
/**
* The stable action row at the bottom of a window or a section.
*
* Its separator is the page's ONE horizontal hairline at that edge, so callers
* pass actions and never re-declare the border.
*/
export function ActionFooter({ start, end, className }: ActionFooterProps): ReactNode {
return (
<div className={clsx(css.actionFooter, className)}>
{start !== undefined && <span>{start}</span>}
{end !== undefined && <span className={css.actionFooterEnd}>{end}</span>}
</div>
)
}
+1
View File
@@ -156,6 +156,7 @@ describe('skin contract: the plugin owns no color of its own', () => {
'src/client/clues/windows/detail.module.css',
'src/client/clues/settings/settings.module.css',
'src/client/ui/workbench-section.module.css',
'src/client/ui/patterns.module.css',
'src/client/ui/loading-indicator.module.css',
'src/client/windows/hosted-window.module.css',
'src/client/windows/windows.module.css',
+302
View File
@@ -0,0 +1,302 @@
/**
* Shared page patterns (`src/client/ui/patterns.tsx`).
*
* These eight components replace ~968 lines of duplicated CSS across 10
* near-identical families in the clue surface, so the contract pinned here is
* deliberately structural rather than cosmetic:
*
* - a DEFAULT state is unstyled (a healthy row, a passing fact and an idle
* status line render no tone), because a 25-row list must not repaint itself;
* - keyboard operation stays native (a navigating title is a `<button>`, a
* choice is a real `<input>`, a retry is a real `<button>`);
* - nothing is filled unless it is a selection, and no component here invents a
* state of its own (an empty list renders the caller's `EmptyState`, never a
* built-in sentence);
* - a coarse pointer gets 44px targets (CSS, asserted by the e2e lane).
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import {
ActionFooter, ChoiceCard, EmptyState, ErrorBlock, FactList, FactRow, Field, ListRow, StatusLine,
} from '../src/client/ui/patterns.tsx'
import { renderRoot, setupReactAct, type RenderedRoot } from './test-utils.ts'
setupReactAct()
let view: RenderedRoot | undefined
afterEach(() => { view?.unmount(); view = undefined; document.body.replaceChildren() })
/** The single element matching one CSS-module class, by its own selector text. */
function byClass(container: HTMLElement, fragment: string): HTMLElement | null {
return container.querySelector<HTMLElement>(`[class*="${fragment}"]`)
}
describe('FactRow / FactList', () => {
it('renders the label in the quiet rung and the value in the primary one', () => {
view = renderRoot(createElement(FactRow, { label: 'Changes', value: '+12 −3' }))
expect(byClass(view.container, 'factLabel')!.textContent).toBe('Changes')
expect(byClass(view.container, 'factValue')!.textContent).toBe('+12 −3')
})
it('omits the label slot for a bare fact', () => {
view = renderRoot(createElement(FactRow, { value: '#42' }))
expect(byClass(view.container, 'factLabel')).toBeNull()
expect(byClass(view.container, 'factValue')!.textContent).toBe('#42')
})
it('carries no tone by default and exactly the requested one otherwise', () => {
view = renderRoot(createElement(FactRow, { label: 'CI', value: 'passing' }))
const row = byClass(view.container, 'factRow')!
expect(row.hasAttribute('data-tone')).toBe(false)
view.rerender(createElement(FactRow, { label: 'CI', value: 'failing', tone: 'error' }))
expect(byClass(view.container, 'factRow')!.dataset.tone).toBe('error')
})
it('gives a mono fact tabular figures through the shared class', () => {
view = renderRoot(createElement(FactRow, { label: 'Hash', value: 'a1b2c3', mono: true }))
expect(byClass(view.container, 'factValue')!.className).toContain('mono')
})
it('renders nothing for an empty list instead of an invented empty line', () => {
view = renderRoot(createElement(FactList, { facts: [] }))
expect(view.container.firstElementChild).toBeNull()
})
it('keeps the caller order and names the group when asked', () => {
view = renderRoot(createElement(FactList, {
label: 'Pull request',
facts: [
{ key: 'number', label: '#', value: '#42' },
{ key: 'author', label: 'Author', value: 'Ada' },
],
}))
const group = view.container.querySelector('[role="group"]')!
expect(group.getAttribute('aria-label')).toBe('Pull request')
expect([...group.children].map(child => child.textContent)).toEqual(['##42', 'AuthorAda'])
})
})
describe('ListRow', () => {
it('renders no selection or dimming state by default', () => {
view = renderRoot(createElement(ListRow, { title: 'Fix the thing' }))
const row = byClass(view.container, 'listRow')!
expect(row.hasAttribute('data-selected')).toBe(false)
expect(row.hasAttribute('data-dimmed')).toBe(false)
})
it('makes the title a real button only when the row navigates', () => {
view = renderRoot(createElement(ListRow, { title: 'Plain row' }))
expect(view.container.querySelector('button')).toBeNull()
const onClick = vi.fn()
view.rerender(createElement(ListRow, { title: 'Nav row', titleAs: 'button', onTitleClick: onClick }))
const button = view.container.querySelector('button')!
expect(button.textContent).toBe('Nav row')
button.click()
expect(onClick).toHaveBeenCalledOnce()
})
it('keeps the roving tabindex contract: one row in the tab order', () => {
view = renderRoot(createElement(ListRow, { title: 'First', titleAs: 'button', primaryTabIndex: true }))
view.rerender(createElement(ListRow, { title: 'First', titleAs: 'button', primaryTabIndex: false }))
expect(view.container.querySelector('button')!.tabIndex).toBe(-1)
})
it('mounts every slot it is given and nothing it is not', () => {
view = renderRoot(createElement(ListRow, {
title: 'Clue title',
leading: createElement('span', { 'data-slot': 'leading' }),
subtitle: 'subtitle copy',
meta: createElement('span', { 'data-slot': 'meta' }, '5 comments'),
actions: createElement('button', { type: 'button', 'data-slot': 'action' }, 'pin'),
selected: true,
}))
expect(view.container.querySelector('[data-slot="leading"]')).not.toBeNull()
expect(view.container.querySelector('[data-slot="meta"]')!.textContent).toBe('5 comments')
expect(view.container.querySelector('[data-slot="action"]')).not.toBeNull()
expect(byClass(view.container, 'listRowSubtitle')!.textContent).toBe('subtitle copy')
expect(byClass(view.container, 'listRow')!.dataset.selected).toBe('true')
})
it('passes data attributes through for a stable e2e locator', () => {
view = renderRoot(createElement(ListRow, { title: 'Row', 'data-clue-result-row': 'clue-1' }))
expect(view.container.querySelector('[data-clue-result-row]')).not.toBeNull()
})
})
describe('EmptyState', () => {
it('renders the title alone when nothing else is known', () => {
view = renderRoot(createElement(EmptyState, { title: 'No clues yet' }))
expect(byClass(view.container, 'emptyTitle')!.textContent).toBe('No clues yet')
expect(byClass(view.container, 'emptyDescription')).toBeNull()
expect(byClass(view.container, 'emptyActions')).toBeNull()
})
it('distinguishes a whole-pane empty state from a block inside a list', () => {
view = renderRoot(createElement(EmptyState, { title: 'Pane', tone: 'page' }))
expect(byClass(view.container, 'empty')!.className).toContain('emptyPage')
view.rerender(createElement(EmptyState, { title: 'Well' }))
expect(byClass(view.container, 'empty')!.className).toContain('emptyWell')
})
})
describe('ErrorBlock', () => {
it('announces the failure and pairs the retry with its own message', () => {
const onRetry = vi.fn()
view = renderRoot(createElement(ErrorBlock, { message: 'Request failed', retryLabel: 'Retry', onRetry }))
expect(view.container.querySelector('[role="alert"]')).not.toBeNull()
expect(byClass(view.container, 'errorMessage')!.textContent).toBe('Request failed')
const retry = view.container.querySelector('button')!
expect(retry.textContent).toBe('Retry')
retry.click()
expect(onRetry).toHaveBeenCalledOnce()
})
it('renders no retry when the caller cannot retry', () => {
view = renderRoot(createElement(ErrorBlock, { message: 'Conflicted' }))
expect(view.container.querySelector('button')).toBeNull()
})
it('locks the retry while one is in flight instead of offering a second', () => {
view = renderRoot(createElement(ErrorBlock, {
message: 'Request failed', retryLabel: 'Retry', onRetry: () => {}, busy: true,
}))
const retry = view.container.querySelector('button')!
expect(retry.disabled).toBe(true)
expect(retry.getAttribute('aria-busy')).toBe('true')
})
it('separates a sanitized detail from the message', () => {
view = renderRoot(createElement(ErrorBlock, { message: 'Request failed', detail: 'github.gh' }))
expect(byClass(view.container, 'errorDetail')!.textContent).toBe('github.gh')
})
})
describe('Field', () => {
it('ties the label to the control through a real label element', () => {
view = renderRoot(createElement(Field, {
label: 'Task name',
htmlFor: 'task-name',
children: createElement('input', { id: 'task-name' }),
}))
const label = view.container.querySelector('label')!
expect(label.getAttribute('for')).toBe('task-name')
expect(label.textContent).toBe('Task name')
})
it('renders the label as text when no control id exists', () => {
view = renderRoot(createElement(Field, { label: 'Group', children: createElement('span', null, 'x') }))
expect(view.container.querySelector('label')).toBeNull()
expect(byClass(view.container, 'fieldLabel')!.textContent).toBe('Group')
})
it('puts the error under the control, in the alert role', () => {
view = renderRoot(createElement(Field, {
label: 'Url', error: 'Not a valid URL', children: createElement('input'),
}))
const error = view.container.querySelector('[role="alert"]')!
expect(error.textContent).toBe('Not a valid URL')
expect(byClass(view.container, 'fieldError')!.textContent).toBe('Not a valid URL')
})
it('switches the label beside the control for an inline field', () => {
view = renderRoot(createElement(Field, { label: 'Name', layout: 'inline', children: createElement('input') }))
expect(byClass(view.container, 'field')!.className).toContain('fieldInline')
})
})
describe('ChoiceCard', () => {
const options = [
{ value: 'snapshot', title: 'Snapshot', meta: 'Copies the content' },
{ value: 'references', title: 'References only', meta: 'Smaller archive' },
]
it('keeps the native input so form and keyboard semantics survive', () => {
view = renderRoot(createElement(ChoiceCard, {
type: 'radio', name: 'mode', options, selected: ['snapshot'], onChange: () => {},
}))
const inputs = view.container.querySelectorAll<HTMLInputElement>('input[type="radio"]')
expect(inputs).toHaveLength(2)
expect(inputs[0]!.checked).toBe(true)
expect(inputs[1]!.checked).toBe(false)
expect(view.container.querySelector('[role="radiogroup"]')).not.toBeNull()
})
it('reports the value and the requested state, never a toggle of its own guess', () => {
const onChange = vi.fn()
view = renderRoot(createElement(ChoiceCard, {
type: 'checkbox', name: 'caps', options, selected: [], onChange,
}))
const input = view.container.querySelectorAll<HTMLInputElement>('input')[1]!
input.click()
expect(onChange).toHaveBeenCalledWith('references', true)
})
it('carries the title and the explanation as two separate rungs', () => {
view = renderRoot(createElement(ChoiceCard, {
type: 'radio', name: 'mode', options, selected: ['snapshot'], onChange: () => {},
}))
const titles = [...view.container.querySelectorAll('[class*="choiceTitle"]')].map(node => node.textContent)
const metas = [...view.container.querySelectorAll('[class*="choiceMeta"]')].map(node => node.textContent)
expect(titles).toEqual(['Snapshot', 'References only'])
expect(metas).toEqual(['Copies the content', 'Smaller archive'])
})
it('keeps the explanation slot empty when the option has none', () => {
view = renderRoot(createElement(ChoiceCard, {
type: 'radio', name: 'x', options: [{ value: 'a', title: 'A' }], selected: [], onChange: () => {},
}))
expect(view.container.querySelector('[class*="choiceMeta"]')).toBeNull()
})
it('refuses a disabled option without hiding it', () => {
view = renderRoot(createElement(ChoiceCard, {
type: 'checkbox', name: 'cap', options: [{ value: 'a', title: 'A', disabled: true }], selected: [], onChange: () => {},
}))
expect(view.container.querySelector<HTMLInputElement>('input')!.disabled).toBe(true)
expect(byClass(view.container, 'choiceTitle')!.textContent).toBe('A')
})
})
describe('StatusLine', () => {
it('carries no tone by default', () => {
view = renderRoot(createElement(StatusLine, { text: '3 selected' }))
expect(byClass(view.container, 'statusLine')!.hasAttribute('data-tone')).toBe(false)
expect(byClass(view.container, 'statusLineText')!.textContent).toBe('3 selected')
})
it('announces a live status only when the caller asks for it', () => {
view = renderRoot(createElement(StatusLine, { text: 'Importing…' }))
expect(view.container.querySelector('[role="status"]')).toBeNull()
view.rerender(createElement(StatusLine, { text: 'Importing…', role: 'status' }))
expect(view.container.querySelector('[role="status"]')).not.toBeNull()
})
it('separates the trailing action from the text', () => {
view = renderRoot(createElement(StatusLine, {
text: 'Failed', tone: 'error',
action: createElement('button', { type: 'button', 'data-slot': 'retry' }, 'Retry'),
}))
expect(byClass(view.container, 'statusLine')!.dataset.tone).toBe('error')
expect(view.container.querySelector('[data-slot="retry"]')).not.toBeNull()
})
})
describe('ActionFooter', () => {
it('renders only the seats the caller fills', () => {
view = renderRoot(createElement(ActionFooter, {}))
expect(view.container.firstElementChild!.children).toHaveLength(0)
})
it('keeps the leading fact and the trailing actions apart', () => {
view = renderRoot(createElement(ActionFooter, {
start: '2 of 12 selected',
end: createElement('button', { type: 'button', 'data-slot': 'save' }, 'Save'),
}))
const footer = view.container.firstElementChild!
expect(footer.firstElementChild!.textContent).toBe('2 of 12 selected')
expect(footer.querySelector('[data-slot="save"]')).not.toBeNull()
expect(footer.querySelector('[class*="actionFooterEnd"]')).not.toBeNull()
})
})