feat(ui): @xenia/ui design tokens, Tailwind preset and base components
Platform-v2 step 2.3 (APPS_PLATFORM D-15 §9): - tokens.css: --x- prefixed colours (light/dark/system + 5 venue accent themes), spacing, radius, type scale, shadows, motion, z-index; variables only - components.css: .x-* classes only, no element selectors (new rule CS-16) - Button, IconButton, Dialog, Sheet, Toast, PinPad, InfoTip, EmptyState, Spinner, Field/Input/Textarea/Select, Switch (accessible: focus trap and restore, ARIA wiring, 44px targets) - tailwind-preset.js (adds names only); manager uses it + styles.css, the waiter imports tokens.css; existing screens unchanged - dev-only /ui-gallery in the manager; e2e suite tests/e2e/ui.mjs; unit tests for PIN rules and WCAG AA contrast of every token pair, both in run-all Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import { cx } from '../internal/cx.js'
|
||||
import { Spinner } from './Spinner.jsx'
|
||||
|
||||
/**
|
||||
* variant: 'primary' | 'secondary' | 'ghost' | 'danger'
|
||||
* size: 'sm' (36px) | 'md' (44px, the touch minimum) | 'lg' (52px)
|
||||
* loading: shows a spinner, disables the button and sets aria-busy
|
||||
* icon / iconEnd: an element (e.g. a lucide icon) before / after the label
|
||||
*/
|
||||
export function Button({
|
||||
variant = 'primary', size = 'md', loading = false, block = false,
|
||||
icon, iconEnd, type = 'button', disabled, className, children, ref, ...rest
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
type={type}
|
||||
className={cx('x-btn', `x-btn--${variant}`, `x-btn--${size}`, block && 'x-btn--block', className)}
|
||||
disabled={disabled || loading}
|
||||
aria-busy={loading || undefined}
|
||||
{...rest}
|
||||
>
|
||||
{loading ? <Spinner size="sm" label={null} /> : icon}
|
||||
{children != null && children !== false && <span className="x-btn__label">{children}</span>}
|
||||
{iconEnd}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** A square button with only an icon. `label` is required: it becomes aria-label and the tooltip. */
|
||||
export function IconButton({
|
||||
label, variant = 'ghost', size = 'md', type = 'button', className, children, ref, ...rest
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
type={type}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={cx('x-btn', 'x-btn--icon', `x-btn--${variant}`, `x-btn--${size}`, className)}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { cx } from '../internal/cx.js'
|
||||
import { ModalFrame } from '../internal/ModalFrame.jsx'
|
||||
|
||||
/**
|
||||
* Centered modal dialog.
|
||||
*
|
||||
* <Dialog open={open} onClose={() => setOpen(false)} title="Delete product?"
|
||||
* footer={<><Button variant="secondary" onClick={close}>Cancel</Button>
|
||||
* <Button variant="danger" onClick={remove}>Delete</Button></>}>
|
||||
* This can't be undone.
|
||||
* </Dialog>
|
||||
*
|
||||
* Escape, the backdrop and the × close it; focus moves in, is trapped, and returns
|
||||
* to where it was. dismissible={false} for steps that must be finished (no ×, no Escape).
|
||||
* size: 'sm' (400px) | 'md' (520px) | 'lg' (720px). closeLabel: the × text (translate it).
|
||||
* initialFocus: a ref to focus first (default: the first field or button in the body).
|
||||
*/
|
||||
export function Dialog({ size = 'md', className, ...props }) {
|
||||
return <ModalFrame {...props} panelClass={cx('x-dialog', `x-dialog--${size}`, className)} />
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { cx } from '../internal/cx.js'
|
||||
|
||||
/**
|
||||
* What a list or page shows when there's nothing in it yet.
|
||||
* <EmptyState icon={<Inbox />} title="No online orders yet"
|
||||
* description="New orders from the QR menu appear here." action={<Button>Open menu settings</Button>} />
|
||||
* compact: less padding, for use inside cards.
|
||||
*/
|
||||
export function EmptyState({ icon, title, description, action, compact = false, className }) {
|
||||
return (
|
||||
<div className={cx('x-empty', compact && 'x-empty--compact', className)}>
|
||||
{icon && <div className="x-empty__icon" aria-hidden="true">{icon}</div>}
|
||||
{title && <div className="x-empty__title">{title}</div>}
|
||||
{description && <div className="x-empty__description">{description}</div>}
|
||||
{action && <div className="x-empty__action">{action}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Children, cloneElement, isValidElement, useId } from 'react'
|
||||
import { cx } from '../internal/cx.js'
|
||||
|
||||
/**
|
||||
* Label + control + hint/error, wired for screen readers (id, aria-describedby,
|
||||
* aria-invalid, required). Wrap exactly one control:
|
||||
*
|
||||
* <Field label="Name" hint="Shown on tickets" error={errors.name} required>
|
||||
* <Input value={name} onChange={e => setName(e.target.value)} />
|
||||
* </Field>
|
||||
*
|
||||
* info: optional element placed after the label, usually an <InfoTip>.
|
||||
*/
|
||||
export function Field({ label, hint, error, required = false, info, id, className, children }) {
|
||||
const auto = useId()
|
||||
const controlId = id || auto
|
||||
const hintId = `${controlId}-hint`
|
||||
const errorId = `${controlId}-error`
|
||||
// The error replaces the hint while there is one
|
||||
const describedBy = error ? errorId : hint ? hintId : undefined
|
||||
|
||||
const only = Children.only(children)
|
||||
const control = isValidElement(only)
|
||||
? cloneElement(only, {
|
||||
id: only.props.id || controlId,
|
||||
'aria-describedby': cx(only.props['aria-describedby'], describedBy) || undefined,
|
||||
'aria-invalid': error ? true : only.props['aria-invalid'],
|
||||
required: required || only.props.required,
|
||||
})
|
||||
: only
|
||||
|
||||
return (
|
||||
<div className={cx('x-field', error && 'x-field--error', className)}>
|
||||
{label && (
|
||||
<div className="x-field__label-row">
|
||||
<label className="x-field__label" htmlFor={controlId}>
|
||||
{label}{required && <span className="x-field__required" aria-hidden="true"> *</span>}
|
||||
</label>
|
||||
{info}
|
||||
</div>
|
||||
)}
|
||||
{control}
|
||||
{error
|
||||
? <div id={errorId} className="x-field__error">{error}</div>
|
||||
: hint && <div id={hintId} className="x-field__hint">{hint}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Text input styled with the tokens. All <input> props pass through; size: 'sm' | 'md' | 'lg'. */
|
||||
export function Input({ size = 'md', className, ref, ...rest }) {
|
||||
return <input ref={ref} className={cx('x-input', `x-input--${size}`, className)} {...rest} />
|
||||
}
|
||||
|
||||
/** Multi-line text input. */
|
||||
export function Textarea({ className, rows = 3, ref, ...rest }) {
|
||||
return <textarea ref={ref} rows={rows} className={cx('x-input', 'x-textarea', className)} {...rest} />
|
||||
}
|
||||
|
||||
/**
|
||||
* Native <select> (best on phones and with screen readers), styled.
|
||||
* <Select value={v} onChange={e => setV(e.target.value)} options={[{ value: 'el', label: 'Ελληνικά' }]} />
|
||||
* or pass <option> children. placeholder adds a first, disabled, empty option.
|
||||
*/
|
||||
export function Select({ options, placeholder, size = 'md', className, children, ref, ...rest }) {
|
||||
return (
|
||||
<span className={cx('x-select', `x-select--${size}`, className)}>
|
||||
<select ref={ref} className="x-select__control" {...rest}>
|
||||
{placeholder != null && <option value="" disabled>{placeholder}</option>}
|
||||
{options
|
||||
? options.map(o => <option key={o.value} value={o.value} disabled={o.disabled}>{o.label}</option>)
|
||||
: children}
|
||||
</select>
|
||||
<svg className="x-select__chevron" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M6 9l6 6 6-6" />
|
||||
</svg>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { cx } from '../internal/cx.js'
|
||||
import { Portal } from '../internal/Portal.jsx'
|
||||
|
||||
const GAP = 8
|
||||
const MARGIN = 8
|
||||
|
||||
/**
|
||||
* The "(i)" help tip next to a setting or label (D-12: every manager page gets them).
|
||||
* Opens on click/tap (works on touch screens), closes on Escape, a click outside, or
|
||||
* a second click. Placed above the button, or below when there's no room.
|
||||
*
|
||||
* <label>Alert after failures <InfoTip>How many failed print attempts before managers are notified. 0 turns it off.</InfoTip></label>
|
||||
*
|
||||
* label: the button's accessible name (translate it). side: 'top' | 'bottom' (preferred side).
|
||||
*/
|
||||
export function InfoTip({ children, label = 'More info', side = 'top', className }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [pos, setPos] = useState(null)
|
||||
const button = useRef(null)
|
||||
const tip = useRef(null)
|
||||
const id = useId()
|
||||
|
||||
const place = useCallback(() => {
|
||||
const b = button.current?.getBoundingClientRect()
|
||||
const t = tip.current?.getBoundingClientRect()
|
||||
if (!b || !t) return
|
||||
const roomAbove = b.top - GAP - MARGIN >= t.height
|
||||
const roomBelow = window.innerHeight - b.bottom - GAP - MARGIN >= t.height
|
||||
const above = side === 'top' ? (roomAbove || !roomBelow) : !(roomBelow || !roomAbove)
|
||||
const top = above ? b.top - GAP - t.height : b.bottom + GAP
|
||||
const left = Math.min(Math.max(MARGIN, b.left + b.width / 2 - t.width / 2), window.innerWidth - MARGIN - t.width)
|
||||
setPos({ top, left, above, arrow: b.left + b.width / 2 - left })
|
||||
}, [side])
|
||||
|
||||
useLayoutEffect(() => { if (open) place() }, [open, place])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const close = () => setOpen(false)
|
||||
const onKey = e => { if (e.key === 'Escape') { e.stopPropagation(); close(); button.current?.focus() } }
|
||||
const onDown = e => {
|
||||
if (button.current?.contains(e.target) || tip.current?.contains(e.target)) return
|
||||
close()
|
||||
}
|
||||
document.addEventListener('keydown', onKey, true)
|
||||
document.addEventListener('pointerdown', onDown)
|
||||
window.addEventListener('resize', place)
|
||||
window.addEventListener('scroll', place, true)
|
||||
return () => {
|
||||
document.removeEventListener('keydown', onKey, true)
|
||||
document.removeEventListener('pointerdown', onDown)
|
||||
window.removeEventListener('resize', place)
|
||||
window.removeEventListener('scroll', place, true)
|
||||
}
|
||||
}, [open, place])
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={button}
|
||||
type="button"
|
||||
className={cx('x-infotip', open && 'x-infotip--open', className)}
|
||||
aria-label={label}
|
||||
aria-expanded={open}
|
||||
aria-describedby={open ? id : undefined}
|
||||
onClick={() => setOpen(o => !o)}
|
||||
>
|
||||
<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
|
||||
<circle cx="8" cy="8" r="7" fill="none" stroke="currentColor" strokeWidth="1.5" />
|
||||
<circle cx="8" cy="4.75" r="1" fill="currentColor" />
|
||||
<path d="M8 7.25v4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
|
||||
</svg>
|
||||
</button>
|
||||
{open && (
|
||||
<Portal>
|
||||
<div
|
||||
ref={tip}
|
||||
id={id}
|
||||
role="tooltip"
|
||||
className={cx('x-infotip__popover', pos && (pos.above ? 'x-infotip__popover--above' : 'x-infotip__popover--below'))}
|
||||
style={pos ? { top: pos.top, left: pos.left, '--x-arrow-x': `${pos.arrow}px` } : { top: 0, left: 0, visibility: 'hidden' }}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</Portal>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { cx } from '../internal/cx.js'
|
||||
import { Spinner } from './Spinner.jsx'
|
||||
import { nextPin, pinAction } from './pin.js'
|
||||
|
||||
const KEYS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', null, '0', 'Backspace']
|
||||
|
||||
/**
|
||||
* Numeric PIN entry: dots + a 3×4 keypad, also driven by the physical keyboard.
|
||||
*
|
||||
* <PinPad length={4} onComplete={async pin => { await unlock(pin) }} />
|
||||
*
|
||||
* onComplete(pin) runs when `length` digits are in. If it returns a promise the pad
|
||||
* shows a spinner until it settles. If it throws / rejects (or returns false), the pad
|
||||
* shakes, shows `error` text if given, and clears for another try. On success it clears too.
|
||||
*
|
||||
* error: text under the dots (e.g. "Wrong PIN"); a change of it also shakes the pad.
|
||||
* captureKeyboard (default true): digits/Backspace typed anywhere go to the pad,
|
||||
* except while the user is typing in a field.
|
||||
* Labels for translation: backspaceLabel, progressLabel(n, length).
|
||||
*/
|
||||
export function PinPad({
|
||||
length = 4, onComplete, onChange, disabled = false, error, title,
|
||||
captureKeyboard = true, backspaceLabel = 'Delete',
|
||||
progressLabel = (n, total) => `${n} of ${total} digits entered`,
|
||||
className,
|
||||
}) {
|
||||
const [value, setValue] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [shake, setShake] = useState(0)
|
||||
const latest = useRef({ value, busy, disabled })
|
||||
useLayoutEffect(() => { latest.current = { value, busy, disabled } })
|
||||
|
||||
const fail = useCallback(() => {
|
||||
setShake(n => n + 1)
|
||||
setValue('')
|
||||
onChange?.('')
|
||||
}, [onChange])
|
||||
|
||||
const submit = useCallback(async pin => {
|
||||
let ok = true
|
||||
try {
|
||||
const result = onComplete?.(pin)
|
||||
if (result && typeof result.then === 'function') {
|
||||
setBusy(true)
|
||||
ok = (await result) !== false
|
||||
} else {
|
||||
ok = result !== false
|
||||
}
|
||||
} catch {
|
||||
ok = false
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
if (ok) { setValue(''); onChange?.('') } else fail()
|
||||
}, [onComplete, onChange, fail])
|
||||
|
||||
const press = useCallback(key => {
|
||||
const { value: current, busy: isBusy, disabled: isDisabled } = latest.current
|
||||
const action = pinAction(key)
|
||||
if (!action || isBusy || isDisabled) return
|
||||
const next = nextPin(current, action, length)
|
||||
if (next === current) return
|
||||
setValue(next)
|
||||
onChange?.(next)
|
||||
if (next.length === length) submit(next)
|
||||
}, [length, onChange, submit])
|
||||
|
||||
useEffect(() => {
|
||||
if (!captureKeyboard) return
|
||||
const onKey = e => {
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return
|
||||
const t = e.target
|
||||
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
|
||||
if (pinAction(e.key)) { e.preventDefault(); press(e.key) }
|
||||
}
|
||||
document.addEventListener('keydown', onKey)
|
||||
return () => document.removeEventListener('keydown', onKey)
|
||||
}, [captureKeyboard, press])
|
||||
|
||||
return (
|
||||
<div className={cx('x-pinpad', disabled && 'x-pinpad--disabled', className)}>
|
||||
{title && <div className="x-pinpad__title">{title}</div>}
|
||||
{/* Re-keyed on every failed attempt and on every new error text, which replays the shake */}
|
||||
<div key={`${shake}:${error || ''}`} className={cx('x-pinpad__dots', (shake > 0 || error) && 'x-pinpad__dots--shake')} aria-hidden="true">
|
||||
{Array.from({ length }, (_, i) => (
|
||||
<span key={i} className={cx('x-pinpad__dot', i < value.length && 'x-pinpad__dot--filled', error && 'x-pinpad__dot--error')} />
|
||||
))}
|
||||
</div>
|
||||
<div className="x-visually-hidden" aria-live="polite">{progressLabel(value.length, length)}</div>
|
||||
<div className="x-pinpad__status">
|
||||
{busy ? <Spinner size="sm" /> : error ? <span className="x-pinpad__error" role="alert">{error}</span> : null}
|
||||
</div>
|
||||
<div className="x-pinpad__keys">
|
||||
{KEYS.map(k => k === null
|
||||
? <span key="blank" aria-hidden="true" />
|
||||
: (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
className={cx('x-pinpad__key', k === 'Backspace' && 'x-pinpad__key--backspace')}
|
||||
onClick={() => press(k)}
|
||||
disabled={disabled || busy}
|
||||
aria-label={k === 'Backspace' ? backspaceLabel : undefined}
|
||||
>
|
||||
{k === 'Backspace'
|
||||
? (
|
||||
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d="M21 5H9l-6 7 6 7h12a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1z" /><path d="M17 9l-6 6M11 9l6 6" />
|
||||
</svg>
|
||||
)
|
||||
: k}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { cx } from '../internal/cx.js'
|
||||
import { ModalFrame } from '../internal/ModalFrame.jsx'
|
||||
|
||||
/**
|
||||
* A panel that slides in from the bottom (phones: action sheets, pickers) or the
|
||||
* right (desktop: detail and edit panels). Same props and behaviour as Dialog.
|
||||
* side: 'bottom' | 'right'
|
||||
*/
|
||||
export function Sheet({ side = 'bottom', className, ...props }) {
|
||||
return (
|
||||
<ModalFrame
|
||||
{...props}
|
||||
overlayClass={`x-overlay--${side}`}
|
||||
panelClass={cx('x-sheet', `x-sheet--${side}`, className)}
|
||||
bodyClass="x-sheet__body"
|
||||
grip={side === 'bottom'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { cx } from '../internal/cx.js'
|
||||
|
||||
/**
|
||||
* Loading indicator. With a `label` (default "Loading") it is announced to screen
|
||||
* readers; pass label={null} when the surrounding element already says it (a busy button).
|
||||
* size: 'sm' (16px) | 'md' (24px) | 'lg' (40px)
|
||||
*/
|
||||
export function Spinner({ size = 'md', label = 'Loading', className, ...rest }) {
|
||||
return (
|
||||
<span
|
||||
className={cx('x-spinner', `x-spinner--${size}`, className)}
|
||||
role={label ? 'status' : undefined}
|
||||
aria-hidden={label ? undefined : true}
|
||||
{...rest}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
|
||||
<circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity="0.25" strokeWidth="3" />
|
||||
<path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
|
||||
</svg>
|
||||
{label && <span className="x-visually-hidden">{label}</span>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useId } from 'react'
|
||||
import { cx } from '../internal/cx.js'
|
||||
|
||||
/**
|
||||
* On/off toggle for settings that take effect immediately.
|
||||
* <Switch checked={on} onChange={setOn} label="Print kitchen tickets" description="..." />
|
||||
* onChange receives the new boolean. Without `label`, pass aria-label.
|
||||
* The whole row (label + description) is clickable.
|
||||
*/
|
||||
export function Switch({ checked, onChange, label, description, disabled = false, id, className, ...rest }) {
|
||||
const auto = useId()
|
||||
const switchId = id || auto
|
||||
const descId = `${switchId}-desc`
|
||||
|
||||
const control = (
|
||||
<button
|
||||
id={switchId}
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={!!checked}
|
||||
aria-describedby={description ? descId : undefined}
|
||||
disabled={disabled}
|
||||
className={cx('x-switch', checked && 'x-switch--on')}
|
||||
onClick={() => onChange?.(!checked)}
|
||||
{...rest}
|
||||
>
|
||||
<span className="x-switch__thumb" />
|
||||
</button>
|
||||
)
|
||||
|
||||
if (!label && !description) return <span className={className}>{control}</span>
|
||||
return (
|
||||
<div className={cx('x-switch-row', disabled && 'x-switch-row--disabled', className)}>
|
||||
<div className="x-switch-row__text">
|
||||
{label && <label className="x-switch-row__label" htmlFor={switchId}>{label}</label>}
|
||||
{description && <div id={descId} className="x-switch-row__description">{description}</div>}
|
||||
</div>
|
||||
{control}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { cx } from '../internal/cx.js'
|
||||
import { Portal } from '../internal/Portal.jsx'
|
||||
import { ToastContext } from './toastContext.js'
|
||||
|
||||
let nextId = 1
|
||||
|
||||
/**
|
||||
* Wrap the app once: <ToastProvider><App /></ToastProvider>
|
||||
* Then anywhere: const toast = useToast()
|
||||
* toast.success('Saved')
|
||||
* toast.show({ tone: 'danger', title: 'Printer offline', description: 'Bar printer', duration: 0 })
|
||||
*
|
||||
* tone: 'neutral' | 'success' | 'warning' | 'danger' | 'info'. duration in ms (0 = stays until closed).
|
||||
* Danger toasts are announced assertively (role="alert"), the rest politely.
|
||||
* The timer pauses while the pointer is over a toast.
|
||||
* placement: 'top-right' | 'top-center' | 'bottom-center'. closeLabel: the × text (translate it).
|
||||
*/
|
||||
export function ToastProvider({ children, placement = 'top-right', max = 4, closeLabel = 'Dismiss' }) {
|
||||
const [toasts, setToasts] = useState([])
|
||||
|
||||
const dismiss = useCallback(id => setToasts(list => list.filter(t => t.id !== id)), [])
|
||||
const show = useCallback(opts => {
|
||||
const t = typeof opts === 'string' ? { title: opts } : opts
|
||||
const id = t.id ?? nextId++
|
||||
const toast = { tone: 'neutral', duration: t.tone === 'danger' ? 8000 : 4000, ...t, id }
|
||||
setToasts(list => [...list.filter(x => x.id !== id), toast].slice(-max))
|
||||
return id
|
||||
}, [max])
|
||||
|
||||
const api = useMemo(() => {
|
||||
const tone = name => (title, opts = {}) => show({ ...opts, title, tone: name })
|
||||
return { show, dismiss, success: tone('success'), error: tone('danger'), warning: tone('warning'), info: tone('info') }
|
||||
}, [show, dismiss])
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={api}>
|
||||
{children}
|
||||
<Portal>
|
||||
<div className={cx('x-toasts', `x-toasts--${placement}`)} role="region" aria-label="Notifications">
|
||||
{toasts.map(t => <ToastItem key={t.id} toast={t} onDismiss={dismiss} closeLabel={closeLabel} />)}
|
||||
</div>
|
||||
</Portal>
|
||||
</ToastContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function ToastItem({ toast, onDismiss, closeLabel }) {
|
||||
const { id, tone, title, description, duration, action } = toast
|
||||
const [paused, setPaused] = useState(false)
|
||||
const remaining = useRef(duration)
|
||||
const started = useRef(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (!duration || paused) return
|
||||
started.current = Date.now()
|
||||
const timer = setTimeout(() => onDismiss(id), remaining.current)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
remaining.current -= Date.now() - started.current
|
||||
}
|
||||
}, [paused, duration, id, onDismiss])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cx('x-toast', `x-toast--${tone}`)}
|
||||
role={tone === 'danger' ? 'alert' : 'status'}
|
||||
onMouseEnter={() => setPaused(true)}
|
||||
onMouseLeave={() => setPaused(false)}
|
||||
>
|
||||
<span className="x-toast__bar" aria-hidden="true" />
|
||||
<div className="x-toast__text">
|
||||
{title && <div className="x-toast__title">{title}</div>}
|
||||
{description && <div className="x-toast__description">{description}</div>}
|
||||
</div>
|
||||
{action && (
|
||||
<button type="button" className="x-toast__action" onClick={() => { action.onClick?.(); onDismiss(id) }}>
|
||||
{action.label}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="x-toast__close" aria-label={closeLabel} title={closeLabel} onClick={() => onDismiss(id)}>
|
||||
<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
|
||||
<path d="M6 6l12 12M18 6L6 18" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// PIN entry rules, kept free of React so they can be unit-tested (tests/pin.test.mjs).
|
||||
|
||||
/** Normalise a key or keypad press into an action, or null if it isn't one. */
|
||||
export function pinAction(key) {
|
||||
if (/^[0-9]$/.test(key)) return { type: 'digit', digit: key }
|
||||
if (key === 'Backspace' || key === 'Delete') return { type: 'backspace' }
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Next PIN value. Digits are ignored once `length` is reached; backspace on an
|
||||
* empty PIN is a no-op; 'clear' empties it.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function nextPin(value, action, length) {
|
||||
switch (action?.type) {
|
||||
case 'digit': return value.length >= length ? value : value + action.digit
|
||||
case 'backspace': return value.slice(0, -1)
|
||||
case 'clear': return ''
|
||||
default: return value
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
|
||||
export const ToastContext = createContext(null)
|
||||
|
||||
/** toast.success('Saved'), toast.error(title, { description }), toast.show({...}), toast.dismiss(id). See ToastProvider. */
|
||||
export function useToast() {
|
||||
const ctx = useContext(ToastContext)
|
||||
if (!ctx) throw new Error('useToast() needs a <ToastProvider> above it')
|
||||
return ctx
|
||||
}
|
||||
Reference in New Issue
Block a user