Files
tansy-ui/src/components/Alert.tsx
T
thekhalidsha f01de83733 Rebuild Tansy UI on Base UI with one API and dark mode (v0.3.0)
Every component is rebuilt on @base-ui/react with a single prop API,
token-only colours and dark mode, and 28 new components are added.

Components
- New: Field, FeaturedTextArea, NumberInput, Combobox, CheckboxGroup,
  Slider, ToggleGroup/Toggle, IconButton, Dialog/Modal, AlertDialog,
  Drawer/Sheet, Popover, InfoTip, DropdownMenu, Tabs, Breadcrumb,
  Pagination, Toast (Toaster, useToast), Progress, Meter, Skeleton,
  CountBadge, Avatar/AvatarGroup, Kbd, Separator, Table
- Rewritten: Button, Input, FeaturedInput, TextArea, Select,
  FeaturedSelect (real ARIA combobox), NativeSelect, Checkbox, Radio,
  Switch, Tooltip, Accordion, Alert, Spinner, Badge, Card
- Removed TextField (use Input) and sonner (use Toast)

Foundations
- Semantic tokens (surfaces, text, borders, status ramps) in
  src/styles/tokens.css, with class-based dark mode
- Visible focus rings, linked labels/descriptions/errors, alert roles by
  severity, keyboard support from Base UI
- Fixed the Classic Blue ramp; Emerald, Amber and Teal 500 steps now
  carry white text at AA
- Library build (per-component ES modules, types, tokens.css, exports)

Quality
- Vitest, Testing Library and axe tests for every component (289 tests)
- scripts/check-stories.mjs renders every story in Chrome and fails on
  errors or axe violations, including contrast; all 423 stories pass in
  light and dark mode and in all seven palettes
- Storybook: controls for every prop, open states for every popup,
  light/dark toolbar, Introduction guides, docs/CONVENTIONS.md

BREAKING CHANGE: component props changed across the kit; see CHANGELOG.md.
2026-09-28 21:12:11 +05:30

151 lines
4.4 KiB
TypeScript

import { useEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react'
import { CircleAlert, CircleCheck, CircleX, Info, TriangleAlert, X } from 'lucide-react'
import { cn } from '../lib/cn'
import { useControllableState } from '../lib/useControllableState'
import { IconButton } from './Button'
import {
ALERT_CLOSE_STYLES,
ALERT_ICON_STYLES,
ALERT_STYLES,
ALERT_URGENT_COLORS,
type AlertColor,
type AlertVariant,
} from './alert.tokens'
export type AlertProps = Omit<ComponentProps<'div'>, 'color' | 'title'> & {
/** Semantic colour. `danger` and `warning` use `role="alert"`; the rest are polite `role="status"`. */
color?: AlertColor
/** Visual weight. */
variant?: AlertVariant
/** Short bold heading. */
title?: ReactNode
/** The message. */
children?: ReactNode
/** Replaces the colour's default icon. */
icon?: ReactNode
/** Hides the icon. */
hideIcon?: boolean
/** Buttons or links shown under the message. */
actions?: ReactNode
/** Shows a close button labelled "Dismiss". */
dismissible?: boolean
/** Controlled visibility. */
open?: boolean
/** Initial visibility when uncontrolled. */
defaultOpen?: boolean
/** Called when the alert is dismissed or auto-closes. */
onOpenChange?: (open: boolean) => void
/** Closes the alert after this many milliseconds. Pauses while hovered or focused. `0` disables. */
autoClose?: number
}
const DEFAULT_ICONS: Record<AlertColor, ReactNode> = {
info: <Info />,
success: <CircleCheck />,
warning: <TriangleAlert />,
danger: <CircleX />,
neutral: <Info />,
primary: <CircleAlert />,
}
/** Counts down `delay` ms, pausing while `paused` is true, then calls `onDone`. */
function useAutoClose(delay: number, paused: boolean, active: boolean, onDone: () => void) {
const remaining = useRef(delay)
const onDoneRef = useRef(onDone)
useEffect(() => {
onDoneRef.current = onDone
})
useEffect(() => {
remaining.current = delay
}, [delay])
useEffect(() => {
if (!active || delay <= 0 || paused) return
const started = Date.now()
const timer = setTimeout(() => onDoneRef.current(), remaining.current)
return () => {
clearTimeout(timer)
remaining.current = Math.max(0, remaining.current - (Date.now() - started))
}
}, [active, delay, paused])
}
/** An inline status message, optionally dismissible or auto-closing. */
export function Alert({
color = 'info',
variant = 'soft',
title,
children,
icon,
hideIcon = false,
actions,
dismissible = false,
open: openProp,
defaultOpen = true,
onOpenChange,
autoClose = 0,
className,
onMouseEnter,
onMouseLeave,
onFocus,
onBlur,
...props
}: AlertProps) {
const [open, setOpen] = useControllableState(openProp, defaultOpen, onOpenChange)
const [hovered, setHovered] = useState(false)
const [focused, setFocused] = useState(false)
useAutoClose(autoClose, hovered || focused, open, () => setOpen(false))
if (!open) return null
const urgent = ALERT_URGENT_COLORS.includes(color)
return (
<div
role={urgent ? 'alert' : 'status'}
className={cn(
'flex w-full items-start gap-3 rounded-xl border p-4 text-sm leading-5',
ALERT_STYLES[variant][color],
className,
)}
onMouseEnter={(e) => {
setHovered(true)
onMouseEnter?.(e)
}}
onMouseLeave={(e) => {
setHovered(false)
onMouseLeave?.(e)
}}
onFocus={(e) => {
setFocused(true)
onFocus?.(e)
}}
onBlur={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(false)
onBlur?.(e)
}}
{...props}
>
{!hideIcon && (
<span aria-hidden="true" className={cn('flex shrink-0 [&_svg]:size-5', ALERT_ICON_STYLES[variant][color])}>
{icon ?? DEFAULT_ICONS[color]}
</span>
)}
<div className="min-w-0 flex-1">
{title != null && <p className="font-semibold">{title}</p>}
{children != null && <div className={cn(title != null && 'mt-1')}>{children}</div>}
{actions != null && <div className="mt-3 flex flex-wrap items-center gap-2">{actions}</div>}
</div>
{dismissible && (
<IconButton
size="sm"
aria-label="Dismiss"
icon={<X />}
onClick={() => setOpen(false)}
className={cn('-my-1.5 -mr-1.5 size-8', ALERT_CLOSE_STYLES[variant])}
/>
)}
</div>
)
}