wrolpi/app/src/components/ui/Feedback.tsx
Roland 4341350c40
ui: semantic roles, so night and amber can tell severity apart at all
A component now asks for what a colour MEANS -- `danger` -- and the theme
decides how that looks.  Five roles: neutral, info, success, warning, danger.

The names are the ones already in the tree.  `--primary/--success/--warning/
--danger` were declared in tokens.css with ZERO consumers, and `MessageKind`
was already `info|success|warning|error`; this is one vocabulary instead of
three.  `error` stays a valid kind because 26 call sites write it, and `danger`
is the same thing under the token's name for new code.

The token set is the easy half.  Light and dark spend a hue per role.  Night is
red and nothing else and amber is amber and nothing else, and there a role has
to be a step on a BRIGHTNESS ramp -- which is why this was worth doing:

  night  --orange is byte-identical to --text
         --yellow is byte-identical to --amber
  amber  the same collisions, one hue over

A call site picking between hue names in those themes is picking between
synonyms.  That is why all four toast kinds were the same pixel in night, and
why an error and an informational message were indistinguishable.

Both ramps are built rather than copied: every role clears 3:1 on the panel
(neutral is allowed lower -- for pending and disabled, dim IS the signal),
severity is strictly increasing in contrast, and danger reaches that theme's
own --text brightness so the loudest role is never quieter than prose.  Amber
needed its own scale, not night's: its --text is 8.6:1 where night's is 5.0:1,
so night's ramp would have left every role dimmer than ordinary text.

Fixes in passing: night's info was 2.29:1, under the 3:1 floor.  And Status
loses its three `html[data-theme="night"]` overrides entirely -- it was the one
component already encoding severity by brightness by hand, and the roles are
that generalised.

Roles are registered as Mantine colors too, so `color='danger'` works anywhere
`color='red'` does.

`isMonochromeTheme` is a new predicate in themes/names.  It is the same set as
`explicitOnlyThemes` today and deliberately separate: one is about how a theme
is chosen, the other about what a theme has to work with.

Scope: tokens plus the library.  The ~24 app-level `color='...'` call sites are
a follow-up -- they need a judgement per site, and two of them already disagree
(Downloads.js colours the same "Download error" label `orange` on one line and
`red` on another).  The 22 `violet` uses are not semantic at all and stay hues.

Tests: the ramp claims are asserted per theme in a browser, and the ordering
and danger-vs-text claims run ONLY for the monochrome themes -- in light, blue
is darker than green on white, so a brightness ramp there would fail a design
that is perfectly fine.  Every guard checked red against a planted regression,
including the original bug (warning and danger collapsed to one value in night)
and night's info back at its old 2.29:1.

The roles were folded into each theme's own block rather than kept in a
standalone one, so the existing "same tokens in every theme" and "only red hues
in night" guards cover them for free.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 18:05:46 -06:00

236 lines
8.6 KiB
TypeScript

