"use client"; import { Glass, type GlassProps, resolveToneTheme, useGlassTheme } from "@open-glass-ui/react"; import { type ButtonHTMLAttributes, type CSSProperties, cloneElement, createContext, type FieldsetHTMLAttributes, forwardRef, type HTMLAttributes, type InputHTMLAttributes, type LabelHTMLAttributes, type ReactElement, type ReactNode, useCallback, useContext, useEffect, useId, useLayoutEffect, useRef, useState, } from "react"; import { createPortal } from "react-dom"; import { joinIds, normalizeToStep, type StepRule } from "./atlas"; import { isInDescendantLayer, isReachableLayer, isTopLayer, openLayer, useIsomorphicLayoutEffect, } from "./layers"; import "./styles.css"; import "./liquid.css"; export type { AccordionItem, AlertProps, AvatarProps, BadgeProps, BannerProps, BreadcrumbItem, CardProps, CheckboxProps, FileDropzoneProps, MeterProps, NumberFieldProps, OverlayProps, PaginationProps, ProgressProps, RadioGroupProps, RadioItem, SearchFieldProps, SelectOption, SelectProps, SemanticTone, StatProps, StepItem, TextareaProps, TextFieldProps, ToastController, ToastOptions, ToastProps, ToastProviderProps, ToggleButtonProps, } from "./atlas"; export { Accordion, Alert, Avatar, AvatarGroup, Badge, Banner, Breadcrumbs, Card, Checkbox, Dialog, Drawer, FileDropzone, Meter, NumberField, Pagination, Progress, RadioGroup, SearchField, Select, Skeleton, Spinner, Stat, Stepper, Textarea, TextField, Toast, ToastProvider, ToggleButton, useToast, } from "./atlas"; function classes(...values: Array) { return values.filter(Boolean).join(" "); } function idPart(value: string) { return encodeURIComponent(value).replaceAll("%", "_"); } /** * Publishes the selected item's box as CSS variables on its container so the * stylesheet can slide one shared indicator between items. Writes go straight * to the element style: the indicator never causes a React render. */ function useSelectionIndicator( containerRef: { current: HTMLElement | null }, selector: string, key: unknown, ) { useIsomorphicLayoutEffect(() => { const container = containerRef.current; if (!container) { return; } const place = () => { const selected = container.querySelector(selector); if (!selected) { container.removeAttribute("data-ogui-indicator"); return; } container.style.setProperty("--ogui-indicator-x", `${selected.offsetLeft}px`); container.style.setProperty("--ogui-indicator-y", `${selected.offsetTop}px`); container.style.setProperty("--ogui-indicator-w", `${selected.offsetWidth}px`); container.style.setProperty("--ogui-indicator-h", `${selected.offsetHeight}px`); container.setAttribute("data-ogui-indicator", "ready"); }; place(); if (typeof ResizeObserver === "undefined") { return; } const observer = new ResizeObserver(place); observer.observe(container); return () => observer.disconnect(); }, [containerRef, selector, key]); } /** Filled fraction (0 to 1) of a range input's track, for the liquid track. */ function rangeProgress(value: unknown, min: unknown, max: unknown) { const low = Number(min); const high = Number(max); const current = Number(value); if (![low, high, current].every(Number.isFinite) || high <= low) { return "0"; } return Math.min(Math.max((current - low) / (high - low), 0), 1).toFixed(4); } function useControllableValue( controlledValue: T | undefined, defaultValue: T, onChange: ((value: T) => void) | undefined, ) { const [internalValue, setInternalValue] = useState(defaultValue); const value = controlledValue ?? internalValue; const setValue = useCallback( (nextValue: T) => { if (controlledValue === undefined) { setInternalValue(nextValue); } onChange?.(nextValue); }, [controlledValue, onChange], ); return [value, setValue] as const; } export type ButtonVariant = "primary" | "secondary" | "quiet" | "danger"; export type ControlSize = "small" | "medium" | "large"; export interface ButtonProps extends ButtonHTMLAttributes { variant?: ButtonVariant; size?: ControlSize; leadingIcon?: ReactNode; trailingIcon?: ReactNode; } export const Button = /* @__PURE__ */ forwardRef(function Button( { variant = "secondary", size = "medium", leadingIcon, trailingIcon, className, children, type = "button", onPointerMove, ...props }, ref, ) { return ( ); }); export interface IconButtonProps extends Omit { "aria-label": string; children: ReactNode; } export const IconButton = /* @__PURE__ */ forwardRef( function IconButton({ size = "medium", variant = "quiet", className, children, ...props }, ref) { return ( ); }, ); export interface SegmentItem { value: T; label: string; icon?: ReactNode; disabled?: boolean; } export interface SegmentedControlProps extends Omit, "onChange" | "defaultValue"> { "aria-label": string; items: readonly SegmentItem[]; value?: T; defaultValue?: T; onValueChange?: (value: T) => void; } export function SegmentedControl({ items, value: controlledValue, defaultValue = items[0]?.value, onValueChange, className, "aria-label": label, ...props }: SegmentedControlProps) { if (defaultValue === undefined) { throw new Error("SegmentedControl requires at least one item or a defaultValue."); } const [value, setValue] = useControllableValue(controlledValue, defaultValue, onValueChange); const segmentsRef = useRef(null); useSelectionIndicator(segmentsRef, '.ogui-segments__item[aria-pressed="true"]', value); return (
{label}
); } export interface SwitchProps extends Omit, "type" | "size"> { label: ReactNode; description?: ReactNode; labelProps?: LabelHTMLAttributes; onCheckedChange?: (checked: boolean) => void; } export const Switch = /* @__PURE__ */ forwardRef(function Switch( { label, description, className, labelProps, checked: controlledChecked, defaultChecked = false, onChange, onCheckedChange, id: suppliedId, "aria-describedby": describedBy, ...props }, ref, ) { const generatedId = useId(); const id = suppliedId ?? generatedId; const descriptionId = description ? `${id}-description` : undefined; const [checked, setChecked] = useControllableValue( controlledChecked, defaultChecked, onCheckedChange, ); return ( ); }); export interface SliderProps extends Omit, "type" | "size"> { label: ReactNode; valueText?: string; unit?: string; } function firstNumber(value: unknown) { const candidate = Array.isArray(value) ? value[0] : value; if (candidate === undefined || candidate === null || candidate === "") { return undefined; } const parsed = Number(candidate); return Number.isFinite(parsed) ? parsed : undefined; } /** * The value text, the filled track and the native thumb all show one value: * clamped to the bounds and aligned to the step from `min` (nearest, ties to * the larger, never past `max`), as the browser itself sanitizes a range * input. `step="any"` only clamps. Without a value the slider starts at `min`. */ export const Slider = /* @__PURE__ */ forwardRef(function Slider( { label, valueText, unit = "", className, id: suppliedId, value, defaultValue, min = 0, max = 100, step, onInput, ...props }, ref, ) { const generatedId = useId(); const id = suppliedId ?? generatedId; const labelId = `${id}-label`; const inputRef = useRef(null); const minValue = firstNumber(min) ?? 0; const maxValue = firstNumber(max) ?? 100; const stepValue = firstNumber(step); const stepSize = step === "any" ? null : stepValue !== undefined && stepValue > 0 ? stepValue : 1; const rule: StepRule = { min: minValue, max: maxValue, base: minValue, step: stepSize }; const uncontrolled = value === undefined; // The current default, normalized like the native input would. It reaches // the native `defaultValue` on every render, so a form reset restores the // latest default; React updates it without touching an edited value. const defaultNumber = normalizeToStep(firstNumber(defaultValue) ?? minValue, rule); const [liveValue, setLiveValue] = useState(defaultNumber); const numericValue = normalizeToStep( (value === undefined ? undefined : firstNumber(value)) ?? liveValue, rule, ); const progress = rangeProgress(numericValue, rule.min, rule.max); // Keeps the internal ref and forwards to the caller's. A React 19 callback // ref may return a cleanup function: pass it back, so React runs it (and // does not call the ref with null) on unmount or when the ref changes. const setRefs = useCallback( (node: HTMLInputElement | null) => { inputRef.current = node; if (typeof ref === "function") { const cleanup: unknown = ref(node); if (typeof cleanup === "function") { return () => { inputRef.current = null; cleanup(); }; } } else if (ref) { ref.current = node; } return undefined; }, [ref], ); // New bounds or a new step make the browser re-sanitize the native value // without an input event, and widening the bounds again does not restore the // old value. An uncontrolled slider reads the native value back so the text and // the track keep showing what the form submits. The normalized value is // written back only where the native one is not on the grid yet (WebKit // skips re-aligning to a new step, jsdom does not sanitize at all); after a // browser's own clamp nothing is written. useIsomorphicLayoutEffect(() => { const input = inputRef.current; if (!uncontrolled || !input) { return; } const native = normalizeToStep(firstNumber(input.value) ?? minValue, { min: minValue, max: maxValue, base: minValue, step: stepSize, }); if (Number(input.value) !== native) { input.value = String(native); } setLiveValue(native); // `defaultNumber` too, so the text keeps matching the native value // whatever the browser does with a new default. }, [minValue, maxValue, stepSize, uncontrolled, defaultNumber]); // A form reset restores the native default after the reset event, so read // the restored value back once it has happened. Listening on the document // and comparing with the input's current form keeps working when the input // moves to another form (a changed `form` attribute) without remounting. useEffect(() => { const input = inputRef.current; if (!input) { return; } const doc = input.ownerDocument; let timeout = 0; const handleReset = (event: Event) => { const current = inputRef.current; if (!current || event.target !== current.form) { return; } window.clearTimeout(timeout); timeout = window.setTimeout(() => { const restored = inputRef.current; if (restored) { setLiveValue(Number(restored.value)); } }, 0); }; // Capture phase, so a handler that stops the event on the form cannot hide it. doc.addEventListener("reset", handleReset, true); return () => { window.clearTimeout(timeout); doc.removeEventListener("reset", handleReset, true); }; }, []); return ( ); }); export interface ToolbarProps extends HTMLAttributes { label: string; orientation?: "horizontal" | "vertical"; material?: GlassProps["material"]; tone?: GlassProps["tone"]; } export function Toolbar({ label, orientation = "horizontal", material = "regular", tone = "auto", className, children, ...props }: ToolbarProps) { return ( {children} ); } export interface DockProps extends HTMLAttributes { label: string; material?: GlassProps["material"]; tone?: GlassProps["tone"]; } export function Dock({ label, material = "regular", tone = "auto", className, children, ...props }: DockProps) { return ( {children} ); } export interface TabItem { value: T; label: ReactNode; content: ReactNode; disabled?: boolean; } export interface TabsProps extends Omit, "onChange" | "defaultValue"> { label: string; items: readonly TabItem[]; value?: T; defaultValue?: T; onValueChange?: (value: T) => void; } export function Tabs({ label, items, value: controlledValue, defaultValue: suppliedDefaultValue, onValueChange, className, ...props }: TabsProps) { const firstEnabled = items.find((item) => !item.disabled); const defaultValue = items.find((item) => item.value === suppliedDefaultValue && !item.disabled)?.value ?? firstEnabled?.value; if (defaultValue === undefined) { throw new Error("Tabs requires at least one enabled item."); } const id = useId(); const [value, setValue] = useControllableValue(controlledValue, defaultValue, onValueChange); const activeItem = items.find((item) => item.value === value && !item.disabled) ?? firstEnabled; const tabsRef = useRef(null); useSelectionIndicator(tabsRef, '[role="tab"][aria-selected="true"]', activeItem?.value); const move = (currentValue: T, direction: number) => { const enabled = items.filter((item) => !item.disabled); const currentIndex = enabled.findIndex((item) => item.value === currentValue); const next = enabled[(currentIndex + direction + enabled.length) % enabled.length]; if (next) { setValue(next.value); const button = [ ...(tabsRef.current?.querySelectorAll("[role=tab]") ?? []), ].find((candidate) => candidate.dataset.tabValue === next.value); button?.focus(); } }; const moveToEdge = (edge: "first" | "last") => { const enabled = items.filter((item) => !item.disabled); const next = edge === "first" ? enabled[0] : enabled.at(-1); if (next) { setValue(next.value); const button = [ ...(tabsRef.current?.querySelectorAll("[role=tab]") ?? []), ].find((candidate) => candidate.dataset.tabValue === next.value); button?.focus(); } }; return (
{activeItem ? (
{activeItem.content}
) : null}
); } export interface DisclosureSurfaceProps extends Omit, "onChange"> { trigger: ReactElement>; triggerLabel?: string; material?: GlassProps["material"]; tone?: GlassProps["tone"]; placement?: "start" | "center" | "end"; defaultOpen?: boolean; open?: boolean; onOpenChange?: (open: boolean) => void; focusOnOpen?: "none" | "first" | "last"; openOnArrowKeys?: boolean; } const DisclosureCloseContext = /* @__PURE__ */ createContext<(() => void) | null>(null); function DisclosureSurface({ trigger, triggerLabel, material = "frosted", tone = "auto", placement = "start", defaultOpen = false, open: controlledOpen, onOpenChange, focusOnOpen = "none", openOnArrowKeys = false, className, children, ...props }: DisclosureSurfaceProps) { const id = useId(); const wrapperRef = useRef(null); const surfaceRef = useRef(null); const requestedFocusRef = useRef(focusOnOpen); const [portalHost, setPortalHost] = useState(null); const [surfacePosition, setSurfacePosition] = useState({ top: -10_000, left: -10_000, }); const [open, setOpen] = useControllableValue(controlledOpen, defaultOpen, onOpenChange); // The surface is portaled out of the theme element, so it carries the theme // tokens itself. A forced `tone` gets that tone's palette, not the // surrounding one, so its text and nested recipes stay readable. const { appearance, tokens } = resolveToneTheme(useGlassTheme(), tone); const focusTrigger = useCallback(() => { wrapperRef.current?.querySelector("button[aria-controls]")?.focus(); }, []); // `setOpen` changes identity with `onOpenChange`; reading it from a ref keeps // the layer effect tied to the open state, so a parent render never moves // this surface to the top of the stack. const setOpenRef = useRef(setOpen); useIsomorphicLayoutEffect(() => { setOpenRef.current = setOpen; }); useEffect(() => { const host = document.createElement("div"); host.setAttribute("data-ogui-portal", "disclosure"); document.body.append(host); setPortalHost(host); return () => host.remove(); }, []); useIsomorphicLayoutEffect(() => { if (!open || !portalHost) { return; } // The layer holding the trigger owns this surface: a menu opened in a // dialog belongs to the dialog and stays usable while it is modal. const closeLayer = openLayer(id, "disclosure", portalHost, wrapperRef.current); const handlePointerDown = (event: PointerEvent) => { if (!isReachableLayer(id)) { return; } if ( event.target instanceof Node && !wrapperRef.current?.contains(event.target) && !surfaceRef.current?.contains(event.target) && !isInDescendantLayer(id, event.target) ) { setOpenRef.current(false); } }; const handleKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape" || event.defaultPrevented || !isTopLayer(id)) { return; } event.preventDefault(); setOpenRef.current(false); focusTrigger(); }; document.addEventListener("pointerdown", handlePointerDown); document.addEventListener("keydown", handleKeyDown); return () => { document.removeEventListener("pointerdown", handlePointerDown); document.removeEventListener("keydown", handleKeyDown); closeLayer(); }; }, [focusTrigger, id, open, portalHost]); useEffect(() => { if (!open || !portalHost || requestedFocusRef.current === "none") { return; } const focusFrame = requestAnimationFrame(() => { const surface = surfaceRef.current; if (!surface) { return; } const autofocus = surface.querySelector("[data-ogui-autofocus]:not([disabled])"); const items = [ ...surface.querySelectorAll( 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])', ), ]; const target = autofocus ?? (requestedFocusRef.current === "last" ? items.at(-1) : items[0]); target?.focus(); }); return () => cancelAnimationFrame(focusFrame); }, [open, portalHost]); useLayoutEffect(() => { if (!open || !portalHost) { return; } const updatePosition = () => { const trigger = wrapperRef.current?.querySelector("button[aria-controls]"); const surface = surfaceRef.current; if (!trigger || !surface) { return; } const gap = 8; const edge = 8; const triggerRect = trigger.getBoundingClientRect(); const surfaceRect = surface.getBoundingClientRect(); const viewportWidth = document.documentElement.clientWidth; const viewportHeight = document.documentElement.clientHeight; const roomBelow = viewportHeight - triggerRect.bottom - gap; const roomAbove = triggerRect.top - gap; const placeAbove = surfaceRect.height > roomBelow && roomAbove > roomBelow; const preferredTop = placeAbove ? triggerRect.top - surfaceRect.height - gap : triggerRect.bottom + gap; const preferredLeft = placement === "center" ? triggerRect.left + (triggerRect.width - surfaceRect.width) / 2 : placement === "end" ? triggerRect.right - surfaceRect.width : triggerRect.left; const maxLeft = Math.max(edge, viewportWidth - surfaceRect.width - edge); const maxTop = Math.max(edge, viewportHeight - surfaceRect.height - edge); setSurfacePosition({ top: Math.min(Math.max(preferredTop, edge), maxTop), left: Math.min(Math.max(preferredLeft, edge), maxLeft), }); }; updatePosition(); window.addEventListener("resize", updatePosition); window.addEventListener("scroll", updatePosition, true); return () => { window.removeEventListener("resize", updatePosition); window.removeEventListener("scroll", updatePosition, true); }; }, [open, placement, portalHost]); const close = useCallback(() => { setOpen(false); focusTrigger(); }, [focusTrigger, setOpen]); return (
{cloneElement(trigger, { id: `${id}-trigger`, "aria-label": triggerLabel ?? trigger.props["aria-label"], "aria-expanded": open, "aria-controls": `${id}-surface`, "aria-haspopup": openOnArrowKeys ? "menu" : trigger.props["aria-haspopup"], onClick: (event) => { trigger.props.onClick?.(event); if (!event.defaultPrevented) { requestedFocusRef.current = focusOnOpen; setOpen(!open); } }, onKeyDown: (event) => { trigger.props.onKeyDown?.(event); if ( !event.defaultPrevented && openOnArrowKeys && (event.key === "ArrowDown" || event.key === "ArrowUp") ) { event.preventDefault(); requestedFocusRef.current = event.key === "ArrowUp" ? "last" : "first"; setOpen(true); } }, })} {open && portalHost ? createPortal( {children} , portalHost, ) : null}
); } export interface MenuProps extends DisclosureSurfaceProps { label: string; } function MenuItems({ label, children }: { label: string; children: ReactNode }) { const menuRef = useRef(null); const close = useContext(DisclosureCloseContext); const focusItem = (intent: "first" | "last" | "next" | "previous", current?: HTMLElement) => { const items = [ ...(menuRef.current?.querySelectorAll( '[role="menuitem"]:not([disabled])', ) ?? []), ]; if (items.length === 0) { return; } if (intent === "first") { items[0]?.focus(); return; } if (intent === "last") { items.at(-1)?.focus(); return; } const currentIndex = current ? items.indexOf(current as HTMLButtonElement) : -1; const delta = intent === "next" ? 1 : -1; items[(currentIndex + delta + items.length) % items.length]?.focus(); }; return (
{ // React bubbles keys from portals through the component tree: a dialog // or nested menu opened from an item would otherwise lose Tab, Home, // End and the arrows to this menu. Only keys pressed in the menu count. if ( event.defaultPrevented || !(event.target instanceof Node) || !event.currentTarget.contains(event.target) ) { return; } const current = event.target instanceof HTMLElement ? event.target : undefined; if (event.key === "ArrowDown") { event.preventDefault(); focusItem("next", current); return; } if (event.key === "ArrowUp") { event.preventDefault(); focusItem("previous", current); return; } if (event.key === "Home") { event.preventDefault(); focusItem("first"); return; } if (event.key === "End") { event.preventDefault(); focusItem("last"); return; } if (event.key === "Tab") { close?.(); return; } if (event.key.length === 1 && /\S/.test(event.key)) { const items = [ ...(menuRef.current?.querySelectorAll( '[role="menuitem"]:not([disabled])', ) ?? []), ]; const currentIndex = current ? items.indexOf(current as HTMLButtonElement) : -1; const orderedItems = [ ...items.slice(currentIndex + 1), ...items.slice(0, currentIndex + 1), ]; orderedItems .find((item) => item.textContent ?.trim() .toLocaleLowerCase() .startsWith(event.key.toLocaleLowerCase()), ) ?.focus(); } }} > {children}
); } export function Menu({ label, children, ...props }: MenuProps) { return ( {children} ); } export interface MenuItemProps extends ButtonHTMLAttributes { destructive?: boolean; } export function MenuItem({ destructive = false, className, children, type = "button", onClick, ...props }: MenuItemProps) { const close = useContext(DisclosureCloseContext); return ( ); } export interface PopoverProps extends DisclosureSurfaceProps { label: string; } export function Popover({ label, children, ...props }: PopoverProps) { return (
{children}
); } export interface TooltipProps { label: ReactNode; children: ReactElement<{ "aria-describedby"?: string }>; placement?: "top" | "bottom"; } /** * The bubble shows on hover or focus (stylesheet), stays up while the pointer * moves onto it, and Escape hides it while it is visible, also when it is * only hovered and focus is elsewhere (WCAG 1.4.13). A visible tooltip is the * top layer, so Escape dismisses it before the dialog or menu beneath. */ export function Tooltip({ label, children, placement = "top" }: TooltipProps) { const id = useId(); const wrapperRef = useRef(null); const [hovered, setHovered] = useState(false); const [focused, setFocused] = useState(false); const [dismissed, setDismissed] = useState(false); const visible = (hovered || focused) && !dismissed; const describedBy = [children.props["aria-describedby"], id].filter(Boolean).join(" "); useEffect(() => { const wrapper = wrapperRef.current; if (!visible || !wrapper) { return; } const closeLayer = openLayer(id, "tooltip", wrapper, wrapper); const handleKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape" || event.defaultPrevented || !isTopLayer(id)) { return; } event.preventDefault(); setDismissed(true); }; document.addEventListener("keydown", handleKeyDown); return () => { document.removeEventListener("keydown", handleKeyDown); closeLayer(); }; }, [id, visible]); return ( // biome-ignore lint/a11y/noStaticElementInteractions: the handlers only observe hover and focus bubbling from the interactive child to track when the tooltip is visible (WCAG 1.4.13); the wrapper itself is never operable. setHovered(true)} onMouseLeave={() => { setHovered(false); setDismissed(false); }} onFocus={() => setFocused(true)} onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) { setFocused(false); } }} onBlurCapture={() => setDismissed(false)} > {cloneElement(children, { "aria-describedby": describedBy })} {label} ); } export interface MediaControlsProps extends HTMLAttributes { playing: boolean; currentTime: number; duration: number; muted?: boolean; onPlayingChange: (playing: boolean) => void; onSeek: (time: number) => void; onMutedChange?: (muted: boolean) => void; } function formatTime(seconds: number) { const safeSeconds = Math.max(Number.isFinite(seconds) ? seconds : 0, 0); const minutes = Math.floor(safeSeconds / 60); const remainder = Math.floor(safeSeconds % 60); return `${minutes}:${remainder.toString().padStart(2, "0")}`; } // Inline vector icons keep playback glyphs crisp and identical across // platforms; text glyphs like "▶" can render as emoji or fall back per font. const MEDIA_ICON_PATHS = { play: "M5 3.2 12.8 8 5 12.8Z", pause: "M4.6 3.2h2.4v9.6H4.6Zm4.4 0h2.4v9.6H9Z", volume: "M2.4 5.6h2.3L8.2 3v10L4.7 10.4H2.4Zm7.6-.3a3.9 3.9 0 0 1 0 5.4l-1-1a2.5 2.5 0 0 0 0-3.4Z", muted: "M2.4 5.6h2.3L8.2 3v10L4.7 10.4H2.4Zm7.5.7 1-1 1.6 1.6 1.6-1.6 1 1L13.5 8l1.6 1.6-1 1-1.6-1.6-1.6 1.6-1-1L11.5 8Z", } as const; function MediaIcon({ name }: { name: keyof typeof MEDIA_ICON_PATHS }) { return ( ); } export function MediaControls({ playing, currentTime, duration, muted = false, onPlayingChange, onSeek, onMutedChange, className, ...props }: MediaControlsProps) { const seekId = useId(); const seekMax = Math.max(duration, 1); return (
onPlayingChange(!playing)} > {formatTime(currentTime)} / {formatTime(duration)} {onMutedChange ? ( onMutedChange(!muted)} > ) : null}
); }