import React from 'react';
import {Loader as MLoader, Skeleton} from '@mantine/core';
import {Icon} from './Icon';
import {RoleName, SemanticColorName} from '../../themes/mantine';
/*
* Feedback: messages, labels, progress, status text, loaders.
*
* These carry the design rules that change form (not just color) between
* themes, so their markup is ours and their values come from tokens.
*/
// ------------------------------------------------------------------ Messages
/*
* `error` is the original spelling and stays: 26 call sites use it, and renaming those
* is app-level churn for no behaviour change. `danger` is the same thing under the
* name the token uses, and is what new code should write.
*/
export type MessageKind = 'info' | 'success' | 'warning' | 'error' | 'danger';
/** The role each kind means. Never a hue -- see the note on roles in tokens.css. */
const messageRoles: Record<MessageKind, RoleName> = {
info: 'info',
success: 'success',
warning: 'warning',
error: 'danger',
danger: 'danger',
};
export interface MessageProps {
kind?: MessageKind;
title?: React.ReactNode;
children?: React.ReactNode;
/** Semantic icon name or a Tabler component, shown to the left of the text. */
icon?: string | React.ComponentType<any>;
/** Renders a dismiss button. Omit for messages the user cannot clear. */
onDismiss?: () => void;
className?: string;
}
export function Message({kind = 'info', title, children, icon, onDismiss, className}: MessageProps) {
return <div
// Errors and warnings interrupt; info and success are announced politely.
role={messageRoles[kind] === 'danger' ? 'alert' : 'status'}
className={['wrolpi-message', messageRoles[kind] === 'danger' ? 'wrolpi-message-error' : '', className]
.filter(Boolean).join(' ')}
style={{['--message-color' as string]: `var(--${messageRoles[kind]})`}}
>
{icon && <div className='wrolpi-message-icon'>
{typeof icon === 'string' ? <Icon name={icon} size={20}/> : <Icon component={icon} size={20}/>}
</div>}
<div className='wrolpi-message-content'>
{title && <div className='wrolpi-message-title'>{title}</div>}
{children && <div className='wrolpi-message-body'>{children}</div>}
</div>
{onDismiss && <button
type='button'
className='wrolpi-message-dismiss'
aria-label='Dismiss'
onClick={onDismiss}
>
<Icon name='close' size={16}/>
</button>}
</div>
}
// -------------------------------------------------------------------- Labels
export interface LabelProps {
color?: SemanticColorName | RoleName | 'black' | 'white';
icon?: string | React.ComponentType<any>;
/**
* Draw it as a physical tag — pointed left edge and an eyelet — rather than a plain
* chip. Reserved for things that actually are tags: the same component also carries
* the count badges in the Tags table, and a point on a number reads as an arrow.
*/
tag?: boolean;
children?: React.ReactNode;
onClick?: React.MouseEventHandler<HTMLSpanElement>;
className?: string;
}
/** A chip. Filled in light, dark and amber; an outline in night, where a filled
* patch would be a bright surface. */
export function Label({color = 'grey', icon, tag, children, onClick, className}: LabelProps) {
return <span
className={['wrolpi-label', `wrolpi-label-${color}`, tag ? 'wrolpi-tag' : '', className]
.filter(Boolean).join(' ')}
style={{['--label-color' as string]: `var(--${color})`, cursor: onClick ? 'pointer' : undefined}}
onClick={onClick}
>
{icon && (typeof icon === 'string' ? <Icon name={icon} size={14}/> : <Icon component={icon} size={14}/>)}
{children}
</span>
}
// ------------------------------------------------------------------ Progress
export interface ProgressProps {
/** 0-100. Values outside the range are clamped. */
percent?: number;
/**
* Work is happening but its size is unknown — an upload that has not reported yet.
* Animates instead of sitting at 0%, which otherwise reads as stalled.
*/
indeterminate?: boolean;
/** Show the percentage inside the bar. */
showPercent?: boolean;
color?: SemanticColorName | RoleName;
/** Replaces the percentage with arbitrary text (e.g. "2.1 GB / 5.3 GB"). */
label?: React.ReactNode;
className?: string;
}
export function Progress({
percent = 0, showPercent = true, color = 'blue', label, indeterminate, className,
}: ProgressProps) {
const clamped = Math.min(100, Math.max(0, Number.isFinite(percent) ? percent : 0));
return <div
className={['wrolpi-progress', indeterminate ? 'wrolpi-progress-indeterminate' : '', className]
.filter(Boolean).join(' ')}
role='progressbar'
// An indeterminate bar reports no value, which is what tells assistive tech the
// amount is unknown rather than zero.
aria-valuenow={indeterminate ? undefined : Math.round(clamped)}
aria-valuemin={0}
aria-valuemax={100}
>
<div
className='wrolpi-progress-fill'
style={{
width: indeterminate ? undefined : `${clamped}%`,
['--progress-color' as string]: `var(--${color})`,
}}
/>
{(showPercent || label) && <span className='wrolpi-progress-text'>
{label ?? `${Math.round(clamped)}%`}
</span>}
</div>
}
// -------------------------------------------------------------------- Status
export type StatusKind = 'complete' | 'active' | 'pending' | 'failed';
/*
* Status was the one component already doing this correctly: it had per-theme overrides
* in ui.css because night has no hues to distinguish four states with. Those are gone --
* the roles carry the brightness ramp now, so this table is the whole of it and every
* theme is served by the same rule.
*/
const statusRoles: Record<StatusKind, RoleName> = {
complete: 'success',
active: 'info',
pending: 'neutral',
failed: 'danger',
};
const statusIcons: Record<StatusKind, string> = {
complete: 'check',
active: 'circle notch',
pending: 'circle',
failed: 'x',
};
export interface StatusProps {
kind: StatusKind;
children?: React.ReactNode;
/** Hide the leading icon. */
plain?: boolean;
}
/**
* Status text. Encoded by hue in light and dark; night mode has no hue to
* spend, so brightness carries it (see ui.css). Callers name the state, never
* the color.
*/
export function Status({kind, children, plain}: StatusProps) {
return <span
className={`wrolpi-status wrolpi-status-${kind}`}
style={{['--status-color' as string]: `var(--${statusRoles[kind]})`}}
>
{!plain && <Icon name={statusIcons[kind]} size={14} loading={kind === 'active'}/>}
{children}
</span>
}
// ------------------------------------------------------------------- Loaders
export interface LoaderProps {
size?: number | 'xs' | 'sm' | 'md' | 'lg' | 'xl';
label?: string;
}
export function Loader({size = 'sm', label}: LoaderProps) {
return <MLoader size={size} color='var(--blue)' aria-label={label ?? 'Loading'}/>
}
export interface LoadingProps {
/** What is being waited on: "Loading backups…". Also the accessible name. */
children?: React.ReactNode;
size?: LoaderProps['size'];
/** Vertical padding around the loader. */
padding?: number | string;
}
/**
* A centered loader with a caption, for a region that has nothing to show yet.
* Replaces Semantic's `<Loader active inline='centered'>`, which 19 call sites
* used with their own wrapper div.
*/
export function Loading({children, size = 'sm', padding = '2em'}: LoadingProps) {
return <div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, padding,
}}>
<Loader size={size} label={typeof children === 'string' ? children : undefined}/>
{children && <div style={{fontSize: 13, color: 'var(--muted)'}}>{children}</div>}
</div>
}
/** Placeholder for content that has not arrived. Replaces Semantic's Placeholder. */
export function Placeholder({lines = 3, height = 12}: {lines?: number; height?: number}) {
return <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
{Array.from({length: lines}, (_, index) => <Skeleton
key={index}
height={height}
// A ragged last line reads as text rather than a block.
width={index === lines - 1 ? '60%' : '100%'}
radius={0}
animate
/>)}
</div>
}
export {Skeleton};