Compare commits

...

1 Commits

Author SHA1 Message Date
github-actions[bot]
93ed7ac282 chore(dashboard): sync the vendored CI UI Kit to 0.43.7
packages/ui-kit moves from upstream 33891c6 to 7d39dbd (0.43.7) through scripts/dev/sync-ui-kit.sh.
2026-11-20 09:24:24 +00:00
103 changed files with 7707 additions and 774 deletions

View File

@@ -0,0 +1 @@
- **chore(dashboard):** the vendored Keak CI UI Kit moves to 0.43.7 (`packages/ui-kit`, upstream `7d39dbd`).

2
package-lock.json generated
View File

@@ -37536,7 +37536,7 @@
},
"packages/ui-kit": {
"name": "@omniroute/ui-kit",
"version": "0.0.116",
"version": "0.43.7",
"license": "UNLICENSED",
"peerDependencies": {
"lucide-react": ">=0.400.0 <2",

View File

@@ -1,10 +1,10 @@
# Upstream snapshot — @keak/cheaper-inference-ui-kit
- repo: https://github.com/keak-ai/cheaper-inference-ui-kit
- commit: 33891c6ec1738ec1e4682130c7911c54e67a4b22
- version: 0.0.116
- upstream-date: 2026-11-14
- synced: 2026-11-14
- commit: 7d39dbd23fed3bb445272a03e019c9e5b0313cdb
- version: 0.43.7
- upstream-date: 2026-11-20
- synced: 2026-11-20
- license-authorization: Diego Souza (Keak, dono do repositório), 2026-10-19, por escrito na sessão de planejamento: "a licença está ok e da nossa empresa e livre para esse uso" — kit da própria empresa, autorizado para redistribuição neste repositório MIT.
Fonte consumida (sem build): `src/` é cópia byte a byte do commit acima, exceto pela única

View File

@@ -1,6 +1,6 @@
{
"name": "@omniroute/ui-kit",
"version": "0.0.116",
"version": "0.43.7",
"private": true,
"license": "UNLICENSED",
"description": "Vendored snapshot of @keak/cheaper-inference-ui-kit (see UPSTREAM.md). Source is consumed directly; no build.",

View File

@@ -3,6 +3,7 @@
import { createContext, useCallback, useContext, useId, useRef, useState } from "react";
import type { ComponentProps, KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";
import { ChevronDown } from "lucide-react";
import { inertProps } from "./lib/inert";
import { cn } from "./lib/utils";
export type AccordionType = "single" | "multiple";
@@ -150,7 +151,7 @@ export function AccordionContent({ className, children, ...props }: ComponentPro
id={`${baseId}-content-${value}`}
aria-labelledby={`${baseId}-trigger-${value}`}
aria-hidden={!open}
inert={!open || undefined}
{...inertProps(!open)}
data-state={open ? "open" : "closed"}
className={cn("ci-accordion__content", className)}
>

View File

@@ -7,11 +7,17 @@ import { cn } from "./lib/utils";
export type AlertVariant = "default" | "info" | "success" | "warning" | "critical";
export type AlertPersistence = "temporary" | "persistent";
export type AlertSize = "sm" | "md";
export interface AlertProps extends Omit<ComponentProps<"div">, "title"> {
variant?: AlertVariant;
/** Compact banner with inline messages and actions that wrap on small screens. */
layout?: "stacked" | "inline";
/**
* `sm` is the compact notice for dialogs, table rows and nested panels: 12px text, a smaller icon,
* a reduced padding and a 24px dismiss button, in both layouts. The role does not change. Default `md`.
*/
size?: AlertSize;
icon?: ReactNode;
title?: ReactNode;
description?: ReactNode;
@@ -29,6 +35,7 @@ export function Alert({
className,
variant = "default",
layout = "stacked",
size = "md",
icon,
title,
description,
@@ -69,6 +76,7 @@ export function Alert({
data-slot="alert"
data-variant={variant}
data-layout={layout}
data-size={size === "sm" ? "sm" : undefined}
data-persistence={persistence}
className={cn("ci-alert", `ci-alert--${variant}`, className)}
{...props}

View File

@@ -1,8 +1,11 @@
"use client";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useEffect, useId, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { ChevronDown, ChevronLeft, ChevronRight, Megaphone, Minus } from "lucide-react";
import { brandTintVars } from "./brand-tint";
import { Button } from "./button";
import { inertProps } from "./lib/inert";
import { resolveLabels } from "./lib/labels";
export interface AnnouncementMediaState {
/** Pause timers/animations for dialogs and hidden/offscreen cards. */
@@ -18,9 +21,43 @@ export interface AnnouncementItem {
icon?: ReactNode;
actions?: ReactNode;
tone?: "neutral" | "accent" | "info" | "success" | "warning" | "violet";
/** A third-party brand as the slide's tint: `#rgb` or `#rrggbb`. Replaces `tone`; other values are ignored. */
brandColor?: string;
/** Decorative media only; the carousel makes this subtree inert and hides it from AT. */
media?: ReactNode | ((state: AnnouncementMediaState) => ReactNode);
}
/** Interface text of the carousel controls. The section name stays the `label` prop. */
export interface AnnouncementCarouselLabels {
/** Previous button accessible name. */
previous: string;
/** Next button accessible name. */
next: string;
/** Minimize button accessible name and tooltip. */
minimize: string;
/** Restore button accessible name and tooltip. */
restore: string;
/** Visible position counter. */
position: (current: number, total: number) => string;
/** Accessible name of the active slide, from the item's `label`. */
slide: (current: number, total: number, label: string) => string;
/** Accessible name of a dot, from the item's `label`. */
show: (label: string) => string;
/** `aria-roledescription` of the section. */
carousel: string;
/** `aria-roledescription` of the active slide. */
slideRole: string;
}
export const defaultAnnouncementCarouselLabels: AnnouncementCarouselLabels = {
previous: "Previous announcement",
next: "Next announcement",
minimize: "Minimize announcements",
restore: "Show announcements",
position: (current, total) => `${current} / ${total}`,
slide: (current, total, label) => `${current} of ${total}: ${label}`,
show: (label) => `Show ${label} announcement`,
carousel: "carousel",
slideRole: "slide",
};
export interface AnnouncementCarouselProps {
items: readonly AnnouncementItem[];
/** Minimize/restore is available by default. Set false to keep the section expanded. */
@@ -35,6 +72,8 @@ export interface AnnouncementCarouselProps {
label?: string;
/** The media variant places illustration/UI media beside copy, then above it on mobile. */
variant?: "compact" | "media";
/** Localized interface text; missing or `undefined` keys fall back to defaultAnnouncementCarouselLabels. */
labels?: Partial<AnnouncementCarouselLabels>;
}
/** Links, dialogs, eligibility and decorative scenes remain consumer-owned. */
@@ -47,7 +86,9 @@ export function AnnouncementCarousel({
interval = 5000,
label = "Announcements",
variant = "compact",
labels: labelOverrides,
}: AnnouncementCarouselProps) {
const labels = resolveLabels(defaultAnnouncementCarouselLabels, labelOverrides);
const root = useRef<HTMLElement>(null);
const contentId = useId();
const [internalCollapsed, setInternalCollapsed] = useState(false);
@@ -110,18 +151,22 @@ export function AnnouncementCarousel({
const move = (delta: number) =>
setActiveId(items[(active + delta + items.length) % items.length].id);
const rich = variant === "media";
// The restore button is a neutral surface, so the tint belongs to the expanded slide only.
const brand = minimized ? undefined : brandTintVars(current.brandColor);
const toggleLabel = minimized ? labels.restore : labels.minimize;
return (
<section
ref={root}
className={minimized ? "ci-announcements-collapsed" : "ci-announcements"}
className={minimized ? "ci-announcements-collapsed" : brand ? "ci-announcements ci-brand-tint" : "ci-announcements"}
style={brand as CSSProperties | undefined}
data-variant={variant}
data-tone={current.tone || "info"}
data-tone={brand ? "brand" : current.tone || "info"}
data-controls={
items.length > 1 || minimizable || undefined
}
data-collapsible={minimizable || undefined}
aria-label={label}
aria-roledescription={minimized ? undefined : "carousel"}
aria-roledescription={minimized ? undefined : labels.carousel}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
onFocusCapture={() => setFocused(true)}
@@ -133,14 +178,12 @@ export function AnnouncementCarousel({
<div className="ci-announcements__controls">
{!minimized && items.length > 1 && (
<>
<span>
{active + 1} / {items.length}
</span>
<span>{labels.position(active + 1, items.length)}</span>
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label="Previous announcement"
aria-label={labels.previous}
onClick={() => move(-1)}
>
<ChevronLeft aria-hidden />
@@ -149,7 +192,7 @@ export function AnnouncementCarousel({
type="button"
variant="ghost"
size="icon-xs"
aria-label="Next announcement"
aria-label={labels.next}
onClick={() => move(1)}
>
<ChevronRight aria-hidden />
@@ -163,10 +206,8 @@ export function AnnouncementCarousel({
type="button"
variant="ghost"
size={minimized ? "sm" : "icon-xs"}
aria-label={
minimized ? "Show announcements" : "Minimize announcements"
}
title={minimized ? "Show announcements" : "Minimize announcements"}
aria-label={toggleLabel}
title={toggleLabel}
aria-expanded={!minimized}
aria-controls={contentId}
onClick={() => changeCollapsed(!minimized)}
@@ -187,8 +228,8 @@ export function AnnouncementCarousel({
<div
className="ci-announcements__slide"
role="group"
aria-roledescription="slide"
aria-label={`${active + 1} of ${items.length}: ${current.label}`}
aria-roledescription={labels.slideRole}
aria-label={labels.slide(active + 1, items.length, current.label)}
>
{!rich && current.icon && (
<span className="ci-announcements__icon" aria-hidden>
@@ -199,7 +240,7 @@ export function AnnouncementCarousel({
<div
className="ci-announcements__media"
aria-hidden="true"
inert
{...inertProps(true)}
key={current.id}
data-paused={mediaPaused}
data-reduced-motion={reducedMotion}
@@ -230,7 +271,7 @@ export function AnnouncementCarousel({
<button
key={item.id}
type="button"
aria-label={`Show ${item.label} announcement`}
aria-label={labels.show(item.label)}
aria-current={index === active ? "true" : undefined}
onClick={() => setActiveId(item.id)}
/>

View File

@@ -55,9 +55,13 @@ export interface AvatarGroupProps extends ComponentProps<"div"> {
size?: AvatarSize;
shape?: AvatarShape;
max?: number;
/** Accessible name of the "+N" avatar shown past `max`. Defaults to "N more members". */
overflowLabel?: (count: number) => string;
}
export function AvatarGroup({ className, size = "md", shape = "circle", max, children, ...props }: AvatarGroupProps) {
const defaultAvatarGroupOverflowLabel = (count: number) => `${count} more members`;
export function AvatarGroup({ className, size = "md", shape = "circle", max, overflowLabel = defaultAvatarGroupOverflowLabel, children, ...props }: AvatarGroupProps) {
const items = Children.toArray(children).filter(isValidElement);
const shown = max != null ? items.slice(0, max) : items;
const overflow = items.length - shown.length;
@@ -73,7 +77,7 @@ export function AvatarGroup({ className, size = "md", shape = "circle", max, chi
))}
{overflow > 0 && (
<span className="ci-avatar-group__item">
<Avatar size={size} shape={shape} fallback={`+${overflow}`} aria-label={`${overflow} more members`} />
<Avatar size={size} shape={shape} fallback={`+${overflow}`} aria-label={overflowLabel(overflow)} />
</span>
)}
</div>

View File

@@ -6,19 +6,25 @@ export type BadgeVariant = "default" | "secondary" | "destructive" | "outline" |
export type BadgeShape = "rounded" | "pill" | "circle";
/** Semantic colour on a subtle tint with AA ink. Omit it to keep the variant's own colours. */
export type BadgeTone = "neutral" | "success" | "warning" | "info" | "danger" | "accent";
/** Chart-series colour: the series ink on its subtle tint, for a badge that names a series drawn in a chart. */
export type BadgeChartTone = "chart-1" | "chart-2" | "chart-3" | "chart-4" | "chart-5" | "chart-6" | "chart-7" | "chart-8";
/** `sm` is 20px tall for dense tables and card headers; the text stays at 12px. */
export type BadgeSize = "sm" | "md";
export function badgeVariants(
options: { variant?: BadgeVariant; shape?: BadgeShape; tone?: BadgeTone; className?: string } = {},
options: { variant?: BadgeVariant; shape?: BadgeShape; size?: BadgeSize; tone?: BadgeTone | BadgeChartTone; className?: string } = {},
): string {
const { variant = "default", shape = "rounded", tone, className } = options;
return cn("ci-badge", `ci-badge--${variant}`, `ci-badge--${shape}`, tone && `ci-badge--tone-${tone}`, className);
const { variant = "default", shape = "rounded", size = "md", tone, className } = options;
return cn("ci-badge", `ci-badge--${variant}`, `ci-badge--${shape}`, size === "sm" && "ci-badge--sm", tone && `ci-badge--tone-${tone}`, className);
}
export interface BadgeProps extends ComponentProps<"span"> {
variant?: BadgeVariant;
shape?: BadgeShape;
/** Status colour and tint, on any variant: `outline` also draws its border in the tone. */
tone?: BadgeTone;
/** `md` (24px) by default. `sm` is 20px tall with the same 12px text. */
size?: BadgeSize;
/** Status or chart-series colour and tint, on any variant: `outline` also draws its border in the tone. */
tone?: BadgeTone | BadgeChartTone;
icon?: ReactNode;
asChild?: boolean;
}
@@ -27,21 +33,25 @@ export function Badge({
className,
variant = "default",
shape = "rounded",
size = "md",
tone,
icon,
asChild = false,
children,
...props
}: BadgeProps) {
const classes = badgeVariants({ variant, shape, tone, className });
const classes = badgeVariants({ variant, shape, size, tone, className });
// The default size adds no class or attribute, so existing markup is unchanged.
const dataSize = size === "sm" ? size : undefined;
if (asChild && isValidElement(children)) {
const child = children as ReactElement<Record<string, unknown>>;
return cloneElement(child, {
...props,
...(dataSize ? { "data-size": dataSize } : {}),
...(tone ? { "data-tone": tone } : {}),
className: cn(classes, child.props.className as string | undefined),
children: <>{icon}{child.props.children as ReactNode}</>,
});
}
return <span data-slot="badge" data-variant={variant} data-shape={shape} data-tone={tone} className={classes} {...props}>{icon}{children}</span>;
return <span data-slot="badge" data-variant={variant} data-shape={shape} data-size={dataSize} data-tone={tone} className={classes} {...props}>{icon}{children}</span>;
}

View File

@@ -30,11 +30,16 @@ export function BreadcrumbSeparator({ className, children, ...props }: Component
);
}
export function BreadcrumbEllipsis({ className, ...props }: ComponentProps<"span">) {
export interface BreadcrumbEllipsisProps extends ComponentProps<"span"> {
/** Visually hidden text of the collapsed levels. Defaults to "More". */
label?: string;
}
export function BreadcrumbEllipsis({ className, label = "More", ...props }: BreadcrumbEllipsisProps) {
return (
<span aria-hidden="true" data-slot="breadcrumb-ellipsis" className={cn("ci-breadcrumb__ellipsis", className)} {...props}>
<MoreHorizontal />
<span className="ci-sr-only">More</span>
<span className="ci-sr-only">{label}</span>
</span>
);
}

View File

@@ -1,9 +1,12 @@
"use client";
import { Slot } from "@radix-ui/react-slot";
import { cloneElement, forwardRef, isValidElement } from "react";
import type { ButtonHTMLAttributes, ReactElement, ReactNode } from "react";
import type { ButtonHTMLAttributes, ReactElement, ReactNode, SyntheticEvent } from "react";
import { cn } from "./lib/utils";
import { SpinnerGraphic } from "./lib/spinner-graphic";
import { TooltipRoot } from "./lib/tooltip-root";
import { TooltipContent, TooltipTrigger, type TooltipSide } from "./tooltip";
export type ButtonVariant =
| "default"
@@ -16,25 +19,32 @@ export type ButtonVariant =
| "link"
| "assistant";
/** `2xs` and `icon-2xs` are the 24px dense sizes for row and inline actions. */
export type ButtonSize =
| "default"
| "2xs"
| "xs"
| "sm"
| "md"
| "lg"
| "icon"
| "icon-2xs"
| "icon-xs"
| "icon-sm"
| "icon-lg";
/** Quieter resting ink. Omit it to keep the variant's own colours. */
export type ButtonTone = "muted";
export function buttonVariants(
options: { variant?: ButtonVariant; size?: ButtonSize; className?: string } = {},
options: { variant?: ButtonVariant; size?: ButtonSize; tone?: ButtonTone; className?: string } = {},
): string {
const { variant = "default", size = "default", className } = options;
const { variant = "default", size = "default", tone, className } = options;
return cn(
"ci-button",
`ci-button--${variant}`,
`ci-button--size-${size}`,
tone && `ci-button--tone-${tone}`,
className,
);
}
@@ -42,33 +52,174 @@ export function buttonVariants(
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
size?: ButtonSize;
/**
* `muted` rests on the muted text colour and takes the variant's own hover, for secondary
* actions in rows and toolbars. It applies to `ghost`, `outline` and `secondary`.
*/
tone?: ButtonTone;
loading?: boolean;
/** Native form navigation must retain an enabled submitter until the browser serializes it. */
disableWhileLoading?: boolean;
asChild?: boolean;
/**
* Shows the kit Tooltip on hover and keyboard focus, with no element around the button. On an
* icon size, a string tooltip also names the button unless `aria-label` does. While `disabled`
* or `loading`, the button stays focusable (`aria-disabled` instead of `disabled`) so the
* tooltip can still be read; it runs no click, pointer-press or key handler and submits nothing.
*/
tooltip?: ReactNode;
/** The side of the button the tooltip opens on. Defaults to `top`. */
tooltipSide?: TooltipSide;
}
function ButtonSpinner() {
return <SpinnerGraphic className="ci-button__spinner" />;
}
function blockActivation(event: SyntheticEvent) {
event.preventDefault();
event.stopPropagation();
}
/**
* An inactive Button with a tooltip is not `disabled`, so that it can still be hovered and
* focused. These props make it act like a disabled one: no default action (submit, navigation,
* a middle-click on a link), no click reaching a parent, and none of the caller's activation
* handlers, in the capture phase either.
*/
const SOFT_DISABLED_PROPS = {
"aria-disabled": true,
"data-soft-disabled": "true",
onClick: blockActivation,
onAuxClick: blockActivation,
onDoubleClick: undefined,
onMouseDown: undefined,
onMouseUp: undefined,
onPointerDown: undefined,
onPointerUp: undefined,
onKeyDown: undefined,
onKeyUp: undefined,
onClickCapture: undefined,
onAuxClickCapture: undefined,
onDoubleClickCapture: undefined,
onMouseDownCapture: undefined,
onMouseUpCapture: undefined,
onPointerDownCapture: undefined,
onPointerUpCapture: undefined,
onKeyDownCapture: undefined,
onKeyUpCapture: undefined,
} as const;
interface TooltipTargetProps {
/** The tooltip's own id, set by the tooltip trigger while the tooltip is open. */
"aria-describedby"?: string;
/** The caller's `aria-describedby`. */
describedBy: string | undefined;
/** False when the tooltip only repeats the accessible name. */
describes: boolean;
children: ReactElement<Record<string, unknown>>;
}
/** Sits between the tooltip trigger and the button to merge the two `aria-describedby` values. */
const TooltipTarget = forwardRef<HTMLElement, TooltipTargetProps>(function TooltipTarget(
{ "aria-describedby": tooltipId, describedBy, describes, children, ...triggerProps },
ref,
) {
const ids = [describedBy, describes ? tooltipId : undefined].filter(Boolean).join(" ") || undefined;
return <Slot ref={ref} {...triggerProps}>{cloneElement(children, { "aria-describedby": ids })}</Slot>;
});
const asString = (value: unknown) => (typeof value === "string" ? value : undefined);
/**
* The text the children give the button, or undefined when the JSX alone does not tell: a
* component can render anything, and an element with a name of its own is not read by its text.
*/
function childText(node: ReactNode): string | undefined {
if (node == null || typeof node === "boolean") return "";
if (typeof node === "string" || typeof node === "number") return String(node);
if (Array.isArray(node)) {
let text = "";
for (const child of node) {
const part = childText(child);
if (part === undefined) return undefined;
text += part;
}
return text;
}
if (!isValidElement<Record<string, unknown>>(node)) return undefined;
const { props } = node;
// Hidden content is not part of the accessible name.
if (props["aria-hidden"] === true || props["aria-hidden"] === "true") return "";
if (props.hidden != null && props.hidden !== false) return "";
if (typeof node.type !== "string") return undefined;
// An explicit name wins over alt and over the text inside, and it is not read here.
if (props["aria-label"] != null || props["aria-labelledby"] != null || props.title != null) return undefined;
if (node.type === "img") return typeof props.alt === "string" ? props.alt : undefined;
return childText(props.children as ReactNode);
}
/** `tooltip=""` and `tooltip={condition && "…"}` mean no tooltip, as they render nothing. */
const hasContent = (node: ReactNode) => node != null && typeof node !== "boolean" && node !== "";
/**
* Wraps the rendered button in the kit tooltip, which adds no element. `own` is what the element
* was rendered with: it tells whether the tooltip names the button, repeats its name or describes it.
*/
function attachTooltip(
element: ReactElement<Record<string, unknown>>,
own: Record<string, unknown>,
tooltip: ReactNode,
side: TooltipSide | undefined,
iconOnly: boolean,
) {
const text = asString(tooltip)?.trim();
const named = own["aria-label"] != null || own["aria-labelledby"] != null;
// An icon-only button with no name of its own takes a string tooltip as its name.
const fallbackLabel = iconOnly && !named && text ? text : undefined;
// The name the button has without the tooltip: aria-label wins over the text of the children.
// It is undefined when it cannot be read here (aria-labelledby, a component child): the tooltip
// then stays a description, since dropping it by a guess would hide what it adds.
const ownName = own["aria-labelledby"] != null
? undefined
: asString(own["aria-label"])?.trim() ?? childText(own.children as ReactNode)?.replace(/\s+/g, " ").trim();
const repeatsName = text !== undefined && (fallbackLabel !== undefined || ownName === text);
return (
<TooltipRoot>
<TooltipTrigger asChild>
<TooltipTarget describedBy={asString(own["aria-describedby"])} describes={!repeatsName}>
{fallbackLabel ? cloneElement(element, { "aria-label": fallbackLabel }) : element}
</TooltipTarget>
</TooltipTrigger>
<TooltipContent side={side}>{tooltip}</TooltipContent>
</TooltipRoot>
);
}
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
{
className,
variant = "default",
size = "default",
tone,
loading = false,
disableWhileLoading = true,
disabled,
asChild = false,
children,
tooltip,
tooltipSide,
...props
},
ref,
) {
const classes = buttonVariants({ variant, size, className });
const classes = buttonVariants({ variant, size, tone, className });
const inactive = disabled || (loading && disableWhileLoading);
const iconOnly = size.startsWith("icon");
const hasTooltip = hasContent(tooltip);
const softDisabled = hasTooltip && inactive ? SOFT_DISABLED_PROPS : undefined;
const withTooltip = (element: ReactElement<Record<string, unknown>>, own: Record<string, unknown>) =>
hasTooltip ? attachTooltip(element, own, tooltip, tooltipSide, iconOnly) : element;
const content = (
<>
{loading && <ButtonSpinner />}
@@ -78,10 +229,12 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
if (asChild && isValidElement(children)) {
const child = children as ReactElement<Record<string, unknown>>;
return cloneElement(child, {
return withTooltip(cloneElement(child, {
...props,
...(tone ? { "data-tone": tone } : {}),
"aria-busy": loading || undefined,
"aria-disabled": inactive || undefined,
...softDisabled,
className: cn(classes, child.props.className as string | undefined),
children: loading ? (
<>
@@ -91,22 +244,25 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
) : (
(child.props.children as ReactNode)
),
});
}), { ...child.props, ...props });
}
return (
return withTooltip(
<button
ref={ref}
data-slot="button"
data-variant={variant}
data-size={size}
data-tone={tone}
data-loading={loading || undefined}
aria-busy={loading || undefined}
className={classes}
disabled={inactive}
disabled={softDisabled ? undefined : inactive}
{...props}
{...softDisabled}
>
{content}
</button>
</button>,
{ ...props, children },
);
});

View File

@@ -3,6 +3,7 @@
import { useMemo, useRef, useState } from "react";
import type { ComponentProps, CSSProperties, KeyboardEvent } from "react";
import { EmptyState } from "./empty-state";
import { heatLevel } from "./heat-cell";
import { cn } from "./lib/utils";
export interface CalendarHeatmapDatum {
@@ -56,12 +57,6 @@ function dayTime(date: string | undefined) {
return Number.isFinite(time) && new Date(time).toISOString().slice(0, 10) === date ? time : null;
}
function levelFor(value: number | null, maximum: number, thresholds?: readonly number[]) {
if (value === null || value <= 0) return 0;
if (thresholds) return Math.min(7, 1 + thresholds.filter(bound => value >= bound).length);
return Math.max(1, Math.min(7, Math.ceil((value / maximum) * 7)));
}
function buildDays(data: readonly CalendarHeatmapDatum[], startDate?: string, endDate?: string, thresholds?: readonly number[]) {
const valid = data.flatMap(datum => {
const time = dayTime(datum.date);
@@ -76,7 +71,7 @@ function buildDays(data: readonly CalendarHeatmapDatum[], startDate?: string, en
const time = start + index * DAY;
const datum = byTime.get(time);
const value = datum?.value ?? null;
return { date: new Date(time).toISOString().slice(0, 10), time, value, hint: datum?.hint, level: levelFor(value, maximum, thresholds) };
return { date: new Date(time).toISOString().slice(0, 10), time, value, hint: datum?.hint, level: heatLevel(value, maximum, thresholds) ?? 0 };
});
}

View File

@@ -3,16 +3,22 @@ import { brandTintVars } from "./brand-tint";
import { cn } from "./lib/utils";
export type CardFooterAlign = "start" | "between" | "end";
export type CardSurface = "default" | "subtle" | "inset";
export interface CardProps extends Omit<ComponentProps<"div">, "title"> {
title?: ReactNode;
description?: ReactNode;
action?: ReactNode;
footer?: ReactNode;
footerAlign?: CardFooterAlign;
/** Renders `children` edge to edge instead of inside the padded content slot. */
flush?: boolean;
/** A subtle neutral gradient for grouped secondary actions. */
surface?: "default" | "subtle";
/** A third-party brand as a tint: `#rgb` or `#rrggbb`. Replaces `surface`; other values are ignored. */
/**
* `subtle`: a neutral gradient for grouped secondary actions.
* `inset`: a flat, compact panel for one level of nesting inside a card or dialog. It pads itself,
* so children need no `CardContent` wrapper.
*/
surface?: CardSurface;
/** A third-party brand as a tint: `#rgb` or `#rrggbb`. Replaces the `subtle` gradient and recolours an inset; other values are ignored. */
brandColor?: string;
}
@@ -20,8 +26,9 @@ export function Card({ className, title, description, action, footer, footerAlig
const brand = brandTintVars(brandColor);
const hasHeader = title != null || description != null || action != null;
const structured = hasHeader || footer != null;
const inset = surface === "inset";
return (
<div data-slot="card" data-surface={surface === "subtle" && !brand ? surface : undefined} className={cn("ci-card", brand && "ci-brand-tint", className)} style={brand ? { ...brand, ...style } as CSSProperties : style} {...props}>
<div data-slot="card" data-surface={inset || (surface === "subtle" && !brand) ? surface : undefined} data-flush={inset && flush ? "" : undefined} className={cn("ci-card", brand && "ci-brand-tint", className)} style={brand ? { ...brand, ...style } as CSSProperties : style} {...props}>
{hasHeader && <CardHeader>{title != null && <CardTitle>{title}</CardTitle>}{description != null && <CardDescription>{description}</CardDescription>}{action != null && <CardAction>{action}</CardAction>}</CardHeader>}
{structured && !flush ? <CardContent>{children}</CardContent> : children}
{footer != null && <CardFooter align={footerAlign}>{footer}</CardFooter>}

View File

@@ -2,6 +2,7 @@
import { useEffect, useId, useMemo, useRef, useState } from "react";
import type { ComponentProps } from "react";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
export interface ChartDatum {
@@ -14,6 +15,23 @@ export interface ChartDatum {
export type ChartVariant = "area" | "bar";
export type ChartTone = "accent" | "positive" | "ink";
/** Interface text of the chart beyond `ariaLabel` and the data labels. */
export interface ChartLabels {
/** Label of the single placeholder point drawn when `data` is empty. */
noData: string;
/** Accessible name of the interactive point group, from `ariaLabel`. */
dataPoints: (ariaLabel: string) => string;
/** Column headers of the hidden data table. */
labelColumn: string;
valueColumn: string;
}
export const defaultChartLabels: ChartLabels = {
noData: "No data",
dataPoints: (ariaLabel) => `${ariaLabel} interactive data points`,
labelColumn: "Label",
valueColumn: "Value",
};
export interface ChartProps extends Omit<ComponentProps<"figure">, "children"> {
data: readonly ChartDatum[];
variant?: ChartVariant;
@@ -25,6 +43,8 @@ export interface ChartProps extends Omit<ComponentProps<"figure">, "children"> {
animate?: boolean;
height?: number;
ariaLabel: string;
/** Localized interface text; missing or `undefined` keys fall back to defaultChartLabels. */
labels?: Partial<ChartLabels>;
}
const VIEWBOX_WIDTH = 720;
@@ -64,8 +84,10 @@ export function Chart({
animate = true,
height = 280,
ariaLabel,
labels: labelOverrides,
...props
}: ChartProps) {
const labels = resolveLabels(defaultChartLabels, labelOverrides);
const figureRef = useRef<HTMLElement | null>(null);
const [visible, setVisible] = useState(!animate);
const [activeIndex, setActiveIndex] = useState<number | null>(null);
@@ -99,7 +121,7 @@ export function Chart({
}, [animate, data]);
const geometry = useMemo(() => {
const safeData: readonly ChartDatum[] = data.length ? data : [{ label: "No data", value: 0 }];
const safeData: readonly ChartDatum[] = data.length ? data : [{ label: labels.noData, value: 0 }];
const chartHeight = Math.max(height, 180);
const plotWidth = VIEWBOX_WIDTH - PADDING.left - PADDING.right;
const plotHeight = chartHeight - PADDING.top - PADDING.bottom;
@@ -123,7 +145,7 @@ export function Chart({
});
const labelEvery = Math.max(1, Math.ceil(safeData.length / Math.max(xTickCount, 1)));
return { safeData, chartHeight, plotWidth, plotHeight, points, linePath, areaPath, ticks, labelEvery, baseline };
}, [data, height, xTickCount, yTickCount]);
}, [data, height, labels.noData, xTickCount, yTickCount]);
const barSlot = geometry.plotWidth / geometry.safeData.length;
const barWidth = Math.min(30, barSlot * 0.58);
@@ -148,7 +170,7 @@ export function Chart({
<svg
viewBox={`0 0 ${VIEWBOX_WIDTH} ${geometry.chartHeight}`}
role="group"
aria-label={`${ariaLabel} interactive data points`}
aria-label={labels.dataPoints(ariaLabel)}
>
<defs>
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
@@ -275,7 +297,7 @@ export function Chart({
) : null}
<table className="ci-sr-only" aria-hidden="true">
<caption>{ariaLabel}</caption>
<thead><tr><th>Label</th><th>Value</th></tr></thead>
<thead><tr><th>{labels.labelColumn}</th><th>{labels.valueColumn}</th></tr></thead>
<tbody>{data.map((item) => <tr key={item.label}><td>{item.label}</td><td>{valueFormatter(item.value)}</td></tr>)}</tbody>
</table>
</figure>

View File

@@ -0,0 +1,75 @@
"use client";
import { useId, type ComponentProps } from "react";
import { ArrowRight, Check, MousePointer2, RotateCcw, ThumbsUp } from "lucide-react";
import { Button } from "./button";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
export interface ChatGuideCardLabels {
/** Text of the eyebrow, before the step count. */
eyebrow: string;
/** Step count of the eyebrow, with its noun. */
stepCount: (count: number) => string;
}
export const defaultChatGuideCardLabels: ChatGuideCardLabels = {
eyebrow: "On-screen walkthrough",
stepCount: (count) => `${count} ${count === 1 ? "step" : "steps"}`,
};
export interface ChatGuideCardProps extends Omit<ComponentProps<"section">, "title"> {
title: string;
stepCount: number;
onStart: () => void;
actionLabel?: string;
description?: string;
note?: string;
disabled?: boolean;
/** Localized text of the eyebrow; omitted or `undefined` keys fall back to defaultChatGuideCardLabels. */
labels?: Partial<ChatGuideCardLabels>;
}
/** A discoverable invitation to an application-owned walkthrough. Starting it never submits a form. */
export function ChatGuideCard({ title, stepCount, onStart, actionLabel = "Guide me step by step", description = "Follow the highlights to see exactly where to click.", note = "You review and submit any changes.", disabled, labels: labelOverrides, className, ...props }: ChatGuideCardProps) {
const id = useId();
const labels = resolveLabels(defaultChatGuideCardLabels, labelOverrides);
return <section {...props} aria-labelledby={id} className={cn("ci-chat-guide-card", className)}>
<div className="ci-chat-guide-card__heading">
<span className="ci-chat-guide-card__icon" aria-hidden="true"><MousePointer2 size={19} /></span>
<div>
<p className="ci-chat-guide-card__eyebrow">{labels.eyebrow} <span aria-hidden="true">·</span> {labels.stepCount(stepCount)}</p>
<h2 id={id}>{title}</h2>
</div>
</div>
<p className="ci-chat-guide-card__description">{description}</p>
<Button type="button" variant="assistant" onClick={onStart} disabled={disabled} className="ci-chat-guide-card__action">{actionLabel}<ArrowRight size={17} aria-hidden="true" /></Button>
<p className="ci-chat-guide-card__note">{note}</p>
</section>;
}
export type ChatFeedbackStatus = "idle" | "pending" | "success" | "error";
export interface ChatFeedbackProps extends Omit<ComponentProps<"div">, "onChange"> {
helpful?: boolean;
status?: ChatFeedbackStatus;
onHelpful: (helpful: boolean) => void;
labels?: { helpful?: string; markedHelpful?: string; sending?: string; retry?: string; removeHelpful?: string; thanks?: string; cleared?: string; error?: string };
}
/** Controlled feedback with a visible selection, live confirmation and recoverable error. */
export function ChatFeedback({ helpful = false, status = "idle", onHelpful, labels = {}, className, ...props }: ChatFeedbackProps) {
const messageId = useId();
const { helpful: helpfulLabel = "Helpful", markedHelpful = "Marked helpful", sending = "Sending feedback…", retry = "Try again", removeHelpful = "Remove helpful feedback", thanks = "Thanks for your feedback.", cleared = "Feedback cleared.", error = "Couldn’t send feedback. Please try again." } = labels;
const pending = status === "pending";
const failed = status === "error";
return <div {...props} className={cn("ci-chat-feedback", className)}>
<Button type="button" variant="ghost" size="sm" loading={pending} disabled={pending} aria-pressed={helpful} aria-describedby={status === "idle" ? undefined : messageId} aria-label={helpful && !pending && !failed ? `${markedHelpful}. ${removeHelpful}` : undefined} data-selected={helpful || undefined} className="ci-chat-feedback__button" onClick={() => onHelpful(!helpful)}>
{failed ? <RotateCcw size={15} aria-hidden="true" /> : <ThumbsUp size={15} aria-hidden="true" />}
{pending ? sending : failed ? retry : helpful ? markedHelpful : helpfulLabel}
</Button>
<span id={messageId} role={failed ? "alert" : "status"} className="ci-chat-feedback__message" data-error={failed || undefined}>
{status === "success" && <><Check size={14} aria-hidden="true" />{helpful ? thanks : cleared}</>}
{failed && error}
</span>
</div>;
}

View File

@@ -1,12 +1,13 @@
"use client";
import { forwardRef, useId } from "react";
import { forwardRef, useId, useState } from "react";
import type { ComponentProps, ReactNode } from "react";
import { AlignLeft, ArrowLeft, ArrowUp, Check, ChevronDown, Copy, History, Menu, MoreVertical, Pencil, Plus, RotateCcw, Square, SquarePen, ThumbsUp, Trash2, X } from "lucide-react";
import { Button } from "./button";
import { Badge } from "./badge";
import { Textarea } from "./textarea";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "./dropdown-menu";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
export interface ChatHeaderProps extends Omit<ComponentProps<"header">, "title"> {
@@ -106,6 +107,8 @@ export interface ChatComposerProps extends Omit<ComponentProps<"form">, "onChang
onAttach?: () => void;
attachLabel?: string;
attachments?: readonly ChatAttachment[];
/** Accessible name of the attachment list. Defaults to "Attachments". */
attachmentsLabel?: string;
onRemoveAttachment?: (id: string) => void;
removeAttachmentLabel?: (attachment: ChatAttachment) => string;
tools?: ReactNode;
@@ -116,13 +119,13 @@ export interface ChatComposerProps extends Omit<ComponentProps<"form">, "onChang
/** A controlled editor. Transport, file selection/uploads and draft persistence stay in the app. */
export const ChatComposer = forwardRef<HTMLTextAreaElement, ChatComposerProps>(function ChatComposer({
value, onValueChange, onSend, placeholder, label = "Ask a question", sendLabel = "Send question", onStop, stopLabel = "Stop response", disabled = false, busy = false, sendDisabled = false, allowEmpty = false,
onAttach, attachLabel = "Attach file", attachments = [], onRemoveAttachment, removeAttachmentLabel = item => `Remove ${item.name}`, tools, footer, error, textareaProps, className, ...props
onAttach, attachLabel = "Attach file", attachments = [], attachmentsLabel = "Attachments", onRemoveAttachment, removeAttachmentLabel = item => `Remove ${item.name}`, tools, footer, error, textareaProps, className, ...props
}, ref) {
const errorId = useId();
const canSend = !disabled && !busy && !sendDisabled && (allowEmpty || !!value.trim());
function send() { if (canSend) onSend(value.trim()); }
return <form className={cn("ci-chat-composer", className)} aria-busy={busy || undefined} {...props} onSubmit={event => { event.preventDefault(); send(); }}>
{!!attachments.length && <ul className="ci-chat-composer__attachments" aria-label="Attachments">{attachments.map(item => <li key={item.id}>
{!!attachments.length && <ul className="ci-chat-composer__attachments" aria-label={attachmentsLabel}>{attachments.map(item => <li key={item.id}>
<Badge variant="outline" className="ci-chat-composer__attachment">
{item.icon != null && <span aria-hidden>{item.icon}</span>}
<span className="ci-chat-composer__filename" title={item.name}>{item.name}</span>
@@ -173,6 +176,29 @@ export function ChatMessage({ kind, author = kind === "user" ? "You" : "Assistan
</article>;
}
export type ChatActivityState = "thinking" | "checking" | "streaming" | "complete" | "stopped" | "error" | "empty";
/** Status text of ChatActivity. `children` still replaces the whole status; `stopLabel` and `retryLabel` stay separate props. */
export interface ChatActivityLabels {
/** The thinking and checking states. */
thinking: string;
/** The streaming and complete states when `elapsed` is set. */
workedFor: (elapsed: ReactNode) => ReactNode;
/** The streaming and complete states without `elapsed`. */
activity: string;
stopped: string;
error: string;
empty: string;
/** Tooltip of the elapsed time shown while thinking. */
elapsedTitle: string;
}
export const defaultChatActivityLabels: ChatActivityLabels = {
thinking: "Thinking…",
workedFor: (elapsed) => <>Worked for {elapsed}</>,
activity: "Activity",
stopped: "Response stopped",
error: "Could not complete the response",
empty: "No response received",
elapsedTitle: "Elapsed thinking time",
};
export interface ChatActivityProps extends Omit<ComponentProps<"div">, "children"> {
state: ChatActivityState;
children?: ReactNode;
@@ -180,6 +206,8 @@ export interface ChatActivityProps extends Omit<ComponentProps<"div">, "children
summary?: ReactNode;
/** Optional accessible name for the disclosure; otherwise its visible label is used. */
summaryLabel?: string;
/** Start expanded; subsequent user toggles survive activity updates. */
defaultSummaryOpen?: boolean;
/** Caller-formatted elapsed time, e.g. "0:03". No clock is started or inferred here. */
elapsed?: ReactNode;
footer?: ReactNode;
@@ -187,22 +215,26 @@ export interface ChatActivityProps extends Omit<ComponentProps<"div">, "children
onRetry?: () => void;
stopLabel?: string;
retryLabel?: string;
/** Localized status text; missing or `undefined` keys fall back to defaultChatActivityLabels. */
labels?: Partial<ChatActivityLabels>;
}
export function ChatActivity({ state, children, summary, summaryLabel, elapsed, footer, onStop, onRetry, stopLabel = "Stop response", retryLabel = "Try again", className, ...props }: ChatActivityProps) {
export function ChatActivity({ state, children, summary, summaryLabel, defaultSummaryOpen = false, elapsed, footer, onStop, onRetry, stopLabel = "Stop response", retryLabel = "Try again", labels: labelOverrides, className, ...props }: ChatActivityProps) {
const text = resolveLabels(defaultChatActivityLabels, labelOverrides);
const [summaryOpen, setSummaryOpen] = useState(defaultSummaryOpen);
const thinking = state === "thinking" || state === "checking";
const active = thinking || state === "streaming";
const labels: Record<ChatActivityState, ReactNode> = {
thinking: "Thinking…", checking: "Thinking…",
streaming: elapsed != null ? <>Worked for {elapsed}</> : "Activity",
complete: elapsed != null ? <>Worked for {elapsed}</> : "Activity",
stopped: "Response stopped", error: "Could not complete the response", empty: "No response received",
thinking: text.thinking, checking: text.thinking,
streaming: elapsed != null ? text.workedFor(elapsed) : text.activity,
complete: elapsed != null ? text.workedFor(elapsed) : text.activity,
stopped: text.stopped, error: text.error, empty: text.empty,
};
const activityLabel = <>
<span className={thinking ? "ci-chat-activity__thinking" : "ci-chat-activity__label"} role={state === "error" ? "alert" : thinking || state === "stopped" || state === "empty" ? "status" : undefined}>{children ?? labels[state]}</span>
{thinking && elapsed != null && <span className="ci-chat-activity__elapsed" title="Elapsed thinking time" aria-hidden="true">{elapsed}</span>}
{thinking && elapsed != null && <span className="ci-chat-activity__elapsed" title={text.elapsedTitle} aria-hidden="true">{elapsed}</span>}
</>;
return <div className={cn("ci-chat-activity", className)} data-state={state} data-has-summary={summary != null || undefined} {...props}>
{summary != null ? <details className="ci-chat-activity__details">
{summary != null ? <details className="ci-chat-activity__details" open={summaryOpen} onToggle={event => setSummaryOpen(event.currentTarget.open)}>
<summary className="ci-chat-activity__header" aria-label={summaryLabel}>{activityLabel}<ChevronDown size={18} strokeWidth={2} className="ci-chat-activity__chevron" aria-hidden="true" /></summary>
<div className="ci-chat-activity__summary">{summary}</div>
</details> : <div className="ci-chat-activity__header">{activityLabel}</div>}

View File

@@ -6,23 +6,26 @@
.ci-announcements[data-tone="success"] { --ci-announcement-tone:var(--ci-color-success); }
.ci-announcements[data-tone="warning"] { --ci-announcement-tone:var(--ci-color-warning); }
.ci-announcements[data-tone="violet"] { --ci-announcement-tone:var(--ci-chart-3); }
/* A third-party brand (item.brandColor): only the tint, border and ink that .ci-brand-tint derives, never the raw hex. */
.ci-announcements[data-tone="brand"] { --ci-announcement-tone:var(--ci-brand); border-color:var(--ci-brand-border); background:linear-gradient(115deg,var(--ci-brand-subtle),var(--ci-color-surface) 72%); }
.ci-announcements[data-tone="brand"] .ci-announcements__icon { border-color:var(--ci-brand-border); background:var(--ci-brand-subtle); color:var(--ci-brand-ink); }
.ci-announcements-collapsed { display:block; width:100%; }
.ci-announcements-collapsed .ci-announcements__controls { position:static; display:block; width:100%; margin:0; }
.ci-announcements-collapsed .ci-announcements__controls .ci-announcements__restore { width:100%; height:3rem; min-height:3rem; justify-content:flex-start; gap:.625rem; padding:0 1rem; border:1px solid var(--ci-color-border); border-radius:var(--ci-radius-md); background:var(--ci-color-surface); color:var(--ci-color-heading); }
.ci-announcements-collapsed .ci-announcements__controls .ci-announcements__restore:hover { background:var(--ci-color-surface-muted); }
.ci-announcements__restore-label { flex:1; min-width:0; text-align:left; }
.ci-announcements__restore-label { flex:1; min-width:0; text-align:start; }
.ci-announcements__restore svg { width:1.125rem; height:1.125rem; color:var(--ci-color-text-muted); }
.ci-announcements__restore-chevron { margin-left:auto; }
.ci-announcements[data-collapsible] .ci-announcements__copy h2 { padding-right:9rem; }
.ci-announcements__restore-chevron { margin-inline-start:auto; }
.ci-announcements[data-collapsible] .ci-announcements__copy h2 { padding-inline-end:9rem; }
.ci-announcements__top { display:contents; }
.ci-announcements__controls { position:absolute; right:1.125rem; top:1rem; display:flex; align-items:center; gap:.25rem; font-size:.75rem; color:var(--ci-color-text-muted); }
.ci-announcements__controls > span { margin-right:.5rem; font-variant-numeric:tabular-nums; }
.ci-announcements__controls { position:absolute; inset-inline-end:1.125rem; top:1rem; display:flex; align-items:center; gap:.25rem; font-size:.75rem; color:var(--ci-color-text-muted); }
.ci-announcements__controls > span { margin-inline-end:.5rem; font-variant-numeric:tabular-nums; }
.ci-announcements__slide { display:flex; align-items:flex-start; gap:1rem; min-height:8.25rem; }
.ci-announcements__icon { display:grid; place-items:center; width:2.75rem; height:2.75rem; flex-shrink:0; border:1px solid color-mix(in srgb,var(--ci-announcement-tone) var(--ci-announcement-icon-border,0%),var(--ci-color-border-subtle)); border-radius:var(--ci-radius-surface); background:color-mix(in srgb,var(--ci-announcement-tone) var(--ci-announcement-icon,10%),var(--ci-color-surface)); color:color-mix(in srgb,var(--ci-announcement-tone) var(--ci-announcement-ink,0%),var(--ci-color-heading)); }
.ci-announcements__icon svg { width:1.625rem; height:1.625rem; }
.ci-announcements__copy { flex:1; min-width:0; }
.ci-announcements__copy h2 { margin:0 0 .375rem; font:400 1.875rem/1.2 var(--ci-font-display); color:var(--ci-color-heading); overflow-wrap:anywhere; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-announcements[data-controls] .ci-announcements__copy h2 { padding-right:6.875rem; }
.ci-announcements[data-controls] .ci-announcements__copy h2 { padding-inline-end:6.875rem; }
.ci-announcements__copy p { margin:0; max-width:45rem; font-size:.875rem; line-height: var(--ci-type-body-leading); color:var(--ci-color-text-muted); font-weight: var(--ci-font-weight-regular); letter-spacing: var(--ci-type-body-tracking); }
.ci-announcements__actions { display:flex; flex-wrap:wrap; align-items:center; gap:.625rem; margin-top:.75rem; min-height:2.25rem; }
.ci-announcements__dots { display:flex; justify-content:center; align-items:center; gap:.25rem; margin-top:.25rem; }
@@ -34,12 +37,12 @@
.ci-announcements { padding:1rem; }
.ci-announcements__top { display:flex; align-items:center; justify-content:space-between; gap:1rem; width:100%; }
.ci-announcements__top:empty { display:none; }
.ci-announcements__controls { position:static; justify-content:flex-end; margin-left:auto; }
.ci-announcements__controls { position:static; justify-content:flex-end; margin-inline-start:auto; }
.ci-announcements__controls .ci-button { width:2.75rem; height:2.75rem; }
.ci-announcements__slide { flex-direction:column; gap:1rem; min-height:0; }
.ci-announcements__copy { width:100%; }
.ci-announcements__icon { width:2.25rem; height:2.25rem; }
.ci-announcements .ci-announcements__copy h2 { padding-right:0; font-size:1.75rem; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-announcements .ci-announcements__copy h2 { padding-inline-end:0; font-size:1.75rem; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-announcements__actions { align-items:stretch; }
.ci-announcements__actions > .ci-button { width:100%; min-height:2.75rem; white-space:normal; }
.ci-announcements__dots { margin-top:.75rem; }
@@ -53,24 +56,25 @@
.ci-announcements[data-variant="media"][data-tone="success"] { --ci-announcement-tone:var(--ci-color-announcement-success); }
.ci-announcements[data-variant="media"][data-tone="violet"] { --ci-announcement-tone:var(--ci-color-announcement-violet); }
.ci-announcements[data-variant="media"][data-tone="warning"] { --ci-announcement-tone:var(--ci-color-announcement-warning); }
.ci-announcements[data-variant="media"][data-tone="brand"] { --ci-announcement-tone:var(--ci-brand); border-color:var(--ci-brand-border); background:linear-gradient(110deg,var(--ci-brand-subtle),var(--ci-color-surface) 92%); }
.ci-announcements[data-variant="media"] { padding:0; overflow:hidden; border-radius:var(--ci-radius-md); background:linear-gradient(110deg,color-mix(in srgb,var(--ci-announcement-tone) 7%,var(--ci-color-surface)),var(--ci-color-surface) 92%); }
.ci-announcements[data-variant="media"] .ci-announcements__slide { display:grid; align-items:stretch; grid-template-columns:30% minmax(0,1fr); gap:0; min-height:258px; }
.ci-announcements[data-variant="media"] .ci-announcements__top { display:contents; }
.ci-announcements__media { display:grid; align-items:center; min-width:0; overflow:hidden; pointer-events:none; background:linear-gradient(145deg,color-mix(in srgb,var(--ci-announcement-tone) 10%,transparent),transparent); border-right:1px solid color-mix(in srgb,var(--ci-announcement-tone) 10%,transparent); }
.ci-announcements__media { display:grid; align-items:center; min-width:0; overflow:hidden; pointer-events:none; background:linear-gradient(145deg,color-mix(in srgb,var(--ci-announcement-tone) 10%,transparent),transparent); border-inline-end:1px solid color-mix(in srgb,var(--ci-announcement-tone) 10%,transparent); }
.ci-announcements__media-content { width:100%; padding:18px 24px; }
.ci-announcements__media[data-paused="true"] * { animation-play-state:paused !important; }
.ci-announcements__media[data-reduced-motion="true"] * { animation:none !important; transition:none !important; }
.ci-announcements[data-variant="media"] .ci-announcements__copy { align-self:center; min-width:0; padding:42px 34px 49px; }
.ci-announcements[data-variant="media"] .ci-announcements__copy h2 { padding-right:12px; margin:0 0 10px; font-size:30px; line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); font-weight: var(--ci-font-weight-medium); }
.ci-announcements[data-variant="media"] .ci-announcements__copy h2 { padding-inline-end:12px; margin:0 0 10px; font-size:30px; line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); font-weight: var(--ci-font-weight-medium); }
.ci-announcements[data-variant="media"] .ci-announcements__copy p { max-width:690px; line-height: var(--ci-type-body-leading); font-weight: var(--ci-font-weight-regular); letter-spacing: var(--ci-type-body-tracking); }
.ci-announcements[data-variant="media"] .ci-announcements__actions { gap:14px; margin-top:17px; }
.ci-announcements[data-variant="media"] .ci-announcements__controls { position:absolute; top:8px; right:12px; gap:4px; margin:0; z-index:1; }
.ci-announcements[data-variant="media"] .ci-announcements__controls { position:absolute; top:8px; inset-inline-end:12px; gap:4px; margin:0; z-index:1; }
.ci-announcements[data-variant="media"] .ci-announcements__controls .ci-button { width:32px; height:32px; }
.ci-announcements[data-variant="media"] .ci-announcements__dots { position:absolute; left:calc(30% + 26px); bottom:4px; margin:0; gap:0; }
:where(.dark,[data-theme="dark"]) .ci-announcements[data-variant="media"] { background:linear-gradient(110deg,color-mix(in srgb,var(--ci-announcement-tone) 18%,var(--ci-color-surface)),var(--ci-color-surface)); border-color:color-mix(in srgb,var(--ci-announcement-tone) 23%,var(--ci-color-border)); }
:where(.dark,[data-theme="dark"]) .ci-announcements__media { background:linear-gradient(140deg,color-mix(in srgb,var(--ci-announcement-tone) 9%,transparent),transparent); }
@media(max-width:1200px) {
.ci-announcements[data-variant="media"] .ci-announcements__copy { padding-left:26px; padding-right:24px; }
.ci-announcements[data-variant="media"] .ci-announcements__copy { padding-inline-start:26px; padding-inline-end:24px; }
.ci-announcements[data-variant="media"] .ci-announcements__copy h2 { font-size:28px; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-announcements__media-content { padding-inline:13px; }
.ci-announcements[data-variant="media"] .ci-announcements__dots { left:calc(30% + 18px); }
@@ -84,11 +88,11 @@
}
@media(max-width:640px) {
.ci-announcements[data-variant="media"] .ci-announcements__slide { display:flex; flex-direction:column; min-height:0; }
.ci-announcements__media { width:100%; border-right:0; border-bottom:1px solid var(--ci-color-border-subtle); }
.ci-announcements__media { width:100%; border-inline-end:0; border-bottom:1px solid var(--ci-color-border-subtle); }
.ci-announcements__media-content { padding:44px 20px 20px; }
.ci-announcements[data-variant="media"] .ci-announcements__copy { width:100%; padding:22px 20px 62px; }
.ci-announcements[data-variant="media"] .ci-announcements__copy h2 { padding:0; font-size:30px; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-announcements[data-variant="media"] .ci-announcements__controls { top:4px; right:12px; }
.ci-announcements[data-variant="media"] .ci-announcements__controls { top:4px; inset-inline-end:12px; }
.ci-announcements[data-variant="media"] .ci-announcements__controls .ci-button { width:40px; height:40px; }
.ci-announcements[data-variant="media"] .ci-announcements__actions { margin-top:18px; }
.ci-announcements[data-variant="media"] .ci-announcements__dots { left:50%; bottom:7px; transform:translateX(-50%); }

View File

@@ -135,6 +135,7 @@
--ci-radius-2xl: 1.5rem;
--ci-radius-control: var(--ci-radius-md);
--ci-radius-surface: var(--ci-radius-lg);
--ci-radius-surface-nested: var(--ci-radius-md);
--ci-radius-pill: var(--ci-radius-full);
--ci-shadow-xs: none;
--ci-shadow-sm: none;
@@ -156,6 +157,9 @@
--ci-sidebar-fg: var(--ci-color-foreground);
--ci-sidebar-active-bg: #20211c;
--ci-sidebar-active-fg: #f2f0e8;
/* One step darker than the default light theme: neutral-500 is 2.95:1 on the muted surface. */
--ci-scrollbar-thumb: var(--ci-neutral-600);
--ci-scrollbar-thumb-hover: var(--ci-neutral-700);
--primary: var(--ci-button-primary-bg);
--primary-foreground: var(--ci-button-primary-fg);
}
@@ -241,6 +245,8 @@
--ci-scale-div-7: #c1e3fc;
--ci-sidebar-active-bg: rgb(229 172 130 / .14);
--ci-sidebar-active-fg: #e5ac82;
--ci-scrollbar-thumb: var(--ci-neutral-500);
--ci-scrollbar-thumb-hover: var(--ci-neutral-400);
}
/* The host normally resolves system preference with data-theme. These tokens
@@ -333,6 +339,8 @@
--ci-scale-div-7: #c1e3fc;
--ci-sidebar-active-bg: rgb(229 172 130 / .14);
--ci-sidebar-active-fg: #e5ac82;
--ci-scrollbar-thumb: var(--ci-neutral-500);
--ci-scrollbar-thumb-hover: var(--ci-neutral-400);
}
}
@@ -381,6 +389,7 @@
--ci-radius-2xl: 8px;
--ci-radius-control: 2px;
--ci-radius-surface: 2px;
--ci-radius-surface-nested: 2px;
--ci-radius-pill: 2px;
--ci-button-primary-fg: #221b14;
--ci-button-primary-hover: #edba94;

View File

@@ -6,13 +6,13 @@
.ci-integration-resources h3, .ci-integration-resources p { margin: 0; }
.ci-integration-resources h3 { font: var(--ci-font-weight-semibold) var(--ci-font-size-base)/1.5 var(--ci-font-ui); color: var(--ci-color-heading); }
.ci-integration-resources p { font-size: var(--ci-font-size-sm); line-height: 1.6; color: var(--ci-color-text-muted); }
.ci-integration-resources__summary { display: flex; align-items: center; gap: var(--ci-space-3); text-align: left; min-width: 0; }
.ci-integration-resources__summary { display: flex; align-items: center; gap: var(--ci-space-3); text-align: start; min-width: 0; }
.ci-integration-resources__summary > span:last-child { display: grid; gap: var(--ci-space-1); min-width: 0; }
.ci-integration-resources__summary strong { font-weight: var(--ci-font-weight-semibold); font-size: var(--ci-font-size-sm); color: var(--ci-color-heading); }
.ci-integration-resources__summary > span:last-child > span { font-size: var(--ci-font-size-sm); font-weight: var(--ci-font-weight-regular); line-height: 1.6; color: var(--ci-color-text-muted); }
.ci-integration-resources__icon { display: flex; align-items: center; justify-content: center; flex: none; width: 32px; height: 32px; border-radius: var(--ci-radius-control); background: var(--ci-color-surface-subtle); color: var(--ci-color-heading); }
.ci-integration-resources__icon svg { width: 16px; height: 16px; }
.ci-integration-resources__body { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--ci-space-3); padding-top: var(--ci-space-2); }
.ci-integration-resources__body ul { display: grid; gap: var(--ci-space-2); margin: 0; padding-left: var(--ci-space-5); font-size: var(--ci-font-size-sm); line-height: 1.7; color: var(--ci-color-text-muted); }
.ci-integration-resources__body ul { display: grid; gap: var(--ci-space-2); margin: 0; padding-inline-start: var(--ci-space-5); font-size: var(--ci-font-size-sm); line-height: 1.7; color: var(--ci-color-text-muted); }
.ci-integration-resources__body code { padding: 1px 4px; border: 1px solid var(--ci-color-border-subtle); border-radius: var(--ci-radius-surface); font: .9em var(--ci-font-mono); overflow-wrap: anywhere; color: var(--ci-color-heading); }
.ci-integration-resources__actions { display: flex; flex-wrap: wrap; gap: var(--ci-space-2); }

View File

@@ -7,6 +7,8 @@
.ci-integration-setup p { font-size: var(--ci-font-size-sm); line-height: 1.6; color: var(--ci-color-text-muted); }
.ci-integration-setup__ai { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: var(--ci-space-4); border: 1px solid var(--ci-color-border-subtle); border-radius: var(--ci-radius-surface); padding: var(--ci-space-5); background: var(--ci-color-surface-subtle); }
.ci-integration-setup__actions { display: flex; flex-wrap: wrap; gap: var(--ci-space-2); }
.ci-integration-setup--stacked .ci-integration-setup__ai { grid-template-columns: minmax(0, 1fr); }
.ci-integration-setup--stacked .ci-integration-setup__actions { justify-content: flex-start; flex-wrap: wrap; }
.ci-integration-setup__tool { grid-column: 1 / -1; display: grid; gap: var(--ci-space-3); }
.ci-integration-setup__tool > p a { display: inline-flex; align-items: center; gap: var(--ci-space-1); text-decoration: underline; text-underline-offset: 3px; color: var(--ci-color-text); }
.ci-integration-setup__tool > p a > svg { width: 12px; height: 12px; }
@@ -20,7 +22,7 @@
.ci-integration-setup__manual-heading > span { border: 1px solid var(--ci-color-border-subtle); border-radius: var(--ci-radius-pill); padding: 2px 8px; font-size: var(--ci-font-size-xs); color: var(--ci-color-text-muted); }
.ci-integration-setup__steps { display: grid; gap: var(--ci-space-8); list-style: none; margin: var(--ci-space-5) 0 0; padding: 0; }
.ci-integration-setup__steps > li { position: relative; display: grid; grid-template-columns: 32px minmax(0, 1fr); gap: var(--ci-space-4); }
.ci-integration-setup__steps > li:not(:last-child)::before { content: ""; position: absolute; left: 15px; top: 40px; bottom: calc(-1 * var(--ci-space-5)); width: 1px; background: var(--ci-color-border-subtle); }
.ci-integration-setup__steps > li:not(:last-child)::before { content: ""; position: absolute; inset-inline-start: 15px; top: 40px; bottom: calc(-1 * var(--ci-space-5)); width: 1px; background: var(--ci-color-border-subtle); }
.ci-integration-setup__step-body { display: grid; grid-template-columns: minmax(0, 1fr); align-content: start; gap: var(--ci-space-3); min-width: 0; padding-top: 3px; }
.ci-integration-setup__steps h4 { font: var(--ci-font-weight-semibold) var(--ci-font-size-base)/1.6 var(--ci-font-ui); color: var(--ci-color-heading); }
.ci-integration-setup__number { display: flex; align-items: center; justify-content: center; width: 32px; height: 32px; border: 1px solid var(--ci-color-border-subtle); border-radius: 50%; background: var(--ci-color-surface-subtle); font: var(--ci-font-weight-medium) var(--ci-font-size-sm)/1 var(--ci-font-mono); color: var(--ci-color-heading); }
@@ -28,10 +30,10 @@
.ci-integration-setup__location > span { flex: none; font-size: var(--ci-font-size-xs); color: var(--ci-color-text-muted); }
.ci-integration-setup__location > div { min-width: 0; overflow-wrap: anywhere; color: var(--ci-color-heading); font-weight: var(--ci-font-weight-medium); }
.ci-integration-setup__instructions { display: grid; gap: var(--ci-space-2); list-style: none; margin: 0; padding: 0; font-size: var(--ci-font-size-sm); line-height: 1.7; color: var(--ci-color-text-muted); }
.ci-integration-setup__instructions > li { position: relative; padding-left: var(--ci-space-4); min-width: 0; overflow-wrap: anywhere; }
.ci-integration-setup__instructions > li::before { content: ""; position: absolute; left: 1px; top: .75em; width: 4px; height: 4px; border-radius: 50%; background: var(--ci-color-text-muted); }
.ci-integration-setup__instructions > li { position: relative; padding-inline-start: var(--ci-space-4); min-width: 0; overflow-wrap: anywhere; }
.ci-integration-setup__instructions > li::before { content: ""; position: absolute; inset-inline-start: 1px; top: .75em; width: 4px; height: 4px; border-radius: 50%; background: var(--ci-color-text-muted); }
.ci-integration-setup__instructions code, .ci-integration-setup__location code, .ci-integration-setup__note code { padding: 1px 5px; border: 1px solid var(--ci-color-border-subtle); border-radius: var(--ci-radius-surface); background: var(--ci-color-surface-subtle); font: .9em/1.6 var(--ci-font-mono); color: var(--ci-color-heading); overflow-wrap: anywhere; }
.ci-integration-setup p.ci-integration-setup__note { border-left: 2px solid var(--ci-color-border); padding-left: var(--ci-space-3); font-size: var(--ci-font-size-xs); }
.ci-integration-setup p.ci-integration-setup__note { border-inline-start: 2px solid var(--ci-color-border); padding-inline-start: var(--ci-space-3); font-size: var(--ci-font-size-xs); }
@media (max-width: 640px) { .ci-integration-setup__ai { grid-template-columns: minmax(0, 1fr); } .ci-integration-setup__actions { flex-direction: column; } .ci-integration-setup__actions > .ci-button { width: 100%; white-space: nowrap; } }
.ci-integration-setup__handoff { grid-column: 1 / -1; border-top: 1px solid var(--ci-color-border-subtle); padding-top: var(--ci-space-3); }

View File

@@ -11,7 +11,7 @@
.ci-choice-card__heading { display:flex; align-items:center; gap:.5rem; font-size:1rem; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-choice-card__icon { display:grid; place-items:center; width:1.625rem; height:1.625rem; flex:0 0 1.625rem; border:1px solid var(--ci-color-border-subtle); border-radius:var(--ci-radius-surface); background:var(--ci-color-surface-subtle); color:var(--ci-color-text-muted); }
.ci-choice-card__icon svg { width:1rem; height:1rem; }
.ci-choice-card:has(.ci-choice-card__icon) .ci-radio__description { padding-left:2.125rem; }
.ci-choice-card:has(.ci-choice-card__icon) .ci-radio__description { padding-inline-start:2.125rem; }
.ci-choice-card .ci-radio__description { font-size:.875rem; line-height: var(--ci-type-body-leading); font-weight: var(--ci-font-weight-regular); letter-spacing: var(--ci-type-body-tracking); }
.ci-setup-progress > .ci-card__content { display:flex; flex-direction:column; gap:.5rem; padding:.75rem; }
@@ -25,13 +25,13 @@
.ci-setup-progress__bar::-moz-progress-bar { background:var(--ci-color-accent); border-radius:var(--ci-radius-pill); }
.ci-setup-progress ol { display:flex; flex-direction:column; gap:.125rem; padding:0; margin:0; list-style:none; }
.ci-setup-progress li { display:flex; align-items:center; gap:.5rem; }
.ci-setup-progress li > button { display:flex; flex:1; min-width:0; align-items:center; gap:.5rem; width:100%; padding:.375rem 0; border:0; border-radius:var(--ci-radius-control); background:transparent; color:var(--ci-color-heading); font:inherit; font-size:.75rem; text-align:left; cursor:pointer; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-setup-progress li > button { display:flex; flex:1; min-width:0; align-items:center; gap:.5rem; width:100%; padding:.375rem 0; border:0; border-radius:var(--ci-radius-control); background:transparent; color:var(--ci-color-heading); font:inherit; font-size:.75rem; text-align:start; cursor:pointer; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-setup-progress li > button span { flex:1; }
.ci-setup-progress li > button[data-complete="true"] { color:var(--ci-color-text-muted); }
.ci-setup-progress li > button[data-complete="true"] > svg:first-child { color:var(--ci-color-success); }
.ci-setup-progress li > button:focus-visible { outline:2px solid var(--ci-color-accent); outline-offset:2px; }
.ci-setup-progress__step-action { display:flex; flex-shrink:0; align-items:center; }
.ci-setup-progress p { margin:0; font-size:.6875rem; text-align:center; color:var(--ci-color-text-muted); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-body-leading); letter-spacing: var(--ci-type-body-tracking); }
.ci-setup-progress p { margin:0; font-size:var(--ci-font-size-2xs); text-align:center; color:var(--ci-color-text-muted); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-body-leading); letter-spacing: var(--ci-type-body-tracking); }
.ci-setup-progress button:disabled { opacity:.5; cursor:wait; }
.ci-save-changes-bar { position:sticky; bottom:0; z-index:20; flex-shrink:0; padding:1rem 2rem max(1rem,env(safe-area-inset-bottom)); background:var(--ci-color-surface); border-top:1px solid var(--ci-color-border); }
@@ -48,23 +48,23 @@
.ci-setup-progress li > button { min-height:2.75rem; font-size:.875rem; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-setup-progress__details > .ci-button { min-height:2.75rem; }
}
.ci-choice-card { padding:14px 16px 14px 12px; gap:8px; box-shadow:var(--ci-shadow-xs); }
.ci-choice-card { padding-block:14px;padding-inline:12px 16px; gap:8px; box-shadow:var(--ci-shadow-xs); }
.ci-choice-card .ci-radio__text { gap:3px; }
.ci-choice-card__heading { position:relative; }
.ci-choice-card:has(.ci-choice-card__icon) .ci-choice-card__heading { padding-left:34px; }
.ci-choice-card__icon { position:absolute; left:0; top:0; }
.ci-choice-card:has(.ci-choice-card__icon) .ci-choice-card__heading { padding-inline-start:34px; }
.ci-choice-card__icon { position:absolute; inset-inline-start:0; top:0; }
.ci-multi-choice-card { padding:var(--ci-space-4); gap:var(--ci-space-3); box-shadow:none; }
.ci-multi-choice-card .ci-checkbox__text { min-width:0; gap:var(--ci-space-1); }
.ci-multi-choice-card .ci-checkbox__control { margin-top:var(--ci-space-1); }
.ci-multi-choice-card .ci-choice-card__heading { line-height:1.5; }
.ci-multi-choice-card:has(.ci-choice-card__icon) .ci-checkbox__description { padding-left:2.125rem; }
.ci-multi-choice-card:has(.ci-choice-card__icon) .ci-checkbox__description { padding-inline-start:2.125rem; }
.ci-multi-choice-card .ci-checkbox__description { line-height:1.5; }
.ci-setup-layout { display:grid; grid-template-columns:minmax(0,1fr) minmax(13rem,.55fr); gap:2rem; align-items:start; }
.ci-setup-layout--wide { grid-template-columns:minmax(0,1fr) minmax(24rem,1.15fr); }
.ci-setup-layout--booking { grid-template-columns:minmax(14rem,1fr) minmax(24rem,3.4fr); }
@media(max-width:1250px) { .ci-setup-layout--booking { grid-template-columns:1fr; } .ci-setup-layout--booking .ci-setup-layout__aside { border-left:0; border-top:1px solid var(--ci-color-border-subtle); padding:1.5rem 0 0; } }
@media(max-width:1250px) { .ci-setup-layout--booking { grid-template-columns:1fr; } .ci-setup-layout--booking .ci-setup-layout__aside { border-inline-start:0; border-top:1px solid var(--ci-color-border-subtle); padding:1.5rem 0 0; } }
.ci-setup-layout__main { min-width:0; }
.ci-setup-layout__aside { border-left:1px solid var(--ci-color-border-subtle); padding-left:1.5rem; }
.ci-setup-layout__aside { border-inline-start:1px solid var(--ci-color-border-subtle); padding-inline-start:1.5rem; }
.ci-setup-benefits h2 { color:var(--ci-color-heading); font-size:1rem; font-weight:var(--ci-font-weight-semibold); margin:0 0 .5rem; }
.ci-setup-benefits p { color:var(--ci-color-text-muted); font-size:.8125rem; line-height:1.5; margin:.25rem 0 0; }
.ci-setup-benefits ul { list-style:none; padding:0; margin:1.5rem 0 0; display:grid; gap:1.25rem; }
@@ -77,7 +77,7 @@
.ci-setup-benefits__footer > p { margin:0; }
.ci-setup-benefits__footer > .ci-button { justify-self:start; max-width:100%; white-space:normal; text-align:start; }
@media(max-width:1100px) { .ci-setup-layout { grid-template-columns:1fr; } .ci-setup-layout__aside { border-left:0; border-top:1px solid var(--ci-color-border-subtle); padding:1.5rem 0 0; } }
@media(max-width:1100px) { .ci-setup-layout { grid-template-columns:1fr; } .ci-setup-layout__aside { border-inline-start:0; border-top:1px solid var(--ci-color-border-subtle); padding:1.5rem 0 0; } }
.ci-setup-layout--compact h2 { font-size:var(--ci-font-size-md); font-weight:var(--ci-font-weight-medium); }
@@ -92,11 +92,11 @@
position:relative; min-height:280px; padding:24px; overflow:hidden;
border-radius:var(--ci-radius-surface); transition:border-color .2s, background .2s, box-shadow .2s;
}
.ci-multi-choice-card--feature .ci-checkbox__control { position:absolute; top:20px; right:20px; z-index:1; margin:0; }
.ci-multi-choice-card--feature .ci-checkbox__control { position:absolute; top:20px; inset-inline-end:20px; z-index:1; margin:0; }
.ci-multi-choice-card--feature .ci-checkbox__text { width:100%; gap:12px; }
.ci-multi-choice-card--feature .ci-choice-card__heading { padding-left:0; gap:10px; font-size:1.375rem; }
.ci-multi-choice-card--feature .ci-choice-card__heading { padding-inline-start:0; gap:10px; font-size:1.375rem; }
.ci-multi-choice-card--feature .ci-choice-card__icon { position:static; width:30px; height:30px; flex-basis:30px; }
.ci-multi-choice-card--feature:has(.ci-choice-card__icon) .ci-checkbox__description { padding-left:0; }
.ci-multi-choice-card--feature:has(.ci-choice-card__icon) .ci-checkbox__description { padding-inline-start:0; }
.ci-multi-choice-card--feature .ci-checkbox__description { font-size:.9375rem; }
.ci-multi-choice-card--feature:has(input:checked) { border-color:var(--ci-color-accent); background:linear-gradient(145deg,color-mix(in srgb,var(--ci-color-accent) 9%,var(--ci-color-surface)),var(--ci-color-surface) 80%); }
.ci-multi-choice-card--feature:has(input:focus-visible) { outline:2px solid var(--ci-color-accent); outline-offset:3px; }

View File

@@ -19,7 +19,7 @@
.ci-overview-panels { grid-template-columns: minmax(0, .85fr) minmax(0, 1.15fr); row-gap: 0; }
.ci-overview-panels__card { grid-row: span 4; grid-template-rows: subgrid; }
}
.ci-token-savings { display: grid; flex: 1; align-content: space-between; gap: var(--ci-space-5); margin: 0; padding: 0; list-style: none; }
.ci-token-savings { display: grid; flex: 1; align-content: start; gap: var(--ci-space-5); margin: 0; padding: 0; list-style: none; }
.ci-token-savings__item { display: flex; align-items: center; gap: var(--ci-space-3); min-width: 0; }
.ci-token-savings__icon { display: grid; place-items: center; flex: none; width: 2.5rem; height: 2.5rem; border: 1px solid var(--ci-color-border-subtle); border-radius: var(--ci-radius-control); background: var(--ci-color-accent-surface-subtle); color: var(--ci-color-accent-active); }
.ci-token-savings__icon svg { width: 1.125rem; height: 1.125rem; }
@@ -39,7 +39,7 @@
.ci-client-quick-start__brand :is(img, svg) { display: block; width: 1.75rem; height: 1.75rem; object-fit: contain; border-radius: var(--ci-radius-sm); }
.ci-client-quick-start__name { font-size: var(--ci-font-size-sm); font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); }
.ci-client-quick-start__description { font-size: var(--ci-font-size-xs); line-height: var(--ci-type-body-leading); color: var(--ci-color-text-muted); }
.ci-client-quick-start__arrow { position: absolute; top: var(--ci-space-3); right: var(--ci-space-3); width: .875rem; height: .875rem; color: var(--ci-color-text-muted); }
.ci-client-quick-start__arrow { position: absolute; top: var(--ci-space-3); inset-inline-end: var(--ci-space-3); width: .875rem; height: .875rem; color: var(--ci-color-text-muted); }
.ci-client-quick-start__connection { display: grid; gap: var(--ci-space-3); padding-top: var(--ci-space-4); border-top: 1px solid var(--ci-color-border-subtle); }
.ci-client-quick-start__eyebrow { margin: 0; font-size: var(--ci-font-size-xs); font-weight: var(--ci-font-weight-medium); color: var(--ci-color-heading); }
.ci-client-quick-start__credentials { display: grid; gap: var(--ci-space-4); min-width: 0; }
@@ -101,7 +101,7 @@
.ci-overview-panels[data-layout="single"][data-client-layout="compact"] .ci-overview-panels__body {
grid-column: 1;
grid-row: 2;
border-right: 1px solid var(--ci-color-border-subtle);
border-inline-end: 1px solid var(--ci-color-border-subtle);
}
.ci-overview-panels[data-layout="single"][data-client-layout="compact"] .ci-overview-panels__guides { flex: initial; }
.ci-overview-panels[data-layout="single"][data-client-layout="compact"] .ci-overview-panels__details {
@@ -111,5 +111,10 @@
padding-bottom: var(--ci-space-5);
}
.ci-overview-panels[data-layout="single"][data-client-layout="compact"] .ci-client-quick-start__connection { border-top: 0; padding-top: 0; }
.ci-overview-panels[data-layout="single"][data-client-layout="compact"] .ci-overview-panels__actions { grid-column: 1; grid-row: 3; padding-top: 0; border-right: 1px solid var(--ci-color-border-subtle); }
.ci-overview-panels[data-layout="single"][data-client-layout="compact"] .ci-overview-panels__actions { grid-column: 1; grid-row: 3; padding-top: 0; border-inline-end: 1px solid var(--ci-color-border-subtle); }
}
/* Compact links need enough space for a readable name and description. */
@container ci-client-quick-start (max-width: 22rem) {
.ci-client-quick-start__integrations[data-layout="compact"] { grid-template-columns: minmax(0, 1fr); }
}

View File

@@ -12,7 +12,7 @@
.ci-request-workbench__header h2 { margin: 0; color: var(--ci-color-heading); font-size: var(--ci-font-size-xl); font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-request-workbench__header p { margin: var(--ci-space-1) 0 0; color: var(--ci-color-text-muted); font-size: var(--ci-font-size-sm); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-body-leading); letter-spacing: var(--ci-type-body-tracking); }
.ci-request-workbench__grid { display: grid; grid-template-columns: minmax(22rem, 0.82fr) minmax(28rem, 1.18fr); }
.ci-request-editor { display: grid; align-content: start; gap: var(--ci-space-5); padding: var(--ci-space-6); border-right: var(--ci-border-hairline) solid var(--ci-color-border-subtle); }
.ci-request-editor { display: grid; align-content: start; gap: var(--ci-space-5); padding: var(--ci-space-6); border-inline-end: var(--ci-border-hairline) solid var(--ci-color-border-subtle); }
.ci-request-editor > .ci-button { justify-self: start; }
.ci-request-model-option { display: flex; width: 100%; min-width: 0; align-items: center; justify-content: space-between; gap: var(--ci-space-4); }
.ci-request-model-option small { color: var(--ci-color-text-subtle); white-space: nowrap; }
@@ -58,7 +58,7 @@
.ci-response-loader i:nth-child(3) { animation-delay: 0.24s; }
.ci-live-response__stream { display: grid; align-content: start; gap: var(--ci-space-4); padding: var(--ci-space-8); }
.ci-live-response__stream p { max-width: 42rem; margin: 0; font-size: var(--ci-font-size-lg); line-height: var(--ci-type-reading-leading); font-weight: var(--ci-font-weight-regular); letter-spacing: var(--ci-type-reading-tracking); }
.ci-live-response__stream p > span { display: inline-block; width: 0.5rem; height: 1.15em; margin-left: 0.2rem; vertical-align: -0.16em; background: var(--ci-color-accent); animation: ci-stream-cursor 0.8s steps(1) infinite; }
.ci-live-response__stream p > span { display: inline-block; width: 0.5rem; height: 1.15em; margin-inline-start: 0.2rem; vertical-align: -0.16em; background: var(--ci-color-accent); animation: ci-stream-cursor 0.8s steps(1) infinite; }
.ci-live-response__stream small { color: rgb(241 247 247 / 0.5); }
.ci-live-response__error { display: flex; min-height: 32rem; align-items: flex-start; justify-content: center; gap: var(--ci-space-4); padding: var(--ci-space-8); padding-top: 8rem; }
.ci-live-response__error > svg { width: var(--ci-icon-size-md); height: var(--ci-icon-size-md); color: #ff8f8f; }
@@ -70,8 +70,8 @@
.ci-request-metrics[data-columns="1"] { --ci-request-metric-columns: 1; }
.ci-request-metrics[data-columns="2"] { --ci-request-metric-columns: 2; }
.ci-request-metrics[data-columns="3"] { --ci-request-metric-columns: 3; }
.ci-request-metric { display: grid; gap: var(--ci-space-2); padding: var(--ci-space-4); border-right: var(--ci-border-hairline) solid rgb(255 255 255 / 0.14); }
.ci-request-metric:last-child { border-right: 0; }
.ci-request-metric { display: grid; gap: var(--ci-space-2); padding: var(--ci-space-4); border-inline-end: var(--ci-border-hairline) solid rgb(255 255 255 / 0.14); }
.ci-request-metric:last-child { border-inline-end: 0; }
.ci-request-metric > span { display: flex; align-items: center; gap: var(--ci-space-2); color: rgb(241 247 247 / 0.55); font-size: var(--ci-font-size-xs); }
.ci-request-metric svg { width: var(--ci-icon-size-sm); height: var(--ci-icon-size-sm); }
.ci-request-metric strong { font-family: var(--ci-font-mono); font-size: var(--ci-font-size-sm); font-weight: var(--ci-font-weight-semibold); line-height: var(--ci-type-body-leading); letter-spacing: 0em; }
@@ -82,7 +82,7 @@
.ci-request-headers { border-top: var(--ci-border-hairline) solid rgb(255 255 255 / 0.14); }
.ci-request-headers > summary { display: flex; min-height: 3.5rem; align-items: center; gap: var(--ci-space-3); padding: 0 var(--ci-space-6); color: rgb(241 247 247 / 0.68); font-size: var(--ci-font-size-xs); cursor: pointer; list-style: none; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-request-headers > summary::-webkit-details-marker { display: none; }
.ci-request-headers > summary > span:first-child { margin-right: auto; color: var(--ci-color-text-inverse); font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-request-headers > summary > span:first-child { margin-inline-end: auto; color: var(--ci-color-text-inverse); font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-request-headers > summary svg { width: var(--ci-icon-size-sm); height: var(--ci-icon-size-sm); transition: transform var(--ci-duration-fast) var(--ci-ease-standard); }
.ci-request-headers[open] > summary svg { transform: rotate(180deg); }
.ci-request-headers dl { padding: 0 var(--ci-space-6) var(--ci-space-5); margin: 0; }
@@ -92,14 +92,14 @@
/* A short first-request flow: one column, ordinary theme surfaces, and content-sized responses. */
.ci-request-workbench[data-variant="onboarding"] .ci-request-workbench__grid { grid-template-columns: minmax(0, 1fr); }
.ci-request-workbench[data-variant="onboarding"] .ci-request-editor { min-width: 0; gap: var(--ci-space-4); padding: var(--ci-space-5); border-right: 0; border-bottom: var(--ci-border-hairline) solid var(--ci-color-border-subtle); }
.ci-request-workbench[data-variant="onboarding"] .ci-request-editor { min-width: 0; gap: var(--ci-space-4); padding: var(--ci-space-5); border-inline-end: 0; border-bottom: var(--ci-border-hairline) solid var(--ci-color-border-subtle); }
.ci-request-workbench[data-variant="onboarding"] .ci-request-editor:last-child { border-bottom: 0; }
.ci-request-workbench[data-variant="onboarding"] .ci-request-model-option { flex-wrap: wrap; gap: var(--ci-space-1) var(--ci-space-3); }
.ci-request-workbench__notice { margin: 0; color: var(--ci-color-text-muted); font-size: var(--ci-font-size-sm); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-body-leading); letter-spacing: var(--ci-type-body-tracking); }
.ci-live-response[data-variant="onboarding"] { min-height: 0; color: var(--ci-color-text); background: var(--ci-color-surface-subtle); }
.ci-live-response[data-variant="onboarding"] .ci-live-response__header { min-height: 3rem; border-color: var(--ci-color-border-subtle); color: var(--ci-color-heading); }
.ci-live-response[data-variant="onboarding"] .ci-live-response__empty,
.ci-live-response[data-variant="onboarding"] .ci-live-response__loading { min-height: 0; place-content: start; justify-items: start; padding: var(--ci-space-5) var(--ci-space-6); color: var(--ci-color-text-muted); text-align: left; }
.ci-live-response[data-variant="onboarding"] .ci-live-response__loading { min-height: 0; place-content: start; justify-items: start; padding: var(--ci-space-5) var(--ci-space-6); color: var(--ci-color-text-muted); text-align: start; }
.ci-live-response[data-variant="onboarding"] .ci-live-response__empty strong,
.ci-live-response[data-variant="onboarding"] .ci-live-response__loading strong { color: var(--ci-color-heading); font-size: var(--ci-font-size-sm); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-live-response[data-variant="onboarding"] .ci-response-loader i { background: var(--ci-color-text-muted); }
@@ -115,7 +115,7 @@
@media (max-width: 64rem) {
.ci-request-workbench__grid { grid-template-columns: minmax(0, 1fr); }
.ci-request-editor { border-right: 0; border-bottom: var(--ci-border-hairline) solid var(--ci-color-border-subtle); }
.ci-request-editor { border-inline-end: 0; border-bottom: var(--ci-border-hairline) solid var(--ci-color-border-subtle); }
}
@media (max-width: 42rem) {
@@ -126,10 +126,10 @@
.ci-request-workbench__grid { display: block; }
.ci-request-editor { padding: var(--ci-space-5); }
.ci-request-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.ci-request-metric:nth-child(2) { border-right: 0; }
.ci-request-metric:nth-child(2) { border-inline-end: 0; }
.ci-request-metric:nth-child(-n + 2) { border-bottom: var(--ci-border-hairline) solid rgb(255 255 255 / 0.14); }
.ci-wallet-notice { flex-wrap: wrap; }
.ci-wallet-notice__action { margin-left: 2.5rem; }
.ci-wallet-notice__action { margin-inline-start: 2.5rem; }
}
@media (prefers-reduced-motion: reduce) {

View File

@@ -0,0 +1,294 @@
.ci-seller-card {
--seller-cap-primary: #343b3b;
--seller-cap-secondary: #7b8383;
--seller-cap-tertiary: #b8bdbd;
}
[data-theme="dark"] .ci-seller-card {
--seller-cap-primary: #d4d8d8;
--seller-cap-secondary: #999f9f;
--seller-cap-tertiary: #626b6b;
}
.ci-seller-card small {
color: var(--ci-color-text-muted);
font-size: 12px;
line-height: 1.3;
}
.ci-seller-card p { margin: 0; }
.ci-seller-card button { cursor: pointer; font: inherit; }
.ci-seller-card button:disabled { cursor: not-allowed; }
.ci-seller-card :focus-visible {
outline: 2px solid var(--ci-color-focus);
outline-offset: 3px;
}
.ci-seller-card__muted { color: var(--ci-color-text-muted); }
.ci-seller-card__text-link {
padding: 0;
border: 0;
background: none;
color: inherit;
text-align: start;
text-decoration: underline;
}
.ci-seller-offer-card {
margin-top: 16px;
overflow: hidden;
background: var(--ci-color-surface);
border: 1px solid var(--ci-color-border);
border-radius: var(--ci-radius-surface);
}
.ci-seller-offer-card__header {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid var(--ci-color-border-subtle);
font-size: 14px;
}
.ci-seller-offer-card__header strong { font-size: 14px; }
.ci-seller-offer-card__header button {
min-height: 36px;
height: 36px;
padding: 0 14px;
border-radius: 12px;
font-size: 14px;
}
.ci-seller-offer-card__inline {
display: inline-flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.ci-seller-offer-card__private-note {
display: block;
margin-top: 3px;
}
.ci-seller-offer-card__body {
display: grid;
grid-template-columns: minmax(175px, 1fr) minmax(320px, 2fr) minmax(160px, 1fr);
gap: 24px;
padding: 20px;
}
.ci-seller-offer-card__body h3 {
margin: 2px 0;
color: var(--ci-color-heading);
font-size: 18px;
font-weight: 500;
letter-spacing: -0.01em;
line-height: 1.45;
}
.ci-seller-offer-card__body p {
margin-top: 4px;
color: var(--ci-color-text-muted);
font-size: 12px;
line-height: 1.45;
}
.ci-seller-offer-card__body > div > .ci-seller-card__text-link {
margin-top: 6px;
font-size: 12px;
}
.ci-seller-offer-card__volume { min-width: 0; }
.ci-seller-offer-card__volume > small {
display: block;
margin-bottom: 8px;
}
.ci-seller-cap-usage {
display: flex;
height: 12px;
margin: 8px 0;
overflow: hidden;
background: var(--ci-color-surface);
border: 1px solid var(--ci-color-border-strong);
border-radius: 999px;
}
.ci-seller-cap-usage[data-calculating] { background: var(--ci-color-surface-muted); }
.ci-seller-cap-usage > span {
flex: none;
height: 100%;
border-inline-end: 2px solid var(--ci-color-surface);
}
.ci-seller-cap-usage > span:nth-child(3n + 1),
.ci-seller-cap-card__breakdown > span:nth-child(3n + 1) i {
background: var(--seller-cap-primary);
}
.ci-seller-cap-usage > span:nth-child(3n + 2),
.ci-seller-cap-card__breakdown > span:nth-child(3n + 2) i {
background: var(--seller-cap-secondary);
}
.ci-seller-cap-usage > span:nth-child(3n),
.ci-seller-cap-card__breakdown > span:nth-child(3n) i {
background: var(--seller-cap-tertiary);
}
.ci-seller-cap-usage > span.ci-seller-cap-usage__forecast {
background: repeating-linear-gradient(
135deg,
transparent 0 3px,
var(--ci-color-text-muted) 3px 4px
), #efd1b4;
}
.ci-seller-offer-card__totals {
display: flex;
flex-wrap: wrap;
gap: 4px 14px;
font-size: 12px;
}
.ci-seller-offer-card__totals b { font-weight: 500; }
.ci-seller-offer-card__footer {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px 16px;
padding: 12px 20px;
background: var(--ci-color-surface-subtle);
border-top: 1px solid var(--ci-color-border-subtle);
font-size: 12px;
}
.ci-seller-offer-card__footer strong { font-weight: 500; }
.ci-seller-offer-card__footer button { margin-inline-start: auto; }
.ci-seller-offer-card__expiry {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 24px;
border-top: 1px solid var(--ci-color-border);
}
.ci-seller-offer-card__expiry button { margin-inline-start: auto; }
.ci-seller-cap-card {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
padding: 18px 20px;
margin: 0;
scroll-margin-top: 80px;
border: 1px solid var(--ci-color-border);
border-radius: var(--ci-radius-surface);
}
.ci-seller-cap-card header {
position: relative;
display: flex;
align-items: flex-start;
gap: 8px;
padding-bottom: 26px;
}
.ci-seller-cap-card header > div:first-child {
flex: 1;
min-width: 0;
}
.ci-seller-cap-card .ci-seller-cap-card__name {
display: -webkit-box;
overflow: hidden;
overflow-wrap: anywhere;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
margin: 6px 0 0;
padding: 0;
border: 0;
background: none;
color: inherit;
text-align: start;
font-size: 16px;
font-weight: 500;
}
.ci-seller-cap-card header > .ci-seller-cap-card__status {
position: absolute;
bottom: 0;
inset-inline-start: 0;
}
.ci-seller-cap-card__total {
display: flex;
align-items: baseline;
gap: 8px;
flex-wrap: wrap;
}
.ci-seller-cap-card__total strong {
font-size: 28px;
font-weight: 500;
letter-spacing: -0.02em;
}
.ci-seller-cap-card__total span {
color: var(--ci-color-text-muted);
font-size: 12px;
}
.ci-seller-cap-card .ci-seller-cap-usage { margin: 0; }
.ci-seller-cap-card__breakdown {
display: flex;
flex-wrap: wrap;
gap: 4px 14px;
margin-bottom: 12px;
font-size: 12px;
}
.ci-seller-cap-card__breakdown > span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.ci-seller-cap-card__breakdown i {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 2px;
}
.ci-seller-cap-card__breakdown b { font-weight: 500; }
.ci-seller-cap-card__warning {
display: flex;
gap: 8px;
padding: 10px 12px;
background: var(--ci-color-warning-bg);
color: var(--ci-color-warning);
border-radius: var(--ci-radius-surface-nested);
font-size: 13px;
}
.ci-seller-cap-card__warning svg {
flex: none;
margin-top: 2px;
}
.ci-seller-cap-card__members {
display: flex;
flex-wrap: wrap;
gap: 6px;
font-size: 12px;
}
.ci-seller-cap-card__members small { width: 100%; }
.ci-seller-cap-card__members > span {
padding: 2px 8px;
border: 1px solid var(--ci-color-border);
border-radius: 999px;
}
.ci-seller-cap-card footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: auto;
padding-top: 10px;
border-top: 1px solid var(--ci-color-border-subtle);
}
@media (max-width: 1050px) {
.ci-seller-offer-card__body > :last-child { grid-column: 1 / -1; }
}
@media (min-width: 1001px) and (max-width: 1050px) {
.ci-seller-offer-card__body { grid-template-columns: minmax(150px, 1fr) minmax(220px, 1.6fr); }
}
@media (min-width: 701px) and (max-width: 1000px) {
.ci-seller-offer-card__body { grid-template-columns: 1fr 2fr; }
}
@media (max-width: 760px) {
.ci-seller-offer-card__inline:last-child { flex-wrap: wrap; }
}
@media (max-width: 700px) {
.ci-seller-offer-card__body {
display: flex;
flex-direction: column;
gap: 18px;
}
.ci-seller-offer-card__inline { flex-wrap: wrap; }
.ci-seller-cap-card header { flex-wrap: wrap; }
.ci-seller-offer-card__footer { gap: 8px; }
.ci-seller-offer-card__footer button { margin-inline-start: 0; }
}

View File

@@ -0,0 +1,91 @@
.ci-seller-earnings-summary-strip {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 0;
margin: 0;
padding: 0 0 20px;
border-bottom: 1px solid var(--ci-color-border-subtle);
color: var(--ci-color-foreground);
font-family: var(--ci-font-ui);
font-size: 14px;
font-weight: 400;
line-height: 1.45;
}
.ci-seller-earnings-summary-strip[data-variant="payments"] {
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: normal;
margin-bottom: 28px;
padding: 16px 0 20px;
border-block: 1px solid var(--ci-color-border-subtle);
}
.ci-seller-earnings-summary-strip > div {
border-inline-end: 1px solid var(--ci-color-border-subtle);
padding: 0 28px;
}
.ci-seller-earnings-summary-strip > div:first-child {
padding-inline-start: 0;
}
.ci-seller-earnings-summary-strip > div > strong {
display: block;
margin: 4px 0;
font-size: 28px;
font-weight: 550;
line-height: 1.2;
letter-spacing: -0.03em;
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
.ci-seller-earnings-summary-strip > div:first-child > strong {
color: var(--ci-color-success);
}
.ci-seller-earnings-summary-strip > div > :is(small, span) {
color: var(--ci-color-text-muted);
font-size: 12px;
}
.ci-seller-earnings-summary-strip > div > small {
line-height: 1.3;
}
@media (max-width: 1100px) {
.ci-seller-earnings-summary-strip:is([data-variant="overview"], [data-variant="payments"]) {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20px;
}
.ci-seller-earnings-summary-strip > div {
padding: 0 0 20px;
border-inline-end: 0;
border-bottom: 1px solid var(--ci-color-border-subtle);
}
}
@media (max-width: 700px) {
.ci-seller-earnings-summary-strip[data-variant="payments"] {
grid-template-columns: 1fr;
}
.ci-seller-earnings-summary-strip[data-variant="payments"] > div {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 4px;
}
.ci-seller-earnings-summary-strip[data-variant="payments"] > div > strong {
grid-column: 2;
grid-row: 1 / 3;
}
.ci-seller-earnings-summary-strip[data-variant="payments"] > div > span {
grid-column: 1;
}
}
.ci-seller-earnings-summary-strip > div:last-child {
border: 0;
}

View File

@@ -0,0 +1,370 @@
.ci-seller-onboarding,
.ci-seller-onboarding__mobile-rail {
font-family: var(--ci-font-ui);
font-size: 14px;
line-height: 1.45;
-webkit-font-smoothing: antialiased;
}
.ci-seller-onboarding {
height: 100dvh;
min-height: 100dvh;
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--ci-color-background);
color: var(--ci-color-foreground);
}
.ci-seller-onboarding *,
.ci-seller-onboarding__mobile-rail * {
box-sizing: border-box;
}
.ci-seller-onboarding p,
.ci-seller-onboarding__mobile-rail p {
margin: 0;
}
.ci-seller-onboarding small {
font-size: 12px;
color: var(--ci-color-text-muted);
}
.ci-seller-onboarding :is(button, input, select) {
font: inherit;
}
.ci-seller-onboarding button {
cursor: pointer;
}
.ci-seller-onboarding button:disabled {
cursor: not-allowed;
}
.ci-seller-onboarding :focus-visible {
outline: 2px solid var(--ci-color-focus);
outline-offset: 3px;
}
.ci-seller-onboarding ::selection {
background: var(--ci-color-selection);
}
.ci-seller-onboarding__top-bar,
.ci-seller-onboarding__brand-header,
.ci-seller-onboarding__mobile-header {
flex-shrink: 0;
}
.ci-seller-onboarding__brand-header {
height: 56px;
padding: 0 32px;
border-bottom: 1px solid var(--ci-color-border);
display: flex;
justify-content: space-between;
align-items: center;
}
.ci-seller-onboarding__brand-header > div,
.ci-seller-onboarding__rail-brand {
display: inline-flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.ci-seller-onboarding__brand-header svg {
max-width: 160px;
}
.ci-seller-onboarding__mobile-header {
display: none;
}
.ci-seller-onboarding__frame {
display: grid;
grid-template-columns: 240px minmax(0, 1fr);
grid-template-rows: minmax(0, 1fr);
flex: 1;
min-height: 0;
width: min(1376px, calc(100% - 48px));
margin: 24px auto;
border: 1px solid var(--ci-color-border);
border-radius: var(--ci-radius-surface);
overflow: hidden;
background: var(--ci-color-surface);
}
.ci-seller-onboarding__rail {
height: 100%;
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 24px;
padding: 32px 24px;
border-inline-end: 1px solid var(--ci-color-border-subtle);
background: var(--ci-color-surface);
}
.ci-seller-onboarding__rail > .ci-seller-onboarding__steps-label,
.ci-seller-onboarding__mobile-rail > .ci-seller-onboarding__steps-label {
margin: 0 10px -12px;
font-size: 12px;
line-height: 1.4;
color: var(--ci-color-text-muted);
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.ci-seller-onboarding__steps {
display: grid;
gap: 4px;
}
.ci-seller-onboarding__steps > button {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 10px 8px;
text-align: start;
border: 0;
background: transparent;
border-radius: var(--ci-radius-control);
color: inherit;
font: inherit;
transition: background-color 150ms ease-out, color 150ms ease-out;
}
.ci-seller-onboarding__steps > button[data-optional] {
margin-top: 12px;
border-top: 1px solid var(--ci-color-border-subtle);
border-radius: 0;
padding-top: 18px;
}
.ci-seller-onboarding__steps > button:disabled {
opacity: 0.55;
}
.ci-seller-onboarding__steps > button:not(:disabled):hover {
background: var(--ci-color-surface-muted);
}
.ci-seller-onboarding__steps > button[aria-current="step"] {
background: var(--ci-color-surface-subtle);
}
.ci-seller-onboarding__step-title {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: nowrap;
font-size: 13px;
font-weight: 550;
}
.ci-seller-onboarding__steps > button[data-optional] .ci-seller-onboarding__step-title {
white-space: nowrap;
font-size: 12px;
gap: 4px;
}
.ci-seller-onboarding__step-badge {
flex-shrink: 0;
border: 1px solid var(--ci-color-border-subtle);
border-radius: 999px;
margin: 0;
font-size: var(--ci-font-size-3xs);
padding: 2px 6px;
}
.ci-seller-onboarding__steps small {
display: block;
margin-top: 3px;
}
.ci-seller-onboarding__step-marker {
width: 24px;
height: 24px;
border: 1px solid var(--ci-color-border);
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
font-size: 12px;
}
.ci-seller-onboarding__step-marker[data-state="complete"] {
color: var(--ci-color-success);
background: var(--ci-color-success-bg);
border-color: transparent;
}
.ci-seller-onboarding__steps > button[aria-current="step"] .ci-seller-onboarding__step-marker {
background: var(--ci-color-accent);
border-color: transparent;
color: var(--ci-color-accent-foreground);
}
.ci-seller-onboarding__rail-utility {
padding: 16px 12px;
}
.ci-seller-onboarding__status {
border-top: 1px solid var(--ci-color-border-subtle);
margin: 0 12px;
padding-top: 24px;
font-size: 13px;
color: var(--ci-color-text-muted);
}
.ci-seller-onboarding__status > strong {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
margin: 8px 0;
color: var(--ci-color-foreground);
}
.ci-seller-onboarding__status > strong::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--ci-color-text-muted);
flex-shrink: 0;
}
.ci-seller-onboarding__status p {
color: var(--ci-color-text-muted);
font-size: 12px;
line-height: 1.6;
}
.ci-seller-onboarding__account {
margin-top: auto;
width: 100%;
text-align: start;
border: 0;
background: transparent;
color: inherit;
padding: 8px 0;
display: flex;
align-items: center;
gap: 10px;
font: inherit;
}
.ci-seller-onboarding__avatar {
background: var(--ci-color-accent);
color: var(--ci-color-accent-foreground);
width: 32px;
height: 32px;
border-radius: var(--ci-radius-md);
display: grid;
place-items: center;
}
.ci-seller-onboarding__account strong {
font-weight: 550;
}
.ci-seller-onboarding__account small {
display: block;
}
.ci-seller-onboarding__account > svg {
margin-inline-start: auto;
flex-shrink: 0;
}
.ci-seller-onboarding__account-menu {
min-width: 240px;
}
.ci-seller-onboarding__main {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
overflow: hidden;
}
.ci-seller-onboarding__content {
flex: 1;
min-height: 0;
width: 100%;
max-width: 1376px;
overflow-y: auto;
margin: 0;
padding: 32px 40px 24px;
scroll-padding: 24px;
}
.ci-seller-onboarding__dock {
flex-shrink: 0;
background: var(--ci-color-surface);
border-top: 1px solid var(--ci-color-border);
padding: 16px 40px;
z-index: 5;
}
.ci-seller-onboarding__footer,
.ci-seller-onboarding__actions {
display: flex;
align-items: center;
}
.ci-seller-onboarding__footer {
justify-content: space-between;
gap: 20px;
}
.ci-seller-onboarding__actions {
margin-inline-start: auto;
justify-content: flex-end;
gap: 18px;
}
.ci-seller-onboarding__actions small {
max-width: 200px;
text-align: end;
line-height: 1.5;
}
.ci-sheet.ci-seller-onboarding__mobile-rail {
width: min(280px, 100vw);
display: flex;
flex-direction: column;
gap: 24px;
overflow-y: auto;
}
.ci-seller-onboarding__mobile-rail .ci-seller-onboarding__drawer-title {
font-size: var(--ci-font-size-3xl);
font-weight: var(--ci-font-weight-medium);
line-height: var(--ci-type-heading-leading);
letter-spacing: var(--ci-type-heading-tracking);
}
.ci-seller-onboarding__rail-brand {
padding-inline: 8px;
gap: 8px;
}
.ci-seller-onboarding__rail-brand [role="img"] {
margin-bottom: 8px;
}
@media (max-width: 1050px) {
.ci-seller-onboarding__content {
padding-inline: 24px;
}
}
@media (max-width: 800px) {
.ci-seller-onboarding__brand-header {
display: none;
}
.ci-seller-onboarding__frame {
grid-template-columns: 1fr;
width: 100%;
margin: 0;
border: 0;
border-radius: 0;
}
.ci-seller-onboarding__dock {
padding: 14px 16px;
}
.ci-seller-onboarding__footer {
gap: 10px;
}
.ci-seller-onboarding__rail {
display: none;
}
.ci-seller-onboarding__mobile-header {
display: flex;
align-items: center;
gap: 12px;
padding: 14px 16px;
border-bottom: 1px solid var(--ci-color-border-subtle);
}
.ci-seller-onboarding__mobile-progress {
margin-inline-start: auto;
font-size: 12px;
color: var(--ci-color-text-muted);
}
}
@media (max-width: 760px) {
.ci-seller-onboarding__actions {
flex-direction: column;
align-items: flex-end;
gap: 10px;
}
.ci-seller-onboarding__actions small {
font-size: var(--ci-font-size-2xs);
max-width: 190px;
}
}
@media (max-width: 640px) {
.ci-seller-onboarding__content {
padding-inline: 16px;
}
}
@media (prefers-reduced-motion: reduce) {
.ci-seller-onboarding__steps > button {
transition: none;
}
}

View File

@@ -0,0 +1,25 @@
@import "./ci-seller-onboarding-layout.css";
@import "./ci-seller-cards.css";
@import "./ci-seller-earnings-summary-strip.css";
/* Surface colors from the approved seller preview. Keep them on seller components. */
:where([data-ci-seller]) {
box-sizing: border-box;
font-family: var(--ci-font-ui);
font-size: 14px;
line-height: 1.45;
color: var(--ci-color-foreground);
}
html:not([data-theme="dark"]) [data-ci-seller]:not([data-theme="dark"], [data-theme="dark"] *) {
--ci-color-background: #fbfbf8;
--ci-color-surface: #ffffff;
--ci-color-surface-subtle: #f7f7f2;
--ci-color-surface-muted: #eeeee8;
--ci-color-foreground: #031a1b;
--ci-color-heading: #040d10;
--ci-color-text-muted: #575f5f;
--ci-color-border: #040d103d;
--ci-color-border-subtle: #040d1017;
--ci-color-accent-surface-strong: #eeeee8;
}

View File

@@ -11,3 +11,5 @@
@import "./invoice-document.css";
@import "./cloud-patterns.css";
@import "./cloud-auth-handoff.css";
@import "./variable-textarea.css";
@import "./ci-seller-patterns.css";

View File

@@ -159,6 +159,13 @@
--ci-scale-div-5: #3969a6;
--ci-scale-div-6: #06498e;
--ci-scale-div-7: #012d5d;
/* Flow-canvas connectors, per state. They are graphics: 3:1 or better on the canvas,
background, surface, subtle and muted surfaces. Aliases, so each theme's status
colours and neutral mid-grey carry over. */
--ci-flow-edge-active: var(--ci-color-success);
--ci-flow-edge-warning: var(--ci-color-warning);
--ci-flow-edge-error: var(--ci-color-danger);
--ci-flow-edge-idle: var(--ci-scale-div-4);
/* Approved muted tints for illustrated announcement surfaces (both themes). */
--ci-color-announcement-info: #689ed7;
@@ -212,6 +219,10 @@
--ci-font-mono: var(--ci-font-ui);
--ci-font-code: ui-monospace, "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace;
/* 3xs and 2xs are for labels only (axis, legend, hint, counter, group label).
Body text starts at xs. */
--ci-font-size-3xs: 0.625rem;
--ci-font-size-2xs: 0.6875rem;
--ci-font-size-xs: 0.75rem;
--ci-font-size-sm: 0.875rem;
--ci-font-size-md: 1rem;
@@ -266,6 +277,12 @@
--ci-type-ui-size: var(--ci-font-size-sm);
--ci-type-ui-weight: var(--ci-font-weight-medium);
--ci-type-ui-leading: var(--ci-line-height-ui);
/* Interface heading sizes: .ci-heading[data-size] and SectionHeader size. */
--ci-type-heading-size-xs: var(--ci-font-size-xs);
--ci-type-heading-size-sm: var(--ci-font-size-sm);
--ci-type-heading-size-md: var(--ci-font-size-md);
--ci-type-heading-size-lg: var(--ci-font-size-lg);
--ci-type-heading-size-xl: var(--ci-font-size-xl);
--ci-type-display-family: var(--ci-font-display);
--ci-type-display-weight: var(--ci-font-weight-medium);
--ci-type-display-leading: var(--ci-type-heading-leading);
@@ -274,7 +291,7 @@
--ci-type-dashboard-display-weight: var(--ci-font-weight-medium);
--ci-type-dashboard-display-leading: var(--ci-type-heading-leading);
/* Approved compact summary geometry for dashboard stat cards. */
--ci-type-stat-eyebrow-size: 0.625rem;
--ci-type-stat-eyebrow-size: var(--ci-font-size-3xs);
--ci-type-stat-eyebrow-value-size: 2.125rem;
--ci-stat-eyebrow-icon-stroke-width: 1.75;
/* App-owned headers/canvases can share the documented appearance contract. */
@@ -308,11 +325,13 @@
--ci-space-40: 10rem;
/* --- sizing and layout --------------------------------------------------- */
--ci-control-height-xs: 1.5rem;
--ci-control-height-sm: 2rem;
--ci-control-height-md: 2.25rem;
--ci-control-height-lg: 2.5rem;
--ci-control-height-xl: 3rem;
--ci-badge-height: 1.5rem;
--ci-badge-height-sm: 1.25rem;
--ci-icon-size-sm: 1rem;
--ci-icon-size-xs: 0.75rem;
--ci-icon-size-md: 1.25rem;
@@ -335,6 +354,8 @@
--ci-radius-full: 9999px;
--ci-radius-control: var(--ci-radius-md);
--ci-radius-surface: var(--ci-radius-sm);
/* A surface inside a surface (an inset card). Never rounder than --ci-radius-surface. */
--ci-radius-surface-nested: var(--ci-radius-sm);
--ci-radius-pill: var(--ci-radius-full);
--ci-border-hairline: 1px;
--ci-border-default: 1px;
@@ -394,6 +415,15 @@
--ci-sidebar-fg: var(--ci-color-foreground);
--ci-sidebar-active-bg: var(--ci-color-surface-inverse);
--ci-sidebar-active-fg: var(--ci-color-text-inverse);
/* Scrollbars, read by the opt-in .ci-scrollbars rule; the persistent scrollbar of Table reads
the two thumb colours too. The thumb is the quietest neutral step that keeps 3:1 on the
background, surface, subtle and muted surfaces of its theme, and the hover step is one
further. The size applies where ::-webkit-scrollbar is supported (Chromium, Safari);
Firefox draws its own thin bar. */
--ci-scrollbar-thumb: var(--ci-neutral-500);
--ci-scrollbar-thumb-hover: var(--ci-neutral-600);
--ci-scrollbar-track: transparent;
--ci-scrollbar-size: var(--ci-space-2);
/* --- shadcn-compatible aliases ------------------------------------------ */
--background: var(--ci-color-background);
@@ -540,6 +570,8 @@
--ci-button-primary-hover: var(--ci-color-accent-hover);
--ci-sidebar-active-bg: var(--ci-color-accent);
--ci-sidebar-active-fg: var(--ci-color-accent-foreground);
--ci-scrollbar-thumb: var(--ci-neutral-400);
--ci-scrollbar-thumb-hover: var(--ci-neutral-300);
--primary: var(--ci-color-accent);
--primary-foreground: var(--ci-color-accent-foreground);

View File

@@ -1,7 +1,19 @@
/* Public typography roles. These deliberately leave font-size and responsive
variants to the component/host. Import through styles.css for font loading. */
variants to the component/host. Import through styles.css for font loading.
Cascade of the tag defaults (the `:where(.ci-theme) …` selectors). They are
unlayered, so by default they beat every layered declaration, kit component
classes and host utilities alike. Two exits, neither changes that default:
- a class that sets all four properties itself (the role classes and
`.ci-eyebrow`) is listed in the `:not()` of each default, so it reads
the same on any tag;
- `data-ci-type-roles="layered"` on a container moves the defaults of its
descendants into `@layer utilities.ci-type-roles` (end of this file):
still above every `components` rule, below the host's utilities.
Keep the layered copy identical to these rules; both modes are measured in
tests/visual/css-typography-roles.spec.ts. */
.type-heading,
:where(.ci-theme) :is(h1, h2, h3, h4, h5, h6, [role="heading"]) {
:where(.ci-theme) :is(h1, h2, h3, h4, h5, h6, [role="heading"]):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-medium);
line-height: var(--ci-type-heading-leading);
@@ -30,7 +42,7 @@
.type-reading,
:where(.type-reading) :where(p, li, dd, blockquote, pre, code, kbd, samp),
:where(.ci-theme) :is(pre, code, kbd, samp) {
:where(.ci-theme) :is(pre, code, kbd, samp):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-regular);
line-height: var(--ci-type-reading-leading);
@@ -38,7 +50,7 @@
}
.type-control,
:where(.ci-theme) :where(button, label, th, [role="button"], [role="tab"], [role="menuitem"], [role="option"]):where(:not(.ci-select__trigger, .ci-searchable-select__trigger--field)) {
:where(.ci-theme) :where(button, label, th, [role="button"], [role="tab"], [role="menuitem"], [role="option"]):where(:not(.ci-select__trigger, .ci-searchable-select__trigger--field, .type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-medium);
line-height: var(--ci-type-control-leading);
@@ -46,7 +58,7 @@
}
.type-data,
:where(.ci-theme) :is(input, textarea, td) {
:where(.ci-theme) :is(input, textarea, td):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-regular);
line-height: var(--ci-type-data-leading);
@@ -54,13 +66,20 @@
}
.type-caption,
:where(.ci-theme) :is(small, figcaption, [role="tooltip"]) {
:where(.ci-theme) :is(small, figcaption, [role="tooltip"]):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-regular);
line-height: var(--ci-type-caption-leading);
letter-spacing: var(--ci-type-caption-tracking);
}
/* `mono` on Input and Textarea. Their rules are in ci-ui.css, inside
@layer components, where the unlayered input and textarea default above
wins whatever the specificity. What that default sets is repeated here. */
.ci-input--mono,
.ci-textarea--mono { font-family: var(--ci-font-code); }
.ci-textarea--mono { line-height: var(--ci-type-reading-leading); }
/* Use for standalone numeric metrics at 24px and above. Small numbers inherit
the component weight and leading; text-valued stats use heading/text roles. */
.type-metric {
@@ -69,14 +88,97 @@
line-height: var(--ci-type-metric-leading);
letter-spacing: var(--ci-type-metric-tracking);
}
/* A page number rendered as a <button> keeps the tracking of the link over the control default above. */
.ci-pagination__link:not(.ci-pagination__link--edge) { letter-spacing: 0em; }
.type-number,
.ci-range-calendar__day-button { letter-spacing: 0em; }
/* Component rules that set their own type on an element the tag defaults
cover. They are written in @layer components, where the unlayered defaults
above would win, so their type declarations are repeated here, and once
more in the layered copy below for `data-ci-type-roles="layered"`. Like
the defaults, they skip an element that carries a role class or
`.ci-eyebrow`. */
.ci-recovery-state__title:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { line-height: 1.15; letter-spacing: -.025em; }
.ci-recovery-state__reference code:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)),
.ci-secret-value__value:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-family: var(--ci-font-code); }
.ci-secret-value__value:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { line-height: var(--ci-type-body-leading); }
.ci-stacked-chart__legend:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { line-height: 1.5; }
.ci-calendar-heatmap__grid th:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: var(--ci-font-weight-regular); }
.ci-chat-composer .ci-chat-composer__input:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { line-height: 1.5; }
.ci-chat-history__group > h3:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: 400; line-height: 1.4; }
.ci-chat-history .ci-chat-history__row:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: 400; }
.ci-usage-receipt__heading h3:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: 600; }
.ci-usage-models th:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)),
.ci-usage-models td:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: 400; }
.ci-usage-models tfoot th:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)),
.ci-usage-models tfoot td:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: 600; }
.ci-notification-feed__body h3:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: 600; line-height: 24px; }
.ci-scope-chip:has(.ci-scope-chip__chevron) .ci-scope-chip__summary:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: var(--ci-font-weight-regular); }
.ci-range-calendar__day--selected:not(.ci-range-calendar__day--range-middle) .ci-range-calendar__day-button:where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow, [data-ci-type-roles="layered"] *)) { font-weight: var(--ci-font-weight-semibold); }
.type-control:is([aria-selected="true"], [aria-pressed="true"], [aria-checked="true"], [aria-current], [data-state="checked"], [data-state="active"]),
:where(.ci-theme) :is(button, [role="tab"], [role="option"], [role="menuitem"], [role="radio"], [role="checkbox"], [role="menuitemcheckbox"], [role="menuitemradio"]):is([aria-selected="true"], [aria-pressed="true"], [aria-checked="true"], [aria-current], [data-state="checked"], [data-state="active"], [data-active]:not([data-active="false"])) {
font-weight: var(--ci-font-weight-semibold);
}
/* The tag defaults and the component rules again for
`data-ci-type-roles="layered"`. A sublayer of `utilities` ranks above `base`
and `components` whatever the import order, and below the rules a host
writes directly in `utilities`. Selected emphasis (the rule above) stays
unlayered in both modes. */
@layer utilities.ci-type-roles {
:where(.ci-theme) :is(h1, h2, h3, h4, h5, h6, [role="heading"]):where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-medium);
line-height: var(--ci-type-heading-leading);
letter-spacing: var(--ci-type-heading-tracking);
}
:where(.ci-theme) :is(pre, code, kbd, samp):where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-regular);
line-height: var(--ci-type-reading-leading);
letter-spacing: var(--ci-type-reading-tracking);
}
:where(.ci-theme) :where(button, label, th, [role="button"], [role="tab"], [role="menuitem"], [role="option"]):where([data-ci-type-roles="layered"] *):where(:not(.ci-select__trigger, .ci-searchable-select__trigger--field, .type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-medium);
line-height: var(--ci-type-control-leading);
letter-spacing: var(--ci-type-control-tracking);
}
:where(.ci-theme) :is(input, textarea, td):where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-regular);
line-height: var(--ci-type-data-leading);
letter-spacing: var(--ci-type-data-tracking);
}
:where(.ci-theme) :is(small, figcaption, [role="tooltip"]):where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) {
font-family: var(--ci-font-ui);
font-weight: var(--ci-font-weight-regular);
line-height: var(--ci-type-caption-leading);
letter-spacing: var(--ci-type-caption-tracking);
}
/* The component rules again, after the defaults they override. */
.ci-recovery-state__title:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { line-height: 1.15; letter-spacing: -.025em; }
.ci-recovery-state__reference code:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)),
.ci-secret-value__value:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-family: var(--ci-font-code); }
.ci-secret-value__value:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { line-height: var(--ci-type-body-leading); }
.ci-stacked-chart__legend:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { line-height: 1.5; }
.ci-calendar-heatmap__grid th:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: var(--ci-font-weight-regular); }
.ci-chat-composer .ci-chat-composer__input:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { line-height: 1.5; }
.ci-chat-history__group > h3:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: 400; line-height: 1.4; }
.ci-chat-history .ci-chat-history__row:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: 400; }
.ci-usage-receipt__heading h3:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: 600; }
.ci-usage-models th:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)),
.ci-usage-models td:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: 400; }
.ci-usage-models tfoot th:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)),
.ci-usage-models tfoot td:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: 600; }
.ci-notification-feed__body h3:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: 600; line-height: 24px; }
.ci-scope-chip:has(.ci-scope-chip__chevron) .ci-scope-chip__summary:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: var(--ci-font-weight-regular); }
.ci-range-calendar__day--selected:not(.ci-range-calendar__day--range-middle) .ci-range-calendar__day-button:where([data-ci-type-roles="layered"] *):where(:not(.type-heading, .type-body, .type-reading, .type-control, .type-data, .type-caption, .ci-eyebrow)) { font-weight: var(--ci-font-weight-semibold); }
}
@layer base {
:is(.ci-theme, .type-reading, .type-body) :is(strong, b) { font-weight: var(--ci-font-weight-semibold); }
/* An inner lang element would otherwise inherit the parent's computed

File diff suppressed because it is too large Load Diff

View File

@@ -57,7 +57,7 @@
.ci-wizard[data-variant="onboarding"] .ci-wizard__steps li { flex:1; min-width:0; gap:0; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__steps li:last-child { flex:0 0 auto; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__steps li:not(:last-child)::after { content:""; height:1px; flex:1; min-width:.5rem; margin-inline:.75rem; background:var(--ci-color-border); }
.ci-wizard[data-variant="onboarding"] .ci-wizard__step-content { gap:8px; white-space:nowrap; text-align:left; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__step-content { gap:8px; white-space:nowrap; text-align:start; }
.ci-wizard__steps [data-complete="true"]:not([aria-current="step"]) .ci-wizard__number { color:var(--ci-color-success); border-color:var(--ci-color-success); }
.ci-wizard[data-variant="onboarding"] [aria-current="step"] .ci-wizard__number { border-color:var(--ci-color-accent); }
.ci-wizard[data-variant="onboarding"] .ci-wizard__number { width:23px; height:23px; font-size:12px; }
@@ -74,7 +74,7 @@
.ci-wizard[data-variant="onboarding"] .ci-wizard__steps { gap:.5rem; align-items:flex-start; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__steps li,.ci-wizard[data-variant="onboarding"] .ci-wizard__steps li:last-child { flex:1; justify-content:center; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__steps li:not(:last-child)::after { display:none; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__step-content { flex-direction:column; min-height:2.75rem; white-space:normal; text-align:center; font-size:.6875rem; line-height: var(--ci-type-control-leading); font-weight: var(--ci-font-weight-medium); letter-spacing: var(--ci-type-control-tracking); }
.ci-wizard[data-variant="onboarding"] .ci-wizard__step-content { flex-direction:column; min-height:2.75rem; white-space:normal; text-align:center; font-size:var(--ci-font-size-2xs); line-height: var(--ci-type-control-leading); font-weight: var(--ci-font-weight-medium); letter-spacing: var(--ci-type-control-tracking); }
.ci-wizard[data-variant="onboarding"] .ci-wizard__step-content > svg { display:none; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__title { font-size:1.875rem; margin-top:1.25rem; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-wizard[data-variant="onboarding"] .ci-wizard__actions { display:grid; grid-template-columns:1fr 1fr; gap:.5rem; }
@@ -91,7 +91,7 @@
@media(max-width:640px) {
.ci-wizard[data-variant="onboarding"] .ci-wizard__steps { padding:8px 0 12px; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__step-content { gap:6px; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__step-link { font-size:10px; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-wizard[data-variant="onboarding"] .ci-wizard__step-link { font-size:var(--ci-font-size-3xs); font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-wizard[data-variant="onboarding"] .ci-wizard__description { padding-bottom:20px; }
.ci-wizard[data-variant="onboarding"][data-layout="sidebar"] .ci-wizard__body { padding-top:0; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__footer { padding:10px 0 max(10px,env(safe-area-inset-bottom)); }
@@ -99,7 +99,7 @@
/* Content-sized setup: public Wizard layout, never dashboard internal overrides. */
.ci-wizard[data-layout="sidebar"] { width:100%; max-width:76rem; margin-block:1.5rem; }
.ci-wizard[data-layout="sidebar"] > .ci-wizard__content { display:grid; grid-template-columns:12rem minmax(0,1fr); column-gap:2rem; padding:2rem; }
.ci-wizard[data-layout="sidebar"] > .ci-wizard__content { display:grid; grid-template-columns:var(--ci-wizard-sidebar-width, 12rem) minmax(0,1fr); column-gap:2rem; padding:2rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__top { grid-column:1; align-self:start; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__steps { grid-column:1; grid-row:2 / span 2; display:flex; flex-direction:column; align-self:start; gap:.625rem; padding:1rem 0; border:0; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__steps li { flex:none; width:100%; padding:.625rem 0; }
@@ -119,7 +119,7 @@
.ci-wizard[data-layout="sidebar"] .ci-wizard__step-title { display:none; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__viewport { margin-top:.75rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__body { padding-block:1.25rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__steps [aria-current="step"] .ci-wizard__step-title { display:block; font-size:.6875rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__steps [aria-current="step"] .ci-wizard__step-title { display:block; font-size:var(--ci-font-size-2xs); }
}
/* The public fill + sidebar composition keeps both navigation and actions in
@@ -254,3 +254,99 @@
.ci-wizard[data-fill="true"][data-layout="sidebar"] > .ci-wizard__content { padding-top:2rem; padding-bottom:1rem; }
.ci-wizard[data-fill="true"][data-layout="sidebar"] .ci-wizard__scroll { padding-top:.5rem; }
}
/* Nested sections share the parent step count; the caller owns their state. */
.ci-wizard__steps > li[data-has-substeps] { flex-direction:column; align-items:flex-start; }
.ci-wizard__substeps-desktop { width:100%; padding-inline-start:1.9375rem; padding-top:.5rem; }
.ci-wizard__substeps { display:flex; flex-direction:column; gap:.25rem; }
.ci-wizard__substep { touch-action:manipulation; -webkit-tap-highlight-color:transparent; appearance:none; border:0; background:transparent; color:var(--ci-color-text-muted); display:flex; align-items:center; gap:.5rem; min-height:2.5rem; padding:.5rem .625rem; border-radius:var(--ci-radius-control); text-align:start; font:inherit; font-size:.8125rem; cursor:pointer; }
.ci-wizard__substep > svg { width:1rem; height:1rem; flex-shrink:0; }
.ci-wizard__substep:hover:not(:disabled) { background:var(--ci-color-surface-muted); color:var(--ci-color-heading); }
.ci-wizard__substep[aria-current="step"] { background:color-mix(in srgb,var(--ci-color-accent) 20%,var(--ci-card-bg)); color:var(--ci-color-heading); font-weight:var(--ci-font-weight-semibold); }
.ci-wizard__substep:focus-visible { outline:2px solid var(--ci-color-focus); outline-offset:2px; }
.ci-wizard__substep:disabled { opacity:.5; cursor:default; }
.ci-wizard__substeps-mobile { display:none; }
@media(max-width:760px), (hover:none) and (pointer:coarse) {
.ci-wizard__substeps-desktop { display:none; }
.ci-wizard__substeps-mobile { display:block; margin-bottom:.75rem; }
.ci-wizard__substeps-mobile .ci-wizard__substeps { flex-direction:row; flex-wrap:wrap; }
.ci-wizard__substeps-mobile .ci-wizard__substep { min-height:2.75rem; }
}
/* Optional public badge slots wrap without changing string-based navigation labels. */
.ci-wizard__title[data-has-badge] { display:flex; flex-wrap:wrap; align-items:center; gap:.5rem .75rem; }
.ci-wizard__title[data-has-badge] > span:first-child { min-width:0; overflow-wrap:anywhere; }
.ci-wizard__title-badge { display:inline-flex; align-items:center; flex:none; min-width:0; max-width:100%; vertical-align:middle; }
.ci-wizard__step-title[data-has-badge] { min-width:0; }
.ci-wizard__step-title[data-has-badge] > .ci-wizard__title-badge { margin-inline-start:.375rem; }
@media(min-width:761px) and (hover:hover) {
.ci-wizard[data-layout="sidebar"]:has(.ci-wizard__step-title[data-has-badge]) > .ci-wizard__content { grid-template-columns:var(--ci-wizard-sidebar-width, 15rem) minmax(0,1fr); }
}
/* Respond to the available panel, including beside a dashboard navigation rail. */
.ci-wizard:has(.ci-wizard__substeps) { container-type: inline-size; container-name: ci-wizard; }
@container ci-wizard (max-width: 760px) {
.ci-wizard[data-layout="sidebar"] > .ci-wizard__content { display:flex; flex-direction:column; padding:1.25rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__steps { flex-direction:row; gap:.5rem; padding:.75rem 0 1rem; flex:none; max-height:none; overflow:visible; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__steps li { width:auto; flex:1; padding:0; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__step-content { flex-direction:column; min-height:2.75rem; text-align:center; gap:.375rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__step-content > svg { display:none; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__step-title { display:none; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__steps [aria-current="step"] .ci-wizard__step-title { display:block; font-size:var(--ci-font-size-2xs); }
.ci-wizard__substeps-desktop { display:none; }
.ci-wizard__substeps-mobile { display:block; flex:none; margin-bottom:.75rem; }
.ci-wizard__substeps-mobile .ci-wizard__substeps { flex-direction:row; flex-wrap:wrap; }
.ci-wizard__substeps-mobile .ci-wizard__substep { min-height:2.75rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__viewport { margin-top:.75rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__body { padding-block:1.25rem; }
.ci-wizard[data-layout="sidebar"] .ci-wizard__footer { flex:none; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__actions { display:grid; grid-template-columns:1fr 1fr; gap:.5rem; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__actions > div { display:contents; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__actions > div > .ci-button:last-child { grid-column:1 / -1; }
.ci-wizard[data-variant="onboarding"] .ci-wizard__actions .ci-button { min-height:2.75rem; white-space:normal; height:auto; }
}
/* Compact phone progress keeps the page heading as the single optional marker. */
@media (max-width:640px) {
.ci-wizard[data-mobile-progress-detail="minimal"] .ci-wizard__substeps-mobile,
.ci-wizard[data-mobile-progress-detail="minimal"] .ci-wizard__step-title > .ci-wizard__title-badge { display:none; }
.ci-wizard[data-mobile-progress-detail="minimal"] .ci-wizard__title > .ci-wizard__title-badge .ci-badge {
font-size:.875rem;
padding:.375rem .625rem;
color:var(--ci-color-heading);
background:var(--ci-color-surface-muted);
font-weight:var(--ci-font-weight-semibold);
}
}
@media(max-width:640px) {
.ci-wizard[data-mobile-progress-detail="minimal"] .ci-wizard__title { text-wrap:wrap; }
.ci-wizard[data-mobile-progress-detail="minimal"] .ci-wizard__title > span:first-child { flex-basis:100%; }
.ci-wizard[data-mobile-progress-detail="minimal"] .ci-wizard__title-badge { gap:.5rem; flex-wrap:wrap; }
}
/* Explicit sticky actions also apply to sidebar and mobile document layouts.
Keep the footer in flow so the last form field can scroll clear of it. */
.ci-wizard[data-footer-position="sticky"] .ci-wizard__footer,
.ci-wizard[data-footer-position="sticky"][data-mobile-layout="document"] .ci-wizard__footer {
position:sticky;
bottom:0;
}
.ci-wizard[data-fill="true"][data-footer-position="sticky"] {
margin-block:0;
}
.ci-wizard[data-footer-position="sticky"] .ci-wizard__actions {
display:flex;
}
.ci-wizard[data-footer-position="sticky"] .ci-wizard__actions > div {
display:flex;
min-width:0;
justify-content:flex-end;
}
.ci-wizard[data-footer-position="sticky"] .ci-wizard__actions > .ci-button {
flex-shrink:0;
}
.ci-wizard[data-footer-position="sticky"] .ci-wizard__actions > div .ci-button {
min-width:0;
}

View File

@@ -1,12 +1,12 @@
.ci-cloud-auth{max-width:680px;margin:36px auto 70px;overflow:hidden;border:1px solid var(--ci-color-border-subtle);border-radius:20px;background:var(--ci-color-surface);font-family:var(--ci-font-ui);color:var(--ci-color-text);box-shadow:0 12px 45px color-mix(in srgb,var(--ci-color-text) 3%,transparent)}
.ci-cloud-auth__visual{position:relative;display:flex;align-items:center;justify-content:center;gap:18px;min-height:218px;padding:28px 40px;background:radial-gradient(ellipse at 65% 50%,color-mix(in srgb,var(--ci-color-accent) 13%,transparent),transparent 70%),var(--ci-color-surface-subtle);border-bottom:1px solid var(--ci-color-border-subtle)}
.ci-cloud-auth__account{display:flex;flex-direction:column;align-items:center;gap:10px;padding:20px 12px;min-width:148px}.ci-cloud-auth__account>svg{color:var(--ci-color-accent-active)}.ci-cloud-auth__account>span{font-size:13px;font-weight:500}.ci-cloud-auth__account>small{display:flex;align-items:center;gap:4px;font-size:10px;color:var(--ci-color-text-muted)}
.ci-cloud-auth__account{display:flex;flex-direction:column;align-items:center;gap:10px;padding:20px 12px;min-width:148px}.ci-cloud-auth__account>svg{color:var(--ci-color-accent-active)}.ci-cloud-auth__account>span{font-size:13px;font-weight:500}.ci-cloud-auth__account>small{display:flex;align-items:center;gap:4px;font-size:var(--ci-font-size-3xs);color:var(--ci-color-text-muted)}
.ci-cloud-auth__wire{position:relative;display:flex;align-items:center;width:90px;color:var(--ci-color-accent-active)}.ci-cloud-auth__wire:before{content:"";height:1px;flex:1;background:var(--ci-color-border)}.ci-cloud-auth__wire>svg{flex:none}.ci-cloud-auth__wire>span{position:absolute;left:0;width:12px;height:2px;background:var(--ci-color-accent-active);border-radius:2px;animation:ci-cloud-auth-flow 1.8s ease-in-out infinite}.ci-cloud-auth:not([data-state=opening]) .ci-cloud-auth__wire>span{display:none}
.ci-cloud-auth__gateway{display:flex;flex-direction:column;align-items:center;gap:4px}.ci-cloud-auth__gateway>[data-slot=brand-loader]{color:var(--ci-color-accent-active)}.ci-cloud-auth__gateway>span{display:flex;gap:6px;align-items:center;font-size:13px;font-weight:500;margin-top:-12px}
.ci-cloud-auth__body{padding:35px 40px 30px}.ci-cloud-auth__eyebrow{display:flex;align-items:center;gap:6px;font:500 10px/1.5 var(--ci-font-ui);letter-spacing:.08em;text-transform:uppercase;color:var(--ci-color-text-muted);margin:0 0 14px}.ci-cloud-auth h1{font:500 clamp(25px,4vw,32px)/1.2 var(--ci-font-ui);letter-spacing:-.04em;color:var(--ci-color-heading);margin:0 0 12px}.ci-cloud-auth__description{font:400 13px/1.85 var(--ci-font-ui);color:var(--ci-color-text-muted);max-width:455px;margin:0}
.ci-cloud-auth__destination{display:flex;align-items:center;gap:9px;margin:22px 0 0;padding:12px 14px;border:1px solid var(--ci-color-border-subtle);background:var(--ci-color-surface-subtle);border-radius:9px;font:11px/1.7 var(--ci-font-mono);color:var(--ci-color-text-muted)}.ci-cloud-auth__destination>svg{flex:none}.ci-cloud-auth__destination>span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ci-cloud-auth__destination>i{margin-left:auto;flex:none;width:5px;height:5px;border-radius:50%;background:var(--ci-color-accent-active);animation:ci-cloud-auth-pulse 2s ease-in-out infinite}
.ci-cloud-auth__actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:26px}.ci-cloud-auth__actions>.ci-button{justify-content:center;font-size:12px;gap:8px;min-height:37px}.ci-cloud-auth__actions>.ci-button svg{flex:none;width:14px;height:14px}.ci-cloud-auth__security{display:flex;align-items:center;gap:6px;font:400 10px/1.7 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:25px 0 0;padding-top:20px;border-top:1px solid var(--ci-color-border-subtle)}.ci-cloud-auth__security>svg{flex:none}
.ci-cloud-connection__progress{display:flex;align-items:center;gap:5px;font:12px/1.7 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:12px 0}.ci-cloud-connection__progress>[data-slot=brand-loader]{flex:none}.ci-cloud-connection .ci-cloud-connection__error{font:12px/1.75 var(--ci-font-ui);color:var(--ci-color-text);border-left:2px solid var(--ci-color-accent-active);padding:3px 0 3px 12px;margin:18px 0}
.ci-cloud-auth__body{padding:35px 40px 30px}.ci-cloud-auth__eyebrow{display:flex;align-items:center;gap:6px;font:500 var(--ci-font-size-3xs)/1.5 var(--ci-font-ui);letter-spacing:.08em;text-transform:uppercase;color:var(--ci-color-text-muted);margin:0 0 14px}.ci-cloud-auth h1{font:500 clamp(25px,4vw,32px)/1.2 var(--ci-font-ui);letter-spacing:-.04em;color:var(--ci-color-heading);margin:0 0 12px}.ci-cloud-auth__description{font:400 13px/1.85 var(--ci-font-ui);color:var(--ci-color-text-muted);max-width:455px;margin:0}
.ci-cloud-auth__destination{display:flex;align-items:center;gap:9px;margin:22px 0 0;padding:12px 14px;border:1px solid var(--ci-color-border-subtle);background:var(--ci-color-surface-subtle);border-radius:9px;font:var(--ci-font-size-2xs)/1.7 var(--ci-font-mono);color:var(--ci-color-text-muted)}.ci-cloud-auth__destination>svg{flex:none}.ci-cloud-auth__destination>span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ci-cloud-auth__destination>i{margin-inline-start:auto;flex:none;width:5px;height:5px;border-radius:50%;background:var(--ci-color-accent-active);animation:ci-cloud-auth-pulse 2s ease-in-out infinite}
.ci-cloud-auth__actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:26px}.ci-cloud-auth__actions>.ci-button{justify-content:center;font-size:12px;gap:8px;min-height:37px}.ci-cloud-auth__actions>.ci-button svg{flex:none;width:14px;height:14px}.ci-cloud-auth__security{display:flex;align-items:center;gap:6px;font:400 var(--ci-font-size-3xs)/1.7 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:25px 0 0;padding-top:20px;border-top:1px solid var(--ci-color-border-subtle)}.ci-cloud-auth__security>svg{flex:none}
.ci-cloud-connection__progress{display:flex;align-items:center;gap:5px;font:12px/1.7 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:12px 0}.ci-cloud-connection__progress>[data-slot=brand-loader]{flex:none}.ci-cloud-connection .ci-cloud-connection__error{font:12px/1.75 var(--ci-font-ui);color:var(--ci-color-text);border-inline-start:2px solid var(--ci-color-accent-active);padding-block:3px;padding-inline:12px 0;margin:18px 0}
@keyframes ci-cloud-auth-flow{0%{transform:translateX(0);opacity:0}25%{opacity:1}100%{transform:translateX(70px);opacity:0}}@keyframes ci-cloud-auth-pulse{50%{opacity:.35}}
@media(max-width:480px){.ci-cloud-auth{margin:10px auto 38px;border-radius:15px}.ci-cloud-auth__visual{padding:20px 16px;min-height:182px;gap:8px}.ci-cloud-auth__account{min-width:118px;padding:16px 0}.ci-cloud-auth__account>span{font-size:11px}.ci-cloud-auth__wire{width:45px}.ci-cloud-auth__gateway>[data-slot=brand-loader]{max-width:105px}.ci-cloud-auth__body{padding:26px 22px}.ci-cloud-auth__actions{flex-direction:column}.ci-cloud-auth__security{font-size:10px}.ci-cloud-auth__wire>span{max-width:6px}@keyframes ci-cloud-auth-flow{100%{transform:translateX(30px);opacity:0}}}
@media(max-width:480px){.ci-cloud-auth{margin:10px auto 38px;border-radius:15px}.ci-cloud-auth__visual{padding:20px 16px;min-height:182px;gap:8px}.ci-cloud-auth__account{min-width:118px;padding:16px 0}.ci-cloud-auth__account>span{font-size:var(--ci-font-size-2xs)}.ci-cloud-auth__wire{width:45px}.ci-cloud-auth__gateway>[data-slot=brand-loader]{max-width:105px}.ci-cloud-auth__body{padding:26px 22px}.ci-cloud-auth__actions{flex-direction:column}.ci-cloud-auth__security{font-size:var(--ci-font-size-3xs)}.ci-cloud-auth__wire>span{max-width:6px}@keyframes ci-cloud-auth-flow{100%{transform:translateX(30px);opacity:0}}}
@media(prefers-reduced-motion:reduce){.ci-cloud-auth *{animation:none!important;transition:none!important}}

View File

@@ -1,38 +1,38 @@
/* Cloud patterns use shared semantic tokens; the decorative topology uses the inverse surface and brand accent. */
.ci-cloud-configurator,.ci-cloud-instance{color:var(--ci-color-text);width:100%;max-width:1180px;margin-inline:auto;font-family:var(--ci-font-ui)}
.ci-cloud-heading{padding:8px 0 32px;max-width:740px}.ci-cloud-eyebrow{display:flex;align-items:center;gap:9px;font-family:var(--ci-font-mono);font-size:10px;font-weight:600;letter-spacing:.11em;color:var(--ci-color-text-muted)}
.ci-cloud-heading{padding:8px 0 32px;max-width:740px}.ci-cloud-eyebrow{display:flex;align-items:center;gap:9px;font-family:var(--ci-font-mono);font-size:var(--ci-font-size-3xs);font-weight:600;letter-spacing:.11em;color:var(--ci-color-text-muted)}
.ci-cloud-heading h1{font-family:var(--ci-font-display);color:var(--ci-color-heading);font-size:clamp(30px,3.1vw,42px);font-weight:500;line-height:1.04;letter-spacing:-.035em;margin:18px 0 14px}.ci-cloud-heading>p{max-width:580px;line-height:1.7;font-size:14px;color:var(--ci-color-text-muted);margin:0}
.ci-cloud-layout{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:48px;align-items:start}.ci-cloud-editor{padding:0}.ci-cloud-divider{height:1px;background:var(--ci-color-border-subtle);margin:30px 0}.ci-cloud-fields{display:grid;grid-template-columns:1fr 1.2fr;gap:14px}.ci-cloud-specs{display:grid;grid-template-columns:1fr 1fr;gap:15px;padding:22px 0;color:var(--ci-color-text-muted);font-size:12px}.ci-cloud-specs>span{display:flex;align-items:center;gap:7px}.ci-cloud-specs strong{color:var(--ci-color-heading);font-weight:500}.ci-cloud-advanced{border-top:1px solid var(--ci-color-border-subtle);padding-top:17px;font-size:12px}.ci-cloud-advanced summary{cursor:pointer;color:var(--ci-color-text-muted)}.ci-cloud-advanced[open] summary{margin-bottom:18px}
.ci-cloud-summary{border:1px solid var(--ci-color-border-subtle);border-radius:14px;overflow:hidden;background:var(--ci-color-surface);position:sticky;top:var(--ci-cloud-sticky-top,24px)}.ci-cloud-summary__body{padding:26px}.ci-cloud-summary__title{display:flex;justify-content:space-between;align-items:center;font-size:12px;color:var(--ci-color-text-muted)}.ci-cloud-price{font-family:var(--ci-font-ui);font-size:46px;font-weight:500;letter-spacing:-.055em;color:var(--ci-color-heading);margin:14px 0 25px;line-height:1.3;font-variant-numeric:tabular-nums}.ci-cloud-price>span{font-size:12px;font-weight:400;letter-spacing:0;margin-left:8px;color:var(--ci-color-text-muted)}.ci-cloud-inclusions{list-style:none;padding:0;margin:0 0 23px;display:grid;gap:13px;font-size:12px}.ci-cloud-inclusions li{display:flex;align-items:center;gap:9px}.ci-cloud-inclusions svg{color:var(--ci-color-heading)}.ci-cloud-inference-note{display:flex;align-items:flex-start;gap:10px;border-top:1px solid var(--ci-color-border-subtle);padding-top:20px;margin-bottom:22px;color:var(--ci-color-text-muted)}.ci-cloud-inference-note svg{flex-shrink:0;margin-top:2px}.ci-cloud-inference-note p{font-size:11px;line-height:1.8;margin:0}.ci-cloud-inference-note strong{font-weight:500;color:var(--ci-color-heading)}.ci-cloud-continue{color:var(--ci-color-accent-foreground);width:min(100%,340px);display:flex;margin-inline:auto;min-height:40px;height:40px;justify-content:center;gap:11px;font-size:13px;font-weight:500;position:relative;isolation:isolate;overflow:hidden;border:1px solid color-mix(in srgb,var(--ci-color-accent-active) 18%,transparent);background:linear-gradient(135deg,color-mix(in srgb,var(--ci-color-accent) 78%,white),var(--ci-color-accent));box-shadow:inset 0 1px 0 #ffffff45,0 3px 10px color-mix(in srgb,var(--ci-color-accent-active) 10%,transparent);transition:box-shadow .2s,transform .2s}
.ci-cloud-summary{border:1px solid var(--ci-color-border-subtle);border-radius:14px;overflow:hidden;background:var(--ci-color-surface);position:sticky;top:var(--ci-cloud-sticky-top,24px)}.ci-cloud-summary__body{padding:26px}.ci-cloud-summary__title{display:flex;justify-content:space-between;align-items:center;font-size:12px;color:var(--ci-color-text-muted)}.ci-cloud-price{font-family:var(--ci-font-ui);font-size:46px;font-weight:500;letter-spacing:-.055em;color:var(--ci-color-heading);margin:14px 0 25px;line-height:1.3;font-variant-numeric:tabular-nums}.ci-cloud-price>span{font-size:12px;font-weight:400;letter-spacing:0;margin-inline-start:8px;color:var(--ci-color-text-muted)}.ci-cloud-inclusions{list-style:none;padding:0;margin:0 0 23px;display:grid;gap:13px;font-size:12px}.ci-cloud-inclusions li{display:flex;align-items:center;gap:9px}.ci-cloud-inclusions svg{color:var(--ci-color-heading)}.ci-cloud-inference-note{display:flex;align-items:flex-start;gap:10px;border-top:1px solid var(--ci-color-border-subtle);padding-top:20px;margin-bottom:22px;color:var(--ci-color-text-muted)}.ci-cloud-inference-note svg{flex-shrink:0;margin-top:2px}.ci-cloud-inference-note p{font-size:var(--ci-font-size-2xs);line-height:1.8;margin:0}.ci-cloud-inference-note strong{font-weight:500;color:var(--ci-color-heading)}.ci-cloud-continue{color:var(--ci-color-accent-foreground);width:min(100%,340px);display:flex;margin-inline:auto;min-height:40px;height:40px;justify-content:center;gap:11px;font-size:13px;font-weight:500;position:relative;isolation:isolate;overflow:hidden;border:1px solid color-mix(in srgb,var(--ci-color-accent-active) 18%,transparent);background:linear-gradient(135deg,color-mix(in srgb,var(--ci-color-accent) 78%,white),var(--ci-color-accent));box-shadow:inset 0 1px 0 #ffffff45,0 3px 10px color-mix(in srgb,var(--ci-color-accent-active) 10%,transparent);transition:box-shadow .2s,transform .2s}
@media(hover:hover) and (pointer:fine){.ci-cloud-continue:hover:not(:disabled),.ci-cloud-instance__open:hover:not(:disabled){transform:translateY(-2px);box-shadow:inset 0 1px 0 #ffffff60,0 8px 22px -8px color-mix(in srgb,var(--ci-color-accent-active) 40%,transparent)}}
.ci-cloud-continue:focus-visible,.ci-cloud-instance__open:focus-visible{outline:var(--ci-focus-ring-width) solid var(--ci-color-focus);outline-offset:var(--ci-focus-ring-offset)}
.ci-cloud-continue>svg{width:15px;height:15px;flex:none}.ci-cloud-continue[data-loading]{transform:none}.ci-cloud-continue>.ci-button__spinner{width:15px;height:15px}
.ci-cloud-field-label{display:inline-flex;gap:7px;align-items:center}.ci-cloud-help{display:inline-grid;place-items:center;width:24px;height:24px;flex:none;border:0;border-radius:50%;padding:0;background:transparent;color:var(--ci-color-text-muted);cursor:help}.ci-cloud-help:hover{color:var(--ci-color-accent-active);background:var(--ci-color-surface-muted)}.ci-cloud-help:focus-visible{outline:2px solid var(--ci-color-focus);outline-offset:2px}.ci-cloud-help__content{max-width:300px;padding:17px 19px;font:12px/1.8 var(--ci-font-ui)}.ci-cloud-help__content strong{color:var(--ci-color-heading);font-size:13px;font-weight:500}.ci-cloud-help__content p{margin:7px 0 0;color:var(--ci-color-text-muted)}.ci-cloud-advanced__help{display:flex;align-items:center;gap:4px;margin-bottom:13px;color:var(--ci-color-text-muted);font-size:11px}
.ci-cloud-field-label{display:inline-flex;gap:7px;align-items:center}.ci-cloud-help{display:inline-grid;place-items:center;width:24px;height:24px;flex:none;border:0;border-radius:50%;padding:0;background:transparent;color:var(--ci-color-text-muted);cursor:help}.ci-cloud-help:hover{color:var(--ci-color-accent-active);background:var(--ci-color-surface-muted)}.ci-cloud-help:focus-visible{outline:2px solid var(--ci-color-focus);outline-offset:2px}.ci-cloud-help__content{max-width:300px;padding:17px 19px;font:12px/1.8 var(--ci-font-ui)}.ci-cloud-help__content strong{color:var(--ci-color-heading);font-size:13px;font-weight:500}.ci-cloud-help__content p{margin:7px 0 0;color:var(--ci-color-text-muted)}.ci-cloud-advanced__help{display:flex;align-items:center;gap:4px;margin-bottom:13px;color:var(--ci-color-text-muted);font-size:var(--ci-font-size-2xs)}
.ci-cloud-consent{display:grid;gap:17px;padding:20px;border:1px solid var(--ci-color-border-subtle);border-radius:12px;background:var(--ci-color-surface-subtle)}.ci-cloud-consent .ci-checkbox__label{font-size:12px;line-height:1.8;font-weight:400}.ci-cloud-consent a{color:var(--ci-color-heading);text-decoration:underline;text-underline-offset:3px}
@media(prefers-reduced-motion:reduce){.ci-button.ci-cloud-continue,.ci-button.ci-cloud-instance__open{transition:none}.ci-cloud-continue:hover:not(:disabled),.ci-cloud-instance__open:hover:not(:disabled){transform:none}}.ci-cloud-fineprint{display:flex;align-items:center;justify-content:center;gap:5px;font-size:10px;color:var(--ci-color-text-muted);line-height:1.6;margin:13px 0 0}.ci-cloud-error{font-size:12px;line-height:1.7;color:var(--ci-color-text);padding:12px 14px;border:1px solid var(--ci-color-border);border-radius:7px;background:var(--ci-color-surface-subtle)}
.ci-cloud-topology{height:257px;background:var(--ci-color-surface-inverse);color:var(--ci-color-text-inverse);position:relative;overflow:hidden;isolation:isolate;font-family:var(--ci-font-ui)}.ci-cloud-topology__grid{position:absolute;inset:0;background-image:radial-gradient(color-mix(in srgb,var(--ci-color-accent) 20%,transparent) .75px,transparent .75px);background-size:16px 16px;mask-image:linear-gradient(transparent,#000 30%,#000 70%,transparent)}.ci-cloud-topology__orbit{position:absolute;border:1px solid color-mix(in srgb,var(--ci-color-accent) 12%,transparent);border-radius:50%;width:320px;height:320px;left:50%;top:44%;transform:translate(-50%,-50%)}.ci-cloud-topology__orbit--two{width:440px;height:440px}.ci-cloud-topology__source{display:flex;gap:8px;align-items:center;position:absolute;left:27px;top:33px;color:var(--ci-neutral-300);font-size:10px}.ci-cloud-topology__gateway{position:absolute;left:50%;top:47%;transform:translate(-50%,-50%);display:flex;align-items:center;flex-direction:column;gap:8px;width:210px;text-align:center;background:linear-gradient(160deg,color-mix(in srgb,var(--ci-color-accent) 23%,var(--ci-color-surface-inverse)),color-mix(in srgb,var(--ci-color-accent) 9%,var(--ci-color-surface-inverse)));padding:17px 10px;border:1px solid color-mix(in srgb,var(--ci-color-accent) 36%,transparent);border-radius:10px;box-shadow:0 0 40px color-mix(in srgb,var(--ci-color-accent) 6%,transparent),0 12px 30px #0003}.ci-cloud-topology__gateway>svg{color:var(--ci-color-accent)}.ci-cloud-topology__gateway strong{font-size:13px;font-weight:500;max-width:185px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ci-cloud-topology__gateway>span{font-size:9px;color:var(--ci-neutral-300);display:flex;align-items:center;gap:5px}.ci-cloud-topology__gateway i{width:4px;height:4px;border-radius:100%;background:var(--ci-color-accent)}.ci-cloud-topology__targets{position:absolute;bottom:39px;display:flex;justify-content:center;gap:16px;width:100%}.ci-cloud-topology__targets>span{display:flex;align-items:center;gap:6px;font-size:9px;background:color-mix(in srgb,var(--ci-color-accent) 8%,var(--ci-color-surface-inverse));padding:8px 10px;border:1px solid color-mix(in srgb,var(--ci-color-accent) 28%,transparent);border-radius:5px;color:var(--ci-color-text-inverse)}.ci-cloud-topology__wire{position:absolute;width:1px;background:color-mix(in srgb,var(--ci-color-accent) 50%,transparent);left:50%;height:30px;z-index:-1}.ci-cloud-topology__wire--in{top:24px;height:45px}.ci-cloud-topology__wire--out{top:173px;height:20px}.ci-cloud-topology__caption{position:absolute;bottom:12px;width:100%;display:flex;align-items:center;justify-content:center;gap:5px;font-family:var(--ci-font-mono);font-size:7px;letter-spacing:.1em;color:var(--ci-neutral-300)}
.ci-cloud-selfhost{margin-top:28px;padding:20px 0;border-top:1px solid var(--ci-color-border-subtle);display:flex;justify-content:space-between;align-items:center;gap:20px}.ci-cloud-selfhost>a{display:flex;gap:7px;align-items:center;font-size:11px;white-space:nowrap;color:var(--ci-color-heading);text-decoration:none}.ci-cloud-selfhost>a:hover{text-decoration:underline}
@media(prefers-reduced-motion:reduce){.ci-button.ci-cloud-continue,.ci-button.ci-cloud-instance__open{transition:none}.ci-cloud-continue:hover:not(:disabled),.ci-cloud-instance__open:hover:not(:disabled){transform:none}}.ci-cloud-fineprint{display:flex;align-items:center;justify-content:center;gap:5px;font-size:var(--ci-font-size-3xs);color:var(--ci-color-text-muted);line-height:1.6;margin:13px 0 0}.ci-cloud-error{font-size:12px;line-height:1.7;color:var(--ci-color-text);padding:12px 14px;border:1px solid var(--ci-color-border);border-radius:7px;background:var(--ci-color-surface-subtle)}
.ci-cloud-topology{height:257px;background:var(--ci-color-surface-inverse);color:var(--ci-color-text-inverse);position:relative;overflow:hidden;isolation:isolate;font-family:var(--ci-font-ui)}.ci-cloud-topology__grid{position:absolute;inset:0;background-image:radial-gradient(color-mix(in srgb,var(--ci-color-accent) 20%,transparent) .75px,transparent .75px);background-size:16px 16px;mask-image:linear-gradient(transparent,#000 30%,#000 70%,transparent)}.ci-cloud-topology__orbit{position:absolute;border:1px solid color-mix(in srgb,var(--ci-color-accent) 12%,transparent);border-radius:50%;width:320px;height:320px;left:50%;top:44%;transform:translate(-50%,-50%)}.ci-cloud-topology__orbit--two{width:440px;height:440px}.ci-cloud-topology__source{display:flex;gap:8px;align-items:center;position:absolute;left:27px;top:33px;color:var(--ci-neutral-300);font-size:var(--ci-font-size-3xs)}.ci-cloud-topology__gateway{position:absolute;left:50%;top:47%;transform:translate(-50%,-50%);display:flex;align-items:center;flex-direction:column;gap:8px;width:210px;text-align:center;background:linear-gradient(160deg,color-mix(in srgb,var(--ci-color-accent) 23%,var(--ci-color-surface-inverse)),color-mix(in srgb,var(--ci-color-accent) 9%,var(--ci-color-surface-inverse)));padding:17px 10px;border:1px solid color-mix(in srgb,var(--ci-color-accent) 36%,transparent);border-radius:10px;box-shadow:0 0 40px color-mix(in srgb,var(--ci-color-accent) 6%,transparent),0 12px 30px #0003}.ci-cloud-topology__gateway>svg{color:var(--ci-color-accent)}.ci-cloud-topology__gateway strong{font-size:13px;font-weight:500;max-width:185px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ci-cloud-topology__gateway>span{font-size:9px;color:var(--ci-neutral-300);display:flex;align-items:center;gap:5px}.ci-cloud-topology__gateway i{width:4px;height:4px;border-radius:100%;background:var(--ci-color-accent)}.ci-cloud-topology__targets{position:absolute;bottom:39px;display:flex;justify-content:center;gap:16px;width:100%}.ci-cloud-topology__targets>span{display:flex;align-items:center;gap:6px;font-size:9px;background:color-mix(in srgb,var(--ci-color-accent) 8%,var(--ci-color-surface-inverse));padding:8px 10px;border:1px solid color-mix(in srgb,var(--ci-color-accent) 28%,transparent);border-radius:5px;color:var(--ci-color-text-inverse)}.ci-cloud-topology__wire{position:absolute;width:1px;background:color-mix(in srgb,var(--ci-color-accent) 50%,transparent);left:50%;height:30px;z-index:-1}.ci-cloud-topology__wire--in{top:24px;height:45px}.ci-cloud-topology__wire--out{top:173px;height:20px}.ci-cloud-topology__caption{position:absolute;bottom:12px;width:100%;display:flex;align-items:center;justify-content:center;gap:5px;font-family:var(--ci-font-mono);font-size:7px;letter-spacing:.1em;color:var(--ci-neutral-300)}
.ci-cloud-selfhost{margin-top:28px;padding:20px 0;border-top:1px solid var(--ci-color-border-subtle);display:flex;justify-content:space-between;align-items:center;gap:20px}.ci-cloud-selfhost>a{display:flex;gap:7px;align-items:center;font-size:var(--ci-font-size-2xs);white-space:nowrap;color:var(--ci-color-heading);text-decoration:none}.ci-cloud-selfhost>a:hover{text-decoration:underline}
.ci-cloud-instance .ci-cloud-layout{grid-template-columns:minmax(0,1.15fr) minmax(300px,.85fr);gap:28px}
.ci-cloud-instance__header{display:flex;justify-content:space-between;align-items:center;gap:20px;padding:4px 0 26px}.ci-cloud-instance__header h1{font:500 clamp(27px,2.6vw,34px)/1.2 var(--ci-font-display);letter-spacing:-.035em;color:var(--ci-color-heading);margin:8px 0;overflow-wrap:anywhere}.ci-cloud-instance__header>.ci-badge{flex:none}
.ci-cloud-instance__main{min-width:0;border:1px solid var(--ci-color-border-subtle);border-radius:14px;overflow:hidden;background:var(--ci-color-surface)}
.ci-cloud-instance__state{display:flex;align-items:center;gap:18px;padding:28px;border-bottom:1px solid var(--ci-color-border-subtle)}.ci-cloud-instance__state[data-provisioning]{display:grid;grid-template-columns:130px minmax(0,1fr);gap:12px;min-height:188px;background:radial-gradient(ellipse at 12% 50%,color-mix(in srgb,var(--ci-color-accent) 12%,transparent),transparent 70%)}.ci-cloud-instance__loader{max-width:100%;color:var(--ci-color-heading)}.ci-cloud-instance__state-icon{display:grid;place-items:center;flex:none;width:48px;height:48px;border:1px solid color-mix(in srgb,var(--ci-color-accent) 24%,var(--ci-color-border-subtle));border-radius:14px;background:var(--ci-color-accent-surface-subtle);color:var(--ci-color-heading)}.ci-cloud-instance__state h2{font:500 21px/1.3 var(--ci-font-display);letter-spacing:-.025em;color:var(--ci-color-heading);margin:0 0 8px}.ci-cloud-instance__state p{font:13px/1.75 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:0;max-width:370px}
.ci-cloud-instance__details{display:grid;grid-template-columns:1fr 1.3fr;gap:22px 18px;padding:25px 28px}.ci-cloud-instance__details>div{display:grid;gap:8px;min-width:0}.ci-cloud-instance__details span{display:flex;align-items:center;gap:7px;font:11px/1.5 var(--ci-font-ui);color:var(--ci-color-text-muted)}.ci-cloud-instance__details code{font:12px/1.8 var(--ci-font-mono);color:var(--ci-color-heading);overflow-wrap:anywhere;user-select:all}.ci-cloud-instance__details strong{font:500 13px/1.6 var(--ci-font-ui);color:var(--ci-color-heading)}.ci-cloud-instance__endpoint{grid-column:1/-1;padding-bottom:20px;border-bottom:1px solid var(--ci-color-border-subtle)}.ci-cloud-instance__endpoint small{font:11px/1.6 var(--ci-font-ui);color:var(--ci-color-text-muted)}
.ci-cloud-instance__details{display:grid;grid-template-columns:1fr 1.3fr;gap:22px 18px;padding:25px 28px}.ci-cloud-instance__details>div{display:grid;gap:8px;min-width:0}.ci-cloud-instance__details span{display:flex;align-items:center;gap:7px;font:var(--ci-font-size-2xs)/1.5 var(--ci-font-ui);color:var(--ci-color-text-muted)}.ci-cloud-instance__details code{font:12px/1.8 var(--ci-font-mono);color:var(--ci-color-heading);overflow-wrap:anywhere;user-select:all}.ci-cloud-instance__details strong{font:500 13px/1.6 var(--ci-font-ui);color:var(--ci-color-heading)}.ci-cloud-instance__endpoint{grid-column:1/-1;padding-bottom:20px;border-bottom:1px solid var(--ci-color-border-subtle)}.ci-cloud-instance__endpoint small{font:var(--ci-font-size-2xs)/1.6 var(--ci-font-ui);color:var(--ci-color-text-muted)}
.ci-cloud-instance__link{display:inline-flex;align-items:center;justify-self:start;gap:7px;max-width:100%;min-width:0;font:12px/1.8 var(--ci-font-mono);color:var(--ci-color-heading);overflow-wrap:anywhere;text-decoration:underline;text-decoration-color:color-mix(in srgb,var(--ci-color-heading) 30%,transparent);text-underline-offset:4px}.ci-cloud-instance__link>svg{width:14px;height:14px;flex:none}.ci-cloud-instance__link:hover{color:var(--ci-color-accent)}.ci-cloud-instance__link:focus-visible{outline:2px solid var(--ci-color-focus);outline-offset:5px;border-radius:2px}
.ci-cloud-instance__actions{display:flex;gap:10px;flex-wrap:wrap;padding:0 28px 28px}.ci-cloud-instance__actions>.ci-button{flex:1;justify-content:center;min-height:42px;font-size:12px;gap:8px}.ci-cloud-instance__actions>.ci-button>svg{width:15px;height:15px;flex:none}.ci-cloud-instance__open{transition:background-color .2s,box-shadow .2s,transform .2s;box-shadow:inset 0 1px 0 #ffffff35,0 2px 7px color-mix(in srgb,var(--ci-color-accent) 12%,transparent)}
.ci-cloud-instance__aside{display:grid;gap:20px;min-width:0}.ci-cloud-connection{padding:24px;border:1px solid var(--ci-color-border-subtle);border-radius:14px;background:var(--ci-color-surface)}.ci-cloud-connection__heading{display:flex;justify-content:space-between;align-items:center;gap:12px}.ci-cloud-connection__icon{width:38px;height:38px;background:var(--ci-color-accent-surface-subtle);border-radius:11px;display:grid;place-items:center;color:var(--ci-color-heading)}.ci-cloud-connection h2{font:500 22px/1.3 var(--ci-font-display);letter-spacing:-.025em;color:var(--ci-color-heading);margin:18px 0 10px}.ci-cloud-connection>p{font:13px/1.75 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:0 0 19px}.ci-cloud-connection__button{width:100%;min-height:41px;justify-content:center;font-size:12px;gap:8px}.ci-cloud-connection__button>svg{width:15px;height:15px;flex:none}.ci-cloud-connection>small{display:block;font:11px/1.7 var(--ci-font-ui);margin-top:12px;color:var(--ci-color-text-muted)}
.ci-cloud-instance__aside{display:grid;gap:20px;min-width:0}.ci-cloud-connection{padding:24px;border:1px solid var(--ci-color-border-subtle);border-radius:14px;background:var(--ci-color-surface)}.ci-cloud-connection__heading{display:flex;justify-content:space-between;align-items:center;gap:12px}.ci-cloud-connection__icon{width:38px;height:38px;background:var(--ci-color-accent-surface-subtle);border-radius:11px;display:grid;place-items:center;color:var(--ci-color-heading)}.ci-cloud-connection h2{font:500 22px/1.3 var(--ci-font-display);letter-spacing:-.025em;color:var(--ci-color-heading);margin:18px 0 10px}.ci-cloud-connection>p{font:13px/1.75 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:0 0 19px}.ci-cloud-connection__button{width:100%;min-height:41px;justify-content:center;font-size:12px;gap:8px}.ci-cloud-connection__button>svg{width:15px;height:15px;flex:none}.ci-cloud-connection>small{display:block;font:var(--ci-font-size-2xs)/1.7 var(--ci-font-ui);margin-top:12px;color:var(--ci-color-text-muted)}
.ci-cloud-byok{display:flex;gap:12px;padding-top:20px;margin-top:21px;border-top:1px solid var(--ci-color-border-subtle)}.ci-cloud-byok>svg{flex:none;margin-top:3px;color:var(--ci-color-text-muted)}.ci-cloud-byok h3{font:500 13px/1.6 var(--ci-font-ui);color:var(--ci-color-heading);margin:0 0 5px}.ci-cloud-byok p{font:12px/1.75 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:0}.ci-cloud-byok .ci-button{padding:7px 0 0;height:auto;min-height:28px;font-size:12px;gap:7px}
.ci-cloud-hosting{padding:21px 24px;border:1px solid var(--ci-color-border-subtle);border-radius:14px;background:var(--ci-color-surface)}.ci-cloud-hosting-bill{display:flex;justify-content:space-between;align-items:center;gap:14px}.ci-cloud-hosting-bill>span{font:13px/1.6 var(--ci-font-ui);color:var(--ci-color-text-muted)}.ci-cloud-hosting-bill>strong{font:500 23px/1.5 var(--ci-font-ui);color:var(--ci-color-heading);letter-spacing:-.035em;white-space:nowrap}.ci-cloud-hosting-bill small{font:400 11px/1.5 var(--ci-font-ui);letter-spacing:0;color:var(--ci-color-text-muted);margin-left:5px}.ci-cloud-hosting>p,.ci-cloud-hosting>small{font:11px/1.7 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:7px 0 17px}.ci-cloud-hosting__button{width:100%;min-height:39px;justify-content:center;font-size:12px;gap:8px}.ci-cloud-hosting__button>svg{width:14px;height:14px;flex:none}.ci-cloud-notice{font:12px/1.8 var(--ci-font-ui);color:var(--ci-color-text-muted)}
.ci-cloud-billing{display:grid;gap:20px;margin-top:16px;color:var(--ci-color-text);font-family:var(--ci-font-ui)}.ci-cloud-billing__summary{border:1px solid var(--ci-color-border-subtle);border-radius:12px;padding:20px;background:var(--ci-color-surface-subtle)}.ci-cloud-billing__summary>span{font:500 13px/1.6 var(--ci-font-ui)}.ci-cloud-billing__summary>strong{display:block;font:500 30px/1.5 var(--ci-font-ui);letter-spacing:-.035em;color:var(--ci-color-heading);margin-top:4px}.ci-cloud-billing__summary small{font:400 12px/1.5 var(--ci-font-ui);color:var(--ci-color-text-muted);letter-spacing:0;margin-left:6px}.ci-cloud-billing__summary p,.ci-cloud-billing__included{font:12px/1.8 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:5px 0 0}.ci-cloud-billing__included{margin:0}.ci-cloud-billing__portal{width:100%;min-height:42px;font-size:12px;justify-content:center;gap:8px}.ci-cloud-billing__portal>svg{width:15px;height:15px;flex:none}.ci-cloud-billing__subscription{border-top:1px solid var(--ci-color-border-subtle);padding-top:20px;display:flex;gap:18px;align-items:center;justify-content:space-between}.ci-cloud-billing__subscription h3{font:500 13px/1.6 var(--ci-font-ui);margin:0}.ci-cloud-billing__subscription p{font:12px/1.8 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:4px 0 0;max-width:290px}.ci-cloud-billing__subscription>.ci-button{flex:none;min-height:38px;font-size:12px;justify-content:center}
.ci-cloud-hosting{padding:21px 24px;border:1px solid var(--ci-color-border-subtle);border-radius:14px;background:var(--ci-color-surface)}.ci-cloud-hosting-bill{display:flex;justify-content:space-between;align-items:center;gap:14px}.ci-cloud-hosting-bill>span{font:13px/1.6 var(--ci-font-ui);color:var(--ci-color-text-muted)}.ci-cloud-hosting-bill>strong{font:500 23px/1.5 var(--ci-font-ui);color:var(--ci-color-heading);letter-spacing:-.035em;white-space:nowrap}.ci-cloud-hosting-bill small{font:400 var(--ci-font-size-2xs)/1.5 var(--ci-font-ui);letter-spacing:0;color:var(--ci-color-text-muted);margin-inline-start:5px}.ci-cloud-hosting>p,.ci-cloud-hosting>small{font:var(--ci-font-size-2xs)/1.7 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:7px 0 17px}.ci-cloud-hosting__button{width:100%;min-height:39px;justify-content:center;font-size:12px;gap:8px}.ci-cloud-hosting__button>svg{width:14px;height:14px;flex:none}.ci-cloud-notice{font:12px/1.8 var(--ci-font-ui);color:var(--ci-color-text-muted)}
.ci-cloud-billing{display:grid;gap:20px;margin-top:16px;color:var(--ci-color-text);font-family:var(--ci-font-ui)}.ci-cloud-billing__summary{border:1px solid var(--ci-color-border-subtle);border-radius:12px;padding:20px;background:var(--ci-color-surface-subtle)}.ci-cloud-billing__summary>span{font:500 13px/1.6 var(--ci-font-ui)}.ci-cloud-billing__summary>strong{display:block;font:500 30px/1.5 var(--ci-font-ui);letter-spacing:-.035em;color:var(--ci-color-heading);margin-top:4px}.ci-cloud-billing__summary small{font:400 12px/1.5 var(--ci-font-ui);color:var(--ci-color-text-muted);letter-spacing:0;margin-inline-start:6px}.ci-cloud-billing__summary p,.ci-cloud-billing__included{font:12px/1.8 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:5px 0 0}.ci-cloud-billing__included{margin:0}.ci-cloud-billing__portal{width:100%;min-height:42px;font-size:12px;justify-content:center;gap:8px}.ci-cloud-billing__portal>svg{width:15px;height:15px;flex:none}.ci-cloud-billing__subscription{border-top:1px solid var(--ci-color-border-subtle);padding-top:20px;display:flex;gap:18px;align-items:center;justify-content:space-between}.ci-cloud-billing__subscription h3{font:500 13px/1.6 var(--ci-font-ui);margin:0}.ci-cloud-billing__subscription p{font:12px/1.8 var(--ci-font-ui);color:var(--ci-color-text-muted);margin:4px 0 0;max-width:290px}.ci-cloud-billing__subscription>.ci-button{flex:none;min-height:38px;font-size:12px;justify-content:center}
@media(max-width:900px){.ci-cloud-instance .ci-cloud-layout{grid-template-columns:minmax(0,1.15fr) minmax(275px,.85fr);gap:22px}.ci-cloud-instance__state{padding:22px}.ci-cloud-instance__state[data-provisioning]{grid-template-columns:100px minmax(0,1fr);gap:9px}.ci-cloud-instance__state h2{font-size:19px}.ci-cloud-instance__details{padding:22px}.ci-cloud-instance__actions{padding:0 22px 22px}.ci-cloud-connection,.ci-cloud-hosting{padding:22px}}
@media(max-width:700px){.ci-cloud-instance .ci-cloud-layout{grid-template-columns:minmax(0,1fr);gap:20px}.ci-cloud-instance__state[data-provisioning]{grid-template-columns:105px minmax(0,1fr);min-height:175px}.ci-cloud-instance__header{padding-bottom:20px}.ci-cloud-instance__header h1{font-size:28px}.ci-cloud-instance__aside{margin-top:0}.ci-cloud-instance__details{grid-template-columns:1fr}.ci-cloud-instance__endpoint{grid-column:auto}.ci-cloud-billing__subscription{align-items:flex-start;flex-direction:column}.ci-cloud-billing__subscription>.ci-button{width:100%}}
@media(max-width:900px){.ci-cloud-layout{gap:24px;grid-template-columns:minmax(0,1fr) minmax(280px,.85fr)}.ci-cloud-summary__body{padding:21px}.ci-cloud-fields{grid-template-columns:1fr}.ci-cloud-topology__source{left:18px}.ci-cloud-topology__targets{gap:7px}.ci-cloud-heading{padding-top:6px}}
@media(max-width:700px){.ci-cloud-layout{grid-template-columns:1fr;gap:12px}.ci-cloud-heading h1{font-size:32px}.ci-cloud-heading{padding-bottom:10px}.ci-cloud-editor{padding:24px 0}.ci-cloud-summary{position:static}.ci-cloud-summary__body{padding:24px}.ci-cloud-fields{grid-template-columns:1fr 1fr}.ci-cloud-selfhost{align-items:flex-start;flex-direction:column}.ci-cloud-instance__header{align-items:flex-start}.ci-cloud-instance__header h1{font-size:28px}.ci-cloud-instance__header>.ci-badge{margin-top:5px}.ci-cloud-instance__aside{margin-top:0}.ci-cloud-connection h2{max-width:none}.ci-cloud-fineprint{font-size:10px}}
@media(max-width:400px){.ci-cloud-fields{grid-template-columns:1fr}.ci-cloud-heading h1{font-size:30px}.ci-cloud-specs{font-size:11px}.ci-cloud-instance__header{flex-direction:column}}
@media(max-width:700px){.ci-cloud-layout{grid-template-columns:1fr;gap:12px}.ci-cloud-heading h1{font-size:32px}.ci-cloud-heading{padding-bottom:10px}.ci-cloud-editor{padding:24px 0}.ci-cloud-summary{position:static}.ci-cloud-summary__body{padding:24px}.ci-cloud-fields{grid-template-columns:1fr 1fr}.ci-cloud-selfhost{align-items:flex-start;flex-direction:column}.ci-cloud-instance__header{align-items:flex-start}.ci-cloud-instance__header h1{font-size:28px}.ci-cloud-instance__header>.ci-badge{margin-top:5px}.ci-cloud-instance__aside{margin-top:0}.ci-cloud-connection h2{max-width:none}.ci-cloud-fineprint{font-size:var(--ci-font-size-3xs)}}
@media(max-width:400px){.ci-cloud-fields{grid-template-columns:1fr}.ci-cloud-heading h1{font-size:30px}.ci-cloud-specs{font-size:var(--ci-font-size-2xs)}.ci-cloud-instance__header{flex-direction:column}}
/* Interactive routing illustration: the same semantic palette as Editions landing pages. */
.ci-cloud-explorer{--explorer-accent:var(--ci-color-accent);--explorer-dark:var(--ci-color-surface-inverse);--explorer-ink:var(--ci-color-text-inverse);border:1px solid var(--ci-color-border);border-radius:16px;overflow:hidden;background:var(--ci-color-surface);color:var(--ci-color-text);font-family:var(--ci-font-ui);width:100%;isolation:isolate}
.ci-cloud-explorer__chrome{display:flex;align-items:center;justify-content:space-between;gap:15px;padding:18px 22px;background:var(--explorer-dark);color:color-mix(in srgb,var(--explorer-ink) 56%,transparent);font-family:var(--ci-font-ui);font-size:11px;border-bottom:1px solid color-mix(in srgb,var(--explorer-ink) 12%,transparent)}
.ci-cloud-explorer__chrome{display:flex;align-items:center;justify-content:space-between;gap:15px;padding:18px 22px;background:var(--explorer-dark);color:color-mix(in srgb,var(--explorer-ink) 56%,transparent);font-family:var(--ci-font-ui);font-size:var(--ci-font-size-2xs);border-bottom:1px solid color-mix(in srgb,var(--explorer-ink) 12%,transparent)}
.ci-cloud-explorer__scene{height:285px;position:relative;overflow:hidden;background:radial-gradient(ellipse at 49% 51%,color-mix(in srgb,var(--explorer-accent) 12%,transparent),transparent 61%),var(--explorer-dark);color:var(--explorer-ink)}
.ci-cloud-explorer__grid{position:absolute;inset:0;opacity:.3;background-image:radial-gradient(color-mix(in srgb,var(--explorer-ink) 38%,transparent) .6px,transparent .6px);background-size:19px 19px;mask-image:radial-gradient(ellipse,black,transparent 78%)}
@@ -41,18 +41,18 @@
.ci-cloud-explorer__wires{position:absolute;inset:0;width:100%;height:100%;overflow:visible}.ci-cloud-explorer__wire{stroke:color-mix(in srgb,var(--explorer-accent) 27%,transparent);stroke-width:1;vector-effect:non-scaling-stroke}.ci-cloud-explorer__packet{stroke:var(--explorer-accent);stroke-width:2.5;stroke-dasharray:4 90;stroke-linecap:round;opacity:0;vector-effect:non-scaling-stroke;animation:ci-cloud-flow 3s linear infinite;animation-play-state:paused}.ci-cloud-explorer__packet--in,.ci-cloud-explorer__packet--active{opacity:1}.ci-cloud-explorer[data-motion=running] .ci-cloud-explorer__packet{animation-play-state:running}
.ci-cloud-explorer__source{position:absolute;left:3%;top:50%;transform:translateY(-50%);width:23%;display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center}.ci-cloud-explorer__source>svg{width:46px;height:46px;padding:11px;border:1px solid color-mix(in srgb,var(--explorer-ink) 17%,transparent);background:color-mix(in srgb,var(--explorer-ink) 5%,var(--explorer-dark));border-radius:13px;color:color-mix(in srgb,var(--explorer-ink) 85%,transparent)}.ci-cloud-explorer__source strong{font-size:12px;font-weight:500}
.ci-cloud-explorer__gateway{position:absolute;left:37%;top:50%;transform:translateY(-50%);width:26%;min-height:118px;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;gap:12px;padding:18px 5px;border:1px solid color-mix(in srgb,var(--explorer-accent) 48%,transparent);border-radius:12px;background:linear-gradient(145deg,color-mix(in srgb,var(--explorer-accent) 22%,var(--explorer-dark)),color-mix(in srgb,var(--explorer-accent) 7%,var(--explorer-dark)))}.ci-cloud-explorer__cloud{color:var(--explorer-accent)}.ci-cloud-explorer__gateway>strong{font-size:12px;line-height:1.3;font-weight:500;letter-spacing:-.025em;max-width:100%;overflow:hidden;text-overflow:ellipsis}.ci-cloud-explorer__gateway>span{display:flex;align-items:center;gap:4px;font-size:8px;line-height:1.5;justify-content:center;color:color-mix(in srgb,var(--explorer-ink) 75%,transparent)}
.ci-cloud-explorer__targets{position:absolute;right:3%;top:50%;transform:translateY(-50%);width:27%;display:flex;flex-direction:column;gap:49px}.ci-cloud-explorer__targets>button{position:relative;display:flex;align-items:center;gap:8px;padding:13px 10px;text-align:left;border:1px solid color-mix(in srgb,var(--explorer-ink) 16%,transparent);border-radius:12px;background:var(--explorer-dark);color:color-mix(in srgb,var(--explorer-ink) 62%,transparent);cursor:pointer;transition:background-color .2s,border-color .2s,box-shadow .2s}.ci-cloud-explorer__targets>button>svg{flex-shrink:0;width:16px}.ci-cloud-explorer__targets>button>span{min-width:0}.ci-cloud-explorer__targets strong{display:block;font:500 11px/1.4 var(--ci-font-ui);letter-spacing:-.02em}.ci-cloud-explorer__targets small{display:block;font-size:8px;line-height:1.6;margin-top:3px;opacity:.8}.ci-cloud-explorer__targets button[aria-pressed=true]{background:color-mix(in srgb,var(--explorer-accent) 11%,var(--explorer-dark));border-color:color-mix(in srgb,var(--explorer-accent) 70%,transparent);color:var(--explorer-ink);box-shadow:0 0 22px color-mix(in srgb,var(--explorer-accent) 5%,transparent)}.ci-cloud-explorer__targets button[aria-pressed=true]>svg{color:var(--explorer-accent)}.ci-cloud-explorer__targets i{position:absolute;right:-3px;top:-3px;width:7px;height:7px;border-radius:50%;background:var(--explorer-accent);box-shadow:0 0 0 3px var(--explorer-dark);opacity:0}.ci-cloud-explorer__targets button[aria-pressed=true] i{opacity:1}.ci-cloud-explorer__targets>button:hover{border-color:var(--explorer-accent)}
.ci-cloud-explorer__endpoint{position:absolute;bottom:20px;left:0;right:0;display:flex;flex-direction:column;align-items:center;gap:7px}.ci-cloud-explorer__endpoint code{font:10px/1.4 var(--ci-font-mono);color:color-mix(in srgb,var(--explorer-ink) 80%,transparent)}
.ci-cloud-explorer__controls{padding:17px 21px;display:flex;align-items:center;justify-content:space-between;gap:10px;border-bottom:1px solid var(--ci-color-border-subtle);background:var(--ci-color-surface)}.ci-cloud-explorer__controls>span{font:10px/1.4 var(--ci-font-ui);color:var(--ci-color-text-muted);white-space:nowrap}.ci-cloud-explorer__controls>div{display:flex;gap:5px;flex-wrap:wrap}.ci-cloud-explorer__controls button{display:flex;align-items:center;gap:5px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--ci-color-text-muted);padding:7px 8px;min-height:32px;font:11px/1.3 var(--ci-font-ui);cursor:pointer;transition:background-color .2s,color .2s}.ci-cloud-explorer__controls button[aria-pressed=true]{border-color:var(--ci-color-border);background:var(--ci-color-background);color:var(--ci-color-heading)}.ci-cloud-explorer__controls button:hover{color:var(--ci-color-heading);background:var(--ci-color-background)}.ci-cloud-explorer button:focus-visible{outline:2px solid var(--ci-color-focus);outline-offset:4px}
.ci-cloud-explorer__targets{position:absolute;right:3%;top:50%;transform:translateY(-50%);width:27%;display:flex;flex-direction:column;gap:49px}.ci-cloud-explorer__targets>button{position:relative;display:flex;align-items:center;gap:8px;padding:13px 10px;text-align:start;border:1px solid color-mix(in srgb,var(--explorer-ink) 16%,transparent);border-radius:12px;background:var(--explorer-dark);color:color-mix(in srgb,var(--explorer-ink) 62%,transparent);cursor:pointer;transition:background-color .2s,border-color .2s,box-shadow .2s}.ci-cloud-explorer__targets>button>svg{flex-shrink:0;width:16px}.ci-cloud-explorer__targets>button>span{min-width:0}.ci-cloud-explorer__targets strong{display:block;font:500 var(--ci-font-size-2xs)/1.4 var(--ci-font-ui);letter-spacing:-.02em}.ci-cloud-explorer__targets small{display:block;font-size:8px;line-height:1.6;margin-top:3px;opacity:.8}.ci-cloud-explorer__targets button[aria-pressed=true]{background:color-mix(in srgb,var(--explorer-accent) 11%,var(--explorer-dark));border-color:color-mix(in srgb,var(--explorer-accent) 70%,transparent);color:var(--explorer-ink);box-shadow:0 0 22px color-mix(in srgb,var(--explorer-accent) 5%,transparent)}.ci-cloud-explorer__targets button[aria-pressed=true]>svg{color:var(--explorer-accent)}.ci-cloud-explorer__targets i{position:absolute;right:-3px;top:-3px;width:7px;height:7px;border-radius:50%;background:var(--explorer-accent);box-shadow:0 0 0 3px var(--explorer-dark);opacity:0}.ci-cloud-explorer__targets button[aria-pressed=true] i{opacity:1}.ci-cloud-explorer__targets>button:hover{border-color:var(--explorer-accent)}
.ci-cloud-explorer__endpoint{position:absolute;bottom:20px;left:0;right:0;display:flex;flex-direction:column;align-items:center;gap:7px}.ci-cloud-explorer__endpoint code{font:var(--ci-font-size-3xs)/1.4 var(--ci-font-mono);color:color-mix(in srgb,var(--explorer-ink) 80%,transparent)}
.ci-cloud-explorer__controls{padding:17px 21px;display:flex;align-items:center;justify-content:space-between;gap:10px;border-bottom:1px solid var(--ci-color-border-subtle);background:var(--ci-color-surface)}.ci-cloud-explorer__controls>span{font:var(--ci-font-size-3xs)/1.4 var(--ci-font-ui);color:var(--ci-color-text-muted);white-space:nowrap}.ci-cloud-explorer__controls>div{display:flex;gap:5px;flex-wrap:wrap}.ci-cloud-explorer__controls button{display:flex;align-items:center;gap:5px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--ci-color-text-muted);padding:7px 8px;min-height:32px;font:var(--ci-font-size-2xs)/1.3 var(--ci-font-ui);cursor:pointer;transition:background-color .2s,color .2s}.ci-cloud-explorer__controls button[aria-pressed=true]{border-color:var(--ci-color-border);background:var(--ci-color-background);color:var(--ci-color-heading)}.ci-cloud-explorer__controls button:hover{color:var(--ci-color-heading);background:var(--ci-color-background)}.ci-cloud-explorer button:focus-visible{outline:2px solid var(--ci-color-focus);outline-offset:4px}
.ci-cloud-explorer__explanation{display:flex;align-items:flex-start;gap:13px;padding:23px 23px 25px;min-height:118px}.ci-cloud-explorer__step{display:grid;place-items:center;width:36px;height:36px;flex-shrink:0;border:1px solid var(--ci-color-border-subtle);background:color-mix(in srgb,var(--ci-color-accent) 8%,var(--ci-color-surface));border-radius:11px;color:var(--ci-color-accent-active)}.ci-cloud-explorer__explanation strong{font-size:14px;font-weight:500;letter-spacing:-.015em;color:var(--ci-color-heading)}.ci-cloud-explorer__explanation p{font-size:12px;line-height:1.8;color:var(--ci-color-text-muted);margin:7px 0 0}
@keyframes ci-cloud-flow{to{stroke-dashoffset:-188}}
@media(max-width:480px){
.ci-cloud-explorer{border-radius:18px}.ci-cloud-explorer__chrome{padding:15px 17px;font-size:8px}
.ci-cloud-explorer__scene{height:360px}.ci-cloud-explorer__labels{grid-template-columns:32% 68%;inset:23px 0 auto;font-size:8px}.ci-cloud-explorer__labels>span:last-child{display:none}
.ci-cloud-explorer__source{left:3%;top:35%;width:27%}.ci-cloud-explorer__source strong{font-size:11px}
.ci-cloud-explorer__source{left:3%;top:35%;width:27%}.ci-cloud-explorer__source strong{font-size:var(--ci-font-size-2xs)}
.ci-cloud-explorer__gateway{left:40%;top:35%;width:45%;min-height:112px}.ci-cloud-explorer__gateway>strong{font-size:13px}.ci-cloud-explorer__gateway>span{font-size:9px}
.ci-cloud-explorer__wires{display:none}.ci-cloud-explorer__source::after{content:"";position:absolute;left:100%;top:24px;width:50%;height:1px;background:color-mix(in srgb,var(--explorer-accent) 55%,transparent)}
.ci-cloud-explorer__targets{left:5%;right:5%;top:auto;bottom:62px;transform:none;width:auto;flex-direction:row;gap:10px}.ci-cloud-explorer__targets>button{flex:1;min-height:63px;padding:11px 9px;gap:7px}.ci-cloud-explorer__targets strong{font-size:11px}.ci-cloud-explorer__targets small{font-size:9px}.ci-cloud-explorer__targets>button>svg{width:16px}
.ci-cloud-explorer__targets{left:5%;right:5%;top:auto;bottom:62px;transform:none;width:auto;flex-direction:row;gap:10px}.ci-cloud-explorer__targets>button{flex:1;min-height:63px;padding:11px 9px;gap:7px}.ci-cloud-explorer__targets strong{font-size:var(--ci-font-size-2xs)}.ci-cloud-explorer__targets small{font-size:9px}.ci-cloud-explorer__targets>button>svg{width:16px}
.ci-cloud-explorer__endpoint{bottom:17px}.ci-cloud-explorer__controls{align-items:flex-start;flex-direction:column;padding:16px 17px;gap:9px}.ci-cloud-explorer__controls>span{font-size:9px}.ci-cloud-explorer__controls button{min-height:38px;padding:7px 10px;font-size:12px}
.ci-cloud-explorer__explanation{padding:20px 17px 24px;gap:10px}.ci-cloud-explorer__explanation strong{font-size:14px}}
@media(prefers-reduced-motion:reduce){.ci-cloud-explorer *{animation:none!important;transition:none!important}}

View File

@@ -18,8 +18,13 @@ export interface CodePreviewToken {
export interface CodePreviewProps extends Omit<ComponentProps<"section">, "onCopy"> {
/** Surface follows the current theme and matches onboarding integration steps. */
variant?: "terminal" | "surface";
/** Defaults to true for terminal, false for surface. */
/** Defaults to true for terminal, false for surface and whenever the header is hidden. */
showLineNumbers?: boolean;
/**
* `false` drops the header for a one-line command or URL: the code and the copy button share one
* row, and `filename`, `language` and `metadata` are not rendered. Defaults to true.
*/
showHeader?: boolean;
filename?: ReactNode;
language?: ReactNode;
metadata?: ReactNode;
@@ -33,7 +38,10 @@ export interface CodePreviewProps extends Omit<ComponentProps<"section">, "onCop
copiedAnnouncement?: string;
/** Visible error after a failed copy. Defaults depend on whether getCopyValue is set. */
copyErrorLabel?: string;
/** Accessible name of the code region. Defaults to "<language> code". */
/**
* Accessible name of the code region. Defaults to "<language> code" (the file name when there is
* no language), built from text only: with an element in both, or neither set, it is "Code".
*/
codeLabel?: string;
/** Resolve clipboard text only after a click; displayed source stays unchanged. */
getCopyValue?: () => Promise<string>;
@@ -42,12 +50,17 @@ export interface CodePreviewProps extends Omit<ComponentProps<"section">, "onCop
onCopyError?: (error: unknown) => void;
}
function textOf(node: ReactNode): string {
return typeof node === "string" || typeof node === "number" ? String(node) : "";
}
export function CodePreview({
className,
variant = "terminal",
showLineNumbers = variant === "terminal",
filename = "request.ts",
language = "TypeScript",
showHeader = true,
showLineNumbers = showHeader && variant === "terminal",
filename = showHeader ? "request.ts" : undefined,
language = showHeader ? "TypeScript" : undefined,
metadata,
code,
lines,
@@ -131,20 +144,28 @@ export function CodePreview({
}
}, [getCopyValue, onCopy, onCopyError, rawCode]);
const copyButton = (
<button type="button" className="ci-code-preview__copy" onClick={copy} disabled={!rawCode || copying} aria-busy={copying || undefined} data-copied={copied || undefined}>
{copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
{copying ? copyingLabel : copied ? copiedLabel : copyLabel}
</button>
);
// Only text can name the region: an element would read as "[object Object]".
const codeName = textOf(language) || textOf(filename);
return (
<section data-slot="code-preview" data-variant={variant} data-line-numbers={showLineNumbers} className={cn("ci-code-preview", className)} {...props}>
<header className="ci-code-preview__header">
<span className="ci-code-preview__meta">
<strong>{filename}</strong>
<span>{language}</span>
{metadata != null ? <span className="ci-code-preview__endpoint">{metadata}</span> : null}
</span>
<button type="button" className="ci-code-preview__copy" onClick={copy} disabled={!rawCode || copying} aria-busy={copying || undefined} data-copied={copied || undefined}>
{copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
{copying ? copyingLabel : copied ? copiedLabel : copyLabel}
</button>
</header>
<pre className="ci-code-preview__pre" tabIndex={0} aria-label={codeLabel ?? `${String(language || filename || "Code")} code`}>
<section data-slot="code-preview" data-variant={variant} data-line-numbers={showLineNumbers} data-header={showHeader ? undefined : "false"} className={cn("ci-code-preview", className)} {...props}>
{showHeader && (
<header className="ci-code-preview__header">
<span className="ci-code-preview__meta">
<strong>{filename}</strong>
<span>{language}</span>
{metadata != null ? <span className="ci-code-preview__endpoint">{metadata}</span> : null}
</span>
{copyButton}
</header>
)}
<pre className="ci-code-preview__pre" tabIndex={0} aria-label={codeLabel ?? (codeName ? `${codeName} code` : "Code")}>
<code>
{sourceLines.map((line, lineIndex) => (
<span className="ci-code-preview__line" key={lineIndex}>
@@ -158,6 +179,8 @@ export function CodePreview({
))}
</code>
</pre>
{/* Without a header the button follows the code, so the tab order matches what is drawn. */}
{!showHeader && copyButton}
{copyFailed && <p className="ci-code-preview__error" role="alert">{copyErrorLabel ?? (getCopyValue ? "Could not copy code. Please try again." : "Could not copy code. Select it and try again.")}</p>}
<span className="ci-sr-only" aria-live="polite">{copied ? copiedAnnouncement : ""}</span>
</section>

View File

@@ -15,6 +15,7 @@ import {
useState,
} from "react";
import type { ComponentProps, KeyboardEvent, ReactNode } from "react";
import { foldSearchText } from "./lib/search-fold";
import { cn } from "./lib/utils";
// React 18 warns about useLayoutEffect during server rendering.
@@ -31,14 +32,10 @@ export interface CommandFilterItem {
/** Decides whether an item stays for a non-blank query. */
export type CommandFilter = (query: string, item: CommandFilterItem) => boolean;
// Accents are dropped so that "configuracoes" finds "Configurações".
function fold(text: string) {
return text.normalize("NFD").replace(/\p{M}/gu, "").toLocaleLowerCase();
}
// Accents are dropped so that "configuracoes" finds "Configurações", in any browser language.
function matchesEveryWord(query: string, { value, keywords }: CommandFilterItem) {
const text = fold([value, ...keywords].join(" "));
return fold(query).trim().split(/\s+/).every((word) => text.includes(word));
const text = foldSearchText([value, ...keywords].join(" "));
return foldSearchText(query).trim().split(/\s+/).every((word) => text.includes(word));
}
interface CommandContextValue {
@@ -318,3 +315,34 @@ export const CommandEmpty = forwardRef<HTMLDivElement, CommandEmptyProps>(functi
</div>
);
});
// What takes focus or text input on a press, so a press on it must not be cancelled.
const FOOTER_CONTROL = 'a[href], button, input, select, textarea, summary, [tabindex], [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]';
export interface CommandFooterProps extends ComponentProps<"div"> {}
/**
* A row under the list for key hints, such as `<Kbd>` plus a label per hint. Render it after
* `CommandList` and `CommandEmpty`. It is not part of the listbox, so the arrows never reach it,
* and a press on a hint keeps focus in `CommandInput`. To have the hints read with the input,
* give the footer an `id` and pass it to `CommandInput` as `aria-describedby`.
*/
export const CommandFooter = forwardRef<HTMLDivElement, CommandFooterProps>(function CommandFooter({ className, onMouseDown, ...props }, ref) {
useCommand();
return (
<div
{...props}
ref={ref}
data-slot="command-footer"
className={cn("ci-command__footer", className)}
onMouseDown={(event) => {
onMouseDown?.(event);
// A press React bubbled from a portal did not happen in the footer: it is left alone.
if (!(event.target instanceof Node) || !event.currentTarget.contains(event.target)) return;
// Keeps focus in the input, except for a control the host put in the footer.
const control = event.target instanceof Element ? event.target.closest(FOOTER_CONTROL) : null;
if (!control || control === event.currentTarget || !event.currentTarget.contains(control)) event.preventDefault();
}}
/>
);
});

View File

@@ -15,7 +15,7 @@ import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
import { Select, type SelectProps } from "./select";
import { TableLoadingRegion } from "./table-loading";
import { TableHead } from "./table";
import { TableHead, type TableVariant } from "./table";
export type DataTableSortDirection = "asc" | "desc";
@@ -38,6 +38,8 @@ export interface DataTableShellProps
toolbarActionsLabel?: string;
children: ReactNode;
pagination?: ReactNode;
/** `"plain"` drops the frame around the table and pagination, for a host that draws it. */
variant?: TableVariant;
}
/**
@@ -58,6 +60,7 @@ export function DataTableShell({
toolbarActionsLabel = "Table actions",
children,
pagination,
variant,
className,
...props
}: DataTableShellProps) {
@@ -78,6 +81,7 @@ export function DataTableShell({
return (
<section
data-slot="data-table-shell"
data-variant={variant === "plain" ? variant : undefined}
className={cn("ci-data-table ci-data-table-shell", className)}
{...props}
>
@@ -347,7 +351,7 @@ export function DataTablePageSizeControl({
}
export interface SortableTableHeadProps
extends Omit<ComponentProps<typeof TableHead>, "aria-sort" | "onChange"> {
extends Omit<ComponentProps<typeof TableHead>, "aria-sort" | "onChange" | "align"> {
direction?: DataTableSortDirection;
defaultDirection?: DataTableSortDirection;
align?: "left" | "right";

View File

@@ -2,23 +2,25 @@
import { useMemo, useState } from "react";
import type { ReactNode } from "react";
import type { TableRowActivateEvent, TableRowFocus } from "./table";
import { Search, X } from "lucide-react";
import { inertProps } from "./lib/inert";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
import { foldSearchText } from "./lib/search-fold";
import { Input } from "./input";
import { SortableTableHead, type DataTableSortDirection } from "./data-table-shell";
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "./pagination";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./table";
import { DataTableFooter, SortableTableHead, type DataTableSortDirection } from "./data-table-shell";
import { PaginationControls } from "./pagination-controls";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, type TableDensity, type TableVariant } from "./table";
export type DataTableValue = string | number | boolean | null | undefined;
/** The sorted column and its direction. */
export interface DataTableSort {
id: string;
direction: DataTableSortDirection;
}
export interface DataTableColumn<Row> {
id: string;
header: ReactNode;
@@ -30,21 +32,109 @@ export interface DataTableColumn<Row> {
width?: string;
}
/** Interface text of the search and pagination chrome. */
export interface DataTableLabels {
/** Clear-search button accessible name. */
clearSearch: string;
/** Visible count of the rows that match the search. */
resultCount: (count: number) => string;
/** Accessible name of the pagination landmark. */
navigation: string;
/** Accessible name of a page button. */
goToPage: (page: number) => string;
/** Visible text of the previous/next buttons. */
previous: string;
next: string;
/** Accessible name of the previous/next buttons. */
previousPage: string;
nextPage: string;
/** Text alternative of the ellipsis between page buttons. */
morePages: string;
}
export const defaultDataTableLabels: DataTableLabels = {
clearSearch: "Clear search",
resultCount: (count) => `${count} results`,
navigation: "Pagination",
goToPage: (page) => `Go to page ${page}`,
previous: "Previous",
next: "Next",
previousPage: "Go to previous page",
nextPage: "Go to next page",
morePages: "More pages",
};
export interface DataTableProps<Row> {
loading?: boolean;
loadingLabel?: string;
columns: DataTableColumn<Row>[];
rows: Row[];
rowKey: (row: Row) => string;
/**
* Makes the body rows interactive: each one is a tab stop, and this runs with the row on a
* click and on Enter or Space, but not from a control inside a cell. See `TableRow`.
*/
onRowActivate?: (row: Row, event: TableRowActivateEvent) => void;
/**
* The `rowKey` of the selected row. Every body row then states `aria-selected`; pass `null`
* while the rows can be selected and none is.
*/
selectedRowKey?: string | null;
/**
* `"roving"` gives the rows that `onRowActivate` makes interactive one tab stop between them,
* with the arrow keys moving focus from row to row. Defaults to `"each"`. See `Table`.
*/
rowFocus?: TableRowFocus;
ariaLabel?: string;
searchPlaceholder?: string;
emptyMessage?: ReactNode;
pageSize?: number;
initialSort?: { id: string; direction: "asc" | "desc" };
initialSort?: DataTableSort;
/**
* Controlled sort. Leave it out and the table keeps its own sort, starting at `initialSort`;
* pass `null` while the sort is yours and no column is sorted.
*/
sort?: DataTableSort | null;
/** Runs when a sortable header is pressed, whether or not `sort` is controlled. */
onSortChange?: (sort: DataTableSort) => void;
/** Controlled page, starting at 1. A value outside the page range is clamped. */
page?: number;
/**
* Runs with the page a pager control asks for, and with 1 when the sort or the search changes
* while another page is held. Runs whether or not `page` is controlled.
*/
onPageChange?: (page: number) => void;
/** Controlled search text, for a search kept in the URL or in a field of your own. */
query?: string;
/** Runs when the built-in search field is edited or cleared, whether or not `query` is controlled. */
onQueryChange?: (query: string) => void;
/** `false` hides the built-in search field. A `query` you pass still filters the rows. */
searchable?: boolean;
/**
* Total number of rows on the server. Set it when `rows` holds only the current page, already
* filtered and sorted: the table then renders `rows` as given and pages over `rowCount`.
*/
rowCount?: number;
/**
* Rows-per-page control for the footer, usually a `DataTablePageSizeControl` bound to `pageSize`.
* The footer then stays when one page holds every row.
*/
pageSizeControl?: ReactNode;
note?: ReactNode;
className?: string;
/**
* Fill a height-constrained parent: the rows scroll under a pinned header in the height left
* by the toolbar and the pagination, which stay in view. `maxHeight` is ignored next to it.
* See `Table`.
*/
fill?: boolean;
/** Caps the table height so the rows scroll under a pinned header. See `Table`. */
maxHeight?: string | number;
/** Localized interface text; missing or `undefined` keys fall back to defaultDataTableLabels. */
labels?: Partial<DataTableLabels>;
/** Row height, cell padding and text size of the table. See `Table`. */
density?: TableDensity;
/** `"plain"` drops the frame around the toolbar, table and pagination, for a host that draws it. */
variant?: TableVariant;
}
function compare(a: DataTableValue, b: DataTableValue) {
@@ -55,48 +145,79 @@ function compare(a: DataTableValue, b: DataTableValue) {
return String(a).localeCompare(String(b), undefined, { numeric: true, sensitivity: "base" });
}
/** Keep navigation bounded even on narrow screens; arrows reach adjacent pages. */
function paginationPages(page: number, count: number): Array<number | "before" | "after"> {
if (count <= 5) return Array.from({ length: count }, (_, index) => index + 1);
if (page <= 2) return [1, 2, 3, "after", count];
if (page >= count - 1) return [1, "before", count - 2, count - 1, count];
return [1, "before", page, "after", count];
}
export function DataTable<Row>({
loading,
loadingLabel,
columns,
rows,
rowKey,
onRowActivate,
selectedRowKey,
rowFocus,
ariaLabel = "Data table",
searchPlaceholder = "Search rows",
emptyMessage = "No matching results.",
pageSize = 5,
initialSort,
sort: controlledSort,
onSortChange,
page: controlledPage,
onPageChange,
query: controlledQuery,
onQueryChange,
searchable = true,
rowCount,
pageSizeControl,
note,
fill,
className,
maxHeight,
labels: labelOverrides,
density,
variant,
}: DataTableProps<Row>) {
const [query, setQuery] = useState("");
const [page, setPage] = useState(1);
const [sort, setSort] = useState(initialSort);
const labels = resolveLabels(defaultDataTableLabels, labelOverrides);
const [ownQuery, setOwnQuery] = useState("");
const [ownPage, setOwnPage] = useState(1);
const [ownSort, setOwnSort] = useState(initialSort);
// Each of the three belongs to the caller when its prop is set, and is kept here otherwise.
const query = controlledQuery ?? ownQuery;
const page = controlledPage ?? ownPage;
const sort = controlledSort === undefined ? ownSort : controlledSort ?? undefined;
const serverRows = rowCount !== undefined;
const filtered = useMemo(() => {
const term = query.trim().toLocaleLowerCase();
const searchable = columns.filter((column) => column.searchable !== false);
// The server already filtered and sorted the page it sent.
if (serverRows) return rows;
const term = foldSearchText(query.trim());
const searchColumns = columns.filter((column) => column.searchable !== false);
const next = term
? rows.filter((row) => searchable.some((column) => String(column.value(row) ?? "").toLocaleLowerCase().includes(term)))
? rows.filter((row) => searchColumns.some((column) => foldSearchText(String(column.value(row) ?? "")).includes(term)))
: [...rows];
if (!sort) return next;
const column = columns.find((item) => item.id === sort.id);
if (!column) return next;
return next.sort((a, b) => compare(column.value(a), column.value(b)) * (sort.direction === "asc" ? 1 : -1));
}, [columns, query, rows, sort]);
}, [columns, query, rows, serverRows, sort]);
const pageCount = Math.max(1, Math.ceil(filtered.length / pageSize));
const activePage = Math.min(page, pageCount);
const visible = filtered.slice((activePage - 1) * pageSize, activePage * pageSize);
const total = serverRows ? Math.max(0, Math.floor(rowCount) || 0) : filtered.length;
const pageCount = Math.max(1, Math.ceil(total / pageSize));
const activePage = Math.min(Math.max(1, Math.floor(page) || 1), pageCount);
const visible = serverRows ? filtered : filtered.slice((activePage - 1) * pageSize, activePage * pageSize);
function setQuery(next: string) {
if (controlledQuery === undefined) setOwnQuery(next);
onQueryChange?.(next);
}
function setPage(next: number) {
if (controlledPage === undefined) setOwnPage(next);
// Against the page held, not the clamped one shown: a page past the end still has to move.
if (next !== page) onPageChange?.(next);
}
function setSort(next: DataTableSort) {
if (controlledSort === undefined) setOwnSort(next);
onSortChange?.(next);
}
function changeSort(column: DataTableColumn<Row>, direction: DataTableSortDirection) {
if (column.sortable === false) return;
@@ -105,10 +226,10 @@ export function DataTable<Row>({
}
return (
<div className={cn("ci-data-table", className)}>
<div data-fill={fill || undefined} data-variant={variant === "plain" ? variant : undefined} className={cn("ci-data-table", className)}>
<div className="ci-data-table__frame">
<div className="ci-data-table__toolbar">
<div className="ci-data-table__search">
{searchable ? <div className="ci-data-table__search">
<Search aria-hidden="true" />
<Input
value={query}
@@ -116,11 +237,11 @@ export function DataTable<Row>({
placeholder={searchPlaceholder}
aria-label={searchPlaceholder}
/>
{query ? <button type="button" onClick={() => setQuery("")} aria-label="Clear search"><X /></button> : null}
</div>
<span className="ci-data-table__count" aria-live="polite">{filtered.length} results</span>
{query ? <button type="button" onClick={() => { setQuery(""); setPage(1); }} aria-label={labels.clearSearch}><X /></button> : null}
</div> : null}
<span className="ci-data-table__count" aria-live="polite">{labels.resultCount(total)}</span>
</div>
<Table aria-label={ariaLabel} loading={loading} loadingLabel={loadingLabel} maxHeight={maxHeight}>
<Table aria-label={ariaLabel} loading={loading} loadingLabel={loadingLabel} maxHeight={maxHeight} density={density} rowFocus={rowFocus} fill={fill}>
<TableHeader>
<TableRow>
{columns.map((column) => {
@@ -151,7 +272,11 @@ export function DataTable<Row>({
</TableHeader>
<TableBody>
{visible.length ? visible.map((row) => (
<TableRow key={rowKey(row)}>
<TableRow
key={rowKey(row)}
onActivate={onRowActivate ? (event) => onRowActivate(row, event) : undefined}
selected={selectedRowKey === undefined ? undefined : rowKey(row) === selectedRowKey}
>
{columns.map((column) => (
<TableCell
key={column.id}
@@ -166,23 +291,29 @@ export function DataTable<Row>({
)}
</TableBody>
</Table>
{pageCount > 1 ? (
<div className="ci-data-table__pagination" inert={loading || undefined} aria-hidden={loading || undefined}>
<Pagination>
<PaginationContent>
<PaginationItem><PaginationPrevious href="#" disabled={loading || activePage === 1} onClick={(event) => { event.preventDefault(); setPage(Math.max(1, activePage - 1)); }} /></PaginationItem>
{paginationPages(activePage, pageCount).map((number) => (
<PaginationItem key={number}>{typeof number === "number"
? <PaginationLink href="#" label={`Go to page ${number}`} disabled={loading} isActive={number === activePage} onClick={(event) => { event.preventDefault(); setPage(number); }}>{number}</PaginationLink>
: <PaginationEllipsis />}</PaginationItem>
))}
<PaginationItem><PaginationNext href="#" disabled={loading || activePage === pageCount} onClick={(event) => { event.preventDefault(); setPage(Math.min(pageCount, activePage + 1)); }} /></PaginationItem>
</PaginationContent>
</Pagination>
</div>
) : null}
<DataTablePagerRow pageSizeControl={pageSizeControl} {...inertProps(loading)} aria-hidden={loading || undefined}>
{pageCount > 1 ? (
<PaginationControls
page={activePage}
pageCount={pageCount}
onPageChange={setPage}
disabled={loading}
labels={{ navigation: labels.navigation, previous: labels.previous, next: labels.next, previousPage: labels.previousPage, nextPage: labels.nextPage, goToPage: labels.goToPage, morePages: labels.morePages }}
/>
) : null}
</DataTablePagerRow>
</div>
{note ? <p className="ci-data-table__note">{note}</p> : null}
</div>
);
}
/** The pager row. With a rows-per-page control it takes the `DataTableShell` footer geometry. */
function DataTablePagerRow({
pageSizeControl,
children,
...props
}: { pageSizeControl?: ReactNode; children: ReactNode; inert?: boolean; "aria-hidden"?: boolean }) {
if (pageSizeControl) return <DataTableFooter pagination={children} pageSizeControl={pageSizeControl} {...props} />;
return children ? <div className="ci-data-table__pagination" {...props}>{children}</div> : null;
}

View File

@@ -15,6 +15,7 @@ import { CalendarDays, Check, ChevronDown, ChevronLeft, ChevronRight, ChevronUp
import { Badge } from "./badge";
import { Button, type ButtonSize } from "./button";
import { Popover, PopoverClose, PopoverContent, PopoverTrigger } from "./popover";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
import {
calendarDayBoundary,
@@ -64,6 +65,74 @@ export type DateRangePickerPresets<M extends DateRangePickerMode = DateRangePick
? readonly DateRangeRelativePreset[]
: readonly DateRangeDayPreset[];
/** Interface text of the popover. `placeholder` and the preset labels stay separate props. */
export interface DateRangePickerLabels {
/** Popover dialog accessible name. */
popover: string;
/** Calendar accessible name. */
calendar: string;
/** Accessible name of the previous/next month controls. */
navigation: string;
previousMonth: string;
nextMonth: string;
/** Accessible name of the preset list in timestamp mode. */
relativeRanges: string;
clear: string;
apply: string;
/** Day states, joined to the full date by `day`. */
today: string;
rangeStart: string;
inRange: string;
rangeEnd: string;
selected: string;
/** Accessible name of a day button, from the formatted date and its states. */
day: (date: string, states: readonly string[]) => string;
/** Selection status before a start date is chosen. */
chooseStart: string;
/** Timestamp mode: status and summary once a start date is chosen. */
chooseEnd: string;
/** Date mode: status once a start date is chosen. */
startSelected: (start: string) => string;
/** Date mode: status for a complete range. */
rangeSelected: (from: string, to: string) => string;
/** Timestamp mode: status and summary for a complete range. */
timestampRange: (from: string, to: string, timeZone: string) => string;
/** Timestamp mode: visible instruction above the range summary. */
summary: string;
}
export const defaultDateRangePickerLabels: DateRangePickerLabels = {
popover: "Choose date range",
calendar: "Date range calendar",
navigation: "Calendar navigation",
previousMonth: "Previous month",
nextMonth: "Next month",
relativeRanges: "Relative ranges",
clear: "Clear",
apply: "Apply range",
today: "today",
rangeStart: "range start",
inRange: "in selected range",
rangeEnd: "range end",
selected: "selected",
day: (date, states) => [date, ...states].join(", "),
chooseStart: "Choose a start date.",
chooseEnd: "Choose an end date.",
startSelected: (start) => `${start} selected as the start date. Choose an end date.`,
rangeSelected: (from, to) => `Selected ${from} through ${to}.`,
timestampRange: (from, to, timeZone) => `${from} – ${to} (${timeZone}).`,
summary: "Select a preset or choose a custom range.",
};
/** Day states in the order the English label always listed them. */
function dayStates(labels: DateRangePickerLabels, modifiers: Record<string, boolean | undefined>, announceSelected: boolean): string[] {
const states: string[] = [];
if (modifiers.today) states.push(labels.today);
if (modifiers.range_start) states.push(labels.rangeStart);
if (modifiers.range_middle) states.push(labels.inRange);
if (modifiers.range_end) states.push(labels.rangeEnd);
if (announceSelected && modifiers.selected && !modifiers.range_start && !modifiers.range_middle && !modifiers.range_end) states.push(labels.selected);
return states;
}
export interface DateRangePickerProps<M extends DateRangePickerMode = DateRangePickerMode> extends Omit<ComponentProps<"button">, "value" | "defaultValue" | "onChange"> {
/** Date mode uses inclusive YYYY-MM-DD values; timestamp mode uses [from, to) ISO instants. */
mode?: M;
@@ -113,6 +182,8 @@ export interface DateRangePickerProps<M extends DateRangePickerMode = DateRangeP
variant?: DateRangePickerVariant;
/** Overrides the trigger height without changing the calendar popover. */
triggerSize?: ButtonSize;
/** Localized interface text; missing or `undefined` keys fall back to defaultDateRangePickerLabels. */
labels?: Partial<DateRangePickerLabels>;
}
function parseIso(value: string) { return new Date(`${value}T00:00:00`); }
@@ -316,8 +387,10 @@ function CalendarDateRangePicker({
valuePreset,
variant = "default",
triggerSize: triggerSizeProp,
labels: labelOverrides,
...props
}: DateRangePickerProps<"date">) {
const labels = useMemo(() => resolveLabels(defaultDateRangePickerLabels, labelOverrides), [labelOverrides]);
const referenceDateIso = referenceDate ?? toIso(startOfDay(new Date()));
const referenceDateValue = useMemo(
() => parseReferenceDate(referenceDateIso),
@@ -365,9 +438,9 @@ function CalendarDateRangePicker({
const selected = useMemo(() => toCalendarRange(draft), [draft.from, draft.to]);
const selectionStatus = draft.from
? draft.to
? `Selected ${fullDate.format(parseIso(draft.from))} through ${fullDate.format(parseIso(draft.to))}.`
: `${fullDate.format(parseIso(draft.from))} selected as the start date. Choose an end date.`
: "Choose a start date.";
? labels.rangeSelected(fullDate.format(parseIso(draft.from)), fullDate.format(parseIso(draft.to)))
: labels.startSelected(fullDate.format(parseIso(draft.from)))
: labels.chooseStart;
const triggerSize = triggerSizeProp ?? (variant === "capsule" ? "sm" : "default");
return (
@@ -380,7 +453,7 @@ function CalendarDateRangePicker({
onOpenChange?.(nextOpen);
}}>
<PopoverTrigger asChild><Button variant="outline" size={triggerSize} data-trigger-variant={variant} className={cn("ci-date-range-trigger", className)} {...props}><CalendarDays aria-hidden="true" /><span>{label}</span></Button></PopoverTrigger>
<PopoverContent className="ci-date-range-popover" align="end" aria-label="Choose date range">
<PopoverContent className="ci-date-range-popover" align="end" aria-label={labels.popover}>
{resolvedPresets.length > 0 && <div className="ci-date-range-presets">
{resolvedPresets.map((preset) => <button type="button" key={preset.id} aria-pressed={activePreset === preset.id} data-active={activePreset === preset.id || undefined} onClick={() => {
const next = normalizeRange(preset.range(presetContext), min, max);
@@ -391,7 +464,7 @@ function CalendarDateRangePicker({
</div>}
<div className="ci-range-calendars" data-months={numberOfMonths}>
<DayPicker
aria-label="Date range calendar"
aria-label={labels.calendar}
classNames={calendarClassNames}
components={{ Chevron: CalendarChevron, DayButton: CalendarDayButton, Month: CalendarMonth }}
disabled={disabledDates}
@@ -404,11 +477,11 @@ function CalendarDateRangePicker({
formatWeekdayName: (date) => weekdayShort.format(date),
}}
labels={{
labelDayButton: (date, modifiers) => `${fullDate.format(date)}${modifiers.today ? ", today" : ""}${modifiers.range_start ? ", range start" : ""}${modifiers.range_middle ? ", in selected range" : ""}${modifiers.range_end ? ", range end" : ""}${modifiers.selected && !modifiers.range_start && !modifiers.range_middle && !modifiers.range_end ? ", selected" : ""}`,
labelDayButton: (date, modifiers) => labels.day(fullDate.format(date), dayStates(labels, modifiers, true)),
labelGrid: (date) => monthYear.format(date),
labelNav: () => "Calendar navigation",
labelNext: () => "Next month",
labelPrevious: () => "Previous month",
labelNav: () => labels.navigation,
labelNext: () => labels.nextMonth,
labelPrevious: () => labels.previousMonth,
labelWeekday: (date) => weekdayLong.format(date),
}}
lang={resolvedLocale}
@@ -425,8 +498,8 @@ function CalendarDateRangePicker({
/>
</div>
<div className="ci-date-range-popover__actions">
<PopoverClose asChild><button type="button" onClick={() => { setActivePreset(undefined); setDraft({ from: "", to: "" }); update({ from: "", to: "" }); onPresetChange?.(undefined); }}>Clear</button></PopoverClose>
<PopoverClose asChild><Button size="sm" onClick={() => { update(draft); onPresetChange?.(activePreset); }} disabled={!draft.from || !draft.to}>Apply range</Button></PopoverClose>
<PopoverClose asChild><button type="button" onClick={() => { setActivePreset(undefined); setDraft({ from: "", to: "" }); update({ from: "", to: "" }); onPresetChange?.(undefined); }}>{labels.clear}</button></PopoverClose>
<PopoverClose asChild><Button size="sm" onClick={() => { update(draft); onPresetChange?.(activePreset); }} disabled={!draft.from || !draft.to}>{labels.apply}</Button></PopoverClose>
</div>
</PopoverContent>
</Popover>
@@ -460,8 +533,10 @@ function TimestampDateRangePicker({
canApply,
variant = "default",
triggerSize: triggerSizeProp,
labels: labelOverrides,
...props
}: DateRangePickerProps<"timestamp">) {
const labels = resolveLabels(defaultDateRangePickerLabels, labelOverrides);
const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
const open = controlledOpen ?? uncontrolledOpen;
const [openedAt, setOpenedAt] = useState(() => new Date().toISOString());
@@ -501,8 +576,8 @@ function TimestampDateRangePicker({
const helperContent = typeof helper === "function" ? helper({ draft, preset: activePreset }) : helper;
const hasHelper = helperContent != null && helperContent !== false && helperContent !== true && helperContent !== "";
const status = complete
? `${formatInstant.format(new Date(draft.from))} – ${formatInstant.format(new Date(draft.to))} (${timeZone}).`
: draft.from ? "Choose an end date." : "Choose a start date.";
? labels.timestampRange(formatInstant.format(new Date(draft.from)), formatInstant.format(new Date(draft.to)), timeZone)
: draft.from ? labels.chooseEnd : labels.chooseStart;
useEffect(() => {
setDraft(value);
@@ -541,13 +616,13 @@ function TimestampDateRangePicker({
return (
<Popover open={open} onOpenChange={handleOpen}>
<PopoverTrigger asChild><Button variant="outline" size={triggerSizeProp ?? (variant === "capsule" ? "sm" : "default")} data-trigger-variant={variant} className={cn("ci-date-range-trigger", className)} {...props}><CalendarDays aria-hidden="true" /><span>{label}</span></Button></PopoverTrigger>
<PopoverContent className="ci-date-range-popover ci-date-range-popover--timestamp" align="end" aria-label="Choose date range" data-calendar-months={visibleMonths} data-presets={presets.length > 0 || undefined}>
{presets.length > 0 && <div className="ci-date-range-presets" aria-label="Relative ranges">
<PopoverContent className="ci-date-range-popover ci-date-range-popover--timestamp" align="end" aria-label={labels.popover} data-calendar-months={visibleMonths} data-presets={presets.length > 0 || undefined}>
{presets.length > 0 && <div className="ci-date-range-presets" aria-label={labels.relativeRanges}>
{candidates.map(({ preset, value: next }) => <button type="button" key={preset.id} aria-pressed={activePreset === preset.id} data-active={activePreset === preset.id || undefined} disabled={!next.from || !next.to || next.from >= next.to} onClick={() => { setActivePreset(preset.id); setDraft(next); setMonth(monthForTimestamp(next)); }}>{preset.shortLabel && <Badge variant="outline" aria-hidden="true" className="ci-date-range-preset__duration">{preset.shortLabel}</Badge>}<span>{preset.label}</span>{activePreset === preset.id && <Check size={16} aria-hidden />}</button>)}
</div>}
<div className="ci-range-calendars" data-months={numberOfMonths}>
<DayPicker
aria-label="Date range calendar"
aria-label={labels.calendar}
classNames={calendarClassNames}
components={{ Chevron: CalendarChevron, DayButton: CalendarDayButton, Month: CalendarMonth }}
disabled={disabledDates}
@@ -556,8 +631,8 @@ function TimestampDateRangePicker({
footer={status}
formatters={{ formatCaption: (date) => monthYear.format(date), formatDay: (date) => dayNumber.format(date), formatWeekdayName: (date) => weekdayShort.format(date) }}
labels={{
labelDayButton: (date, modifiers) => `${fullDate.format(date)}${modifiers.today ? ", today" : ""}${modifiers.range_start ? ", range start" : ""}${modifiers.range_middle ? ", in selected range" : ""}${modifiers.range_end ? ", range end" : ""}`,
labelGrid: (date) => monthYear.format(date), labelNav: () => "Calendar navigation", labelNext: () => "Next month", labelPrevious: () => "Previous month", labelWeekday: (date) => weekdayLong.format(date),
labelDayButton: (date, modifiers) => labels.day(fullDate.format(date), dayStates(labels, modifiers, false)),
labelGrid: (date) => monthYear.format(date), labelNav: () => labels.navigation, labelNext: () => labels.nextMonth, labelPrevious: () => labels.previousMonth, labelWeekday: (date) => weekdayLong.format(date),
}}
lang={new Intl.DateTimeFormat(locale).resolvedOptions().locale}
mode="range"
@@ -571,12 +646,12 @@ function TimestampDateRangePicker({
today={parseIso(today)}
weekStartsOn={weekStartsOn}
/>
{(showSummary || (hasHelper && helperPlacement === "summary")) && <div className="ci-date-range-popover__summary">{showSummary && <><p>{draft.from && !draft.to ? "Choose an end date." : "Select a preset or choose a custom range."}</p>{complete && <p>{status}</p>}</>}{hasHelper && helperPlacement === "summary" && <div className="ci-date-range-popover__helper">{helperContent}</div>}</div>}
{(showSummary || (hasHelper && helperPlacement === "summary")) && <div className="ci-date-range-popover__summary">{showSummary && <><p>{draft.from && !draft.to ? labels.chooseEnd : labels.summary}</p>{complete && <p>{status}</p>}</>}{hasHelper && helperPlacement === "summary" && <div className="ci-date-range-popover__helper">{helperContent}</div>}</div>}
</div>
<div className="ci-date-range-popover__actions" data-has-helper={hasHelper && helperPlacement === "actions" || undefined}>
<PopoverClose asChild><button type="button" onClick={() => { setDraft({ from: "", to: "" }); setActivePreset(undefined); update({ from: "", to: "" }); }}>Clear</button></PopoverClose>
<PopoverClose asChild><button type="button" onClick={() => { setDraft({ from: "", to: "" }); setActivePreset(undefined); update({ from: "", to: "" }); }}>{labels.clear}</button></PopoverClose>
{hasHelper && helperPlacement === "actions" && <div className="ci-date-range-popover__helper">{helperContent}</div>}
<PopoverClose asChild><Button size="sm" disabled={!allowed} onClick={() => { if (allowed) update(draft, activePreset); }}>Apply range</Button></PopoverClose>
<PopoverClose asChild><Button size="sm" disabled={!allowed} onClick={() => { if (allowed) update(draft, activePreset); }}>{labels.apply}</Button></PopoverClose>
</div>
</PopoverContent>
</Popover>

View File

@@ -18,10 +18,22 @@ export const DialogTrigger = forwardRef<HTMLButtonElement, DialogTriggerProps>(f
return <DialogPrimitive.Trigger ref={ref} data-slot="dialog-trigger" {...props} />;
});
/**
* The width cap of the dialog: `default` 30rem, `wide` 36rem, `lg` 48rem, `xl` 64rem, and `full`,
* which fills the viewport minus the dialog margin in both directions, whatever its content.
* `checkout` (64rem) is the cap of the fixed-footer checkout dialogs.
*/
export type DialogSize = "default" | "wide" | "lg" | "xl" | "full" | "checkout";
export interface DialogContentProps extends Omit<ComponentProps<typeof DialogPrimitive.Content>, "asChild"> {
showCloseButton?: boolean;
/** Wider review forms while retaining viewport scrolling on small screens. */
size?: "default" | "wide";
/**
* Wider surfaces for review forms, tables and editors. Every size is as wide as the viewport
* minus the margin on a small screen, and content taller than the cap scrolls inside the dialog.
*/
size?: DialogSize;
/** Keep the header and footer visible while DialogBody scrolls. */
layout?: "default" | "fixed-footer";
/** Accessible name of the built-in close button. Defaults to "Close dialog". */
closeLabel?: string;
overlayClassName?: string;
@@ -32,6 +44,7 @@ export const DialogContent = forwardRef<HTMLDivElement, DialogContentProps>(func
overlayClassName,
showCloseButton = true,
size = "default",
layout = "default",
closeLabel = "Close dialog",
forceMount,
children,
@@ -49,6 +62,7 @@ export const DialogContent = forwardRef<HTMLDivElement, DialogContentProps>(func
forceMount={forceMount}
data-slot="dialog-content"
data-size={size}
data-layout={layout === "fixed-footer" ? layout : undefined}
className={cn("ci-dialog", className)}
{...props}
>
@@ -73,6 +87,10 @@ export function DialogHeader({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="dialog-header" className={cn("ci-dialog__header", className)} {...props} />;
}
export const DialogBody = forwardRef<HTMLDivElement, ComponentProps<"div">>(function DialogBody({ className, ...props }, ref) {
return <div ref={ref} data-slot="dialog-body" className={cn("ci-dialog__body", className)} {...props} />;
});
export function DialogFooter({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="dialog-footer" className={cn("ci-dialog__footer", className)} {...props} />;
}

View File

@@ -1,20 +1,40 @@
import type { ComponentProps, ReactNode } from "react";
import { cn } from "./lib/utils";
export type EmptyStateLayout = "stacked" | "inline";
export type EmptyStateBorder = "solid" | "dashed" | "none";
export interface EmptyStateProps extends Omit<ComponentProps<"div">, "title"> {
icon?: ReactNode;
title: ReactNode;
description?: ReactNode;
actions?: ReactNode;
/** Shorter panel (10rem instead of 16rem). Only the `stacked` layout has a minimum height. */
compact?: boolean;
/**
* `stacked` (default) is the centered panel. `inline` is one line for the empty state of a short
* list, a field or a table cell: no minimum height, 14px text, a small icon beside the text and the
* actions at the end of the line. Its title is a paragraph, not a heading.
*/
layout?: EmptyStateLayout;
/** Box around the empty state. Defaults to `solid` in the `stacked` layout and `none` in `inline`. */
border?: EmptyStateBorder;
}
export function EmptyState({ className, icon, title, description, actions, compact = false, ...props }: EmptyStateProps) {
export function EmptyState({ className, icon, title, description, actions, compact = false, layout = "stacked", border, ...props }: EmptyStateProps) {
const Title = layout === "inline" ? "p" : "h3";
return (
<div data-slot="empty-state" data-compact={compact || undefined} className={cn("ci-empty-state", className)} {...props}>
<div
data-slot="empty-state"
data-compact={compact || undefined}
data-layout={layout === "inline" ? "inline" : undefined}
data-border={border}
className={cn("ci-empty-state", className)}
{...props}
>
{icon != null && <span className="ci-empty-state__icon">{icon}</span>}
<div className="ci-empty-state__content">
<h3 className="ci-empty-state__title">{title}</h3>
<Title className="ci-empty-state__title">{title}</Title>
{description != null && <p className="ci-empty-state__description">{description}</p>}
</div>
{actions != null && <div className="ci-empty-state__actions">{actions}</div>}

View File

@@ -1,7 +1,8 @@
"use client";
import { forwardRef, useId, useRef, useState } from "react";
import type { ChangeEvent, DragEvent, InputHTMLAttributes, ReactNode } from "react";
import { Slot } from "@radix-ui/react-slot";
import { cloneElement, forwardRef, useId, useImperativeHandle, useRef, useState } from "react";
import type { ChangeEvent, DragEvent, InputHTMLAttributes, MouseEvent, ReactElement, ReactNode } from "react";
import { FileUp, Upload } from "lucide-react";
import { cn } from "./lib/utils";
@@ -174,6 +175,74 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(function F
);
});
export interface FileTriggerProps
extends Pick<NativeFileProps, "accept" | "multiple" | "capture" | "id">,
Pick<FileSelectionProps, "maxSize" | "onFilesChange" | "onFilesRejected"> {
/**
* Keeps the picker closed. Also passed to the child as `disabled`, unless the child sets its
* own. A child that is disabled, `aria-disabled` or `aria-busy` (a loading `Button`) never
* opens the picker either.
*/
disabled?: boolean;
/**
* One control that forwards its ref and click handler, usually a `Button`. It keeps its own
* accessible name, look, focus ring and loading state, and gets `type="button"` unless it
* sets a `type`.
*/
children: ReactElement;
}
/**
* Opens the native file picker from any control, with the filtering of `FileInput` and nothing
* else on screen: no "Choose file" control and no status line. For actions that start as soon
* as a file is picked (a toolbar "Import"). The ref and any other attribute (`data-*`) go to the
* hidden native input, rendered right after the child. Keep the trigger mounted until the picker
* closes: a menu item that unmounts on select loses the selection.
*/
export const FileTrigger = forwardRef<HTMLInputElement, FileTriggerProps>(function FileTrigger(
{ accept, multiple = false, maxSize, disabled = false, onFilesChange, onFilesRejected, children, ...props },
ref,
) {
const inputRef = useRef<HTMLInputElement>(null);
// Hands the input to the forwarded ref once, and keeps a callback ref's cleanup (React 19).
useImperativeHandle(ref, () => inputRef.current as HTMLInputElement, []);
const select = createFileSelector({ accept, maxSize, multiple, onFilesChange, onFilesRejected });
// Button defaults for the child. A value the child sets wins; a prop passed as `undefined` does not.
const child = children as ReactElement<{ type?: unknown; disabled?: unknown }>;
const defaults: { type?: "button"; disabled?: true } = {};
if (child.props.type === undefined) defaults.type = "button";
if (disabled && child.props.disabled === undefined) defaults.disabled = true;
const open = (event: MouseEvent<HTMLElement>) => {
const control = event.currentTarget;
if (event.defaultPrevented || disabled) return;
if (control.getAttribute("aria-disabled") === "true" || control.getAttribute("aria-busy") === "true") return;
inputRef.current?.click();
};
return (
<>
<Slot onClick={open}>{cloneElement(child, defaults)}</Slot>
<input
{...props}
ref={inputRef}
type="file"
// Out of sight, the tab order and the accessibility tree: the child is the only control.
hidden
tabIndex={-1}
style={{ display: "none" }}
accept={accept}
multiple={multiple}
disabled={disabled}
onChange={(event) => {
select(event.currentTarget.files);
// Clear the native value so picking the same file again fires `change`.
event.currentTarget.value = "";
}}
/>
</>
);
});
export interface FileDropZoneProps extends FileSelectionProps {
/** Main line; also the input's accessible name unless `aria-label(ledby)` is passed. */
dropLabel?: ReactNode;

View File

@@ -0,0 +1,68 @@
import { forwardRef } from "react";
import type { ComponentPropsWithoutRef, ReactNode } from "react";
import type { BadgeTone } from "./badge";
import { cn } from "./lib/utils";
/** The `Badge` tones: the frame, the dot and the state text take the tone's ink. */
export type FlowNodeStatus = BadgeTone;
export type FlowNodeSize = "sm" | "md";
export interface FlowNodeProps extends Omit<ComponentPropsWithoutRef<"div">, "title"> {
/** Main line: the name of the step, provider or agent. One line, ellipsized. */
title: ReactNode;
/** Secondary line under the title (a model id, a source). One line, ellipsized. */
description?: ReactNode;
/** Decorative leading mark: an icon or a logo. */
icon?: ReactNode;
/** Trailing slot on the title row (Badge, count, check mark). */
meta?: ReactNode;
/** Tone of the frame and of the state line. Pass `statusLabel` with it: a tone alone only colours the frame. */
status?: FlowNodeStatus;
/** The state as text ("Running", "Failed"), beside a dot in the status tone. The kit has no default text. */
statusLabel?: ReactNode;
/** The node is on the path in use now: a thicker frame in the status tone, or the active edge colour, and a halo. */
active?: boolean;
/** The node is the user's selection: a ring around the frame. */
selected?: boolean;
/** `md` (default) sets the title at 14px; `sm` sets it at 12px with tighter padding, for dense canvases. */
size?: FlowNodeSize;
}
/**
* The frame of a node on a flow canvas: title, secondary line, state and body. Presentation only:
* it has no role, no tab stop and no position, and it draws no connector. The canvas library, the
* handles and the layout belong to the host, which names the node and wires the interaction.
*/
export const FlowNode = forwardRef<HTMLDivElement, FlowNodeProps>(function FlowNode(
{ title, description, icon, meta, status, statusLabel, active = false, selected = false, size = "md", className, children, ...props },
ref,
) {
return (
<div
ref={ref}
{...props}
data-slot="flow-node"
data-size={size}
data-status={status}
data-active={active ? "true" : undefined}
data-selected={selected ? "true" : undefined}
className={cn("ci-flow-node", className)}
>
<div className="ci-flow-node__header">
{icon != null && <span className="ci-flow-node__icon" aria-hidden="true">{icon}</span>}
<div className="ci-flow-node__heading">
<div className="ci-flow-node__title">{title}</div>
{description != null && <div className="ci-flow-node__description">{description}</div>}
</div>
{meta != null && <div className="ci-flow-node__meta">{meta}</div>}
</div>
{statusLabel != null && (
<div className="ci-flow-node__status">
<span className="ci-flow-node__status-dot" aria-hidden="true" />
{statusLabel}
</div>
)}
{children != null && <div className="ci-flow-node__body">{children}</div>}
</div>
);
});

View File

@@ -5,7 +5,7 @@ import type { MouseEventHandler } from "react";
import { Button, type ButtonProps } from "./button";
import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";
export interface GuardedActionProps extends Omit<ButtonProps, "asChild" | "aria-disabled"> {
export interface GuardedActionProps extends Omit<ButtonProps, "asChild" | "aria-disabled" | "tooltip" | "tooltipSide"> {
/** An unmet requirement. The action stays focusable and explains this reason. */
reason?: string;
/** Reveal inline errors and focus the relevant field here. Never submits. */

View File

@@ -0,0 +1,267 @@
"use client";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { MousePointer2, X } from "lucide-react";
import { Button } from "./button";
import { resolveLabels } from "./lib/labels";
export interface GuidedWalkthroughLabels {
/** Step counter in the card heading. */
stepCount: (step: number, totalSteps: number) => string;
/** Accessible name of the button that stops the walkthrough. */
stop: string;
/** Status text while the target is missing or hidden. */
unavailable: string;
/** Text of the back button. */
back: string;
}
export const defaultGuidedWalkthroughLabels: GuidedWalkthroughLabels = {
stepCount: (step, totalSteps) => `Step ${step} of ${totalSteps}`,
stop: "Stop walkthrough",
unavailable:
"This control is not currently available. Open the relevant page or stop this walkthrough and ask for help.",
back: "Back",
};
export interface GuidedWalkthroughProps {
/** Application-resolved target. Never a model-supplied selector. */
target: HTMLElement | null;
title: string;
children: ReactNode;
step: number;
totalSteps: number;
onNext: () => void;
onBack?: () => void;
onStop: () => void;
/** Preparation only; never an implicit submit. */
onPrepare?: () => void;
prepareLabel?: string;
nextLabel?: string;
/** Localized text of the card; omitted or `undefined` keys fall back to defaultGuidedWalkthroughLabels. */
labels?: Partial<GuidedWalkthroughLabels>;
}
interface Geometry {
left: number;
top: number;
width: number;
height: number;
panelLeft: number;
panelTop: number;
panelMaxHeight: number;
}
/** Non-modal guidance. The caller owns actions, authorization and focus restoration. */
export function GuidedWalkthrough({
target,
title,
children,
step,
totalSteps,
onNext,
onBack,
onStop,
onPrepare,
prepareLabel = "Prepare this step",
nextLabel = "Next",
labels: labelOverrides,
}: GuidedWalkthroughProps) {
const labels = resolveLabels(defaultGuidedWalkthroughLabels, labelOverrides);
const id = useId();
const portal = useRef<HTMLDivElement>(null);
const panel = useRef<HTMLElement>(null);
const [rect, setRect] = useState<Geometry | null>(null);
const [theme, setTheme] = useState<string | undefined>();
useEffect(() => {
let frame = 0;
const measure = () => {
const scope = target?.closest("[data-theme]") ?? document.documentElement;
const nextTheme = scope.getAttribute("data-theme");
setTheme(
nextTheme === "dark" || nextTheme === "light" ? nextTheme : undefined,
);
if (
!target?.isConnected ||
target.getClientRects().length === 0 ||
["hidden", "collapse"].includes(getComputedStyle(target).visibility) ||
target.closest("[inert]")
) {
setRect(null);
return;
}
const box = target.getBoundingClientRect(),
margin = 16,
gap = 18;
const width = Math.min(
panel.current?.getBoundingClientRect().width ?? 352,
window.innerWidth - margin * 2,
);
const height = Math.min(
panel.current ? Math.ceil(Math.max(panel.current.getBoundingClientRect().height, panel.current.scrollHeight + panel.current.offsetHeight - panel.current.clientHeight)) : 280,
window.innerHeight - margin * 2,
);
const clampX = (x: number) =>
Math.max(margin, Math.min(x, window.innerWidth - width - margin));
const clampY = (y: number) =>
Math.max(margin, Math.min(y, window.innerHeight - height - margin));
const below = window.innerHeight - margin - box.bottom - gap;
const above = box.top - gap - margin;
let panelLeft = clampX(box.left),
panelTop: number,
panelMaxHeight = window.innerHeight - margin * 2;
if (below >= height) panelTop = clampY(box.bottom + gap);
else if (above >= height) panelTop = clampY(box.top - gap - height);
else if (window.innerWidth - margin - box.right - gap >= width) {
panelLeft = box.right + gap;
panelTop = clampY(box.top);
} else if (box.left - gap - margin >= width) {
panelLeft = box.left - gap - width;
panelTop = clampY(box.top);
} else if (Math.max(above, below) >= 160) {
panelMaxHeight = Math.max(above, below);
panelTop = above > below ? margin : box.bottom + gap;
} else {
panelLeft = clampX(window.innerWidth - width - margin);
panelTop = clampY(window.innerHeight - height - margin);
}
const next: Geometry = {
left: box.left,
top: box.top,
width: box.width,
height: box.height,
panelLeft,
panelTop,
panelMaxHeight,
};
setRect((previous) =>
previous &&
(Object.keys(next) as Array<keyof Geometry>).every(
(key) => previous[key] === next[key],
)
? previous
: next,
);
};
const schedule = () => {
if (frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
measure();
});
};
const resize = new ResizeObserver(schedule);
if (target) resize.observe(target);
if (panel.current) resize.observe(panel.current);
resize.observe(document.documentElement);
const mutations = new MutationObserver((records) => {
if (records.some((record) => !portal.current?.contains(record.target)))
schedule();
});
mutations.observe(document.documentElement, {
childList: true,
subtree: true,
characterData: true,
attributes: true,
attributeFilter: ["class", "style", "hidden", "inert", "data-theme"],
});
window.addEventListener("resize", schedule);
window.addEventListener("scroll", schedule, true);
document.fonts?.addEventListener("loadingdone", schedule);
measure();
return () => {
resize.disconnect();
mutations.disconnect();
cancelAnimationFrame(frame);
window.removeEventListener("resize", schedule);
window.removeEventListener("scroll", schedule, true);
document.fonts?.removeEventListener("loadingdone", schedule);
};
}, [target]);
useEffect(() => {
const stop = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
onStop();
}
};
window.addEventListener("keydown", stop);
return () => window.removeEventListener("keydown", stop);
}, [onStop]);
if (typeof document === "undefined") return null;
return createPortal(
<div
ref={portal}
className="ci-theme ci-guided-walkthrough"
data-theme={theme}
data-slot="guided-walkthrough"
>
{rect && (
<div
aria-hidden="true"
className="ci-guided-walkthrough__highlight"
style={{
left: rect.left - 4,
top: rect.top - 4,
width: rect.width + 8,
height: rect.height + 8,
}}
>
<MousePointer2 className="ci-guided-walkthrough__pointer" size={25} />
</div>
)}
<section
ref={panel}
className="ci-guided-walkthrough__panel"
aria-labelledby={id}
style={
rect
? {
left: rect.panelLeft,
top: rect.panelTop,
maxHeight: rect.panelMaxHeight,
}
: undefined
}
>
<div className="ci-guided-walkthrough__heading">
<span>{labels.stepCount(step, totalSteps)}</span>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label={labels.stop}
onClick={onStop}
>
<X aria-hidden="true" size={16} />
</Button>
</div>
<h2 id={id}>{title}</h2>
<div role="status">
{rect ? children : labels.unavailable}
</div>
<div className="ci-guided-walkthrough__actions">
{onBack && (
<Button type="button" variant="outline" size="sm" onClick={onBack}>
{labels.back}
</Button>
)}
{rect && onPrepare && (
<Button
type="button"
variant="outline"
size="sm"
onClick={onPrepare}
>
{prepareLabel}
</Button>
)}
<Button type="button" size="sm" onClick={onNext} disabled={!rect}>
{nextLabel}
</Button>
</div>
</section>
</div>,
document.body,
);
}

View File

@@ -0,0 +1,67 @@
import type { ComponentProps } from "react";
import { cn } from "./lib/utils";
/** A step of the `--ci-scale-seq` ramp. 0 is off the ramp: zero or nothing measured. 1 is nearest the surface, 7 the strongest. */
export type HeatLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
export type HeatCellSize = "sm" | "md" | "lg";
/** Every level in order, for a "less to more" key. */
export const heatLevels = [0, 1, 2, 3, 4, 5, 6, 7] as const satisfies readonly HeatLevel[];
/**
* The step of the `--ci-scale-seq` ramp for `value`, as `CalendarHeatmap` draws it.
*
* - Missing and non-finite values are `null`: unavailable, never zero. `HeatCell` takes it as it is.
* - Zero and negative values are level 0: a measurement that is off the ramp.
* - Without `thresholds`, levels 1 to 7 divide the range up to `max` evenly; a value above `max` stays on 7.
* When `max` is not a positive number there is no range to divide, so every positive value is 7.
* - `thresholds` are six ascending lower bounds for levels 2 to 7 (quantiles or fixed bands); `max` is then unused.
*/
export function heatLevel(value: number | null | undefined, max: number, thresholds?: readonly number[]): HeatLevel | null {
if (value == null || !Number.isFinite(value)) return null;
if (value <= 0) return 0;
if (thresholds) return Math.min(7, 1 + thresholds.filter((bound) => value >= bound).length) as HeatLevel;
if (!(max > 0)) return 7;
return Math.max(1, Math.min(7, Math.ceil((value / max) * 7))) as HeatLevel;
}
interface HeatCellBaseProps extends Omit<ComponentProps<"span">, "children" | "aria-label" | "aria-hidden"> {
/** Step to paint: pass `heatLevel(value, max)` as it is. `null` is unavailable: a dashed outline, never zero. */
level: HeatLevel | null;
/** `sm` is 14px, the `CalendarHeatmap` cell; `md` (default) is 24px and `lg` is 36px. */
size?: HeatCellSize;
}
interface NamedHeatCellProps extends HeatCellBaseProps {
/** Accessible text with what the cell stands for and its value, for example "Tuesday: 1,204 requests". */
label: string;
"aria-hidden"?: undefined;
}
interface HiddenHeatCellProps extends HeatCellBaseProps {
label?: undefined;
/** Hides the cell from assistive technology, for a key or a cell whose value is written beside it. */
"aria-hidden": true;
}
/** A cell is either named by `label` or explicitly hidden with `aria-hidden`. */
export type HeatCellProps = NamedHeatCellProps | HiddenHeatCellProps;
/**
* One cell on the `--ci-scale-seq` ramp, for a short heat strip or a small matrix beside a `CalendarHeatmap`.
* The mark grows with the level, as in the calendar, so the level never depends on colour alone.
*/
export function HeatCell({ level, size = "md", label, className, ...props }: HeatCellProps) {
// Callers without types can pass anything; the mark only has the eight levels.
const step = level === null ? null : Math.min(7, Math.max(0, Math.round(level) || 0));
return (
<span
role={label === undefined ? undefined : "img"}
aria-label={label}
{...props}
className={cn("ci-heat-cell", className)}
data-size={size}
>
<span aria-hidden="true" className="ci-heat-cell__mark" data-level={step ?? undefined} data-unavailable={step === null || undefined} />
</span>
);
}

View File

@@ -1,8 +1,8 @@
"use client";
import * as HoverCardPrimitive from "@radix-ui/react-hover-card";
import { forwardRef } from "react";
import type { ComponentProps } from "react";
import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react";
import type { ComponentProps, FocusEvent, PointerEvent, ReactNode } from "react";
import { cn } from "./lib/utils";
export type HoverCardSide = NonNullable<ComponentProps<typeof HoverCardPrimitive.Content>["side"]>;
@@ -61,3 +61,273 @@ export const HoverCardContent = forwardRef<HTMLDivElement, HoverCardContentProps
</HoverCardPrimitive.Portal>
);
});
/** What a card can be positioned against: an element, or anything that reports a rectangle. */
export type HoverCardAnchorTarget = Element | { getBoundingClientRect(): DOMRect };
export interface HoverCardAnchorProps {
/** The element, or virtual rectangle, the card is positioned against. Keep a virtual one stable between renders. */
anchor: HoverCardAnchorTarget | null;
}
/** Renders nothing: it hands the host's element to Radix as the node of its trigger. */
const HoverCardAnchorHandle = forwardRef<HoverCardAnchorTarget | null, HoverCardAnchorProps>(function HoverCardAnchorHandle({ anchor }, ref) {
useImperativeHandle<HoverCardAnchorTarget | null, HoverCardAnchorTarget | null>(ref, () => anchor, [anchor]);
return null;
});
/**
* Used inside a `HoverCard` in place of `HoverCardTrigger`: the card is positioned against an
* element the host owns. It adds no element and no event handler, so the host decides when the
* card opens (`open` and `onOpenChange` on `HoverCard`). `useSharedHoverCard` does that for a
* group of triggers.
*/
export function HoverCardAnchor({ anchor }: HoverCardAnchorProps) {
return (
<HoverCardPrimitive.Trigger asChild>
<HoverCardAnchorHandle anchor={anchor} />
</HoverCardPrimitive.Trigger>
);
}
export interface SharedHoverCardOptions {
/** Milliseconds the pointer rests on a trigger before the card opens. Keyboard focus opens it at once. */
openDelay?: number;
/** Milliseconds the card stays open after the pointer or the focus leaves. */
closeDelay?: number;
}
/** Spread on each trigger. A handler of your own for the same event has to call the one given here. */
export interface SharedHoverCardTriggerProps {
"data-hover-card-trigger": string;
"aria-describedby": string | undefined;
onPointerEnter: (event: PointerEvent<Element>) => void;
onPointerLeave: (event: PointerEvent<Element>) => void;
onPointerDown: (event: PointerEvent<Element>) => void;
onFocus: (event: FocusEvent<Element>) => void;
onBlur: (event: FocusEvent<Element>) => void;
}
export interface SharedHoverCardState {
open: boolean;
/** Value of the trigger the card is open for, `null` while it is closed. */
value: string | null;
/** Props of the trigger with this value. The value has to be unique among the triggers of the card. */
getTriggerProps: (value: string) => SharedHoverCardTriggerProps;
/** Opens the card for a mark that is not an element (a point of a canvas chart), after `openDelay`. */
show: (value: string, anchor: HoverCardAnchorTarget) => void;
/** Closes the card after `closeDelay`, unless the pointer reaches the card or another trigger first. */
hide: () => void;
/** Closes the card now. */
close: () => void;
/** Wiring read by `SharedHoverCard`. */
controller: {
contentId: string;
/** Last value and anchor shown; kept after closing so an exit animation still has its content. */
value: string | null;
anchor: HoverCardAnchorTarget | null;
hold: () => void;
press: () => void;
};
}
function isKeyboardFocus(element: Element) {
try {
return element.matches(":focus-visible");
} catch {
return true;
}
}
/**
* Hover intent of one card shared by many triggers. The triggers stay plain elements of the host
* (`getTriggerProps`), and `SharedHoverCard` renders the single card, so a long list does not pay
* for one Radix root per trigger.
*/
export function useSharedHoverCard({ openDelay = 300, closeDelay = 200 }: SharedHoverCardOptions = {}): SharedHoverCardState {
const contentId = useId();
const [target, setTarget] = useState<{ value: string; anchor: HoverCardAnchorTarget } | null>(null);
const [open, setOpen] = useState(false);
const live = useRef({ open: false, value: null as string | null, openDelay, closeDelay, openTimer: 0, closeTimer: 0, pressed: false, pressedOnCard: false, selection: false }).current;
useEffect(() => {
live.openDelay = openDelay;
live.closeDelay = closeDelay;
}, [live, openDelay, closeDelay]);
const actions = useMemo(() => {
const commit = (value: string, anchor: HoverCardAnchorTarget) => {
live.open = true;
// A selection belongs to the content of the previous trigger.
if (live.value !== value) live.selection = false;
live.value = value;
setTarget((previous) => (previous?.value === value && previous.anchor === anchor ? previous : { value, anchor }));
setOpen(true);
};
const close = () => {
window.clearTimeout(live.openTimer);
window.clearTimeout(live.closeTimer);
live.open = false;
live.value = null;
setOpen(false);
};
const show = (value: string, anchor: HoverCardAnchorTarget, now = false) => {
window.clearTimeout(live.openTimer);
window.clearTimeout(live.closeTimer);
// An open card moves to the next trigger at once; only the first open waits.
if (now || live.open) commit(value, anchor);
else live.openTimer = window.setTimeout(() => commit(value, anchor), live.openDelay);
};
const hide = () => {
window.clearTimeout(live.openTimer);
// As in Radix HoverCard: a press or a text selection inside the card keeps it open.
if (!live.open || live.pressedOnCard || live.selection) return;
window.clearTimeout(live.closeTimer);
live.closeTimer = window.setTimeout(close, live.closeDelay);
};
const release = () => {
live.pressed = false;
document.removeEventListener("pointerup", release, true);
document.removeEventListener("pointercancel", release, true);
};
const enter = (element: Element, now: boolean) => {
const value = element.getAttribute("data-hover-card-trigger");
if (value !== null) show(value, element, now);
};
return {
show: (value: string, anchor: HoverCardAnchorTarget) => show(value, anchor),
hide,
close,
hold: () => window.clearTimeout(live.closeTimer),
press: () => {
live.pressedOnCard = true;
live.selection = false;
},
onPointerEnter: (event: PointerEvent<Element>) => {
if (event.pointerType !== "touch") enter(event.currentTarget, false);
},
onPointerLeave: (event: PointerEvent<Element>) => {
if (event.pointerType !== "touch") hide();
},
// A press dismisses the card (Radix closes it on the press outside) and cancels a pending
// open; the focus that the press causes must not open it again.
onPointerDown: () => {
window.clearTimeout(live.openTimer);
live.pressed = true;
// Capture phase: a host handler that stops propagation must not leave the press pending.
document.addEventListener("pointerup", release, true);
document.addEventListener("pointercancel", release, true);
},
onFocus: (event: FocusEvent<Element>) => {
if (!live.pressed && isKeyboardFocus(event.currentTarget)) enter(event.currentTarget, true);
},
onBlur: () => hide(),
dispose: () => {
window.clearTimeout(live.openTimer);
window.clearTimeout(live.closeTimer);
release();
},
};
}, [live]);
useEffect(() => actions.dispose, [actions]);
useEffect(() => {
if (!open) return;
const settle = () => {
live.pressedOnCard = false;
window.setTimeout(() => {
const selection = document.getSelection();
const card = document.getElementById(contentId);
live.selection = Boolean(selection && card && selection.toString() !== "" && card.contains(selection.anchorNode));
});
};
document.addEventListener("pointerup", settle, true);
return () => {
document.removeEventListener("pointerup", settle, true);
live.pressedOnCard = false;
live.selection = false;
};
}, [open, live, contentId]);
// A trigger removed from the document fires neither pointerleave nor blur.
useEffect(() => {
if (open && target && target.anchor instanceof Element && !target.anchor.isConnected) actions.close();
});
const active = open && target ? target.value : null;
const { onPointerEnter, onPointerLeave, onPointerDown, onFocus, onBlur, show, hide, close, hold, press } = actions;
const getTriggerProps = useCallback((value: string): SharedHoverCardTriggerProps => ({
"data-hover-card-trigger": value,
"aria-describedby": value === active ? contentId : undefined,
onPointerEnter,
onPointerLeave,
onPointerDown,
onFocus,
onBlur,
}), [active, contentId, onPointerEnter, onPointerLeave, onPointerDown, onFocus, onBlur]);
return useMemo(() => ({
open,
value: active,
getTriggerProps,
show,
hide,
close,
controller: { contentId, value: target?.value ?? null, anchor: target?.anchor ?? null, hold, press },
}), [open, active, getTriggerProps, show, hide, close, contentId, target, hold, press]);
}
export interface SharedHoverCardProps extends Omit<HoverCardContentProps, "children" | "id" | "forceMount"> {
/** What `useSharedHoverCard` returned. */
card: SharedHoverCardState;
/** Content of the card for the active trigger. Called only while the card is mounted. */
children: (value: string) => ReactNode;
}
function SharedHoverCardBody({ value, render }: { value: string; render: (value: string) => ReactNode }) {
return <>{render(value)}</>;
}
/**
* The single card of `useSharedHoverCard`: a `HoverCardContent` anchored to the active trigger.
* Render it once, next to the triggers.
*/
export const SharedHoverCard = forwardRef<HTMLDivElement, SharedHoverCardProps>(function SharedHoverCard({
card,
children,
onPointerEnter,
onPointerLeave,
onPointerDown,
...props
}, ref) {
const { close, hide, controller } = card;
return (
// Radix only reports the dismissals here (Escape, a press outside): the delays belong to the hook.
<HoverCardPrimitive.Root open={card.open} onOpenChange={(next) => { if (!next) close(); }}>
<HoverCardAnchor anchor={controller.anchor} />
<HoverCardContent
ref={ref}
id={controller.contentId}
{...props}
// preventDefault keeps Radix from starting its own timers for the pointer on the card.
onPointerEnter={(event) => {
onPointerEnter?.(event);
if (!event.defaultPrevented && event.pointerType !== "touch") controller.hold();
event.preventDefault();
}}
onPointerLeave={(event) => {
onPointerLeave?.(event);
if (!event.defaultPrevented && event.pointerType !== "touch") hide();
event.preventDefault();
}}
onPointerDown={(event) => {
onPointerDown?.(event);
if (!event.defaultPrevented) controller.press();
}}
>
{controller.value !== null && <SharedHoverCardBody value={controller.value} render={children} />}
</HoverCardContent>
</HoverCardPrimitive.Root>
);
});

View File

@@ -0,0 +1,45 @@
import { forwardRef } from "react";
import type { ComponentPropsWithoutRef } from "react";
import type { BadgeTone } from "./badge";
import { cn } from "./lib/utils";
import type { CiChartSlot } from "./tokens";
/** The `Badge` status tones, or a chart series: the same ink on the same tint. */
export type IconChipTone = BadgeTone | `chart-${CiChartSlot}`;
/** The `Avatar` scale: 24, 32, 40, 48 and 64px. */
export type IconChipSize = "xs" | "sm" | "md" | "lg" | "xl";
export type IconChipShape = "rounded" | "circle";
export interface IconChipProps extends ComponentPropsWithoutRef<"span"> {
/** Ink and tint of the chip. Defaults to "neutral". */
tone?: IconChipTone;
/** Width and height: `xs` 24px, `sm` 32px, `md` 40px (default), `lg` 48px, `xl` 64px. The icon is half the chip. */
size?: IconChipSize;
/** "rounded" uses the control radius (default); "circle" is fully round. */
shape?: IconChipShape;
}
/**
* An icon on a tinted square or circle, for card headers, list rows, empty states and status
* indicators. Decorative by default; pass `aria-label` or `aria-labelledby` when the chip is the
* only carrier of the information, and it becomes an image with that name.
*/
export const IconChip = forwardRef<HTMLSpanElement, IconChipProps>(function IconChip(
{ tone = "neutral", size = "md", shape = "rounded", className, ...props },
ref,
) {
const named = Boolean(props["aria-label"] || props["aria-labelledby"]);
return (
<span
ref={ref}
role={named ? "img" : undefined}
aria-hidden={named ? undefined : true}
{...props}
data-slot="icon-chip"
data-tone={tone}
data-size={size}
data-shape={shape}
className={cn("ci-icon-chip", className)}
/>
);
});

View File

@@ -1,11 +1,16 @@
export { SidebarBranch, type SidebarBranchItem, type SidebarBranchProps } from "./sidebar-branch";
export { SellerOnboardingLayout, type SellerOnboardingLayoutProps, type SellerOnboardingStep } from "./seller-onboarding-layout";
export { SellerKeyOfferCard, SellerVolumeCapCard, type SellerKeyOfferCardProps, type SellerVolumeCapCardProps, type SellerCapUsageBarProps, type SellerCardAction, type SellerCardStatus, type SellerOfferVolume } from "./seller-cards";
export { SellerEarningsSummaryStrip, type SellerEarningsSummaryStripProps, type SellerEarningsMetric } from "./seller-earnings-summary-strip";
export { SidebarBranch, defaultSidebarBranchLabels, type SidebarBranchItem, type SidebarBranchLabels, type SidebarBranchProps } from "./sidebar-branch";
export { SignalDiagram, DiagramFrame, type SignalNode, type SignalEdge, type SignalDiagramProps, type DiagramFrameProps } from "./signal-diagram";
export { OverviewCard, type OverviewCardProps, type OverviewMetric, type OverviewTone } from "./overview-card";
export { MetricChartFrame, MetricFunnel, MetricDonut, StatusMatrix, defaultStatusMatrixToneLabels, statusMatrixToneOrder, type MetricChartFrameProps, type MetricFunnelDatum, type MetricFunnelProps, type MetricDonutDatum, type MetricDonutProps, type StatusMatrixItem, type StatusMatrixProps, type StatusMatrixTone } from "./metric-charts";
export { LineChart, StackedBarChart, Sparkline, type ChartSeries, type LineChartDatum, type LineChartProps, type LineChartSeries, type StackedBarDatum, type StackedBarChartProps, type SparklineProps } from "./reporting-charts";
export { LineChart, StackedBarChart, Sparkline, type ChartSeries, type LineChartDatum, type LineChartProps, type LineChartSeries, type StackedBarDatum, type StackedBarChartProps, type SparklineProps, type SparklineVariant } from "./reporting-charts";
export { chartTheme } from "./chart-theme";
export { MetricCard, MetricTrend, type MetricCardProps, type MetricTrendProps } from "./metric-card";
export { StackedAreaChart, type StackedAreaChartProps, type StackedBarLineSeries } from "./reporting-charts";
export { MetricCard, MetricTrend, defaultMetricTrendLabels, type MetricCardProps, type MetricTrendLabels, type MetricTrendProps } from "./metric-card";
export { CalendarHeatmap, type CalendarHeatmapDatum, type CalendarHeatmapProps } from "./calendar-heatmap";
export { HeatCell, heatLevel, heatLevels, type HeatCellProps, type HeatCellSize, type HeatLevel } from "./heat-cell";
export { LegendMarker, chartSeries, legendMarkerShapes, type ChartSeriesStyle, type LegendMarkerProps, type LegendMarkerShape, type LegendMarkerSize } from "./legend-marker";
export { WorkflowGuide, type WorkflowGuideItem, type WorkflowGuideProps } from "./workflow-guide";
export {
@@ -18,23 +23,26 @@ export {
} from "./tokens";
export { brandTintVars, type BrandTintVars } from "./brand-tint";
export { Button, buttonVariants, type ButtonProps, type ButtonSize, type ButtonVariant } from "./button";
export { Button, buttonVariants, type ButtonProps, type ButtonSize, type ButtonTone, type ButtonVariant } from "./button";
export { GuardedAction, type GuardedActionProps } from "./guarded-action";
export { StickyRegion, type StickyRegionProps } from "./sticky-region";
export { Badge, badgeVariants, type BadgeProps, type BadgeShape, type BadgeTone, type BadgeVariant } from "./badge";
export { Badge, badgeVariants, type BadgeChartTone, type BadgeProps, type BadgeShape, type BadgeSize, type BadgeTone, type BadgeVariant } from "./badge";
export { Kbd, KbdGroup, type KbdGroupProps, type KbdProps, type KbdSize } from "./kbd";
export { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, type AlertDialogActionProps, type AlertDialogCancelProps, type AlertDialogContentProps, type AlertDialogProps, type AlertDialogTone } from "./alert-dialog";
export { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, type CommandEmptyProps, type CommandFilter, type CommandFilterItem, type CommandGroupProps, type CommandInputProps, type CommandItemProps, type CommandListProps, type CommandProps } from "./command";
export { IconChip, type IconChipProps, type IconChipShape, type IconChipSize, type IconChipTone } from "./icon-chip";
export { Command, CommandEmpty, CommandFooter, CommandGroup, CommandInput, CommandItem, CommandList, type CommandEmptyProps, type CommandFilter, type CommandFilterItem, type CommandFooterProps, type CommandGroupProps, type CommandInputProps, type CommandItemProps, type CommandListProps, type CommandProps } from "./command";
export { JsonTree, defaultJsonTreeLabels, formatJsonTreePath, type JsonTreeCopyDetail, type JsonTreeCopyKind, type JsonTreeLabels, type JsonTreeNode, type JsonTreePath, type JsonTreeProps } from "./json-tree";
export { Tile, type TileLayout, type TileProps } from "./tile";
export { ToggleChip, type ToggleChipProps, type ToggleChipSize } from "./toggle-chip";
export { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, type CardFooterAlign, type CardFooterProps, type CardProps } from "./card";
export { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, type CardFooterAlign, type CardFooterProps, type CardProps, type CardSurface } from "./card";
export { Input, type InputProps, type InputSize } from "./input";
export { NumberInput, type NumberInputProps } from "./number-input";
export { Label } from "./label";
export { Separator, type SeparatorLabelAlign, type SeparatorOrientation, type SeparatorProps } from "./separator";
export { Skeleton, type SkeletonAnimation, type SkeletonProps, type SkeletonVariant } from "./skeleton";
export { Switch, type SwitchProps, type SwitchSide, type SwitchSize } from "./switch";
export { Textarea, type TextareaProps } from "./textarea";
export { Item, ItemList, type ItemListDensity, type ItemListProps, type ItemListVariant, type ItemProps } from "./item-list";
export {
Checkbox,
CheckboxGroup,
@@ -80,12 +88,14 @@ export {
export {
FileDropZone,
FileInput,
FileTrigger,
fileMatchesAccept,
partitionFiles,
type FileDropZoneProps,
type FileInputProps,
type FileRejection,
type FileRejectionReason,
type FileTriggerProps,
} from "./file-input";
export { NumberTicker, type NumberTickerProps } from "./number-ticker";
export {
@@ -99,6 +109,7 @@ export {
type TabsTriggerProps,
type TabsVariant,
} from "./tabs";
export { SegmentedControl, type SegmentedControlOption, type SegmentedControlProps, type SegmentedControlSize } from "./segmented-control";
export {
Table,
TableActionLink,
@@ -110,14 +121,24 @@ export {
TableHeader,
TableNote,
TableRow,
type TableCellAlign,
type TableCellProps,
type TableDensity,
type TableHeadProps,
type TableActionLinkProps,
type TableRowActivateEvent,
type TableRowFocus,
type TableRowProps,
type TableProps,
type TableStickyEdge,
type TableVariant,
} from "./table";
export {
TableScrollArea,
TableScrollAreaLabelsProvider,
defaultTableScrollAreaLabels,
type TableScrollAreaLabels,
type TableScrollAreaLabelsProviderProps,
type TableScrollAreaProps,
} from "./table-scroll-area";
export {
@@ -128,18 +149,22 @@ export {
type StatProps,
type StatRowProps,
type StatLabelVariant,
type StatSize,
type StatTone,
} from "./stat";
export { Progress, type ProgressProps, type ProgressTone, type ProgressSegment, type ProgressBand } from "./progress";
export { Progress, type ProgressProps, type ProgressTone, type ProgressSize, type ProgressSemantics, type ProgressSegment, type ProgressBand } from "./progress";
export { RadialMeter, type RadialMeterProps, type RadialMeterSize } from "./radial-meter";
export { Spinner, type SpinnerProps, type SpinnerSize } from "./spinner";
export {
Chart,
defaultChartLabels,
type ChartDatum,
type ChartLabels,
type ChartProps,
type ChartTone,
type ChartVariant,
} from "./chart";
export { ModelIdentity, type ModelIdentityProps } from "./model-identity";
export { ModelIdentity, type ModelIdentityProps, type ModelIdentitySize } from "./model-identity";
export {
Alert,
AlertActions,
@@ -147,21 +172,25 @@ export {
AlertTitle,
type AlertPersistence,
type AlertProps,
type AlertSize,
type AlertVariant,
} from "./alert";
export {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
type TooltipContentProps,
type TooltipAlign,
type TooltipProps,
type TooltipProviderProps,
type TooltipSide,
type TooltipTriggerProps,
} from "./tooltip";
export { InfoTooltip, type InfoTooltipProps } from "./info-tooltip";
export {
Dialog,
DialogBody,
DialogClose,
DialogContent,
DialogDescription,
@@ -172,6 +201,7 @@ export {
type DialogCloseProps,
type DialogContentProps,
type DialogProps,
type DialogSize,
type DialogTriggerProps,
} from "./dialog";
export {
@@ -188,14 +218,24 @@ export {
} from "./popover";
export {
HoverCard,
HoverCardAnchor,
HoverCardContent,
HoverCardTrigger,
SharedHoverCard,
useSharedHoverCard,
type HoverCardAlign,
type HoverCardAnchorProps,
type HoverCardAnchorTarget,
type HoverCardContentProps,
type HoverCardProps,
type HoverCardSide,
type HoverCardTriggerProps,
type SharedHoverCardOptions,
type SharedHoverCardProps,
type SharedHoverCardState,
type SharedHoverCardTriggerProps,
} from "./hover-card";
export { FlowNode, type FlowNodeProps, type FlowNodeSize, type FlowNodeStatus } from "./flow-node";
export {
DropdownMenu,
DropdownMenuCheckboxItem,
@@ -231,6 +271,7 @@ export {
type ToasterProps,
} from "./toast";
export { ControlHighlight, type ControlHighlightProps } from "./control-highlight";
export { GuidedWalkthrough, defaultGuidedWalkthroughLabels, type GuidedWalkthroughLabels, type GuidedWalkthroughProps } from "./guided-walkthrough";
export { FeatureNotice, type FeatureNoticeProps, type FeatureNoticeAlign, type FeatureNoticeSide } from "./feature-notice";
export {
Avatar,
@@ -259,7 +300,7 @@ export {
} from "./accordion";
export { Disclosure, DisclosureContent, DisclosureTrigger, type DisclosureContentProps, type DisclosureProps, type DisclosureTriggerProps } from "./disclosure";
export { LoadingState, type LoadingStateProps, type LoadingStateVariant } from "./loading-state";
export { EmptyState, type EmptyStateProps } from "./empty-state";
export { EmptyState, type EmptyStateBorder, type EmptyStateLayout, type EmptyStateProps } from "./empty-state";
export {
Breadcrumb,
BreadcrumbEllipsis,
@@ -268,8 +309,9 @@ export {
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
type BreadcrumbEllipsisProps,
} from "./breadcrumb";
export { PageHeader, SectionHeader, type PageHeaderProps, type SectionHeaderProps } from "./page-header";
export { PageHeader, SectionHeader, type SectionHeaderSize, type PageHeaderProps, type SectionHeaderProps } from "./page-header";
export {
Pagination,
PaginationContent,
@@ -278,8 +320,16 @@ export {
PaginationLink,
PaginationNext,
PaginationPrevious,
PaginationSummary,
type PaginationEllipsisProps,
type PaginationLinkProps,
} from "./pagination";
export {
PaginationControls,
defaultPaginationControlsLabels,
type PaginationControlsLabels,
type PaginationControlsProps,
} from "./pagination-controls";
export {
Sidebar,
SidebarBrand,
@@ -305,6 +355,9 @@ export {
type SidebarActionProps,
type SidebarContextProps,
type SidebarCollapsible,
type SidebarGroupContentProps,
type SidebarGroupLabelProps,
type SidebarGroupProps,
type SidebarMenuButtonProps,
type SidebarProps,
type SidebarProviderProps,
@@ -312,7 +365,7 @@ export {
type SidebarState,
type SidebarVariant,
} from "./sidebar";
export { DataTable, type DataTableColumn, type DataTableProps, type DataTableValue } from "./data-table";
export { DataTable, defaultDataTableLabels, type DataTableColumn, type DataTableLabels, type DataTableProps, type DataTableSort, type DataTableValue } from "./data-table";
export {
DataTableColumnsMenu,
DataTableFilterField,
@@ -345,7 +398,7 @@ export {
type MultiSelectFilterValue,
} from "./multi-select-filter";
export { Slider, type SliderProps, type SliderPreset, type SliderMark } from "./slider";
export { DateRangePicker, defaultDateRangePresets, type DateRangeDayPreset, type DateRangeDayPresetContext, type DateRangePickerMode, type DateRangePickerPresets, type DateRangePickerProps, type DateRangePickerVariant, type DateRangePreset, type DateRangePresetId, type DateRangePresetOption, type DateRangeValue } from "./date-range-picker";
export { DateRangePicker, defaultDateRangePickerLabels, defaultDateRangePresets, type DateRangePickerLabels, type DateRangeDayPreset, type DateRangeDayPresetContext, type DateRangePickerMode, type DateRangePickerPresets, type DateRangePickerProps, type DateRangePickerVariant, type DateRangePreset, type DateRangePresetId, type DateRangePresetOption, type DateRangeValue } from "./date-range-picker";
export { defaultDateRangeRelativePresets, resolveDateRangePreset, calendarDayBoundary, type DateRangeRelativePreset, type DateRangePresetContext } from "./date-range-time";
export {
LanguageSegmentedControl,
@@ -358,6 +411,7 @@ export {
type CodePreviewToken,
type CodePreviewTokenTone,
} from "./code-preview";
export { InlineCode, type InlineCodeProps } from "./inline-code";
export {
LiveResponsePanel,
ParameterControls,
@@ -401,10 +455,10 @@ export {
type SheetTriggerProps,
} from "./sheet";
export { SearchableSelect } from "./searchable-select";
export type { SearchableSelectProps, SearchableSelectOption } from "./searchable-select";
export type { SearchableSelectProps, SearchableSelectOption, SearchableSelectFilter } from "./searchable-select";
export { Wizard, defaultWizardLabels, type WizardLabels, type WizardProps } from "./wizard";
export { ChoiceCard, MultiChoiceCard, SetupLayout, SetupBenefits, SetupProgressCard, SaveChangesBar, type MultiChoiceCardProps, type SetupLayoutProps, type SetupBenefitsProps, type ChoiceCardProps, type ChoiceCardTone, type SetupProgressCardProps, type SaveChangesBarProps, defaultSetupProgressCardLabels, type SetupProgressCardLabels, type SetupProgressCardStep } from "./onboarding-patterns";
export { AnnouncementCarousel, type AnnouncementCarouselProps, type AnnouncementItem, type AnnouncementMediaState } from "./announcement-carousel";
export { AnnouncementCarousel, defaultAnnouncementCarouselLabels, type AnnouncementCarouselLabels, type AnnouncementCarouselProps, type AnnouncementItem, type AnnouncementMediaState } from "./announcement-carousel";
export { BrandLoader, type BrandLoaderProps, type BrandLoaderVariant } from "./brand-loader";
export { LoadingScreen, type LoadingScreenProps, type LoadingMessage } from "./loading-screen";
@@ -416,15 +470,15 @@ export { KeakMark, KeakLogo, ProductIcon, ProductLockup, ProductSwitcher, Editor
type KeakMarkProps, type KeakLogoProps, type ProductIconProps, type KeakProduct, type ProductLockupProps,
type ProductSwitcherItem, type ProductSwitcherProps, type EditorialSectionProps, type EditorialCardProps,
} from "./keak-brand";
export { InvoiceDocument, type InvoiceDocumentProps, type InvoiceDocumentParty } from "./invoice-document";
export { InvoiceDocument, defaultInvoiceDocumentLabels, type InvoiceDocumentLabels, type InvoiceDocumentProps, type InvoiceDocumentParty } from "./invoice-document";
export { IntegrationSetup, type IntegrationSetupProps, type IntegrationSetupStep } from "./integration-setup";
export { IntegrationSetup, IntegrationSetupSteps, defaultIntegrationSetupLabels, type IntegrationSetupLabels, type IntegrationSetupProps, type IntegrationSetupStep, type IntegrationSetupStepsProps } from "./integration-setup";
export { IntegrationResources, type IntegrationResource, type IntegrationResourcesProps } from "./integration-resources";
export { TokenSavingsList, ClientQuickStart, OverviewPanels, type TokenSavingsItem, type QuickStartIntegration, type OverviewPanelsProps } from "./overview-patterns";
export { IntegrationResources, defaultIntegrationResourcesLabels, type IntegrationResource, type IntegrationResourcesLabels, type IntegrationResourcesProps } from "./integration-resources";
export { TokenSavingsList, ClientQuickStart, OverviewPanels, defaultClientQuickStartLabels, defaultTokenSavingsListLabels, type ClientQuickStartLabels, type TokenSavingsItem, type TokenSavingsListLabels, type QuickStartIntegration, type OverviewPanelsProps } from "./overview-patterns";
export { RecoveryState, type RecoveryStateProps } from "./recovery-state";
export { SuccessTransition, type SuccessTransitionProps } from "./success-transition";
export { SecretValue, type SecretValueProps } from "./secret-value";
export { SecretValue, defaultSecretValueLabels, type SecretValueLabels, type SecretValueProps } from "./secret-value";
export { SetupSelectionSummary, type SetupSelectionSummaryProps } from "./onboarding-patterns";
@@ -437,8 +491,12 @@ export { CloudFieldHelp, CloudHostingConsent, defaultCloudFieldHelpLabels, defau
export { DockedLayout, DockedRail, DockedRailHeader, DockedRailBody, DockedRailFooter, DockedRailClose, type DockedLayoutProps, type DockedRailProps } from "./docked-rail";
export { ScopeChip, type ScopeChipProps } from "./scope-chip";
export { ChatHeader, ChatWelcome, ChatPromptList, ChatComposer, ChatThread, ChatMessage, ChatActivity, ChatMessageActions, ChatHistory, type ChatHeaderProps, type ChatWelcomeProps, type ChatPrompt, type ChatPromptListProps, type ChatAttachment, type ChatComposerProps, type ChatThreadProps, type ChatMessageProps, type ChatActivityState, type ChatActivityProps, type ChatMessageActionsProps, type ChatHistoryItem, type ChatHistoryGroup, type ChatHistoryProps } from "./chat";
export { ChatHeader, ChatWelcome, ChatPromptList, ChatComposer, ChatThread, ChatMessage, ChatActivity, ChatMessageActions, ChatHistory, defaultChatActivityLabels, type ChatActivityLabels, type ChatHeaderProps, type ChatWelcomeProps, type ChatPrompt, type ChatPromptListProps, type ChatAttachment, type ChatComposerProps, type ChatThreadProps, type ChatMessageProps, type ChatActivityState, type ChatActivityProps, type ChatMessageActionsProps, type ChatHistoryItem, type ChatHistoryGroup, type ChatHistoryProps } from "./chat";
export { UsageInfoTooltip, UsageDrilldownHeader, UsageRequestIdentity, UsageCostBreakdown, UsageTokenUsage, UsageDetailSection, UsageTimingDelivery, UsageModelsUsed, UsageDrilldownBody, UsageDrilldownActions, UsageRequestFailure, UsageDrilldownLoading, type UsageDetailValue, type UsageInfoTooltipProps, type UsageDrilldownHeaderProps, type UsageRequestIdentityProps, type UsageReceiptRow, type UsageCostBreakdownProps, type UsageTokenUsageProps, type UsageDetailRow, type UsageDetailSectionProps, type UsageTimingDeliveryProps, type UsageModelRow, type UsageModelsUsedProps, type UsageDrilldownLoadingProps } from "./usage-drilldown";
export { UsageInfoTooltip, UsageDrilldownHeader, UsageRequestIdentity, UsageCostBreakdown, UsageTokenUsage, UsageDetailSection, UsageTimingDelivery, UsageModelsUsed, UsageDrilldownBody, UsageDrilldownActions, UsageRequestFailure, UsageDrilldownLoading, defaultUsageCostBreakdownLabels, defaultUsageModelsUsedLabels, defaultUsageRequestIdentityLabels, defaultUsageTokenUsageLabels, type UsageCostBreakdownLabels, type UsageModelsUsedLabels, type UsageRequestIdentityLabels, type UsageTokenUsageLabels, type UsageDetailValue, type UsageInfoTooltipProps, type UsageDrilldownHeaderProps, type UsageRequestIdentityProps, type UsageReceiptRow, type UsageCostBreakdownProps, type UsageTokenUsageProps, type UsageDetailRow, type UsageDetailSectionProps, type UsageTimingDeliveryProps, type UsageModelRow, type UsageModelsUsedProps, type UsageDrilldownLoadingProps } from "./usage-drilldown";
export { NotificationCard, NotificationCardLink, NotificationCategoryBadge, type NotificationCardProps, type NotificationCardUpdate, type NotificationCategory } from "./notification-card";
export { NotificationFeed, type NotificationFeedProps, type NotificationFeedItem, type NotificationFeedGroup, type NotificationFeedCategory } from "./notification-feed";
export { VariableTextarea, type VariableTextareaProps } from "./variable-textarea";
export { WorkflowAnimation, type WorkflowAnimationProps } from "./workflow-animation";
export { ChatGuideCard, ChatFeedback, defaultChatGuideCardLabels, type ChatGuideCardLabels, type ChatGuideCardProps, type ChatFeedbackProps, type ChatFeedbackStatus } from "./chat-answer-actions";

View File

@@ -0,0 +1,15 @@
import { forwardRef } from "react";
import type { ComponentProps } from "react";
import { cn } from "./lib/utils";
export type InlineCodeProps = ComponentProps<"code">;
/**
* A short piece of code inside running text, a table cell or a label: a model id, an environment
* variable, a flag, a path. It is the `.ci-prose code` chip for use outside prose. The size follows
* the surrounding text and never drops under 12px, and a long identifier wraps instead of
* overflowing. For a command or URL the reader copies, use `CodePreview showHeader={false}`.
*/
export const InlineCode = forwardRef<HTMLElement, InlineCodeProps>(function InlineCode({ className, ...props }, ref) {
return <code {...props} ref={ref} data-slot="inline-code" className={cn("ci-inline-code", className)} />;
});

View File

@@ -2,19 +2,28 @@ import { forwardRef } from "react";
import type { InputHTMLAttributes, ReactNode } from "react";
import { cn } from "./lib/utils";
export type InputSize = "default" | "sm";
/** `default` is 40px tall and `sm` 36px, both with 14px text; `xs` is 32px with 12px text, like `Select` and `NativeSelect` `xs`. */
export type InputSize = "default" | "sm" | "xs";
export interface InputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "size"> {
error?: boolean;
size?: InputSize;
/**
* Sets the value in the kit code font (`--ci-font-code`), for keys, JSON, code and URLs. Also turns
* `spellCheck`, `autoCapitalize` and `autoCorrect` off; pass any of them to turn it back on.
*/
mono?: boolean;
leadingIcon?: ReactNode;
trailingIcon?: ReactNode;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input({ className, error, size = "default", leadingIcon, trailingIcon, ...props }, ref) {
// Text assistance meant for prose, which only gets in the way of a key or a snippet.
const monoDefaults = { spellCheck: false, autoCapitalize: "none", autoCorrect: "off" } as const;
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input({ className, error, size = "default", mono, leadingIcon, trailingIcon, ...props }, ref) {
const invalid = Boolean(error || props["aria-invalid"] === true || props["aria-invalid"] === "true");
const input = <input ref={ref} data-slot="input" data-size={size} className={cn("ci-input", size === "sm" && "ci-input--sm", invalid && !leadingIcon && !trailingIcon && "ci-input--error", className)} {...props} aria-invalid={invalid || undefined} />;
const input = <input ref={ref} data-slot="input" data-size={size} className={cn("ci-input", size !== "default" && `ci-input--${size}`, mono && "ci-input--mono", invalid && !leadingIcon && !trailingIcon && "ci-input--error", className)} {...(mono ? monoDefaults : undefined)} {...props} aria-invalid={invalid || undefined} />;
if (leadingIcon == null && trailingIcon == null) return input;
return <span className={cn("ci-input-shell", invalid && "ci-input-shell--error", size === "sm" && "ci-input-shell--sm")}>
return <span className={cn("ci-input-shell", invalid && "ci-input-shell--error", size !== "default" && `ci-input-shell--${size}`)}>
{leadingIcon != null && <span className="ci-input-shell__icon" aria-hidden="true">{leadingIcon}</span>}
{input}
{trailingIcon != null && <span className="ci-input-shell__icon" aria-hidden="true">{trailingIcon}</span>}

View File

@@ -5,6 +5,7 @@ import type { ReactNode } from "react";
import { ArrowUpRight } from "lucide-react";
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from "./accordion";
import { Button } from "./button";
import { resolveLabels } from "./lib/labels";
export interface IntegrationResource {
id: string;
@@ -14,20 +15,32 @@ export interface IntegrationResource {
content: ReactNode;
actions?: { label: string; href: string }[];
}
/** Heading and intro of the section. */
export interface IntegrationResourcesLabels {
title: string;
description: string;
}
export const defaultIntegrationResourcesLabels: IntegrationResourcesLabels = {
title: "After setup",
description: "Check your connection or learn how to reduce repeat-request costs.",
};
export interface IntegrationResourcesProps {
resources: IntegrationResource[];
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
/** Localized interface text; missing or `undefined` keys fall back to defaultIntegrationResourcesLabels. */
labels?: Partial<IntegrationResourcesLabels>;
}
/** Follow-up help belongs after setup; no measured savings or connection state is inferred. */
export function IntegrationResources({ resources, value, defaultValue = "", onValueChange }: IntegrationResourcesProps) {
export function IntegrationResources({ resources, value, defaultValue = "", onValueChange, labels: labelOverrides }: IntegrationResourcesProps) {
const labels = resolveLabels(defaultIntegrationResourcesLabels, labelOverrides);
const headingId = useId();
const [internal, setInternal] = useState(defaultValue);
const open = value ?? internal;
return <section id="after-setup" className="ci-integration-resources" aria-labelledby={headingId}>
<header><h3 id={headingId}>After setup</h3><p>Check your connection or learn how to reduce repeat-request costs.</p></header>
<header><h3 id={headingId}>{labels.title}</h3><p>{labels.description}</p></header>
<Accordion variant="bordered" value={open} onValueChange={next => { const id = typeof next === "string" ? next : ""; setInternal(id); onValueChange?.(id); }}>
{resources.map(resource => <AccordionItem key={resource.id} value={resource.id} id={resource.id}>
<AccordionTrigger><span className="ci-integration-resources__summary">

View File

@@ -7,6 +7,7 @@ import { Button } from "./button";
import { Accordion } from "./accordion";
import { Input } from "./input";
import { Label } from "./label";
import { resolveLabels } from "./lib/labels";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "./dropdown-menu";
export interface IntegrationSetupStep {
@@ -21,7 +22,67 @@ export interface IntegrationSetupStep {
action?: { label: string; href: string };
}
/** Interface text of IntegrationSetup. Step, assistant and tool copy still come from the data props. */
export interface IntegrationSetupLabels {
title: string;
/** Intro under the title, from the integration `name`. */
description: (name: string) => string;
copyPrompt: string;
/** Menu trigger and menu heading. */
askAi: string;
/** Menu item for one assistant, from its `name`. */
askAssistant: (name: string) => string;
copyPromptForAgent: string;
copyDocs: string;
viewMarkdown: string;
viewLlms: string;
toolDocumentation: string;
/** Disabled open button shown until the instance address resolves to a link. */
openIn: (name: string) => string;
/** Help text under the instance address field. */
instanceHelp: string;
/** Hint shown with `toolHandoff`. */
toolHint: string;
/** Hint shown without `toolHandoff`. */
hint: string;
manualTitle: string;
stepCount: (count: number) => string;
/** Label before a step's `location`. */
location: string;
/** Accordion label of `details`. */
details: string;
/** Status messages after a copy action. */
promptCopied: string;
docsCopied: string;
copyError: string;
}
export const defaultIntegrationSetupLabels: IntegrationSetupLabels = {
title: "Set up with AI",
description: (name) => `Let your agent connect ${name} for you.`,
copyPrompt: "Copy setup prompt",
askAi: "Ask AI",
askAssistant: (name) => `Ask ${name}`,
copyPromptForAgent: "Copy prompt for any agent",
copyDocs: "Copy docs as Markdown",
viewMarkdown: "View Markdown guide",
viewLlms: "View llms.txt",
toolDocumentation: "Tool documentation",
openIn: (name) => `Open in ${name}`,
instanceHelp: "Use the app’s base address, including any subpath. This address stays in this page; no connection is made until you open the link.",
toolHint: "Keep your API key local. Copy the prompt to use any other agent.",
hint: "Apps open when supported. Use the web fallback or copy the prompt for any agent. Keep your API key local.",
manualTitle: "Or set up manually",
stepCount: (count) => `${count} steps`,
location: "Where",
details: "Full guide & troubleshooting",
promptCopied: "Setup prompt copied. Paste it into your agent.",
docsCopied: "Docs copied as Markdown.",
copyError: "Could not copy. Open the Markdown guide to copy it manually.",
};
export interface IntegrationSetupProps {
/** Stack the AI introduction above its actions in narrow content columns. */
layout?: "auto" | "stacked";
name: string;
description: string;
steps: IntegrationSetupStep[];
@@ -43,77 +104,98 @@ export interface IntegrationSetupProps {
markdownHref: string;
llmsHref: string;
details?: ReactNode;
/** Localized interface text; missing or `undefined` keys fall back to defaultIntegrationSetupLabels. */
labels?: Partial<IntegrationSetupLabels>;
}
/** Reusable onboarding pattern. No requests, secrets, or provider logic live here. */
export function IntegrationSetup({ name, description, steps, assistants, assistantOptions, assistantFeedback, toolHandoff, onCopyPrompt, onCopyDocs, markdownHref, llmsHref, details }: IntegrationSetupProps) {
export function IntegrationSetup({ layout = "auto", name, description, steps, assistants, assistantOptions, assistantFeedback, toolHandoff, onCopyPrompt, onCopyDocs, markdownHref, llmsHref, details, labels: labelOverrides }: IntegrationSetupProps) {
const labels = resolveLabels(defaultIntegrationSetupLabels, labelOverrides);
const titleId = useId();
const instanceId = useId();
const [assistantMenuOpen, setAssistantMenuOpen] = useState(false);
const [detailsOpen, setDetailsOpen] = useState(false);
const [status, setStatus] = useState("");
// The outcome, not its text: the status is read from the current labels on every render.
const [copyOutcome, setCopyOutcome] = useState<"prompt" | "docs" | "error" | null>(null);
const [pending, setPending] = useState(false);
async function copy(kind: "prompt" | "docs") {
setPending(true);
setStatus("");
setCopyOutcome(null);
try {
await (kind === "prompt" ? onCopyPrompt() : onCopyDocs());
setStatus(kind === "prompt" ? "Setup prompt copied. Paste it into your agent." : "Docs copied as Markdown.");
setCopyOutcome(kind);
} catch {
setStatus("Could not copy. Open the Markdown guide to copy it manually.");
setCopyOutcome("error");
} finally {
setPending(false);
}
}
return <section className="ci-integration-setup" aria-labelledby={titleId}>
const status = copyOutcome === "prompt" ? labels.promptCopied : copyOutcome === "docs" ? labels.docsCopied : copyOutcome === "error" ? labels.copyError : "";
return <section className={`ci-integration-setup${layout === "stacked" ? " ci-integration-setup--stacked" : ""}`} aria-labelledby={titleId}>
<div className="ci-integration-setup__ai">
<div>
<h3 id={titleId}><Sparkles aria-hidden="true" />Set up with AI</h3>
<p>Let your agent connect {name} for you.</p>
<h3 id={titleId}><Sparkles aria-hidden="true" />{labels.title}</h3>
<p>{labels.description(name)}</p>
</div>
<div className="ci-integration-setup__actions">
{toolHandoff?.action && !toolHandoff.instance && <Button asChild><a href={toolHandoff.action.href} target={toolHandoff.action.target ?? "_self"} rel="noopener noreferrer" onClick={toolHandoff.action.onClick}><ArrowUpRight aria-hidden="true" />{toolHandoff.action.label}</a></Button>}
<Button type="button" variant={toolHandoff?.action && !toolHandoff.instance ? "outline" : "default"} disabled={pending} onClick={() => void copy("prompt")}><Copy aria-hidden="true" />Copy setup prompt</Button>
<Button type="button" variant={toolHandoff?.action && !toolHandoff.instance ? "outline" : "default"} disabled={pending} onClick={() => void copy("prompt")}><Copy aria-hidden="true" />{labels.copyPrompt}</Button>
<DropdownMenu open={assistantMenuOpen} onOpenChange={setAssistantMenuOpen}>
<DropdownMenuTrigger asChild><Button type="button" variant="outline"><Sparkles aria-hidden="true" />Ask AI</Button></DropdownMenuTrigger>
<DropdownMenuTrigger asChild><Button type="button" variant="outline"><Sparkles aria-hidden="true" />{labels.askAi}</Button></DropdownMenuTrigger>
<DropdownMenuContent align="end" scrollable>
<DropdownMenuLabel>Ask AI</DropdownMenuLabel>
{assistants.map(assistant => <DropdownMenuItem key={assistant.name} asChild><a href={assistant.href} target={assistant.target ?? "_blank"} rel="noopener noreferrer" onClick={event => { assistant.onClick?.(event); setAssistantMenuOpen(false); }} aria-description={assistant.description}>Ask {assistant.name}<ExternalLink aria-hidden="true" /></a></DropdownMenuItem>)}
<DropdownMenuLabel>{labels.askAi}</DropdownMenuLabel>
{assistants.map(assistant => <DropdownMenuItem key={assistant.name} asChild><a href={assistant.href} target={assistant.target ?? "_blank"} rel="noopener noreferrer" onClick={event => { assistant.onClick?.(event); setAssistantMenuOpen(false); }} aria-description={assistant.description}>{labels.askAssistant(assistant.name)}<ExternalLink aria-hidden="true" /></a></DropdownMenuItem>)}
{assistantOptions && <><DropdownMenuSeparator />{assistantOptions}</>}
<DropdownMenuSeparator />
<DropdownMenuItem icon={<Copy />} disabled={pending} onSelect={() => void copy("prompt")}>Copy prompt for any agent</DropdownMenuItem>
<DropdownMenuItem icon={<Copy />} disabled={pending} onSelect={() => void copy("docs")}>Copy docs as Markdown</DropdownMenuItem>
<DropdownMenuItem asChild><a href={markdownHref} target="_blank" rel="noopener noreferrer"><FileText aria-hidden="true" />View Markdown guide</a></DropdownMenuItem>
<DropdownMenuItem asChild><a href={llmsHref} target="_blank" rel="noopener noreferrer"><FileText aria-hidden="true" />View llms.txt</a></DropdownMenuItem>
<DropdownMenuItem icon={<Copy />} disabled={pending} onSelect={() => void copy("prompt")}>{labels.copyPromptForAgent}</DropdownMenuItem>
<DropdownMenuItem icon={<Copy />} disabled={pending} onSelect={() => void copy("docs")}>{labels.copyDocs}</DropdownMenuItem>
<DropdownMenuItem asChild><a href={markdownHref} target="_blank" rel="noopener noreferrer"><FileText aria-hidden="true" />{labels.viewMarkdown}</a></DropdownMenuItem>
<DropdownMenuItem asChild><a href={llmsHref} target="_blank" rel="noopener noreferrer"><FileText aria-hidden="true" />{labels.viewLlms}</a></DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{toolHandoff && <div className="ci-integration-setup__tool">
<p>{toolHandoff.instruction} <a href={toolHandoff.sourceHref} target="_blank" rel="noopener noreferrer">Tool documentation<ExternalLink aria-hidden="true" /></a></p>
<p>{toolHandoff.instruction} <a href={toolHandoff.sourceHref} target="_blank" rel="noopener noreferrer">{labels.toolDocumentation}<ExternalLink aria-hidden="true" /></a></p>
{toolHandoff.instance && <div className="ci-integration-setup__instance">
<Label htmlFor={instanceId}>{toolHandoff.instance.label}</Label>
<div className="ci-integration-setup__instance-actions">
<Input id={instanceId} type="url" value={toolHandoff.instance.value} placeholder={toolHandoff.instance.placeholder} onChange={event => toolHandoff.instance?.onChange(event.target.value)} error={!!toolHandoff.instance.error} aria-invalid={!!toolHandoff.instance.error} aria-describedby={toolHandoff.instance.error ? `${instanceId}-error` : `${instanceId}-help`} autoComplete="off" spellCheck={false} />
{toolHandoff.action ? <Button asChild><a href={toolHandoff.action.href} target={toolHandoff.action.target ?? "_blank"} rel="noopener noreferrer" onClick={toolHandoff.action.onClick}>{toolHandoff.action.label}<ArrowUpRight aria-hidden="true" /></a></Button> : <Button type="button" disabled>Open in {name}<ArrowUpRight aria-hidden="true" /></Button>}
{toolHandoff.action ? <Button asChild><a href={toolHandoff.action.href} target={toolHandoff.action.target ?? "_blank"} rel="noopener noreferrer" onClick={toolHandoff.action.onClick}>{toolHandoff.action.label}<ArrowUpRight aria-hidden="true" /></a></Button> : <Button type="button" disabled>{labels.openIn(name)}<ArrowUpRight aria-hidden="true" /></Button>}
</div>
<p id={`${instanceId}-help`}>Use the app’s base address, including any subpath. This address stays in this page; no connection is made until you open the link.</p>
<p id={`${instanceId}-help`}>{labels.instanceHelp}</p>
{toolHandoff.instance.error && <p id={`${instanceId}-error`} role="alert">{toolHandoff.instance.error}</p>}
</div>}
</div>}
<p className="ci-integration-setup__hint">{toolHandoff ? "Keep your API key local. Copy the prompt to use any other agent." : "Apps open when supported. Use the web fallback or copy the prompt for any agent. Keep your API key local."}</p>
<p className="ci-integration-setup__hint">{toolHandoff ? labels.toolHint : labels.hint}</p>
{assistantFeedback && <div className="ci-integration-setup__handoff">{assistantFeedback}</div>}
<p className="ci-integration-setup__status" role="status">{status}</p>
</div>
<div className="ci-integration-setup__manual">
<div className="ci-integration-setup__manual-heading"><h3>Or set up manually</h3><span>{steps.length} steps</span></div>
{steps.length > 0 && <div className="ci-integration-setup__manual">
<div className="ci-integration-setup__manual-heading"><h3>{labels.manualTitle}</h3><span>{labels.stepCount(steps.length)}</span></div>
<p>{description}</p>
<ol className="ci-integration-setup__steps">
<IntegrationSetupSteps steps={steps} labels={{ location: labels.location }} />
</div>}
{details && <Accordion value={detailsOpen ? "details" : ""} onValueChange={value => setDetailsOpen(value === "details")} items={[{ value: "details", label: labels.details, content: detailsOpen ? details : null }]} />}
</section>;
}
export interface IntegrationSetupStepsProps {
steps: IntegrationSetupStep[];
/** Localized interface text of the steps; a missing or `undefined` key falls back to defaultIntegrationSetupLabels. */
labels?: Partial<Pick<IntegrationSetupLabels, "location">>;
}
/** Numbered setup steps for custom flows. Render inside a ci-integration-setup container. */
export function IntegrationSetupSteps({ steps, labels: labelOverrides }: IntegrationSetupStepsProps) {
const labels = resolveLabels({ location: defaultIntegrationSetupLabels.location }, labelOverrides);
return <ol className="ci-integration-setup__steps">
{steps.map((step, index) => <li key={step.id}>
<span className="ci-integration-setup__number" aria-hidden="true">{index + 1}</span>
<div className="ci-integration-setup__step-body">
<h4>{step.title}</h4>
{step.description && <p>{step.description}</p>}
{step.location && <div className="ci-integration-setup__location"><span>Where</span><div>{step.location}</div></div>}
{step.location && <div className="ci-integration-setup__location"><span>{labels.location}</span><div>{step.location}</div></div>}
{step.instructions?.length ? <ul className="ci-integration-setup__instructions">{step.instructions.map((instruction, index) => <li key={index}>{instruction}</li>)}</ul> : null}
{step.content}
{step.after?.length ? <ul className="ci-integration-setup__instructions">{step.after.map((instruction, index) => <li key={index}>{instruction}</li>)}</ul> : null}
@@ -121,8 +203,5 @@ export function IntegrationSetup({ name, description, steps, assistants, assista
{step.action && <div><Button variant="outline" size="sm" asChild><a href={step.action.href}>{step.action.label}<ArrowUpRight aria-hidden="true" /></a></Button></div>}
</div>
</li>)}
</ol>
</div>
{details && <Accordion value={detailsOpen ? "details" : ""} onValueChange={value => setDetailsOpen(value === "details")} items={[{ value: "details", label: "Full guide & troubleshooting", content: detailsOpen ? details : null }]} />}
</section>;
</ol>;
}

View File

@@ -3,23 +3,23 @@
.ci-invoice p, .ci-invoice h3, .ci-invoice dl, .ci-invoice dd { margin: 0; }
.ci-invoice__header { display: flex; gap: 16px; justify-content: space-between; padding-bottom: 24px; border-bottom: 3px solid #16a16d; }
.ci-invoice__brand { font-size: 19px; font-weight: var(--ci-font-weight-medium); letter-spacing: var(--ci-type-heading-tracking); line-height: var(--ci-type-heading-leading); }
.ci-invoice__eyebrow { color: #66736d; letter-spacing: var(--ci-type-caption-tracking); font-size: 10px; padding-top: 8px; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); }
.ci-invoice__number { text-align: right; display: flex; flex-direction: column; justify-content: center; }
.ci-invoice__number span { color: #66736d; font-size: 10px; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-invoice__eyebrow { color: #66736d; letter-spacing: var(--ci-type-caption-tracking); font-size: var(--ci-font-size-3xs); padding-top: 8px; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); }
.ci-invoice__number { text-align: end; display: flex; flex-direction: column; justify-content: center; }
.ci-invoice__number span { color: #66736d; font-size: var(--ci-font-size-3xs); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-invoice__parties { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; padding: 24px 0; }
.ci-invoice h3 { color: #66736d; font-size: 10px; font-weight: var(--ci-font-weight-medium); text-transform: uppercase; letter-spacing: var(--ci-type-heading-tracking); padding-bottom: 8px; line-height: var(--ci-type-heading-leading); }
.ci-invoice h3 { color: #66736d; font-size: var(--ci-font-size-3xs); font-weight: var(--ci-font-weight-medium); text-transform: uppercase; letter-spacing: var(--ci-type-heading-tracking); padding-bottom: 8px; line-height: var(--ci-type-heading-leading); }
.ci-invoice__parties strong { font-size: 13px; font-weight: var(--ci-font-weight-semibold); }
.ci-invoice__dates { display: flex; flex-wrap: wrap; gap: 16px 32px; padding-bottom: 24px; }
.ci-invoice dt { color: #66736d; }
.ci-invoice__dates dd { font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-data-leading); letter-spacing: var(--ci-type-data-tracking); }
.ci-invoice__table-wrap { overflow-x: auto; }
.ci-invoice table { border-collapse: collapse; width: 100%; min-width: 340px; table-layout: auto; }
.ci-invoice th { background: #f1f7f4; color: #66736d; font-size: 10px; font-weight: var(--ci-font-weight-medium); padding: 10px 8px; text-align: right; line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-invoice th:first-child { text-align: left; width: 45%; }
.ci-invoice td { padding: 12px 8px; border-bottom: 1px solid #dce7e1; text-align: right; vertical-align: top; font-variant-numeric: tabular-nums; }
.ci-invoice td:first-child { text-align: left; }
.ci-invoice th { background: #f1f7f4; color: #66736d; font-size: var(--ci-font-size-3xs); font-weight: var(--ci-font-weight-medium); padding: 10px 8px; text-align: end; line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-invoice th:first-child { text-align: start; width: 45%; }
.ci-invoice td { padding: 12px 8px; border-bottom: 1px solid #dce7e1; text-align: end; vertical-align: top; font-variant-numeric: tabular-nums; }
.ci-invoice td:first-child { text-align: start; }
.ci-invoice td:not(:first-child), .ci-invoice th:not(:first-child) { white-space: nowrap; }
.ci-invoice__totals { max-width: 300px; margin: 16px 0 24px auto !important; }
.ci-invoice__totals { max-width: 300px; margin-block: 16px 24px !important; margin-inline: auto 0 !important; }
.ci-invoice__totals > div { display: flex; justify-content: space-between; gap: 16px; padding: 4px 0; }
.ci-invoice__total { border-top: 1px solid #dce7e1; margin-top: 8px; padding-top: 12px !important; font-size: 18px; font-weight: var(--ci-font-weight-semibold); line-height: var(--ci-type-data-leading); letter-spacing: 0em; }
.ci-invoice__total dt { color: #17211d; }
@@ -28,7 +28,7 @@
.ci-invoice__payment dd, .ci-invoice__customer-bank dd { white-space: pre-wrap; }
.ci-invoice__payment > p { padding-top: 10px; font-weight: 600; }
.ci-invoice__notes, .ci-invoice__customer-bank { padding-top: 20px; white-space: pre-wrap; }
.ci-invoice__footer { border-top: 1px solid #dce7e1; margin-top: 24px; padding-top: 16px; display: flex; justify-content: space-between; gap: 16px; color: #66736d; font-size: 10px; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
@media (max-width: 480px) { .ci-invoice__header { flex-direction: column; } .ci-invoice__number { text-align: left; } .ci-invoice__parties { gap: 12px; } .ci-invoice th, .ci-invoice td { padding-left: 4px; padding-right: 4px; } }
.ci-invoice__footer { border-top: 1px solid #dce7e1; margin-top: 24px; padding-top: 16px; display: flex; justify-content: space-between; gap: 16px; color: #66736d; font-size: var(--ci-font-size-3xs); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
@media (max-width: 480px) { .ci-invoice__header { flex-direction: column; } .ci-invoice__number { text-align: start; } .ci-invoice__parties { gap: 12px; } .ci-invoice th, .ci-invoice td { padding-inline-start: 4px; padding-inline-end: 4px; } }
@media print { .ci-invoice { border: 0; box-shadow: none; border-radius: 0; } }
}

View File

@@ -1,10 +1,72 @@
import type { ComponentProps } from "react";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
export interface InvoiceDocumentParty {
name: string;
lines: string[];
}
/** Fixed text of the invoice. Amounts, dates, tax and bank rows come from the data props. */
export interface InvoiceDocumentLabels {
/** Accessible name of the document; a native `aria-label` still takes precedence. */
document: string;
invoice: string;
draftInvoice: string;
/** Under the invoice number of a draft. */
draftNote: string;
/** Under the invoice number of an issued invoice. */
paymentMethod: string;
from: string;
billTo: string;
/** Placeholder for a party without a name. */
companyName: string;
issued: string;
due: string;
reference: string;
/** Hidden caption of the line-item table. */
lineItems: string;
description: string;
quantity: string;
unitPrice: string;
amount: string;
/** Placeholder for a line without a description. */
lineItem: string;
subtotal: string;
amountDue: string;
paymentInstructions: string;
/** Sentence under the payment details, from `invoiceNumber`. */
paymentReference: (invoiceNumber: string) => string;
customerBankDetails: string;
notes: string;
thanks: string;
}
export const defaultInvoiceDocumentLabels: InvoiceDocumentLabels = {
document: "Invoice preview",
invoice: "INVOICE",
draftInvoice: "DRAFT INVOICE",
draftNote: "Preview · not issued",
paymentMethod: "Payment by bank transfer",
from: "From",
billTo: "Bill to",
companyName: "Company name",
issued: "Issued",
due: "Due",
reference: "PO / reference",
lineItems: "Invoice line items",
description: "Description",
quantity: "Qty",
unitPrice: "Unit price",
amount: "Amount",
lineItem: "Line item",
subtotal: "Subtotal",
amountDue: "Amount due",
paymentInstructions: "Wire payment instructions",
paymentReference: (invoiceNumber) => `Include ${invoiceNumber} as the payment reference.`,
customerBankDetails: "Customer bank details",
notes: "Notes",
thanks: "Thank you for your business.",
};
export interface InvoiceDocumentProps extends ComponentProps<"article"> {
brand?: string;
invoiceNumber: string;
@@ -21,43 +83,46 @@ export interface InvoiceDocumentProps extends ComponentProps<"article"> {
customerBankDetails?: { label: string; value: string }[];
notes?: string;
draft?: boolean;
/** Localized fixed text; missing or `undefined` keys fall back to defaultInvoiceDocumentLabels. */
labels?: Partial<InvoiceDocumentLabels>;
}
/** A paper invoice, with the same readable document surface in either app theme. */
export function InvoiceDocument({ brand = "Cheaper Inference", invoiceNumber, issueDate, dueDate,
reference, seller, customer, items, subtotal, tax, total, paymentDetails, customerBankDetails,
notes, draft = false, className, ...props }: InvoiceDocumentProps) {
return <article className={cn("ci-invoice", className)} aria-label="Invoice preview" {...props}>
notes, draft = false, labels: labelOverrides, className, ...props }: InvoiceDocumentProps) {
const labels = resolveLabels(defaultInvoiceDocumentLabels, labelOverrides);
return <article className={cn("ci-invoice", className)} aria-label={labels.document} {...props}>
<header className="ci-invoice__header">
<div><div className="ci-invoice__brand">{brand}</div><p className="ci-invoice__eyebrow">{draft ? "DRAFT INVOICE" : "INVOICE"}</p></div>
<div className="ci-invoice__number"><strong>{invoiceNumber}</strong><span>{draft ? "Preview · not issued" : "Payment by bank transfer"}</span></div>
<div><div className="ci-invoice__brand">{brand}</div><p className="ci-invoice__eyebrow">{draft ? labels.draftInvoice : labels.invoice}</p></div>
<div className="ci-invoice__number"><strong>{invoiceNumber}</strong><span>{draft ? labels.draftNote : labels.paymentMethod}</span></div>
</header>
<div className="ci-invoice__parties">
{([["From", seller], ["Bill to", customer]] as const).map(([label, party]) => <section key={label}>
<h3>{label}</h3><strong>{party.name || "Company name"}</strong>
{([["from", seller], ["billTo", customer]] as const).map(([role, party]) => <section key={role}>
<h3>{labels[role]}</h3><strong>{party.name || labels.companyName}</strong>
{party.lines.filter(Boolean).map((line, i) => <p key={i}>{line}</p>)}
</section>)}
</div>
<dl className="ci-invoice__dates">
<div><dt>Issued</dt><dd>{issueDate}</dd></div><div><dt>Due</dt><dd>{dueDate}</dd></div>
{reference && <div><dt>PO / reference</dt><dd>{reference}</dd></div>}
<div><dt>{labels.issued}</dt><dd>{issueDate}</dd></div><div><dt>{labels.due}</dt><dd>{dueDate}</dd></div>
{reference && <div><dt>{labels.reference}</dt><dd>{reference}</dd></div>}
</dl>
<div className="ci-invoice__table-wrap"><table><caption className="ci-sr-only">Invoice line items</caption>
<thead><tr><th scope="col">Description</th><th scope="col">Qty</th><th scope="col">Unit price</th><th scope="col">Amount</th></tr></thead>
<tbody>{items.map((item, i) => <tr key={i}><td>{item.description || "Line item"}</td><td>{item.quantity}</td><td>{item.unitPrice}</td><td>{item.amount}</td></tr>)}</tbody>
<div className="ci-invoice__table-wrap"><table><caption className="ci-sr-only">{labels.lineItems}</caption>
<thead><tr><th scope="col">{labels.description}</th><th scope="col">{labels.quantity}</th><th scope="col">{labels.unitPrice}</th><th scope="col">{labels.amount}</th></tr></thead>
<tbody>{items.map((item, i) => <tr key={i}><td>{item.description || labels.lineItem}</td><td>{item.quantity}</td><td>{item.unitPrice}</td><td>{item.amount}</td></tr>)}</tbody>
</table></div>
<dl className="ci-invoice__totals"><div><dt>Subtotal</dt><dd>{subtotal}</dd></div>
<dl className="ci-invoice__totals"><div><dt>{labels.subtotal}</dt><dd>{subtotal}</dd></div>
{tax && <div><dt>{tax.label}</dt><dd>{tax.amount}</dd></div>}
<div className="ci-invoice__total"><dt>Amount due</dt><dd>{total}</dd></div>
<div className="ci-invoice__total"><dt>{labels.amountDue}</dt><dd>{total}</dd></div>
</dl>
<section className="ci-invoice__payment"><h3>Wire payment instructions</h3>
<section className="ci-invoice__payment"><h3>{labels.paymentInstructions}</h3>
<dl>{paymentDetails.filter(row => row.value).map(row => <div key={row.label}><dt>{row.label}</dt><dd>{row.value}</dd></div>)}</dl>
<p>Include {invoiceNumber} as the payment reference.</p>
<p>{labels.paymentReference(invoiceNumber)}</p>
</section>
{!!customerBankDetails?.some(row => row.value) && <section className="ci-invoice__customer-bank"><h3>Customer bank details</h3>
{!!customerBankDetails?.some(row => row.value) && <section className="ci-invoice__customer-bank"><h3>{labels.customerBankDetails}</h3>
<dl>{customerBankDetails.filter(row => row.value).map(row => <div key={row.label}><dt>{row.label}</dt><dd>{row.value}</dd></div>)}</dl>
</section>}
{notes && <section className="ci-invoice__notes"><h3>Notes</h3><p>{notes}</p></section>}
<footer className="ci-invoice__footer">Thank you for your business.<span>{brand}</span></footer>
{notes && <section className="ci-invoice__notes"><h3>{labels.notes}</h3><p>{notes}</p></section>}
<footer className="ci-invoice__footer">{labels.thanks}<span>{brand}</span></footer>
</article>;
}

View File

@@ -0,0 +1,180 @@
"use client";
import { cloneElement, forwardRef, isValidElement, useId } from "react";
import type { ComponentPropsWithoutRef, MouseEvent, ReactElement, ReactNode } from "react";
import { cn } from "./lib/utils";
export type ItemListVariant = "separated" | "divided";
export type ItemListDensity = "default" | "compact";
export interface ItemListProps extends ComponentPropsWithoutRef<"ul"> {
/**
* `separated` (default) gives every row its own border and the control radius, with a gap
* between rows. `divided` draws one divider between rows and no frame, for a list that sits
* inside a `Card` or a panel.
*/
variant?: ItemListVariant;
/** `compact` is a 36px row with tighter padding; the default is 48px. */
density?: ItemListDensity;
}
/** A short list of rows. Name it with `aria-label` or `aria-labelledby` when a heading does not. */
export const ItemList = forwardRef<HTMLUListElement, ItemListProps>(function ItemList(
{ className, variant = "separated", density = "default", ...props },
ref,
) {
return (
<ul
ref={ref}
// Safari drops the list semantics of a list without markers; the explicit role keeps them.
role="list"
data-slot="item-list"
data-variant={variant}
data-density={density}
className={cn("ci-item-list", className)}
{...props}
/>
);
});
export interface ItemProps extends Omit<ComponentPropsWithoutRef<"li">, "title"> {
/** Main line. It is the content, and so the name, of the row's link or button when there is one. */
title: ReactNode;
/** Secondary line; describes the row's link or button through `aria-describedby`. */
description?: ReactNode;
/** Mark at the start of the row: an icon, an `Avatar`, a status dot. */
leading?: ReactNode;
/** Passive content at the end of the row: a `Badge`, a count, a timestamp. */
meta?: ReactNode;
/**
* Controls at the end of the row. They sit above the row's hit area and are tab stops of their
* own, after the row's control, so they never activate the row. Put every control here.
*/
actions?: ReactNode;
/**
* One line for the title and one for the description, cut with an ellipsis; they wrap by
* default. The copy can then go down to 6rem beside the trailing group instead of 10rem.
*/
truncate?: boolean;
/**
* Marks the row as the current one: `data-state="selected"` on the row and `aria-current="true"`
* on its link or button (on the row itself when it has neither).
*/
selected?: boolean;
/**
* Dims the row and disables its control: a button gets `disabled`; a link gets
* `aria-disabled="true"`, stays in the tab order and ignores a click, Enter and the middle
* button (its `href` is kept, so the browser's context menu can still open it). `actions` are
* left alone.
*/
disabled?: boolean;
/**
* Makes the whole row activate: the title is rendered in a `<button>` whose hit area covers the
* row. Runs on a click and on Enter or Space, as for any button. Ignored with `asChild`.
*/
onActivate?: (event: MouseEvent<HTMLButtonElement>) => void;
/**
* Makes the whole row a link: the single child element (an `<a>` or a router `Link`) is rendered
* around the title, with a hit area that covers the row. The child's own content is replaced.
*/
asChild?: boolean;
}
function cancel(event: MouseEvent<HTMLElement>) {
event.preventDefault();
}
/** Slot rule: null, undefined, booleans and "" are absent, so `meta={show && <Badge />}` renders nothing. */
function present(node: ReactNode) {
return node != null && typeof node !== "boolean" && node !== "";
}
/**
* A row of an `ItemList`. Static by default; `onActivate` or `asChild` make the whole row one
* control without nesting it around the `actions`.
*/
export const Item = forwardRef<HTMLLIElement, ItemProps>(function Item(
{
className,
title,
description,
leading,
meta,
actions,
truncate = false,
selected,
disabled = false,
onActivate,
asChild = false,
children,
...props
},
ref,
) {
const baseId = useId();
const descriptionId = present(description) ? `${baseId}-description` : undefined;
const linkChild = asChild && isValidElement(children) ? (children as ReactElement<Record<string, unknown>>) : null;
const interactive = linkChild != null || onActivate != null;
const hasBody = !linkChild && present(children);
const hasMeta = present(meta);
const hasActions = present(actions);
let heading: ReactNode = title;
if (linkChild) {
const childProps = linkChild.props;
heading = cloneElement(linkChild, {
className: cn("ci-item__primary", childProps.className as string | undefined),
"aria-describedby":
[descriptionId, childProps["aria-describedby"] as string | undefined].filter(Boolean).join(" ") || undefined,
...(selected ? { "aria-current": childProps["aria-current"] ?? "true" } : {}),
// A link has no disabled state: it stays focusable, says so, and its activation is cancelled.
// The middle button opens a link through auxclick, so both events are cancelled.
...(disabled ? { "aria-disabled": true, onClick: cancel, onAuxClick: cancel } : {}),
children: title,
});
} else if (onActivate) {
heading = (
<button
type="button"
className="ci-item__primary"
disabled={disabled}
aria-describedby={descriptionId}
aria-current={selected ? "true" : undefined}
onClick={onActivate}
>
{title}
</button>
);
}
return (
<li
ref={ref}
aria-current={selected && !interactive ? "true" : undefined}
{...props}
data-slot="item"
data-interactive={interactive ? "" : undefined}
data-state={selected ? "selected" : undefined}
data-disabled={disabled ? "" : undefined}
data-truncate={truncate ? "" : undefined}
className={cn("ci-item", className)}
>
{present(leading) && <span className="ci-item__leading">{leading}</span>}
<div className="ci-item__content">
<div className="ci-item__title">{heading}</div>
{descriptionId && (
<div id={descriptionId} className="ci-item__description">
{description}
</div>
)}
{hasBody && <div className="ci-item__body">{children}</div>}
</div>
{(hasMeta || hasActions) && (
<div className="ci-item__trailing">
{hasMeta && <div className="ci-item__meta">{meta}</div>}
{hasActions && <div className="ci-item__actions">{actions}</div>}
</div>
)}
</li>
);
});

View File

@@ -6,7 +6,7 @@
.ci-keak-logo > .ci-keak-wordmark { display: block; width: 2.31em; height: .73em; flex-shrink: 0; }
.ci-keak-product-icon { display: block; width: 2em; height: 2em; flex-shrink: 0; }
.ci-keak-lockup { display: inline-flex; align-items: center; flex-wrap: wrap; gap: .5rem; color: var(--ci-color-heading); }
.ci-keak-lockup > .ci-keak-product-icon { width: 2rem; height: 2rem; margin-right: .2rem; }
.ci-keak-lockup > .ci-keak-product-icon { width: 2rem; height: 2rem; margin-inline-end: .2rem; }
.ci-keak-lockup > .ci-keak-logo { font-size: 1.3rem; }
.ci-keak-product { font-family: var(--ci-font-ui); font-weight: 600; font-size: 1rem; }
.ci-keak-switcher { position: relative; font-family: var(--ci-font-ui); font-size: var(--ci-font-size-sm); }
@@ -16,22 +16,22 @@
.ci-keak-switcher details[open] .ci-keak-switcher-caret { transform: rotate(45deg); }
.ci-keak-switcher-product { display: flex; gap: .65rem; align-items: center; }
.ci-keak-switcher .ci-keak-product-icon { width: 1.5rem; height: 1.5rem; }
.ci-keak-switcher ul { position: absolute; top: 100%; right: 0; width: min(19rem, calc(100vw - 2rem)); padding: .5rem; list-style: none; background: var(--ci-color-surface); border: 1px solid var(--ci-color-border); box-shadow: var(--ci-shadow-md); z-index: var(--ci-z-dropdown); }
.ci-keak-switcher ul { position: absolute; top: 100%; inset-inline-end: 0; width: min(19rem, calc(100vw - 2rem)); padding: .5rem; list-style: none; background: var(--ci-color-surface); border: 1px solid var(--ci-color-border); box-shadow: var(--ci-shadow-md); z-index: var(--ci-z-dropdown); }
.ci-keak-switcher a { display: flex; flex-direction: column; gap: .25rem; padding: .85rem; color: var(--ci-color-heading); text-decoration: none; }
.ci-keak-switcher a:hover, .ci-keak-switcher a[aria-current] { background: var(--ci-color-surface-muted); }
.ci-keak-switcher small { color: var(--ci-color-text-muted); }
.ci-editorial-section { padding-block: var(--ci-space-20); border-top: 1px solid var(--ci-color-border); }
.ci-editorial-label { display: flex; gap: var(--ci-space-8); font: 400 .6875rem/1.5 var(--ci-font-mono); text-transform: uppercase; margin-bottom: var(--ci-space-12); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-editorial-label { display: flex; gap: var(--ci-space-8); font: 400 var(--ci-font-size-2xs)/1.5 var(--ci-font-mono); text-transform: uppercase; margin-bottom: var(--ci-space-12); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-editorial-label > :first-child { color: var(--ci-color-text-muted); }
.ci-editorial-card { position: relative; display: flex; flex-direction: column; align-items: start; border-top: 1px solid var(--ci-color-border); padding: var(--ci-space-6) 0; }
.ci-editorial-card-eyebrow { font: 400 .6875rem/1.5 var(--ci-font-mono); color: var(--ci-color-text-muted); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-editorial-card-eyebrow { font: 400 var(--ci-font-size-2xs)/1.5 var(--ci-font-mono); color: var(--ci-color-text-muted); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-editorial-card h3 { font: 400 2rem/1.1 var(--ci-font-display); margin: var(--ci-space-6) 0 var(--ci-space-4); font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-heading-leading); letter-spacing: var(--ci-type-heading-tracking); }
.ci-editorial-card h3 a { color: var(--ci-color-heading); text-decoration: none; }
.ci-editorial-card h3 a:hover { text-decoration: underline; text-underline-offset: .15em; }
.ci-editorial-card p { font-size: var(--ci-font-size-sm); color: var(--ci-color-text-muted); margin: 0 0 var(--ci-space-6); }
.ci-editorial-card-link { display: inline-flex; gap: var(--ci-space-8); margin-top: auto; font: 400 .75rem/1.5 var(--ci-font-ui); color: var(--ci-color-heading); text-decoration: none; font-weight: var(--ci-font-weight-medium); line-height: var(--ci-type-control-leading); letter-spacing: var(--ci-type-control-tracking); }
.ci-editorial-card { position: relative; }
.ci-editorial-card::before { content: ""; position: absolute; left: 0; top: -1px; height: 2px; width: 100%; background: var(--ci-color-accent); transform: scaleX(0); transform-origin: left; transition: transform .3s; }
.ci-editorial-card::before { content: ""; position: absolute; inset-inline-start: 0; top: -1px; height: 2px; width: 100%; background: var(--ci-color-accent); transform: scaleX(0); transform-origin: left; transition: transform .3s; }
.ci-editorial-card:hover::before, .ci-editorial-card:focus-within::before { transform: scaleX(1); }
.ci-editorial-card-link > span { transition: transform .2s; }
.ci-editorial-card:hover .ci-editorial-card-link > span, .ci-editorial-card:focus-within .ci-editorial-card-link > span { transform: translate(2px, -2px); }

View File

@@ -68,12 +68,14 @@ export interface ProductSwitcherItem { product: KeakProduct; href: string; descr
export interface ProductSwitcherProps extends HTMLAttributes<HTMLElement> {
items: ProductSwitcherItem[];
activeProduct?: KeakProduct;
/** Trigger text while no product is active. Defaults to "Our products". The nav name is the native `aria-label`. */
triggerLabel?: string;
}
/** Native disclosure and links remain usable without client-side JavaScript; once hydrated, Escape and outside presses close the list. */
export function ProductSwitcher({ items, activeProduct, className, ...props }: ProductSwitcherProps) {
export function ProductSwitcher({ items, activeProduct, triggerLabel = "Our products", className, ...props }: ProductSwitcherProps) {
return <nav aria-label="Keak products" className={cn("ci-keak-switcher", className)} {...props}>
<details><summary>{activeProduct && <ProductIcon product={activeProduct} />}{activeProduct ? `Keak ${keakProductNames[activeProduct]}` : "Our products"}
<details><summary>{activeProduct && <ProductIcon product={activeProduct} />}{activeProduct ? `Keak ${keakProductNames[activeProduct]}` : triggerLabel}
<span className="ci-keak-switcher-caret" aria-hidden="true">+</span></summary>
<ul>{items.map(item => <li key={item.product}><a href={item.href}
aria-current={activeProduct === item.product ? "true" : undefined}>

View File

@@ -0,0 +1,23 @@
import { version } from "react";
/**
* Whether this React writes `inert` as a boolean attribute. React DOM 19 does; React DOM 18 does not know the
* attribute, warns "Received `true` for a non-boolean attribute" and leaves a boolean out of the DOM, but writes
* a string. React DOM 19 in turn leaves an empty string out, so the value has to follow the version.
*/
export function supportsBooleanInert(reactVersion: string = version): boolean {
return Number.parseInt(reactVersion, 10) >= 19;
}
const BOOLEAN_INERT = supportsBooleanInert();
/**
* Props that make an element inert when `active`, in the form the running React writes to the DOM (`true` on
* React 19, `""` on React 18). Spread them on the element: `<div {...inertProps(loading)} />`. When `active` is
* false they are empty, so the attribute is removed.
*/
export function inertProps(active: boolean | undefined, booleanInert: boolean = BOOLEAN_INERT): { inert?: boolean } {
if (!active) return {};
// React 18's types do not list `inert`; React 19's type it as boolean. The empty string is what React 18 writes.
return { inert: (booleanInert ? true : "") as unknown as boolean };
}

View File

@@ -0,0 +1,56 @@
/**
* Tells a focus the user moved with the keyboard from a focus that code moved, such as a dialog
* focusing its first control when it opens or handing focus back to its opener when it closes.
*
* `:focus-visible` does not tell them apart: Chromium matches it on a focus moved by code before
* any interaction, after Enter or Space on a dialog trigger, and when Escape hands focus back. So
* this looks at the key instead: a focus counts as keyboard navigation while a key that moves focus
* is down, from its `keydown` until just after its `keyup`, a pointer press or the window losing focus.
*/
/** Keys that move focus: Tab by the browser, the others by a roving-focus widget (toolbar, table rows). */
const FOCUS_MOVING_KEYS = new Set(["Tab", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown"]);
interface Navigation {
active: boolean;
}
/** One record per document, so a trigger in an iframe or another window reads its own keys. */
const navigationByDocument = new WeakMap<Document, Navigation>();
/** Starts listening for focus-moving keys in `doc`, once. Safe to call on every render or focus. */
export function watchKeyboardNavigation(doc: Document): Navigation {
const known = navigationByDocument.get(doc);
if (known) return known;
const navigation: Navigation = { active: false };
navigationByDocument.set(doc, navigation);
// Bumped by every event below, so that a stop scheduled by a keyup never ends a later key.
let latest = 0;
const stop = () => {
latest += 1;
navigation.active = false;
};
// Capture phase: a widget that stops the key's propagation must not hide it from this.
doc.addEventListener("keydown", (event) => {
latest += 1;
navigation.active = FOCUS_MOVING_KEYS.has(event.key);
}, true);
doc.addEventListener("keyup", () => {
// A roving-focus group may move focus in a timeout set on keydown (Radix RovingFocusGroup
// does), which a quick key press can release before. Stop after the timeouts already queued.
const at = ++latest;
setTimeout(() => {
if (latest === at) navigation.active = false;
});
}, true);
doc.addEventListener("pointerdown", stop, true);
doc.addEventListener("mousedown", stop, true);
// A Tab that leaves the page never sends its keyup here; the focus the browser restores on return is not navigation.
doc.defaultView?.addEventListener("blur", stop);
return navigation;
}
/** Whether the focus being handled now follows a key that moves focus. */
export function isKeyboardNavigationFocus(doc: Document): boolean {
return watchKeyboardNavigation(doc).active;
}

View File

@@ -0,0 +1,27 @@
const ASCII_ONLY = /^[\x00-\x7f]*$/;
// Accents only. The supplement block is taken up to U+1DCF: after it come combining letters
// (U+1DE0 is a small "n" written above), which are part of the word, not an accent on it.
const ACCENTS = /[\u0300-\u036f\u1ab0-\u1aff\u1dc0-\u1dcf\ufe20-\ufe2f]/g;
/**
* The form in which the search fields compare text: `Command`, `DataTable`, `MultiSelectFilter` and
* `SearchableSelect` fold the query and the text they search with it, so the four cannot drift.
*
* Case and accents are dropped, so "sao" finds "São Paulo". The lower-casing is locale-independent on
* purpose: toLocaleLowerCase() follows the browser language, and in Turkish and Azerbaijani it turns
* "I" into a dotless "ı", so the label "OpenAI" never matched the query "openai". Dotted and dotless
* i both fold to a plain "i" here, and the two lower-case Greek sigmas to one.
*/
export function foldSearchText(text: string) {
const lower = text.toLowerCase();
// ASCII has no accent and no dotless i to fold. DataTable folds every searchable cell of every row
// on each keystroke, and most of them are ASCII.
if (ASCII_ONLY.test(lower)) return lower;
// Composed again after the accents are gone: decomposed, the Hangul syllable "가" would be a prefix
// of "각". The final sigma that toLowerCase() writes at the end of a word folds to the plain one, so
// "ΟΣ" still finds "ΟΣΑ".
// Only the combining diacritical marks, which carry the accents of Latin, Greek and Cyrillic: the
// main block, the extended and half-mark blocks, and the accents of the supplement block. Every mark (\p{M}) would also take
// the vowel signs of Devanagari, Arabic or Thai, which tell one word from another.
return lower.normalize("NFD").replace(ACCENTS, "").normalize("NFC").replace(/ı/g, "i").replace(/ς/g, "σ");
}

View File

@@ -0,0 +1,67 @@
"use client";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { createContext, useContext } from "react";
import type { ReactNode } from "react";
/** The delay a kit tooltip waits before opening, in ms, unless it or a TooltipProvider sets another. */
const DEFAULT_DELAY = 300;
/** True below a TooltipProvider: tooltips there join it instead of mounting a provider each. */
const SharedTooltipProviderContext = createContext(false);
export interface TooltipProviderProps {
/** Delay before a tooltip opens, in ms. A `delayDuration` set on a tooltip itself wins. Defaults to 300. */
delayDuration?: number;
/** After a tooltip closes, the next one opens without delay inside this window, in ms. Defaults to 300. */
skipDelayDuration?: number;
/** Close a tooltip as soon as the pointer leaves its trigger, even on the way to its content. */
disableHoverableContent?: boolean;
children?: ReactNode;
}
/**
* Optional. One provider for every kit tooltip below it (`Tooltip`, `InfoTooltip`, `Button tooltip`),
* for screens that mount many of them, such as a table with icon actions in every row. It renders
* no element. Without it each tooltip keeps its own provider.
*/
export function TooltipProvider({
delayDuration = DEFAULT_DELAY,
skipDelayDuration,
disableHoverableContent,
children,
}: TooltipProviderProps) {
return (
<TooltipPrimitive.Provider
delayDuration={delayDuration}
skipDelayDuration={skipDelayDuration}
disableHoverableContent={disableHoverableContent}
>
<SharedTooltipProviderContext.Provider value={true}>{children}</SharedTooltipProviderContext.Provider>
</TooltipPrimitive.Provider>
);
}
export interface TooltipRootProps {
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
delayDuration?: number;
disableHoverableContent?: boolean;
children?: ReactNode;
}
/** A tooltip's state without the `.ci-tooltip` box, shared by `Tooltip` and `Button tooltip`. */
export function TooltipRoot({ delayDuration, children, ...props }: TooltipRootProps) {
const shared = useContext(SharedTooltipProviderContext);
if (shared) {
// Left undefined, the delay and hoverable content come from the TooltipProvider.
return <TooltipPrimitive.Root delayDuration={delayDuration} {...props}>{children}</TooltipPrimitive.Root>;
}
const delay = delayDuration ?? DEFAULT_DELAY;
return (
<TooltipPrimitive.Provider delayDuration={delay}>
<TooltipPrimitive.Root delayDuration={delay} {...props}>{children}</TooltipPrimitive.Root>
</TooltipPrimitive.Provider>
);
}

View File

@@ -14,7 +14,7 @@
.ci-loading-screen__art { position: relative; display: grid; width: clamp(6rem, 25svh, 12rem); aspect-ratio: 1; margin: 0 auto 1.75rem; place-items: center; color: var(--ci-color-accent); }
.ci-loading-screen__halo { position: absolute; inset: -3rem; border-radius: 50%; background: radial-gradient(circle, color-mix(in srgb, var(--ci-color-accent) 13%, transparent), transparent 68%); animation: ci-loading-breathe 4s ease-in-out infinite; }
.ci-loading-screen__orbit { position: absolute; inset: 0; border: 1px solid color-mix(in srgb, var(--ci-color-accent) 16%, transparent); border-radius: 50%; animation: ci-spin 9s linear infinite; }
.ci-loading-screen__orbit > span { position: absolute; top: -3px; left: calc(50% - 3px); width: 6px; height: 6px; border-radius: 50%; background: currentColor; box-shadow: 0 0 14px color-mix(in srgb, var(--ci-color-accent) 45%, transparent); }
.ci-loading-screen__orbit > span { position: absolute; top: -3px; inset-inline-start: calc(50% - 3px); width: 6px; height: 6px; border-radius: 50%; background: currentColor; box-shadow: 0 0 14px color-mix(in srgb, var(--ci-color-accent) 45%, transparent); }
.ci-loading-screen__orbit--inner { inset: 1rem; border-style: dashed; border-color: color-mix(in srgb, var(--ci-color-accent) 10%, transparent); animation-duration: 14s; animation-direction: reverse; }
.ci-loading-screen__orbit--inner > span { width: 4px; height: 4px; top: -2px; opacity: .5; }
.ci-loading-screen__mark { position: relative; width: 36%; animation: ci-loading-breathe 4s ease-in-out infinite; }

View File

@@ -2,6 +2,7 @@
import type { ComponentProps, ReactNode } from "react";
import { ArrowDown, ArrowRight, ArrowUp, Minus } from "lucide-react";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
import { Card } from "./card";
import { Stat, type StatProps } from "./stat";
@@ -9,18 +10,29 @@ import { Skeleton } from "./skeleton";
import { EmptyState } from "./empty-state";
import { Button } from "./button";
/** Screen-reader text for each trend direction, read before the value. */
export interface MetricTrendLabels {
up: string;
down: string;
flat: string;
}
export const defaultMetricTrendLabels: MetricTrendLabels = { up: "Increase", down: "Decrease", flat: "No change" };
export interface MetricTrendProps extends ComponentProps<"div"> {
/** Already formatted change. No percentage or comparison-period math happens here. */
value: ReactNode;
direction?: "up" | "down" | "flat";
tone?: "neutral" | "positive" | "negative";
comparison?: ReactNode;
/** Localized direction text; missing or `undefined` keys fall back to defaultMetricTrendLabels. */
labels?: Partial<MetricTrendLabels>;
}
export function MetricTrend({ value, direction, tone = "neutral", comparison, className, ...props }: MetricTrendProps) {
export function MetricTrend({ value, direction, tone = "neutral", comparison, labels: labelOverrides, className, ...props }: MetricTrendProps) {
const labels = resolveLabels(defaultMetricTrendLabels, labelOverrides);
const Icon = direction === "up" ? ArrowUp : direction === "down" ? ArrowDown : direction === "flat" ? Minus : null;
return <div {...props} className={cn("ci-metric-trend", className)} data-tone={tone}>
<div className="ci-metric-trend__value">{Icon && <Icon size={17} aria-hidden="true" />}{direction && <span className="ci-sr-only">{direction === "up" ? "Increase " : direction === "down" ? "Decrease " : "No change "}</span>}{value}</div>
<div className="ci-metric-trend__value">{Icon && <Icon size={17} aria-hidden="true" />}{direction && <span className="ci-sr-only">{labels[direction]} </span>}{value}</div>
{comparison != null && <div className="ci-metric-trend__comparison">{comparison}</div>}
</div>;
}

View File

@@ -63,14 +63,18 @@ export interface MetricDonutProps extends Omit<MetricChartFrameProps, "children"
label: string;
data: MetricDonutDatum[];
totalLabel?: string;
/** Formats the total, the legend values and the values in the accessible name, such as currency or a compact count. Defaults to the raw number. */
valueFormatter?: (value: number) => string;
/** Read in the accessible name for a value that is not measured. Defaults to "unavailable". */
unavailableLabel?: string;
}
export function MetricDonut({ data, label, totalLabel = "total", className, ...props }: MetricDonutProps) {
export function MetricDonut({ data, label, totalLabel = "total", unavailableLabel = "unavailable", valueFormatter = String, className, ...props }: MetricDonutProps) {
const replay = useContext(MetricMotionContext);
const sum = data.reduce((value, item) => value + item.value, 0);
const total = data.every((item) => measured(item.value)) && Number.isFinite(sum) ? sum : null;
let offset = 0;
return <MetricChartFrame {...props} className={cn("ci-metric-donut", className)}
aria-label={`${label}: ${data.map((item) => `${item.label} ${measured(item.value) ? item.value : "unavailable"}`).join(", ")}`}>
aria-label={`${label}: ${data.map((item) => `${item.label} ${measured(item.value) ? valueFormatter(item.value) : unavailableLabel}`).join(", ")}`}>
<div className="ci-metric-donut__summary">
<div className="ci-metric-donut__chart">
<svg key={replay} viewBox="0 0 160 160" aria-hidden>
@@ -95,10 +99,10 @@ export function MetricDonut({ data, label, totalLabel = "total", className, ...p
})}
</svg>
</div>
<div className="ci-metric-donut__total"><strong>{total ?? "—"}</strong><span>{totalLabel}</span></div>
<div className="ci-metric-donut__total"><strong>{total === null ? "—" : valueFormatter(total)}</strong><span>{totalLabel}</span></div>
</div>
<figcaption className="ci-metric-donut__legend">
{data.map((item) => <div key={item.key}><i aria-hidden style={{ background: item.color }} /><span>{item.label}</span><strong>{measured(item.value) ? item.value : "—"}</strong></div>)}
{data.map((item) => <div key={item.key}><i aria-hidden style={{ background: item.color }} /><span>{item.label}</span><strong>{measured(item.value) ? valueFormatter(item.value) : "—"}</strong></div>)}
</figcaption>
</MetricChartFrame>;
}

View File

@@ -1,23 +1,36 @@
import type { ComponentProps, ReactNode } from "react";
import { cn } from "./lib/utils";
export type ModelIdentitySize = "sm" | "md" | "lg";
export interface ModelIdentityProps extends ComponentProps<"span"> {
name: ReactNode;
/** Provider name used to generate the temporary logo mark. */
provider?: string;
/** Replace the temporary mark with the final provider or model logo. */
logo?: ReactNode;
/** Mark size: `sm` 20px for dense rows, `md` 24px (default), `lg` 32px for card headers. */
size?: ModelIdentitySize;
/** Second line under the name, such as a description or a status. Truncated like the name. */
description?: ReactNode;
}
export function ModelIdentity({ className, name, provider, logo, ...props }: ModelIdentityProps) {
export function ModelIdentity({ className, name, provider, logo, size = "md", description, ...props }: ModelIdentityProps) {
const placeholder = provider?.trim().charAt(0).toUpperCase() || "M";
const title = <strong className="ci-model-identity__name">{name}</strong>;
const described = description !== undefined && description !== null && description !== false && description !== "";
return (
<span className={cn("ci-model-identity", className)} {...props}>
<span className={cn("ci-model-identity", className)} data-size={size === "md" ? undefined : size} {...props}>
<span className="ci-model-identity__mark" aria-hidden="true">
{logo ?? placeholder}
</span>
<strong className="ci-model-identity__name">{name}</strong>
{described ? (
<span className="ci-model-identity__text">
{title}
<span className="ci-model-identity__description">{description}</span>
</span>
) : title}
</span>
);
}

View File

@@ -6,6 +6,7 @@ import type { ReactNode } from "react";
import { Button, type ButtonSize } from "./button";
import { Checkbox } from "./checkbox";
import { Input } from "./input";
import { foldSearchText } from "./lib/search-fold";
import { cn } from "./lib/utils";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";
@@ -115,12 +116,12 @@ export function filterMultiSelectFilterOptions(
options: readonly MultiSelectFilterOption[],
query: string,
): MultiSelectFilterOption[] {
const wanted = query.trim().toLocaleLowerCase();
const wanted = foldSearchText(query.trim());
if (!wanted) return [...options];
return options.filter((option) =>
[option.label, option.value, ...(option.keywords ?? [])]
.filter((candidate): candidate is string => Boolean(candidate))
.some((candidate) => candidate.toLocaleLowerCase().includes(wanted)),
.some((candidate) => foldSearchText(candidate).includes(wanted)),
);
}

View File

@@ -0,0 +1,283 @@
"use client";
import { forwardRef, useId, useMemo, useRef, useState } from "react";
import type { ChangeEvent, CompositionEvent, FocusEvent, KeyboardEvent, ReactNode } from "react";
import { Input, type InputProps } from "./input";
import { cn } from "./lib/utils";
export interface NumberInputProps extends Omit<InputProps, "type" | "value" | "defaultValue" | "onChange" | "min" | "max" | "step"> {
/** Controlled value. `null` is an empty field; `NaN` and `Infinity` are shown as empty. */
value?: number | null;
/** Starting value when the field is uncontrolled. */
defaultValue?: number | null;
/** Called with the number as the person types, steps or leaves the field; `null` when there is no number yet. Never `NaN`. */
onValueChange?: (value: number | null) => void;
/** Called once with the final value when an edit ends, on blur or Enter. Use it to save. */
onValueCommit?: (value: number | null) => void;
/** Lower bound, applied by the arrow keys and, with `clamp`, on blur. `0` or more also blocks the minus sign. */
min?: number;
/** Upper bound, applied by the arrow keys and, with `clamp`, on blur. */
max?: number;
/** Arrow key increment, counted from `min` (or `0`). Its decimal places set the default `precision`. Default `1`. */
step?: number;
/** Most decimal places the person can type. Defaults to the decimal places of `step` and `min`; `0` is whole numbers. */
precision?: number;
/** Bring an edited value into `min`/`max` on blur and Enter. Default `true`; an empty field stays empty. */
clamp?: boolean;
/** Unit shown at the inline end (`ms`, `%`) and read as the field's description. */
unit?: ReactNode;
/** Sets the decimal separator the field shows (`pt-BR` shows `0,7`). Typing accepts `.` and `,` in every locale. */
locale?: Intl.LocalesArgument;
}
type Separator = "." | ",";
type Draft = { text: string; value: number | null };
const finite = (value: number | null | undefined): number | null => {
if (value == null || !Number.isFinite(value)) return null;
return value === 0 ? 0 : value;
};
function localeSeparator(locale: Intl.LocalesArgument | undefined): Separator | undefined {
if (locale === undefined) return undefined;
try {
const decimal = new Intl.NumberFormat(locale).formatToParts(1.5).find((part) => part.type === "decimal")?.value;
return decimal === "," ? "," : ".";
} catch {
return ".";
}
}
function format(value: number | null, separator: Separator): string {
if (value === null) return "";
let text = String(value);
if (text.includes("e")) text = value.toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 20 });
return separator === "," ? text.replace(".", ",") : text;
}
/** Full-width, Arabic-Indic and Persian digits become ASCII; the typographic minus becomes a hyphen; spaces go. */
function normalize(raw: string): string {
return raw
.normalize("NFKC")
.replace(/[٠-٩]/g, (digit) => String(digit.charCodeAt(0) - 0x0660))
.replace(/[۰-۹]/g, (digit) => String(digit.charCodeAt(0) - 0x06f0))
.replace(/٫/g, ".")
.replace(/−/g, "-")
.replace(/\s+/g, "");
}
const SHAPE = /^(-?)(\d*)(?:([.,])(\d*))?$/;
function parse(text: string): number | null {
const match = SHAPE.exec(text);
if (!match || (match[2] === "" && !match[4])) return null;
return finite(Number(text.replace(",", ".")));
}
/** A partial entry (`-`, `1.`, empty) is acceptable. What the current text already has is never refused, so it can be edited down. */
function acceptable(next: string, current: string, allowNegative: boolean, precision: number): boolean {
const match = SHAPE.exec(next);
if (!match) return false;
const before = SHAPE.exec(current);
if (match[1] && !allowNegative && !before?.[1]) return false;
if (match[3] && precision === 0 && !before?.[3]) return false;
const decimals = match[4]?.length ?? 0;
if (decimals > precision && decimals > (before?.[4]?.length ?? 0)) return false;
const hasDigits = match[2] !== "" || Boolean(match[4]);
return !hasDigits || parse(next) !== null;
}
function decimalsOf(value: number): number {
if (!Number.isFinite(value)) return 0;
const [mantissa, exponent] = String(value).split("e");
return Math.max(0, (mantissa.split(".")[1]?.length ?? 0) - Number(exponent ?? 0));
}
/** Rounds away floating-point noise; a result of `-0` (from `-1e-16`) becomes `0`. */
const round = (value: number, decimals: number) => {
const rounded = Number(value.toFixed(Math.min(decimals, 100)));
return rounded === 0 ? 0 : rounded;
};
function clampTo(value: number, min: number | undefined, max: number | undefined): number {
let next = value;
if (max !== undefined && next > max) next = max;
if (min !== undefined && next < min) next = min;
return next;
}
/** The next value on the step grid, which starts at `min` (or `0`), kept inside the range. */
function stepFrom(current: number | null, direction: 1 | -1, step: number, min: number | undefined, max: number | undefined): number {
if (current === null) {
const start = clampTo(0, min, max);
return start === 0 ? clampTo(round(direction * step, decimalsOf(step)), min, max) : start;
}
const base = min ?? 0;
const ratio = (current - base) / step;
const nearest = Math.round(ratio);
const onGrid = Math.abs(ratio - nearest) < 1e-9;
const index = onGrid ? nearest + direction : direction > 0 ? Math.ceil(ratio) : Math.floor(ratio);
return clampTo(round(base + index * step, Math.max(decimalsOf(step), decimalsOf(base))), min, max);
}
/**
* A numeric field on `Input`: the value is `number | null`, the text stays the person's while
* they type, and `min`/`max` apply when they leave. It is a text field with `inputmode`, not
* `type="number"`, so a decimal comma works, the mouse wheel does not change the value and
* partial entries are not lost.
*/
export const NumberInput = forwardRef<HTMLInputElement, NumberInputProps>(function NumberInput(
{
value,
defaultValue,
onValueChange,
onValueCommit,
min,
max,
step: stepProp = 1,
precision: precisionProp,
clamp = true,
unit,
locale,
className,
inputMode,
trailingIcon,
name,
form,
disabled,
readOnly,
"aria-describedby": describedBy,
onKeyDown,
onBlur,
onCompositionStart,
onCompositionEnd,
...props
},
ref,
) {
const controlled = value !== undefined;
const [uncontrolled, setUncontrolled] = useState<number | null>(() => finite(defaultValue));
const current = controlled ? finite(value) : uncontrolled;
const step = Number.isFinite(stepProp) && stepProp > 0 ? stepProp : 1;
const precision = Math.max(0, Math.floor(precisionProp ?? Math.max(decimalsOf(step), decimalsOf(min ?? 0))));
const allowNegative = min === undefined || !(min >= 0);
const shownSeparator = useMemo(() => localeSeparator(locale), [locale]);
// The typed text is kept only while it still stands for the current value, so an outside
// change, or a change the owner did not accept, shows the owner's value again.
const [draft, setDraft] = useState<Draft | null>(null);
const [composing, setComposing] = useState<string | null>(null);
const isComposing = useRef(false);
const edited = useRef(false);
const settled = draft && Object.is(draft.value, current) ? draft.text : format(current, shownSeparator ?? ".");
// While an input method composes, the field shows its text untouched; it is read when composition ends.
const text = composing ?? settled;
// Without a locale, a comma the person typed is kept when the field rewrites the text.
const separator: Separator = shownSeparator ?? (settled.includes(",") ? "," : ".");
const unitId = useId();
const hasUnit = unit != null && unit !== false && unit !== "";
const emit = (next: number | null) => {
if (Object.is(next, current)) return;
if (!controlled) setUncontrolled(next);
onValueChange?.(next);
};
const read = (element: HTMLInputElement) => {
const raw = element.value;
const next = normalize(raw);
if (!acceptable(next, settled, allowNegative, precision)) {
// Put the text and the caret back where they were instead of letting React move the caret to the end.
const caret = Math.max(0, (element.selectionStart ?? raw.length) - Math.max(raw.length - settled.length, 0));
element.value = settled;
element.setSelectionRange(caret, caret);
return;
}
const parsed = parse(next);
edited.current = true;
setDraft({ text: next, value: parsed });
emit(parsed);
};
const commit = () => {
if (!edited.current) return;
edited.current = false;
const final = clamp && current !== null ? clampTo(current, min, max) : current;
setDraft({ text: format(final, separator), value: final });
emit(final);
onValueCommit?.(final);
};
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
if (isComposing.current) setComposing(event.target.value);
else read(event.target);
};
const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
onKeyDown?.(event);
if (event.defaultPrevented || isComposing.current || event.nativeEvent.isComposing) return;
if (event.key === "Enter") {
commit();
return;
}
if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
if (disabled || readOnly || event.altKey || event.ctrlKey || event.metaKey) return;
event.preventDefault();
const next = stepFrom(current, event.key === "ArrowUp" ? 1 : -1, step, min, max);
// A step past the largest number would be Infinity; the value stays where it is.
if (!Number.isFinite(next)) return;
edited.current = true;
setDraft({ text: format(next, separator), value: next });
emit(next);
};
const handleBlur = (event: FocusEvent<HTMLInputElement>) => {
onBlur?.(event);
commit();
};
const handleCompositionStart = (event: CompositionEvent<HTMLInputElement>) => {
isComposing.current = true;
onCompositionStart?.(event);
};
const handleCompositionEnd = (event: CompositionEvent<HTMLInputElement>) => {
isComposing.current = false;
setComposing(null);
read(event.currentTarget);
onCompositionEnd?.(event);
};
const trailing: ReactNode = hasUnit || trailingIcon != null
? <>{hasUnit && <span id={unitId} className="ci-number-input__unit">{unit}</span>}{trailingIcon}</>
: undefined;
return (
<>
<Input
autoComplete="off"
autoCorrect="off"
spellCheck={false}
{...props}
ref={ref}
type="text"
inputMode={inputMode ?? (allowNegative ? "text" : precision > 0 ? "decimal" : "numeric")}
className={cn("ci-number-input", className)}
trailingIcon={trailing}
value={text}
form={form}
disabled={disabled}
readOnly={readOnly}
aria-describedby={[hasUnit ? unitId : null, describedBy].filter(Boolean).join(" ") || undefined}
onChange={handleChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
/>
{name != null && <input type="hidden" name={name} form={form} disabled={disabled} value={current === null ? "" : String(current)} />}
</>
);
});

View File

@@ -22,6 +22,17 @@ export interface NumberTickerProps extends Omit<HTMLAttributes<HTMLSpanElement>,
locale?: string;
/** Animate only after the number enters the viewport. */
animateOnView?: boolean;
/**
* Formats the number on screen and the accessible value, instead of `formatOptions` and
* `locale`. While counting it receives in-between values, so round inside it if needed.
*/
valueFormatter?: (value: number) => string;
/**
* How the first value appears. `"count"` (default) counts it up. `"static"` renders it as it
* is, in the server markup too, and animates only later changes: use it for a number that is
* already known when the component mounts. Read on mount only.
*/
initial?: "count" | "static";
}
export const NumberTicker = forwardRef<HTMLSpanElement, NumberTickerProps>(
@@ -35,24 +46,31 @@ export const NumberTicker = forwardRef<HTMLSpanElement, NumberTickerProps>(
formatOptions,
locale,
animateOnView = true,
valueFormatter,
initial = "count",
...props
},
forwardedRef,
) {
const localRef = useRef<HTMLSpanElement | null>(null);
const hasAnimated = useRef(false);
// True once a count has drawn its first frame (or reduced motion showed a value).
const hasCounted = useRef(false);
// With initial="static", the value rendered on mount; null once a different value arrives.
const staticValue = useRef(initial === "static" ? value : null);
// True once a count has drawn its first frame (or reduced motion or initial="static" showed a value).
const hasCounted = useRef(staticValue.current !== null);
const followsPrevious = from === "previous";
const origin = followsPrevious ? 0 : from;
const [displayValue, setDisplayValue] = useState(origin);
const [displayValue, setDisplayValue] = useState(staticValue.current ?? origin);
// The number on screen, read when a live value interrupts or follows a count.
const shownValue = useRef(origin);
const shownValue = useRef(staticValue.current ?? origin);
// With from="previous", when the first delayed count is due (performance.now() clock). A
// live value that arrives before then keeps this deadline instead of restarting the delay.
const firstCountAt = useRef<number | null>(null);
useEffect(() => {
// The static first value is already on screen: nothing to count until it changes.
if (staticValue.current !== null && Object.is(staticValue.current, value)) return;
staticValue.current = null;
const show = (next: number) => {
shownValue.current = next;
setDisplayValue(next);
@@ -132,10 +150,12 @@ export const NumberTicker = forwardRef<HTMLSpanElement, NumberTickerProps>(
};
}, [animateOnView, delay, duration, followsPrevious, origin, value]);
const formatter = new Intl.NumberFormat(locale, {
// Built only as the fallback: a caller's function must not depend on `formatOptions` and
// `locale` being valid for Intl.
const format = valueFormatter ?? new Intl.NumberFormat(locale, {
maximumFractionDigits: Number.isInteger(value) ? 0 : 2,
...formatOptions,
});
}).format;
return (
<span
@@ -145,10 +165,10 @@ export const NumberTicker = forwardRef<HTMLSpanElement, NumberTickerProps>(
else if (forwardedRef) forwardedRef.current = node;
}}
className={cn("ci-number-ticker", className)}
aria-label={formatter.format(value)}
aria-label={format(value)}
{...props}
>
{formatter.format(displayValue)}
{format(displayValue)}
</span>
);
},

View File

@@ -61,9 +61,9 @@ export function SetupLayout({ children, aside, className, headingVariant = "defa
: <aside className="ci-setup-layout__aside">{aside}</aside>)}</div>;
}
export interface SetupBenefitsProps { title: string; description?: string; items: readonly { title: string; description: string; icon?: ReactNode }[]; /** Optional follow-up content, aligned to benefit text with a consistent action gap. */ footer?: ReactNode; }
export function SetupBenefits({ title, description, items, footer }: SetupBenefitsProps) {
return <div className="ci-setup-benefits"><h2>{title}</h2>{description && <p>{description}</p>}<ul>{items.map(item => <li key={item.title}>{item.icon && <span aria-hidden>{item.icon}</span>}<div><strong>{item.title}</strong><p>{item.description}</p></div></li>)}</ul>{footer && <div className="ci-setup-benefits__footer" data-icon-aligned={items.some(item => item.icon) || undefined}>{footer}</div>}</div>;
export interface SetupBenefitsProps { title: string; description?: string; items: readonly { title: string; description: string; icon?: ReactNode }[]; /** Optional follow-up content with a consistent action gap. */ footer?: ReactNode; /** Align the footer with benefit text (default) or the starting icon edge. */ footerAlign?: "text" | "start"; }
export function SetupBenefits({ title, description, items, footer, footerAlign = "text" }: SetupBenefitsProps) {
return <div className="ci-setup-benefits"><h2>{title}</h2>{description && <p>{description}</p>}<ul>{items.map(item => <li key={item.title}>{item.icon && <span aria-hidden>{item.icon}</span>}<div><strong>{item.title}</strong><p>{item.description}</p></div></li>)}</ul>{footer && <div className="ci-setup-benefits__footer" data-icon-aligned={footerAlign === "text" && items.some(item => item.icon) || undefined}>{footer}</div>}</div>;
}
/** Interface text for SetupProgressCard; `title` and `note` remain separate props. */

View File

@@ -1,6 +1,7 @@
import type { ReactNode } from "react";
import { ArrowUpRight, Sparkles } from "lucide-react";
import { Card } from "./card";
import { resolveLabels } from "./lib/labels";
export interface TokenSavingsItem {
id: string;
@@ -10,20 +11,38 @@ export interface TokenSavingsItem {
icon?: ReactNode;
}
/** Interface text of TokenSavingsList. */
export interface TokenSavingsListLabels {
/** Accessible name of the list. */
list: string;
/** Unit shown after each formatted value. */
unit: string;
/** Accessible name of a bar, from the item's `label` and `formattedValue`. */
saved: (label: string, formattedValue: string) => string;
}
export const defaultTokenSavingsListLabels: TokenSavingsListLabels = {
list: "Token savings by technique",
unit: "tokens",
saved: (label, formattedValue) => `${label}: ${formattedValue} tokens saved`,
};
/** A ranked comparison, not a task-completion progress indicator. */
export function TokenSavingsList({ items, maxValue }: {
export function TokenSavingsList({ items, maxValue, labels: labelOverrides }: {
items: TokenSavingsItem[];
maxValue: number;
/** Localized interface text; missing or `undefined` keys fall back to defaultTokenSavingsListLabels. */
labels?: Partial<TokenSavingsListLabels>;
}) {
return <ul className="ci-token-savings" aria-label="Token savings by technique">
const labels = resolveLabels(defaultTokenSavingsListLabels, labelOverrides);
return <ul className="ci-token-savings" aria-label={labels.list}>
{items.map(item => {
const width = Number.isFinite(item.value) && Number.isFinite(maxValue) && maxValue > 0
? Math.max(0, Math.min(100, item.value / maxValue * 100)) : 0;
return <li key={item.id} className="ci-token-savings__item">
<span className="ci-token-savings__icon" aria-hidden="true">{item.icon ?? <Sparkles />}</span>
<div className="ci-token-savings__body">
<div className="ci-token-savings__label"><span>{item.label}</span><strong>{item.formattedValue}<span> tokens</span></strong></div>
<div className="ci-token-savings__track" role="img" aria-label={`${item.label}: ${item.formattedValue} tokens saved`}>
<div className="ci-token-savings__label"><span>{item.label}</span><strong>{item.formattedValue}<span> {labels.unit}</span></strong></div>
<div className="ci-token-savings__track" role="img" aria-label={labels.saved(item.label, item.formattedValue)}>
<span style={{ width: `${width}%` }} />
</div>
</div>
@@ -37,12 +56,26 @@ export interface QuickStartIntegration {
name: string;
description: string;
href: string;
/** Link browsing context; defaults to the current tab. */
target?: "_self" | "_blank";
icon: ReactNode;
}
function ClientGuideLinks({ integrations, compact = false }: { integrations: QuickStartIntegration[]; compact?: boolean }) {
return <nav className="ci-client-quick-start__integrations" data-layout={compact ? "compact" : "cards"} aria-label="Client setup guides">
{integrations.map(integration => <a key={integration.id} href={integration.href} className="ci-client-quick-start__integration">
/** Interface text shared by ClientQuickStart and the client card of OverviewPanels. */
export interface ClientQuickStartLabels {
/** Accessible name of the guide links. */
guides: string;
/** Eyebrow above the credentials. */
connection: string;
}
export const defaultClientQuickStartLabels: ClientQuickStartLabels = {
guides: "Client setup guides",
connection: "Connection details",
};
function ClientGuideLinks({ integrations, compact = false, label }: { integrations: QuickStartIntegration[]; compact?: boolean; label: string }) {
return <nav className="ci-client-quick-start__integrations" data-layout={compact ? "compact" : "cards"} aria-label={label}>
{integrations.map(integration => <a key={integration.id} href={integration.href} target={integration.target} rel={integration.target === "_blank" ? "noopener noreferrer" : undefined} className="ci-client-quick-start__integration">
<span className="ci-client-quick-start__brand" aria-hidden="true">{integration.icon}</span>
<span className="ci-client-quick-start__name">{integration.name}</span>
<span className="ci-client-quick-start__description">{integration.description}</span>
@@ -51,22 +84,25 @@ function ClientGuideLinks({ integrations, compact = false }: { integrations: Qui
</nav>;
}
function ClientConnection({ credentials }: { credentials: ReactNode }) {
function ClientConnection({ credentials, label }: { credentials: ReactNode; label: string }) {
return <div className="ci-client-quick-start__connection">
<p className="ci-client-quick-start__eyebrow">Connection details</p>
<p className="ci-client-quick-start__eyebrow">{label}</p>
<div className="ci-client-quick-start__credentials">{credentials}</div>
</div>;
}
/** Links open application-owned guides; credentials and copy actions stay app-owned. */
export function ClientQuickStart({ integrations, credentials, actions }: {
export function ClientQuickStart({ integrations, credentials, actions, labels: labelOverrides }: {
integrations: QuickStartIntegration[];
credentials: ReactNode;
actions?: ReactNode;
/** Localized interface text; missing or `undefined` keys fall back to defaultClientQuickStartLabels. */
labels?: Partial<ClientQuickStartLabels>;
}) {
const labels = resolveLabels(defaultClientQuickStartLabels, labelOverrides);
return <div className="ci-client-quick-start">
<ClientGuideLinks integrations={integrations} />
<ClientConnection credentials={credentials} />
<ClientGuideLinks integrations={integrations} label={labels.guides} />
<ClientConnection credentials={credentials} label={labels.connection} />
{actions && <div className="ci-client-quick-start__actions">{actions}</div>}
</div>;
}
@@ -83,12 +119,15 @@ export interface OverviewPanelsProps {
clientIntegrations: QuickStartIntegration[];
clientCredentials: ReactNode;
clientActions?: ReactNode;
/** Localized text of the client card; missing or `undefined` keys fall back to defaultClientQuickStartLabels. */
clientLabels?: Partial<ClientQuickStartLabels>;
}
/** Shared rows align card headers, visual content, details rules, and actions.
* Stacked cards size their own sections independently below the desktop breakpoint.
*/
export function OverviewPanels({ showOptimization = true, clientLayout = "cards", optimizationHeader, optimizationContent, optimizationSummary, clientHeader, clientIntegrations, clientCredentials, clientActions }: OverviewPanelsProps) {
export function OverviewPanels({ showOptimization = true, clientLayout = "cards", optimizationHeader, optimizationContent, optimizationSummary, clientHeader, clientIntegrations, clientCredentials, clientActions, clientLabels }: OverviewPanelsProps) {
const labels = resolveLabels(defaultClientQuickStartLabels, clientLabels);
return <div className="ci-overview-panels" data-layout={showOptimization ? "paired" : "single"} data-client-layout={clientLayout}>
{showOptimization && <Card flush className="ci-overview-panels__card">
<div className="ci-overview-panels__header">{optimizationHeader}</div>
@@ -99,9 +138,9 @@ export function OverviewPanels({ showOptimization = true, clientLayout = "cards"
<Card flush className="ci-overview-panels__card ci-overview-panels__client">
<div className="ci-overview-panels__header">{clientHeader}</div>
<div className="ci-overview-panels__body"><div className="ci-client-quick-start ci-overview-panels__guides">
<ClientGuideLinks integrations={clientIntegrations} compact={clientLayout === "compact"} />
<ClientGuideLinks integrations={clientIntegrations} compact={clientLayout === "compact"} label={labels.guides} />
</div></div>
<div className="ci-overview-panels__details"><ClientConnection credentials={clientCredentials} /></div>
<div className="ci-overview-panels__details"><ClientConnection credentials={clientCredentials} label={labels.connection} /></div>
<div className="ci-overview-panels__actions"><div className="ci-client-quick-start__actions">{clientActions}</div></div>
</Card>
</div>;

View File

@@ -5,19 +5,31 @@ export interface PageHeaderProps extends Omit<ComponentProps<"header">, "title">
eyebrow?: ReactNode;
breadcrumbs?: ReactNode;
title: ReactNode;
/**
* An icon or a logo before the title, sized from the title and centred on its first line. It is
* decorative: it sits outside the `<h1>`, hidden from assistive technology, so the heading holds
* only `title`.
*/
icon?: ReactNode;
description?: ReactNode;
actions?: ReactNode;
compact?: boolean;
}
export function PageHeader({ className, eyebrow, breadcrumbs, title, description, actions, compact = false, ...props }: PageHeaderProps) {
export function PageHeader({ className, eyebrow, breadcrumbs, title, icon, description, actions, compact = false, ...props }: PageHeaderProps) {
const heading = <h1 className="ci-page-header__title">{title}</h1>;
return (
<header data-slot="page-header" data-compact={compact || undefined} className={cn("ci-page-header", className)} {...props}>
{breadcrumbs != null && <div className="ci-page-header__breadcrumbs">{breadcrumbs}</div>}
<div className="ci-page-header__row">
<div className="ci-page-header__content">
{eyebrow != null && <div className="ci-eyebrow">{eyebrow}</div>}
<h1 className="ci-page-header__title">{title}</h1>
{icon != null && icon !== false ? (
<div className="ci-page-header__heading">
<span className="ci-page-header__icon" aria-hidden="true">{icon}</span>
{heading}
</div>
) : heading}
{description != null && <p className="ci-page-header__description">{description}</p>}
</div>
{actions != null && <div className="ci-page-header__actions">{actions}</div>}
@@ -26,17 +38,31 @@ export function PageHeader({ className, eyebrow, breadcrumbs, title, description
);
}
/** Steps of the interface heading scale (`--ci-type-heading-size-*`): 12, 14, 16, 18 and 20px. */
export type SectionHeaderSize = "xs" | "sm" | "md" | "lg" | "xl";
export interface SectionHeaderProps extends Omit<ComponentProps<"header">, "title"> {
title: ReactNode;
/** Title size on the heading scale. Without it the title is 18px (`lg`). `xs` and `sm` also set the description to 12px. */
size?: SectionHeaderSize;
description?: ReactNode;
actions?: ReactNode;
/**
* The element of the title, `<h2>` by default. Pick the level that keeps the page outline in
* order, such as `3` for a header inside a card under an `<h2>`. The title looks the same at
* every level.
*/
headingLevel?: 2 | 3 | 4 | 5 | 6;
/** `bordered` (default) draws the rule under the header; `plain` drops the rule and its padding. */
variant?: "bordered" | "plain";
}
export function SectionHeader({ className, title, description, actions, ...props }: SectionHeaderProps) {
export function SectionHeader({ className, title, description, actions, size, headingLevel = 2, variant = "bordered", ...props }: SectionHeaderProps) {
const Heading = `h${headingLevel}` as "h2" | "h3" | "h4" | "h5" | "h6";
return (
<header data-slot="section-header" className={cn("ci-section-header", className)} {...props}>
<header data-slot="section-header" data-size={size} className={cn("ci-section-header", variant === "plain" && "ci-section-header--plain", className)} {...props}>
<div>
<h2 className="ci-section-header__title">{title}</h2>
<Heading className="ci-section-header__title">{title}</Heading>
{description != null && <p className="ci-section-header__description">{description}</p>}
</div>
{actions != null && <div className="ci-section-header__actions">{actions}</div>}

View File

@@ -0,0 +1,137 @@
"use client";
import { useEffect, useRef } from "react";
import type { ComponentProps, FocusEvent, MouseEvent } from "react";
import { resolveLabels } from "./lib/labels";
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
PaginationSummary,
} from "./pagination";
/** Interface text of the pager. */
export interface PaginationControlsLabels {
/** Accessible name of the navigation landmark. */
navigation: string;
/** Visible text of the previous/next buttons. */
previous: string;
next: string;
/** Accessible name of the previous/next buttons. */
previousPage: string;
nextPage: string;
/** Accessible name of a page button. */
goToPage: (page: number) => string;
/** Text alternative of an ellipsis. */
morePages: string;
/** Text of the `summary` variant. */
summary: (page: number, pageCount: number) => string;
}
export const defaultPaginationControlsLabels: PaginationControlsLabels = {
navigation: "Pagination",
previous: "Previous",
next: "Next",
previousPage: "Go to previous page",
nextPage: "Go to next page",
goToPage: (page) => `Go to page ${page}`,
morePages: "More pages",
summary: (page, pageCount) => `Page ${page} of ${pageCount}`,
};
export interface PaginationControlsProps extends Omit<ComponentProps<"nav">, "children"> {
/** Current page, starting at 1. A value outside `1..pageCount` is clamped. */
page: number;
pageCount: number;
onPageChange: (page: number) => void;
/** `pages` lists page numbers (first, last, current, with ellipses); `summary` shows "Page X of Y" between previous and next. */
variant?: "pages" | "summary";
/** Disables every button, for example while the next page loads. */
disabled?: boolean;
/** Localized interface text; missing or `undefined` keys fall back to defaultPaginationControlsLabels. */
labels?: Partial<PaginationControlsLabels>;
}
/** Keep navigation bounded even on narrow screens; arrows reach adjacent pages. */
function paginationPages(page: number, count: number): Array<number | "before" | "after"> {
if (count <= 5) return Array.from({ length: count }, (_, index) => index + 1);
if (page <= 2) return [1, 2, 3, "after", count];
if (page >= count - 1) return [1, "before", count - 2, count - 1, count];
return [1, "before", page, "after", count];
}
/** Ready pager for paging kept in state: buttons, not links, so there is no `href` to fake. */
export function PaginationControls({ page, pageCount, onPageChange, variant = "pages", disabled = false, labels: labelOverrides, ...props }: PaginationControlsProps) {
const labels = resolveLabels(defaultPaginationControlsLabels, labelOverrides);
const count = Math.max(1, Math.floor(pageCount) || 1);
const current = Math.min(Math.max(1, Math.floor(page) || 1), count);
const pressed = useRef<HTMLButtonElement | null>(null);
// A focused button that becomes disabled drops keyboard focus: the arrow at either end of the
// range, or every button while `disabled`. Once a button is enabled again, give focus back to
// the pressed one, or to the current page (or the other arrow) when it stays disabled.
useEffect(() => {
const control = pressed.current;
if (!control) return;
const focused = control.ownerDocument.activeElement;
const movedOn = focused !== null && focused !== control && focused !== control.ownerDocument.body;
if (movedOn || !control.isConnected) { pressed.current = null; return; }
let target: HTMLElement | null | undefined = control;
if (control.disabled) {
const nav = control.closest('[data-slot="pagination"]');
target = nav?.querySelector<HTMLElement>('button[aria-current="page"]:not(:disabled)') ?? nav?.querySelector<HTMLElement>("button:not(:disabled)");
// Every button is disabled: try again when that changes.
if (!target) return;
}
pressed.current = null;
if (target !== focused) target.focus();
}, [current, count, disabled]);
// Focus that lands on another element, even for a moment, means the user moved on, so a pending
// recovery is dropped. The body is where focus falls when a button is disabled, so it does not count.
useEffect(() => {
const moved = (event: Event) => { if (event.target !== pressed.current && event.target !== document.body) pressed.current = null; };
document.addEventListener("focusin", moved);
return () => document.removeEventListener("focusin", moved);
}, []);
const press = (next: number) => ({
onClick: (event: MouseEvent<HTMLButtonElement>) => {
const control = event.currentTarget;
// Only a button that holds focus can lose it; Safari does not focus a clicked button.
pressed.current = control.ownerDocument.activeElement === control ? control : null;
if (next !== current) onPageChange(next);
},
onBlur: (event: FocusEvent<HTMLButtonElement>) => {
// Focus left an enabled button, so the user moved on.
if (pressed.current === event.currentTarget && !event.currentTarget.disabled) pressed.current = null;
},
});
return (
<Pagination aria-label={labels.navigation} {...props}>
<PaginationContent>
<PaginationItem>
<PaginationPrevious asChild label={labels.previousPage} disabled={disabled || current === 1}>
<button type="button" {...press(current - 1)}><span>{labels.previous}</span></button>
</PaginationPrevious>
</PaginationItem>
{variant === "summary"
? <PaginationItem><PaginationSummary>{labels.summary(current, count)}</PaginationSummary></PaginationItem>
: paginationPages(current, count).map((number) => (
<PaginationItem key={number}>{typeof number === "number"
? <PaginationLink asChild label={labels.goToPage(number)} disabled={disabled} isActive={number === current}><button type="button" {...press(number)}>{number}</button></PaginationLink>
: <PaginationEllipsis label={labels.morePages} />}</PaginationItem>
))}
<PaginationItem>
<PaginationNext asChild label={labels.nextPage} disabled={disabled || current === count}>
<button type="button" {...press(current + 1)}><span>{labels.next}</span></button>
</PaginationNext>
</PaginationItem>
</PaginationContent>
</Pagination>
);
}

View File

@@ -1,4 +1,5 @@
import type { ComponentProps } from "react";
import { cloneElement, isValidElement } from "react";
import type { ComponentProps, MouseEvent, ReactElement, ReactNode } from "react";
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "./lib/utils";
@@ -19,9 +20,45 @@ export interface PaginationLinkProps extends ComponentProps<"a"> {
disabled?: boolean;
/** Accessible name. PaginationPrevious/Next default to "Go to previous page"/"Go to next page"; pass children to replace the visible text. */
label?: string;
/**
* Render the single child with the pagination treatment instead of an `<a>`: a `<button>` for paging
* kept in state, or a router link. A `<button>` child gets `type="button"` and the real `disabled`
* attribute; any other child is disabled the way the link is (`aria-disabled`, out of the tab order).
*/
asChild?: boolean;
}
export function PaginationLink({ className, isActive = false, disabled = false, label, onClick, ...props }: PaginationLinkProps) {
/** cloneElement overrides with `undefined` too, so only the keys that carry a value reach the child. */
function defined(props: Record<string, unknown>) {
return Object.fromEntries(Object.entries(props).filter(([, value]) => value !== undefined));
}
export function PaginationLink({ className, isActive = false, disabled = false, label, asChild = false, onClick, children, ...props }: PaginationLinkProps) {
if (asChild && isValidElement(children)) {
const child = children as ReactElement<Record<string, unknown>>;
const childClick = child.props.onClick as ((event: MouseEvent<HTMLElement>) => void) | undefined;
const nativeButton = child.type === "button";
// A button the caller disabled itself looks disabled too.
const inactive = disabled || (nativeButton && Boolean(child.props.disabled));
const state = nativeButton
? { type: child.props.type ?? "button", disabled: disabled || undefined }
: { "aria-disabled": disabled || undefined, tabIndex: disabled ? -1 : undefined };
return cloneElement(child, defined({
...state,
"aria-current": isActive ? "page" : undefined,
"aria-label": label,
"data-slot": "pagination-link",
"data-active": isActive || undefined,
"data-disabled": inactive || undefined,
...props,
className: cn("ci-pagination__link", className, child.props.className as string | undefined),
onClick: (event: MouseEvent<HTMLElement>) => {
if (disabled) { event.preventDefault(); return; }
childClick?.(event);
onClick?.(event as MouseEvent<HTMLAnchorElement>);
},
}));
}
return (
<a
aria-current={isActive ? "page" : undefined}
@@ -34,18 +71,48 @@ export function PaginationLink({ className, isActive = false, disabled = false,
className={cn("ci-pagination__link", className)}
onClick={(event) => { if (disabled) event.preventDefault(); else onClick?.(event); }}
{...props}
/>
>
{children}
</a>
);
}
export function PaginationPrevious({ className, children, ...props }: PaginationLinkProps) {
return <PaginationLink label="Go to previous page" className={cn("ci-pagination__link--edge", className)} {...props}><ChevronLeft />{children ?? <span>Previous</span>}</PaginationLink>;
/** With `asChild` the arrow and the text go inside the child, which stays the only element. */
function edgeContent(children: ReactNode, slot: boolean, content: (text: ReactNode) => ReactNode) {
if (slot && isValidElement(children)) {
const child = children as ReactElement<{ children?: ReactNode }>;
return cloneElement(child, undefined, content(child.props.children));
}
return content(children);
}
export function PaginationNext({ className, children, ...props }: PaginationLinkProps) {
return <PaginationLink label="Go to next page" className={cn("ci-pagination__link--edge", className)} {...props}>{children ?? <span>Next</span>}<ChevronRight /></PaginationLink>;
/** The default name yields to one the `asChild` child already carries. */
function edgeLabel(children: ReactNode, slot: boolean, fallback: string) {
if (!slot || !isValidElement(children)) return fallback;
const named = children.props as Record<string, unknown>;
return named["aria-label"] == null && named["aria-labelledby"] == null ? fallback : undefined;
}
export function PaginationEllipsis({ className, ...props }: ComponentProps<"span">) {
return <span aria-hidden="true" data-slot="pagination-ellipsis" className={cn("ci-pagination__ellipsis", className)} {...props}><MoreHorizontal /><span className="ci-sr-only">More pages</span></span>;
export function PaginationPrevious({ className, children, asChild, ...props }: PaginationLinkProps) {
const slot = Boolean(asChild) && isValidElement(children);
return <PaginationLink label={edgeLabel(children, slot, "Go to previous page")} className={cn("ci-pagination__link--edge", className)} asChild={slot} {...props}>{edgeContent(children, slot, (text) => <><ChevronLeft />{text ?? <span>Previous</span>}</>)}</PaginationLink>;
}
export function PaginationNext({ className, children, asChild, ...props }: PaginationLinkProps) {
const slot = Boolean(asChild) && isValidElement(children);
return <PaginationLink label={edgeLabel(children, slot, "Go to next page")} className={cn("ci-pagination__link--edge", className)} asChild={slot} {...props}>{edgeContent(children, slot, (text) => <>{text ?? <span>Next</span>}<ChevronRight /></>)}</PaginationLink>;
}
export interface PaginationEllipsisProps extends ComponentProps<"span"> {
/** Text alternative of the gap, read by screen readers (default "More pages"). */
label?: string;
}
export function PaginationEllipsis({ className, label = "More pages", ...props }: PaginationEllipsisProps) {
return <span data-slot="pagination-ellipsis" className={cn("ci-pagination__ellipsis", className)} {...props}><MoreHorizontal aria-hidden="true" /><span className="ci-sr-only">{label}</span></span>;
}
/** "Page X of Y" text for a pager without page numbers; a change of page is announced politely. */
export function PaginationSummary({ className, ...props }: ComponentProps<"span">) {
return <span aria-live="polite" aria-atomic="true" data-slot="pagination-summary" className={cn("ci-pagination__summary", className)} {...props} />;
}

View File

@@ -1,16 +1,22 @@
"use client";
import { useEffect, useId, useRef, useState } from "react";
import type { ComponentProps, ReactNode } from "react";
import type { ComponentProps, CSSProperties, ReactNode } from "react";
import { cn } from "./lib/utils";
import { NumberTicker } from "./number-ticker";
export type ProgressTone = "default" | "success" | "warning" | "danger" | "info";
/** Track height: `xs` is 4px, `sm` is 6px and `md` (default) is 8px. */
export type ProgressSize = "xs" | "sm" | "md";
/** `progress` is a task that advances to completion; `meter` is a measurement inside a known range. */
export type ProgressSemantics = "progress" | "meter";
export interface ProgressSegment {
value: number;
/** Colour of this part. Defaults to the bar's `tone`. */
tone?: ProgressTone;
/** Any CSS colour for this part, for example `chartSeries(index).color`. Wins over `tone`; defaults to the bar's `color` when the part has no `tone`. */
color?: string;
}
/** One allocation band with its own track: `max` is its capacity, `value` the used part inside it. */
@@ -27,11 +33,13 @@ export interface ProgressBand {
valueText?: string;
/** Colour of this band's edge and fill. Defaults to the bar's `tone`. */
tone?: ProgressTone;
/** Any CSS colour for this band's edge and fill, for example `chartSeries(index).color`. Wins over `tone`; defaults to the bar's `color` when the band has no `tone`. */
color?: string;
/** Visible caption under this band, aligned with its track. */
legend?: ReactNode;
}
export interface ProgressProps extends Omit<ComponentProps<"div">, "children"> {
export interface ProgressProps extends Omit<ComponentProps<"div">, "children" | "color"> {
/** Current value. Omit it (or pass `indeterminate`) when the amount of work is unknown. */
value?: number;
max?: number;
@@ -43,6 +51,19 @@ export interface ProgressProps extends Omit<ComponentProps<"div">, "children"> {
delay?: number;
/** Indicator colour. "default" keeps the accent gradient. */
tone?: ProgressTone;
/**
* Any CSS colour for the indicator, set through `--ci-progress-color`. Prefer `chartSeries(index).color`,
* so the bar matches its series in a chart or a `LegendMarker`. Wins over `tone`.
*/
color?: string;
/** Track height: `xs` is 4px, `sm` is 6px and `md` (default) is 8px. Applies to `segments` and `bands` too. */
size?: ProgressSize;
/**
* `progress` (default) is a `progressbar`: a task that advances to completion. `meter` is a `meter`:
* a measurement inside a known range, such as quota used, coverage or a share of a total. Both are
* named the same way. An unknown value is always a `progressbar`, because a meter has a value.
*/
semantics?: ProgressSemantics;
/** Unknown amount of work: a looping sweep and no `aria-valuenow`. Wins over `value` and `segments`. */
indeterminate?: boolean;
/** Stacked parts of one total (for example completed + failed). Their sum is the bar value; `value` is ignored. */
@@ -58,6 +79,15 @@ export interface ProgressProps extends Omit<ComponentProps<"div">, "children"> {
// Only NaN has no meaningful position; ±Infinity is clamped to [0, max] below, as before.
const orZero = (value: number) => (Number.isNaN(value) ? 0 : value);
// The most specific colour wins: the part's own colour, then the part's own tone, then the bar's colour.
const partColor = (part: { color?: string; tone?: ProgressTone }, barColor: string | undefined) =>
part.color || (part.tone == null ? barColor : undefined) || undefined;
// A coloured part carries its colour instead of a tone; a part without a colour is marked exactly as before.
const paint = (color: string | undefined, tone: ProgressTone) =>
color ? { "data-color": "" } : { "data-tone": tone === "default" ? undefined : tone };
const colorVar = (color: string | undefined) => (color ? ({ "--ci-progress-color": color } as CSSProperties) : undefined);
export function Progress({
className,
value,
@@ -67,6 +97,9 @@ export function Progress({
animate = true,
delay = 0,
tone = "default",
color,
size = "md",
semantics = "progress",
indeterminate = false,
segments,
bands,
@@ -82,12 +115,12 @@ export function Progress({
.filter((band) => Number.isFinite(band.max) && band.max > 0)
.map((band) => {
const amount = Math.min(Math.max(orZero(band.value), 0), band.max);
return { ...band, tone: band.tone ?? tone, amount, percent: (amount / band.max) * 100 };
return { ...band, tone: band.tone ?? tone, color: partColor(band, color), amount, percent: (amount / band.max) * 100 };
});
const hasBands = !indeterminate && bandParts.length > 0;
const hasSegments = Boolean(segments?.length);
const isIndeterminate = indeterminate || (value == null && !hasSegments && !hasBands);
const sourceParts: ProgressSegment[] = segments?.length ? segments : [{ value: value ?? 0, tone }];
const sourceParts: ProgressSegment[] = segments?.length ? segments : [{ value: value ?? 0 }];
// Each part is capped so the stacked total never exceeds max. Empty segments
// are dropped so they do not draw a seam; a plain bar always keeps its indicator.
let used = 0;
@@ -95,7 +128,7 @@ export function Progress({
.map((part) => {
const amount = Math.min(Math.max(orZero(part.value), 0), safeMax - used);
used += amount;
return { tone: part.tone ?? tone, amount, percent: (amount / safeMax) * 100 };
return { tone: part.tone ?? tone, color: partColor(part, color), amount, percent: (amount / safeMax) * 100 };
})
.filter((part) => !hasSegments || part.amount > 0);
const current = used;
@@ -152,6 +185,8 @@ export function Progress({
// aria-labelledby wins, then aria-label, then the visible `label`.
const hasVisibleLabel = label != null && label !== false && label !== "";
const labelledBy = ariaLabelledBy ?? (ariaLabel == null && hasVisibleLabel ? labelId : undefined);
// A meter always has a value, so the indeterminate sweep stays a progressbar.
const role = semantics === "meter" && !isIndeterminate ? "meter" : "progressbar";
return (
<div
@@ -161,6 +196,7 @@ export function Progress({
// After the forwarded props, so a consumer data-state cannot switch the sweep off.
{...(isIndeterminate ? { "data-state": "indeterminate" } : null)}
{...(hasBands ? { "data-layout": "bands" } : null)}
{...(size === "xs" || size === "sm" ? { "data-size": size } : null)}
>
{(label != null || (showValue && !isIndeterminate)) && (
<div className="ci-progress__header">
@@ -187,11 +223,11 @@ export function Progress({
<div
key={bandKeys[index]}
className="ci-progress__band"
data-tone={band.tone === "default" ? undefined : band.tone}
style={{ flexGrow: band.max * growScale }}
{...paint(band.color, band.tone)}
style={{ flexGrow: band.max * growScale, ...colorVar(band.color) }}
>
<div
role="progressbar"
role={role}
aria-label={band.label}
aria-valuetext={band.valueText}
aria-valuemin={0}
@@ -215,7 +251,7 @@ export function Progress({
</div>
) : (
<div
role="progressbar"
role={role}
aria-label={ariaLabel}
aria-labelledby={labelledBy}
aria-describedby={ariaDescribedBy}
@@ -227,16 +263,17 @@ export function Progress({
data-segmented={hasSegments && !isIndeterminate ? "" : undefined}
>
{isIndeterminate ? (
<span className="ci-progress__indicator" data-tone={tone === "default" ? undefined : tone} />
<span className="ci-progress__indicator" {...paint(color || undefined, tone)} style={colorVar(color)} />
) : (
parts.map((part, index) => (
<span
key={index}
className={cn("ci-progress__indicator", hasSegments && "ci-progress__segment")}
data-tone={part.tone === "default" ? undefined : part.tone}
{...paint(part.color, part.tone)}
style={{
width: isVisible ? `${part.percent}%` : "0%",
transitionDelay: isVisible ? `${delay}s` : "0s",
...colorVar(part.color),
}}
/>
))

View File

@@ -0,0 +1,106 @@
import { useId } from "react";
import type { ComponentProps, ReactNode } from "react";
import { cn } from "./lib/utils";
import type { ProgressTone } from "./progress";
export type RadialMeterSize = "sm" | "md" | "lg";
interface RadialMeterBaseProps extends Omit<ComponentProps<"div">, "children" | "aria-label" | "aria-labelledby"> {
/** Current value, clamped to `[0, max]`. A value that is not a number counts as 0. */
value: number;
/** Top of the range. Defaults to 100; anything that is not a positive number counts as 1. */
max?: number;
/** Arc colour: the `Progress` tones. "default" is the accent ink. */
tone?: ProgressTone;
/** Ring diameter: `sm` is 48px, `md` (default) is 80px and `lg` is 120px. */
size?: RadialMeterSize;
/**
* Text for the value, shown in the centre and spoken as `aria-valuetext`. Gets the clamped value and the
* maximum in use. Defaults to the rounded percentage, such as "72%".
*/
valueFormatter?: (value: number, max: number) => string;
/** Show the value text in the centre. Set false for a ring too small or too busy for text; the value is still spoken. */
showValue?: boolean;
/** Draw the arc in when the meter mounts. Set false for a static ring; a new value still eases in. OS reduced-motion preferences always win. */
animate?: boolean;
/** Centre content in place of the value text. It is not exposed to assistive technology, so keep it non-interactive. */
children?: ReactNode;
}
/** The meter needs a name: a visible `label`, an `aria-label`, or the id of the element that names it. */
type RadialMeterName =
| { label: ReactNode; "aria-label"?: string; "aria-labelledby"?: string }
| { label?: ReactNode; "aria-label": string; "aria-labelledby"?: string }
| { label?: ReactNode; "aria-label"?: string; "aria-labelledby": string };
export type RadialMeterProps = RadialMeterBaseProps & RadialMeterName;
const present = (value: string | undefined) => (value != null && value.trim() !== "" ? value : undefined);
/**
* A ring gauge for one value in a known range: quota used, coverage, a score, a share of a total.
* It is a `role="meter"` with the naming rules of `Progress`: `aria-labelledby`, then `aria-label`, then `label`.
*/
export function RadialMeter({
className,
value,
max = 100,
tone = "default",
size = "md",
label,
valueFormatter,
showValue = true,
animate = true,
children,
"aria-label": ariaLabel,
"aria-labelledby": ariaLabelledBy,
"aria-describedby": ariaDescribedBy,
"aria-valuetext": ariaValueText,
...props
}: RadialMeterProps) {
const labelId = useId();
const safeMax = Number.isFinite(max) && max > 0 ? max : 1;
// Only NaN has no position in the range; ±Infinity clamps to an end of it, as in Progress.
const current = Math.min(Math.max(Number.isNaN(value) ? 0 : value, 0), safeMax);
const percent = (current / safeMax) * 100;
const valueText = valueFormatter ? valueFormatter(current, safeMax) : `${Math.round(percent)}%`;
// The meter, not the wrapper, owns the accessible name: explicit aria-labelledby wins, then aria-label, then the visible `label`.
// An empty attribute names nothing, so it counts as absent and does not switch the visible label off.
const namedBy = present(ariaLabelledBy);
const namedAs = present(ariaLabel);
const hasVisibleLabel = label != null && label !== false && label !== "";
const labelledBy = namedBy ?? (namedAs == null && hasVisibleLabel ? labelId : undefined);
const hasChildren = children != null && children !== false && children !== "";
return (
<div
{...props}
className={cn("ci-radial-meter", className)}
// After the forwarded props, so a consumer data attribute cannot replace the component's own.
data-size={size}
data-tone={tone === "default" ? undefined : tone}
data-animate={animate ? "" : undefined}
>
<div
role="meter"
aria-label={namedAs}
aria-labelledby={labelledBy}
aria-describedby={ariaDescribedBy}
aria-valuetext={ariaValueText ?? valueText}
aria-valuemin={0}
aria-valuemax={safeMax}
aria-valuenow={current}
className="ci-radial-meter__gauge"
>
<svg className="ci-radial-meter__ring" viewBox="0 0 100 100" aria-hidden="true" focusable="false">
<circle className="ci-radial-meter__track" cx="50" cy="50" r="45" />
{percent > 0 ? (
<circle className="ci-radial-meter__arc" cx="50" cy="50" r="45" pathLength={100} strokeDasharray="100" strokeDashoffset={100 - percent} />
) : null}
</svg>
{hasChildren || showValue ? <span className="ci-radial-meter__center">{hasChildren ? children : valueText}</span> : null}
</div>
{hasVisibleLabel ? <span id={labelId} className="ci-radial-meter__label">{label}</span> : null}
</div>
);
}

View File

@@ -11,13 +11,15 @@ export interface RecoveryStateProps extends Omit<ComponentProps<"section">, "tit
title: string;
description: string;
reference?: string;
/** Text before `reference`. Defaults to "Support reference". */
referenceLabel?: string;
actions?: ReactNode;
help?: ReactNode;
announce?: boolean;
}
/** Router- and provider-independent recovery for failed pages and sections. */
export function RecoveryState({ variant = "page", brand, headerAction, icon, eyebrow, title, description, reference, actions, help, announce = true, className, ...props }: RecoveryStateProps) {
export function RecoveryState({ variant = "page", brand, headerAction, icon, eyebrow, title, description, reference, referenceLabel = "Support reference", actions, help, announce = true, className, ...props }: RecoveryStateProps) {
const id = useId();
const Heading = variant === "page" ? "h1" : "h2";
return <section data-slot="recovery-state" data-variant={variant} className={cn("ci-recovery-state", className)} aria-labelledby={id} {...props}>
@@ -33,7 +35,7 @@ export function RecoveryState({ variant = "page", brand, headerAction, icon, eye
{actions && <div className="ci-recovery-state__actions">{actions}</div>}
{(help || reference) && <footer className="ci-recovery-state__footer">
{help && <div>{help}</div>}
{reference && <p className="ci-recovery-state__reference">Support reference <code>{reference}</code></p>}
{reference && <p className="ci-recovery-state__reference">{referenceLabel} <code>{reference}</code></p>}
</footer>}
</div>
</div>

View File

@@ -1,8 +1,9 @@
"use client";
import { useId, useMemo, useRef, useState } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, Customized, DefaultTooltipContent, Line, LineChart as RechartsLineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import type { ComponentProps, CSSProperties, MutableRefObject, ReactNode } from "react";
import { useCallback, useId, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, ComposedChart, DefaultTooltipContent, Line, LineChart as RechartsLineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import type { ComponentProps, CSSProperties, ReactNode } from "react";
import { chartTheme } from "./chart-theme";
import { cn } from "./lib/utils";
import { EmptyState } from "./empty-state";
@@ -26,10 +27,23 @@ export interface StackedBarDatum {
values: Readonly<Record<string, number | null | undefined>>;
}
/** A series drawn as a line over the bars, on an axis of its own. */
export interface StackedBarLineSeries extends ChartSeries {
/** Formats this series in the tooltip and in each point's accessible name. Defaults to the chart's `valueFormatter`. */
valueFormatter?: (value: number) => string;
/** Compact text for the 48px axis, such as `$1.2k`. Defaults to this series' `valueFormatter`. */
yTickFormatter?: (value: number) => string;
}
export interface StackedBarChartProps extends Omit<ComponentProps<"figure">, "children" | "onSelect"> {
ariaLabel: string;
data: readonly StackedBarDatum[];
series: readonly ChartSeries[];
/**
* One more series from the same `values`, drawn as a line on a second Y axis at the right of the plot:
* a measure in another unit, such as cost over request bars. It is never part of the total.
*/
lineSeries?: StackedBarLineSeries;
/** The caller supplies already aggregated data and owns any filtering/navigation. */
onPointSelect?: (datum: StackedBarDatum, index: number) => void;
selectedId?: string | null;
@@ -42,89 +56,132 @@ export interface StackedBarChartProps extends Omit<ComponentProps<"figure">, "ch
totalLabel?: string;
unavailableLabel?: string;
emptyLabel?: string;
/** Accessible name of the keyboard point group, from `ariaLabel`. Defaults to "… data points". */
dataPointsLabel?: (ariaLabel: string) => string;
}
const defaultDataPointsLabel = (ariaLabel: string) => `${ariaLabel} data points`;
const formatNumber = (value: number) => new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 }).format(value);
const measured = (value: number | null | undefined): value is number => typeof value === "number" && Number.isFinite(value);
const palette = ["var(--ci-chart-1)", "var(--ci-chart-2)", "var(--ci-chart-3)", "var(--ci-chart-4)", "var(--ci-chart-5)"];
const seriesColor = (series: ChartSeries, index: number) => series.color ?? palette[index % palette.length];
const tooltipStyle = chartTheme.tooltip.contentStyle;
const lineAxisId = "line";
// The second axis takes the place of the right margin, as the first one does on the left.
const lineAxisMargin = { ...chartTheme.margin, right: 0 };
// Over the keyboard hit areas, so a focused one's outline never crosses the pointer tooltip.
const pointerTooltipStyle = { zIndex: 1 };
// Keeps the pointer tooltip in series order: recharts 3 sorts its items by name unless told how.
const inSeriesOrder = () => 0;
// Drawn under the line in the surface colour, so the line stays legible where it crosses a bar.
const lineHalo = { stroke: "var(--ci-color-surface)", strokeWidth: chartTheme.line.strokeWidth + 2, dot: false, activeDot: false, legendType: "none", tooltipType: "none" } as const;
type ChartValues = { values: Readonly<Record<string, number | null | undefined>> };
// The plot's box inside the chart, in CSS: from the Y axis to `end`, the width kept free at its right.
const plotStart = chartTheme.margin.left + chartTheme.yAxis.width;
const plotEnd = chartTheme.margin.right;
const plotSpan = (ratio: number, end: number = plotEnd) => `(100% - ${plotStart + end}px) * ${ratio}`;
const plotX = (ratio: number, end: number = plotEnd) => `calc(${plotStart}px + ${plotSpan(ratio, end)})`;
const keyboardTooltipWidth = 220;
interface ChartPointZonesProps {
offset?: { top: number; left: number; width: number; height: number };
points: readonly StackedBarDatum[];
/** Width kept free at the right of the plot: the chart margin, or the line series' axis. */
end: number;
/** Already resolved name of the point group. */
ariaLabel: string;
rovingId?: string | null;
selectedId?: string | null;
keyboardIndex?: number;
/** The point whose keyboard tooltip is open. */
describedId?: string | null;
tooltipId: string;
zones: MutableRefObject<(SVGRectElement | null)[]>;
selectable: boolean;
describe: (datum: StackedBarDatum) => string;
onPointSelect?: StackedBarChartProps["onPointSelect"];
onFocused: (id: string | null) => void;
onTooltip: (point: { index: number; x: number; y: number } | null) => void;
onTooltip: (id: string | null) => void;
}
function ChartPointZones({ offset, points, ariaLabel, rovingId, selectedId, keyboardIndex, tooltipId, zones, selectable, describe, onPointSelect, onFocused, onTooltip }: ChartPointZonesProps) {
if (!offset) return null;
const slot = offset.width / points.length;
return <g role="group" aria-label={`${ariaLabel} data points`}>{points.map((datum, index) => <rect key={datum.id} ref={node => { zones.current[index] = node; }}
/** One hit area per band of the X axis, placed from `chartTheme`'s plot geometry. */
function ChartPointZones({ points, end, ariaLabel, rovingId, selectedId, describedId, tooltipId, selectable, describe, onPointSelect, onFocused, onTooltip }: ChartPointZonesProps) {
const zones = useRef<(HTMLDivElement | null)[]>([]);
return <div className="ci-stacked-chart__zones" role="group" aria-label={ariaLabel}>{points.map((datum, index) => <div key={datum.id} ref={node => { zones.current[index] = node; }}
className="ci-stacked-chart__zone" data-selected={selectedId === datum.id || undefined}
x={offset.left + index * slot} y={offset.top} width={slot} height={offset.height}
style={{ left: plotX(index / points.length, end), width: `calc(${plotSpan(1 / points.length, end)})` }}
role={selectable ? "button" : "img"} tabIndex={rovingId === datum.id ? 0 : -1}
aria-label={describe(datum)} aria-pressed={selectable ? selectedId === datum.id : undefined}
aria-describedby={keyboardIndex === index ? tooltipId : undefined}
onFocus={() => { onFocused(datum.id); onTooltip({ index, x: Math.max(0, Math.min(offset.left + (index + .5) * slot + 10, offset.left + offset.width - 220)), y: offset.top + 12 }); }}
aria-describedby={describedId === datum.id ? tooltipId : undefined}
onFocus={() => { onFocused(datum.id); onTooltip(datum.id); }}
onBlur={() => { onFocused(null); onTooltip(null); }} onPointerMove={() => onTooltip(null)} onClick={() => onPointSelect?.(datum, index)}
onKeyDown={event => {
const next = event.key === "ArrowRight" ? (index + 1) % points.length : event.key === "ArrowLeft" ? (index + points.length - 1) % points.length : event.key === "Home" ? 0 : event.key === "End" ? points.length - 1 : null;
if (next !== null) { event.preventDefault(); zones.current[next]?.focus(); }
if ((event.key === "Enter" || event.key === " ") && onPointSelect) { event.preventDefault(); onPointSelect(datum, index); }
if (event.key === "Escape") { event.preventDefault(); onTooltip(null); }
}} />)}</g>;
}} />)}</div>;
}
/** The approved preview's Recharts composition, with additive keyboard hit areas. */
/**
* The approved preview's Recharts composition, with additive keyboard hit areas. The hit areas are
* HTML placed from `chartTheme`'s plot geometry, as in `LineChart`, because recharts 3 gives a chart's
* children no layout. They go inside the element recharts listens on, so its tooltip still follows
* the pointer over them.
*/
export function StackedBarChart({
ariaLabel, data, series, onPointSelect, selectedId, valueFormatter = formatNumber,
ariaLabel, data, series, lineSeries, onPointSelect, selectedId, valueFormatter = formatNumber,
height = 215, showLegend = true, showGrid = true, yTickCount = 5, allowDecimals = true,
totalLabel = "Total", unavailableLabel = "Unavailable", emptyLabel,
totalLabel = "Total", unavailableLabel = "Unavailable", emptyLabel, dataPointsLabel = defaultDataPointsLabel,
className, ...props
}: StackedBarChartProps) {
const zones = useRef<(SVGRectElement | null)[]>([]);
const [focusedId, setFocusedId] = useState<string | null>(null);
const [keyboardTooltip, setKeyboardTooltip] = useState<{ index: number; x: number; y: number } | null>(null);
// By id, not by position: the points can change while one of them has focus.
const [describedId, setDescribedId] = useState<string | null>(null);
// The element around the chart's <svg>: recharts 2 and 3 both size it to the chart and listen on it.
const [chart, setChart] = useState<HTMLElement | null>(null);
const anchor = useCallback((node: SVGGElement | null) => setChart(node?.ownerSVGElement?.parentElement ?? null), []);
const tooltipId = `ci-stacked-tooltip-${useId().replace(/:/g, "")}`;
const rovingId = data.some(datum => datum.id === focusedId) ? focusedId : data.some(datum => datum.id === selectedId) ? selectedId : data[0]?.id;
const safeData = useMemo(() => data.map(datum => ({ ...datum, values: Object.fromEntries(series.map(item => [item.key, measured(datum.values[item.key]) ? datum.values[item.key] : null])) })), [data, series]);
const lineKey = lineSeries?.key;
const safeData = useMemo(() => data.map(datum => ({ ...datum, values: Object.fromEntries([...series.map(item => item.key), ...(lineKey === undefined ? [] : [lineKey])].map(key => [key, measured(datum.values[key]) ? datum.values[key]! : null])) })), [data, series, lineKey]);
// One accessor per key, so the pointer tooltip can tell the line's entry from a bar's.
const lineValue = useMemo(() => lineKey === undefined ? undefined : (datum: ChartValues) => datum.values[lineKey], [lineKey]);
const line = lineSeries && lineValue ? { ...lineSeries, color: seriesColor(lineSeries, series.length), value: lineValue, format: lineSeries.valueFormatter ?? valueFormatter } : null;
const lineReading = (datum: ChartValues) => line ? measured(datum.values[line.key]) ? line.format(datum.values[line.key]!) : unavailableLabel : "";
const Plot = line ? ComposedChart : BarChart;
const describe = (datum: StackedBarDatum) => {
const values = series.map(item => datum.values[item.key]);
const sum = values.every(measured) ? values.reduce<number>((total, value) => total + value!, 0) : null;
return `${datum.tooltipLabel ?? datum.label}: ${series.map(item => `${item.label} ${measured(datum.values[item.key]) ? valueFormatter(datum.values[item.key]!) : unavailableLabel}`).join(", ")}. ${totalLabel} ${sum === null || !Number.isFinite(sum) ? unavailableLabel : valueFormatter(sum)}${datum.hint ? `. ${datum.hint}` : ""}`;
return `${datum.tooltipLabel ?? datum.label}: ${series.map(item => `${item.label} ${measured(datum.values[item.key]) ? valueFormatter(datum.values[item.key]!) : unavailableLabel}`).join(", ")}. ${totalLabel} ${sum === null || !Number.isFinite(sum) ? unavailableLabel : valueFormatter(sum)}${line ? `. ${line.label} ${lineReading(datum)}` : ""}${datum.hint ? `. ${datum.hint}` : ""}`;
};
const focused = keyboardTooltip ? safeData[keyboardTooltip.index] : undefined;
const keyboardIndex = describedId === null ? -1 : data.findIndex(datum => datum.id === describedId);
// The described point left the data: forget it, or its tooltip would reopen if the point came back.
if (describedId !== null && keyboardIndex < 0) setDescribedId(null);
const focused = keyboardIndex < 0 ? undefined : safeData[keyboardIndex];
const end = line ? lineAxisMargin.right + chartTheme.yAxis.width : plotEnd;
return <figure {...props} className={cn("ci-stacked-chart", className)} aria-label={ariaLabel}>
{(!data.length || !series.length) && emptyLabel != null ? <EmptyState compact title={emptyLabel} /> : <>
<div className="ci-stacked-chart__plot" style={{ height }}>
<ResponsiveContainer width="100%" height={height}>
<BarChart data={safeData} margin={chartTheme.margin} stackOffset="sign">
<Plot data={safeData} margin={line ? lineAxisMargin : chartTheme.margin} stackOffset="sign" accessibilityLayer={false}>
{showGrid && <CartesianGrid {...chartTheme.grid} />}
<XAxis dataKey="label" {...chartTheme.xAxis} />
<YAxis {...chartTheme.yAxis} tickCount={yTickCount} allowDecimals={allowDecimals} tickFormatter={valueFormatter} />
<Tooltip active={keyboardTooltip ? false : undefined} filterNull={false} cursor={false}
{line && <YAxis yAxisId={lineAxisId} orientation="right" {...chartTheme.yAxis} tickCount={yTickCount} tickFormatter={line.yTickFormatter ?? line.format} />}
<Tooltip active={focused ? false : undefined} filterNull={false} cursor={false} wrapperStyle={pointerTooltipStyle}
labelFormatter={(label, payload) => payload?.[0]?.payload?.tooltipLabel || label}
content={properties => <DefaultTooltipContent {...properties} payload={properties.payload?.map(entry => ({ ...entry, value: entry.value ?? unavailableLabel }))} formatter={(value, name) => [typeof value === "number" ? valueFormatter(value) : value, name]} />}
content={properties => <DefaultTooltipContent {...properties} itemSorter={inSeriesOrder} payload={properties.payload?.map(entry => ({ ...entry, value: line && (entry.dataKey as unknown) === line.value && typeof entry.value === "number" ? line.format(entry.value) : entry.value ?? unavailableLabel }))} formatter={(value, name) => [typeof value === "number" ? valueFormatter(value) : value, name]} />}
contentStyle={tooltipStyle} />
{series.map((item, index) => <Bar key={item.key} dataKey={datum => datum.values[item.key]} name={item.label} stackId="usage" fill={seriesColor(item, index)} maxBarSize={32} isAnimationActive={false} />)}
<Customized component={<ChartPointZones points={data} ariaLabel={ariaLabel} rovingId={rovingId} selectedId={selectedId} keyboardIndex={keyboardTooltip?.index} tooltipId={tooltipId} zones={zones} selectable={!!onPointSelect} describe={describe}
onPointSelect={onPointSelect} onFocused={id => setFocusedId(id)} onTooltip={setKeyboardTooltip} />} />
</BarChart>
{line && <Line {...chartTheme.line} {...lineHalo} yAxisId={lineAxisId} dataKey={line.value} connectNulls={false} />}
{line && <Line {...chartTheme.line} yAxisId={lineAxisId} dataKey={line.value} name={line.label} stroke={line.color} dot={seriesMarkers(safeData, { key: line.key, color: line.color, shape: "dot" })} activeDot={false} connectNulls={false} />}
{/* A plain SVG child is the one thing recharts 2 and 3 both render in place. */}
<g key="points" ref={anchor}>{chart && createPortal(<ChartPointZones points={data} end={end} ariaLabel={dataPointsLabel(ariaLabel)} rovingId={rovingId} selectedId={selectedId} describedId={describedId} tooltipId={tooltipId} selectable={!!onPointSelect} describe={describe}
onPointSelect={onPointSelect} onFocused={setFocusedId} onTooltip={setDescribedId} />, chart)}</g>
</Plot>
</ResponsiveContainer>
{focused && keyboardTooltip && <div id={tooltipId} role="tooltip" className="ci-stacked-chart__keyboard-tooltip" style={{ left: keyboardTooltip.x, top: keyboardTooltip.y }}>
<DefaultTooltipContent label={focused.tooltipLabel ?? focused.label} payload={series.map((item, index) => ({ name: item.label, value: focused.values[item.key] ?? unavailableLabel, color: seriesColor(item, index), graphicalItemId: item.key }))} formatter={(value, name) => [typeof value === "number" ? valueFormatter(value) : value, name]} contentStyle={tooltipStyle} />
{focused && <div id={tooltipId} role="tooltip" className="ci-stacked-chart__keyboard-tooltip" style={{ left: `max(0px, min(${plotX((keyboardIndex + .5) / data.length, end)} + 10px, 100% - ${end + keyboardTooltipWidth}px))`, top: chartTheme.margin.top + 12 }}>
<DefaultTooltipContent label={focused.tooltipLabel ?? focused.label} payload={[...series.map((item, index) => ({ name: item.label, value: focused.values[item.key] ?? unavailableLabel, color: seriesColor(item, index), graphicalItemId: item.key })), ...(line ? [{ name: line.label, value: lineReading(focused), color: line.color, graphicalItemId: `${lineAxisId}:${line.key}` }] : [])]} formatter={(value, name) => [typeof value === "number" ? valueFormatter(value) : value, name]} contentStyle={tooltipStyle} />
</div>}
</div>
{showLegend && <figcaption className="ci-stacked-chart__legend">{series.map((item, index) => <span key={item.key}><i aria-hidden style={{ background: seriesColor(item, index) }} /><span className="ci-stacked-chart__series">{item.icon && <span aria-hidden>{item.icon}</span>}{item.label}</span></span>)}</figcaption>}
{showLegend && <figcaption className="ci-stacked-chart__legend">{series.map((item, index) => <span key={item.key}><i aria-hidden style={{ background: seriesColor(item, index) }} /><span className="ci-stacked-chart__series">{item.icon && <span aria-hidden>{item.icon}</span>}{item.label}</span></span>)}{line && <span data-kind="line"><i aria-hidden style={{ background: line.color }} /><span className="ci-stacked-chart__series">{line.icon && <span aria-hidden>{line.icon}</span>}{line.label}</span></span>}</figcaption>}
</>}
</figure>;
}
@@ -153,14 +210,20 @@ export interface LineChartProps extends Omit<ComponentProps<"figure">, "children
showPoints?: boolean;
yTickCount?: number;
allowDecimals?: boolean;
/**
* Fixed Y axis range, such as `[0, 100]` for a rate. Without it the axis fits the data.
* A measurement outside the range widens the axis rather than being clipped.
*/
yDomain?: readonly [number, number];
/**
* Draw each line across its unavailable values instead of breaking it. The gap still reads as
* unavailable, and the measurements on each side of it are marked.
*/
connectNulls?: boolean;
unavailableLabel?: string;
emptyLabel?: string;
}
const plotStart = chartTheme.margin.left + chartTheme.yAxis.width;
const plotEnd = chartTheme.margin.right;
const plotSpan = (ratio: number) => `(100% - ${plotStart + plotEnd}px) * ${ratio}`;
const plotX = (ratio: number) => `calc(${plotStart}px + ${plotSpan(ratio)})`;
const pointRatio = (index: number, count: number) => count > 1 ? index / (count - 1) : .5;
interface LineMarkerProps { cx?: number | null; cy?: number | null; index: number }
@@ -171,6 +234,84 @@ function LineMarker({ cx, cy, shape, color }: { cx: number; cy: number; shape: L
return <rect {...paint} x={cx - 4.5} y={cy - 4.5} width={9} height={9} rx={1} transform={shape === "diamond" ? `rotate(45 ${cx} ${cy})` : undefined} />;
}
/**
* The recharts `dot` of one series. A measurement with a gap on both sides draws no segment, so it is
* always marked, as is every point of a series whose shape is not the plain dot. With `connectNulls`
* the measurements at each end of a bridged gap are marked too.
*/
function seriesMarkers(rows: readonly ChartValues[], item: { key: string; color: string; shape: LegendMarkerShape }, { showPoints = false, connectNulls = false } = {}) {
const known = rows.map(row => measured(row.values[item.key]));
const first = known.indexOf(true);
const last = known.lastIndexOf(true);
return (dot: unknown) => {
const { cx, cy, index } = dot as LineMarkerProps;
const gapBefore = !known[index - 1];
const gapAfter = !known[index + 1];
const shown = showPoints || item.shape !== "dot" || (gapBefore && gapAfter) || (connectNulls && ((gapBefore && index > first) || (gapAfter && index < last)));
return <g key={`${item.key}-${index}`}>{shown && typeof cx === "number" && typeof cy === "number" && known[index] ? <LineMarker cx={cx} cy={cy} shape={item.shape} color={item.color} /> : null}</g>;
};
}
interface PlotPoint { id: string; label: string; tooltipLabel?: string; hint?: string }
interface PlotPointsProps<Point extends PlotPoint> {
points: readonly Point[];
describe: (point: Point) => string;
/** The `<li>` rows of the tooltip for one point. */
rows: (point: Point) => ReactNode;
selectedId?: string | null;
onSelect?: (index: number) => void;
}
/**
* The HTML layer over a point-scale plot: one hit area per X position, the guide and the tooltip,
* all placed from `chartTheme`'s plot geometry.
*/
function PlotPoints<Point extends PlotPoint>({ points, describe, rows, selectedId, onSelect }: PlotPointsProps<Point>) {
const zones = useRef<(HTMLDivElement | null)[]>([]);
const [activeId, setActiveId] = useState<string | null>(null);
const [focusedId, setFocusedId] = useState<string | null>(null);
const indexOf = (id: string | null | undefined) => id == null ? -1 : points.findIndex(point => point.id === id);
const selectedIndex = indexOf(selectedId);
const focusedIndex = indexOf(focusedId);
const activeIndex = indexOf(activeId);
// A point that left the data is forgotten, so it takes back neither the tooltip nor the tab stop
// if it comes back. Reset while rendering, as React allows for a component's own state: no effect, no loop.
if (focusedId !== null && focusedIndex < 0) setFocusedId(null);
if (activeId !== null && activeIndex < 0) setActiveId(null);
const rovingId = focusedIndex >= 0 ? focusedId : selectedIndex >= 0 ? selectedId : points[0]?.id;
const active = points[activeIndex];
const activeRatio = pointRatio(activeIndex, points.length);
const last = points.length - 1;
return <>
{selectedIndex >= 0 && <span aria-hidden className="ci-line-chart__guide" data-selected style={{ left: plotX(pointRatio(selectedIndex, points.length)) }} />}
{active && <span aria-hidden className="ci-line-chart__guide" style={{ left: plotX(activeRatio) }} />}
{points.map((point, index) => {
const start = index === 0 ? 0 : (index - .5) / last;
const end = index === last ? 1 : (index + .5) / last;
return <div key={point.id} ref={node => { zones.current[index] = node; }} className="ci-line-chart__zone" role={onSelect ? "button" : "img"} aria-label={describe(point)} aria-pressed={onSelect ? selectedId === point.id : undefined} tabIndex={rovingId === point.id ? 0 : -1}
style={{ left: plotX(start), right: `calc(${plotEnd}px + ${plotSpan(1 - end)})` }}
onFocus={() => { setFocusedId(point.id); setActiveId(point.id); }} onBlur={() => setActiveId(null)}
onPointerEnter={() => setActiveId(point.id)} onPointerLeave={event => { if (event.pointerType !== "touch") setActiveId(null); }} onPointerDown={() => setActiveId(point.id)}
onClick={onSelect && (() => onSelect(index))}
onKeyDown={event => {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
const next = event.key === "ArrowRight" ? (index + 1) % points.length : event.key === "ArrowLeft" ? (index + last) % points.length : event.key === "Home" ? 0 : event.key === "End" ? last : null;
if (next !== null) { event.preventDefault(); zones.current[next]?.focus(); }
if ((event.key === "Enter" || event.key === " ") && onSelect) { event.preventDefault(); onSelect(index); }
if (event.key === "Escape") { event.preventDefault(); setActiveId(null); }
}} />;
})}
{active && <div role="tooltip" className="ci-line-chart__tooltip" data-side={activeRatio > .5 ? "start" : "end"} style={{ "--ci-line-chart-x": plotX(activeRatio) } as CSSProperties}>
<span className="ci-line-chart__tooltip-label">{active.tooltipLabel ?? active.label}</span>
<ul>{rows(active)}</ul>
{active.hint && <small>{active.hint}</small>}
</div>}
</>;
}
const seriesLabel = (item: ChartSeries) => item.icon ? <span className="ci-stacked-chart__series"><span aria-hidden>{item.icon}</span>{item.label}</span> : item.label;
/**
* Multi-series line or time-series chart. Recharts only draws the axes and lines; the hit areas,
* guide and tooltip are HTML placed from `chartTheme`'s plot geometry, because a recharts 3 chart
@@ -178,26 +319,15 @@ function LineMarker({ cx, cy, shape, color }: { cx: number; cy: number; shape: L
*/
export function LineChart({
ariaLabel, data, series, valueFormatter = formatNumber, yTickFormatter = valueFormatter, height = 240, showLegend = series.length > 1,
showGrid = true, showPoints = false, yTickCount = 5, allowDecimals = true, unavailableLabel = "Unavailable", emptyLabel,
showGrid = true, showPoints = false, yTickCount = 5, allowDecimals = true, yDomain, connectNulls = false, unavailableLabel = "Unavailable", emptyLabel,
className, ...props
}: LineChartProps) {
const zones = useRef<(HTMLDivElement | null)[]>([]);
const [activeId, setActiveId] = useState<string | null>(null);
const [focusedId, setFocusedId] = useState<string | null>(null);
const styled = series.map((item, index) => ({ ...item, color: item.color ?? chartSeries(index).color, shape: item.shape ?? chartSeries(index).shape }));
const safeData = useMemo(() => data.map(datum => ({ ...datum, values: Object.fromEntries(series.map(item => [item.key, measured(datum.values[item.key]) ? datum.values[item.key]! : null])) })), [data, series]);
const rovingId = safeData.some(datum => datum.id === focusedId) ? focusedId : safeData[0]?.id;
const activeIndex = safeData.findIndex(datum => datum.id === activeId);
const active = safeData[activeIndex];
const [low, high] = yDomain ?? [];
const domain = measured(low) && measured(high) && low < high ? [low, high] : undefined;
const reading = (value: number | null) => value === null ? unavailableLabel : valueFormatter(value);
const describe = (datum: LineChartDatum) => `${datum.tooltipLabel ?? datum.label}: ${series.map(item => `${item.label} ${reading(datum.values[item.key] ?? null)}`).join(", ")}${datum.hint ? `. ${datum.hint}` : ""}`;
const marker = (item: (typeof styled)[number]) => (dot: unknown) => {
const { cx, cy, index } = dot as LineMarkerProps;
const value = (offset: number) => safeData[index + offset]?.values[item.key] ?? null;
const shown = showPoints || item.shape !== "dot" || (value(-1) === null && value(1) === null);
return <g key={`${item.key}-${index}`}>{shown && typeof cx === "number" && typeof cy === "number" && value(0) !== null ? <LineMarker cx={cx} cy={cy} shape={item.shape} color={item.color} /> : null}</g>;
};
const activeRatio = pointRatio(activeIndex, safeData.length);
return <figure {...props} className={cn("ci-line-chart", className)} aria-label={ariaLabel}>
{(!data.length || !series.length) && emptyLabel != null ? <EmptyState compact title={emptyLabel} /> : <>
<div className="ci-line-chart__plot" style={{ height }}>
@@ -205,33 +335,78 @@ export function LineChart({
<RechartsLineChart data={safeData} margin={chartTheme.margin} accessibilityLayer={false}>
{showGrid && <CartesianGrid {...chartTheme.grid} />}
<XAxis dataKey="label" scale="point" {...chartTheme.xAxis} />
<YAxis {...chartTheme.yAxis} tickCount={yTickCount} allowDecimals={allowDecimals} tickFormatter={yTickFormatter} />
{styled.map(item => <Line key={item.key} {...chartTheme.line} dataKey={datum => datum.values[item.key]} name={item.label} stroke={item.color} dot={marker(item)} activeDot={false} connectNulls={false} />)}
<YAxis {...chartTheme.yAxis} {...(domain && { domain })} tickCount={yTickCount} allowDecimals={allowDecimals} tickFormatter={yTickFormatter} />
{styled.map(item => <Line key={item.key} {...chartTheme.line} dataKey={datum => datum.values[item.key]} name={item.label} stroke={item.color} dot={seriesMarkers(safeData, item, { showPoints, connectNulls })} activeDot={false} connectNulls={connectNulls} />)}
</RechartsLineChart>
</ResponsiveContainer>
{active && <span aria-hidden className="ci-line-chart__guide" style={{ left: plotX(activeRatio) }} />}
{safeData.map((datum, index) => {
const last = safeData.length - 1;
const start = index === 0 ? 0 : (index - .5) / last;
const end = index === last ? 1 : (index + .5) / last;
return <div key={datum.id} ref={node => { zones.current[index] = node; }} className="ci-line-chart__zone" role="img" aria-label={describe(datum)} tabIndex={rovingId === datum.id ? 0 : -1}
style={{ left: plotX(start), right: `calc(${plotEnd}px + ${plotSpan(1 - end)})` }}
onFocus={() => { setFocusedId(datum.id); setActiveId(datum.id); }} onBlur={() => setActiveId(null)}
onPointerEnter={() => setActiveId(datum.id)} onPointerLeave={event => { if (event.pointerType !== "touch") setActiveId(null); }} onPointerDown={() => setActiveId(datum.id)}
onKeyDown={event => {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
const next = event.key === "ArrowRight" ? (index + 1) % safeData.length : event.key === "ArrowLeft" ? (index + last) % safeData.length : event.key === "Home" ? 0 : event.key === "End" ? last : null;
if (next !== null) { event.preventDefault(); zones.current[next]?.focus(); }
if (event.key === "Escape") { event.preventDefault(); setActiveId(null); }
}} />;
})}
{active && <div role="tooltip" className="ci-line-chart__tooltip" data-side={activeRatio > .5 ? "start" : "end"} style={{ "--ci-line-chart-x": plotX(activeRatio) } as CSSProperties}>
<span className="ci-line-chart__tooltip-label">{active.tooltipLabel ?? active.label}</span>
<ul>{styled.map(item => <li key={item.key}><LegendMarker color={item.color} shape={item.shape} label={item.label} /><strong>{reading(active.values[item.key])}</strong></li>)}</ul>
{active.hint && <small>{active.hint}</small>}
</div>}
<PlotPoints points={safeData} describe={describe} rows={active => styled.map(item => <li key={item.key}><LegendMarker color={item.color} shape={item.shape} label={item.label} /><strong>{reading(active.values[item.key])}</strong></li>)} />
</div>
{showLegend && <figcaption className="ci-line-chart__legend">{styled.map(item => <LegendMarker key={item.key} color={item.color} shape={item.shape} label={item.icon ? <span className="ci-stacked-chart__series"><span aria-hidden>{item.icon}</span>{item.label}</span> : item.label} />)}</figcaption>}
{showLegend && <figcaption className="ci-line-chart__legend">{styled.map(item => <LegendMarker key={item.key} color={item.color} shape={item.shape} label={seriesLabel(item)} />)}</figcaption>}
</>}
</figure>;
}
export interface StackedAreaChartProps extends Omit<ComponentProps<"figure">, "children" | "onSelect"> {
ariaLabel: string;
/** One entry per X position, in axis order. The caller formats dates into `label`. */
data: readonly StackedBarDatum[];
/** Stacked in this order, from the axis up. Colours default to `chartSeries(index)`; pin `color` when a filter can remove series. */
series: readonly ChartSeries[];
/** The caller supplies already aggregated data and owns any filtering/navigation. */
onPointSelect?: (datum: StackedBarDatum, index: number) => void;
selectedId?: string | null;
valueFormatter?: (value: number) => string;
/** Compact Y axis text for the 48px axis, such as `1.2k`. Defaults to `valueFormatter`. */
yTickFormatter?: (value: number) => string;
height?: number;
showLegend?: boolean;
showGrid?: boolean;
yTickCount?: number;
allowDecimals?: boolean;
totalLabel?: string;
unavailableLabel?: string;
emptyLabel?: string;
}
const areaShape = "square" satisfies LegendMarkerShape;
/**
* Stacked areas over time: the `StackedBarChart` data, series and labels, with the `LineChart`
* points, tooltip and legend. Areas read as parts of a whole, so keep the values non-negative and
* use `StackedBarChart` for signed deltas.
*/
export function StackedAreaChart({
ariaLabel, data, series, onPointSelect, selectedId, valueFormatter = formatNumber, yTickFormatter = valueFormatter,
height = 240, showLegend = true, showGrid = true, yTickCount = 5, allowDecimals = true,
totalLabel = "Total", unavailableLabel = "Unavailable", emptyLabel,
className, ...props
}: StackedAreaChartProps) {
const styled = series.map((item, index) => ({ ...item, color: item.color ?? chartSeries(index).color }));
const safeData = useMemo(() => data.map(datum => ({ ...datum, values: Object.fromEntries(series.map(item => [item.key, measured(datum.values[item.key]) ? datum.values[item.key]! : null])) })), [data, series]);
const reading = (value: number | null | undefined) => measured(value) ? valueFormatter(value) : unavailableLabel;
const total = (datum: ChartValues) => {
const values = series.map(item => datum.values[item.key]);
return reading(values.every(measured) ? values.reduce<number>((sum, value) => sum + value, 0) : null);
};
const describe = (datum: StackedBarDatum) => `${datum.tooltipLabel ?? datum.label}: ${series.map(item => `${item.label} ${reading(datum.values[item.key])}`).join(", ")}. ${totalLabel} ${total(datum)}${datum.hint ? `. ${datum.hint}` : ""}`;
return <figure {...props} className={cn("ci-line-chart ci-stacked-area-chart", className)} aria-label={ariaLabel}>
{(!data.length || !series.length) && emptyLabel != null ? <EmptyState compact title={emptyLabel} /> : <>
<div className="ci-line-chart__plot" style={{ height }}>
<ResponsiveContainer width="100%" height={height}>
<AreaChart data={safeData} margin={chartTheme.margin} accessibilityLayer={false}>
{showGrid && <CartesianGrid {...chartTheme.grid} />}
<XAxis dataKey="label" scale="point" {...chartTheme.xAxis} />
<YAxis {...chartTheme.yAxis} tickCount={yTickCount} allowDecimals={allowDecimals} tickFormatter={yTickFormatter} />
{styled.map(item => <Area key={item.key} {...chartTheme.line} dataKey={datum => datum.values[item.key]} name={item.label} stackId="stack" stroke={item.color} fill={item.color} fillOpacity={.3} dot={seriesMarkers(safeData, { ...item, shape: "dot" })} activeDot={false} connectNulls={false} />)}
</AreaChart>
</ResponsiveContainer>
<PlotPoints points={safeData} describe={describe} selectedId={selectedId} onSelect={onPointSelect && (index => onPointSelect(data[index], index))}
rows={active => <>
{styled.map(item => <li key={item.key}><LegendMarker color={item.color} shape={areaShape} label={item.label} /><strong>{reading(active.values[item.key])}</strong></li>)}
<li className="ci-line-chart__tooltip-total"><span>{totalLabel}</span><strong>{total(active)}</strong></li>
</>} />
</div>
{showLegend && <figcaption className="ci-line-chart__legend">{styled.map(item => <LegendMarker key={item.key} color={item.color} shape={areaShape} label={seriesLabel(item)} />)}</figcaption>}
</>}
</figure>;
}
@@ -242,18 +417,38 @@ export interface SparklineProps extends Omit<ComponentProps<"div">, "children">
/** A label makes the sparkline informative; omit it for a decorative duplicate of nearby data. */
ariaLabel?: string;
color?: string;
/** Plot height in pixels. Defaults to 52. */
height?: number;
/** `area` (default) is the monotone line with a fading fill. `bar` draws one column per value from a zero baseline. */
variant?: SparklineVariant;
}
export function Sparkline({ values, ariaLabel, color = "var(--ci-color-success)", className, style, ...props }: SparklineProps) {
export type SparklineVariant = "area" | "bar";
const SPARKLINE_HEIGHT = 52;
/** Pixels a measured zero still gets in the bar variant, so it is not read as a missing value. */
const SPARKLINE_ZERO_MARK = 2;
const sparklineMargin = { top: 4, right: 2, bottom: 0, left: 2 };
export function Sparkline({ values, ariaLabel, color = "var(--ci-color-success)", height, variant = "area", className, style, ...props }: SparklineProps) {
const gradientId = `ci-sparkline-${useId().replace(/:/g, "")}`;
const hasMeasurements = values.some(value => value !== null && Number.isFinite(value));
return <div className={cn("ci-sparkline", className)} role={ariaLabel ? "img" : undefined} aria-label={ariaLabel} aria-hidden={ariaLabel ? undefined : true} style={{ color, ...style }} {...props}>
{hasMeasurements && <ResponsiveContainer width="100%" height={52}>
<AreaChart data={values.map(value => ({ value: value !== null && Number.isFinite(value) ? value : null }))} margin={{ top: 4, right: 2, bottom: 0, left: 2 }}>
const sized = typeof height === "number" && Number.isFinite(height) && height > 0;
const plotHeight = sized ? height : SPARKLINE_HEIGHT;
const data = values.map(value => ({ value: value !== null && Number.isFinite(value) ? value : null }));
const measurements = data.flatMap(point => point.value === null ? [] : [point.value]);
// reduce, not a spread: a long series would pass one argument per value to Math.min and Math.max.
const low = measurements.reduce((min, value) => Math.min(min, value), 0);
const high = measurements.reduce((max, value) => Math.max(max, value), 0);
return <div className={cn("ci-sparkline", className)} data-variant={variant === "bar" ? "bar" : undefined} role={ariaLabel ? "img" : undefined} aria-label={ariaLabel} aria-hidden={ariaLabel ? undefined : true} style={{ color, ...(sized && { height }), ...style }} {...props}>
{measurements.length > 0 && <ResponsiveContainer width="100%" height={plotHeight}>
{variant === "bar" ? <BarChart data={data} margin={sparklineMargin} barCategoryGap="20%">
<YAxis hide domain={low === high ? [0, 1] : [low, high]} />
<Bar dataKey="value" fill={color} isAnimationActive={false} minPointSize={value => value === null || value === undefined ? 0 : SPARKLINE_ZERO_MARK} />
</BarChart> : <AreaChart data={data} margin={sparklineMargin}>
<defs><linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor={color} stopOpacity={.25} /><stop offset="100%" stopColor={color} stopOpacity={0} /></linearGradient></defs>
<YAxis hide domain={["dataMin * 0.9", "dataMax * 1.1"]} />
<Area type="monotone" dataKey="value" stroke={color} fill={`url(#${gradientId})`} strokeWidth={2} dot={false} isAnimationActive={false} />
</AreaChart>
</AreaChart>}
</ResponsiveContainer>}
</div>;
}

View File

@@ -3,13 +3,15 @@
import { useId, useState } from "react";
import type { ComponentProps, ReactNode } from "react";
import { ChevronDown, X } from "lucide-react";
import { Badge } from "./badge";
import { Badge, type BadgeChartTone, type BadgeTone } from "./badge";
import { Button } from "./button";
import { cn } from "./lib/utils";
export interface ScopeChipProps extends Omit<ComponentProps<"div">, "onChange"> {
/** Filled carried filters remain the default; outline matches attachment chips for captured context. */
variant?: "secondary" | "outline";
/** Badge tone for a scope that carries a status or a chart series. `outline` draws its border in the tone, over the tint. */
tone?: BadgeTone | BadgeChartTone;
icon?: ReactNode;
/** Full inline scope replaces the truncated summary while expanded. */
details?: ReactNode;
@@ -25,7 +27,7 @@ export interface ScopeChipProps extends Omit<ComponentProps<"div">, "onChange">
/** Common presentation for carried filters and one captured chat context. */
export function ScopeChip({
variant = "secondary", icon, details, count, expanded: controlledExpanded, defaultExpanded = false,
variant = "secondary", tone, icon, details, count, expanded: controlledExpanded, defaultExpanded = false,
onExpandedChange, onRemove, expandLabel = "Context details", removeLabel = "Remove context",
children, className, ...props
}: ScopeChipProps) {
@@ -39,7 +41,7 @@ export function ScopeChip({
{!expanded && count != null && count > 0 && <span className="ci-scope-chip__count">+{count}</span>}
{expandable && <ChevronDown className="ci-scope-chip__chevron" aria-hidden="true" />}
</>;
return <Badge asChild variant={variant}><div {...props} data-slot="scope-chip" data-variant={variant} data-expanded={expanded || undefined} className={cn("ci-scope-chip", className)}>
return <Badge asChild variant={variant} tone={tone}><div {...props} data-slot="scope-chip" data-variant={variant} data-expanded={expanded || undefined} className={cn("ci-scope-chip", className)}>
{expandable ? <Button type="button" variant="ghost" size="sm" className="ci-scope-chip__summary" aria-label={expandLabel} aria-expanded={expanded} aria-controls={id} onClick={() => {
if (controlledExpanded === undefined) setLocalExpanded(!expanded);
onExpandedChange?.(!expanded);

View File

@@ -4,6 +4,7 @@ import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { Check, ChevronDown, Search } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger, type PopoverAlign } from "./popover";
import { Input } from "./input";
import { foldSearchText } from "./lib/search-fold";
import { cn } from "./lib/utils";
export interface SearchableSelectOption {
@@ -20,6 +21,20 @@ export interface SearchableSelectOption {
trailingLabel?: string;
}
/** Decides whether an option stays for a non-blank query. */
export type SearchableSelectFilter = (query: string, option: SearchableSelectOption) => boolean;
function matchesEveryWord(query: string, option: SearchableSelectOption) {
const text = foldSearchText(`${option.label} ${option.description ?? ""} ${option.keywords ?? ""} ${option.group ?? ""}`);
return foldSearchText(query).trim().split(/\s+/).every((word) => text.includes(word));
}
// Enter, Escape and the arrows belong to an input method while it composes. Key code 229 covers the
// browsers that end the composition before they send the keydown that confirmed it.
function fromInputMethod(event: { isComposing: boolean; keyCode: number }) {
return event.isComposing || event.keyCode === 229;
}
export interface SearchableSelectProps {
id?: string;
value: string;
@@ -39,6 +54,11 @@ export interface SearchableSelectProps {
optionLayout?: "default" | "model";
/** Always available at the end of the results, including an empty search. */
action?: { label: string; icon?: ReactNode; disabled?: boolean; onSelect: () => void };
/**
* Replaces the default filter, which keeps an option when every word of the query appears in its
* `label`, `description`, `keywords` or `group`, ignoring case and accents in any browser language.
*/
filter?: SearchableSelectFilter;
}
/** Single selection with searchable labels, descriptions, and aliases. */
@@ -46,21 +66,18 @@ export function SearchableSelect({
id, value, onValueChange, options, label = "Choose an option",
placeholder = "Select…", searchPlaceholder = "Search options…",
emptyMessage = "No matching options", disabled, className,
variant = "capsule", align = "start", optionLayout = "default", action,
variant = "capsule", align = "start", optionLayout = "default", action, filter = matchesEveryWord,
}: SearchableSelectProps) {
const listId = useId();
const input = useRef<HTMLInputElement>(null);
const actionSelected = useRef(false);
const list = useRef<HTMLDivElement>(null);
const composing = useRef(false);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const selected = options.find((option) => option.value === value);
const terms = query.toLocaleLowerCase().trim().split(/\s+/);
const matches = options.filter((option) => {
const text = `${option.label} ${option.description ?? ""} ${option.keywords ?? ""} ${option.group ?? ""}`.toLocaleLowerCase();
return terms.every((term) => text.includes(term));
});
const matches = query.trim() === "" ? options : options.filter((option) => filter(query, option));
const actionOption: SearchableSelectOption | undefined = action ? {
value: `${listId}-action`, label: action.label, icon: action.icon, disabled: action.disabled,
} : undefined;
@@ -83,6 +100,8 @@ export function SearchableSelect({
function changeOpen(next: boolean) {
setOpen(next);
// A composition cut short by closing never reports its end.
composing.current = false;
if (next) {
actionSelected.current = false;
setQuery("");
@@ -144,6 +163,7 @@ export function SearchableSelect({
</PopoverTrigger>
<PopoverContent className={cn("ci-searchable-select__popover", `ci-searchable-select__popover--${variant}`, optionLayout === "model" && "ci-searchable-select__popover--model")} align={align}
onCloseAutoFocus={(event) => { if (actionSelected.current) event.preventDefault(); }}
onEscapeKeyDown={(event) => { if (composing.current || fromInputMethod(event)) event.preventDefault(); }}
onOpenAutoFocus={(event) => { event.preventDefault(); input.current?.focus(); }}>
<div className="ci-searchable-select__search">
<Input ref={input} type="search" name="option-query" autoComplete="off" autoCorrect="off"
@@ -152,7 +172,10 @@ export function SearchableSelect({
aria-activedescendant={activeOption ? optionId(active) : undefined}
leadingIcon={<Search size={16} />} value={query} placeholder={searchPlaceholder}
onChange={(event) => { setQuery(event.target.value); setActive(0); }}
onCompositionStart={() => { composing.current = true; }}
onCompositionEnd={() => { composing.current = false; }}
onKeyDown={(event) => {
if (composing.current || fromInputMethod(event.nativeEvent)) return;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); move(event.key === "ArrowDown" ? 1 : -1);
} else if (event.key === "Enter") {

View File

@@ -4,8 +4,31 @@ import { useEffect, useId, useRef, useState, type ComponentProps, type ReactNode
import { Eye, EyeOff } from "lucide-react";
import { Alert } from "./alert";
import { Button } from "./button";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
/** Interface text of the reveal control. `label` and `errorMessage` stay separate props. */
export interface SecretValueLabels {
/** Button text while the value is masked. */
reveal: string;
/** Button text while the value is shown. */
hide: string;
/** Button text while `getValue` is pending. */
revealing: string;
/** Accessible name of the shown value, from `label`. */
revealed: (label: string) => string;
/** Accessible name of the masked value, from `label`. */
masked: (label: string) => string;
}
export const defaultSecretValueLabels: SecretValueLabels = {
reveal: "Reveal key",
hide: "Hide key",
revealing: "Revealing…",
revealed: (label) => `${label} (revealed)`,
masked: (label) => `${label} (masked)`,
};
export interface SecretValueProps extends Omit<ComponentProps<"div">, "children"> {
/** Stable identity of the credential. Changing it clears any revealed value. */
valueKey: string;
@@ -17,6 +40,8 @@ export interface SecretValueProps extends Omit<ComponentProps<"div">, "children"
errorMessage?: string;
/** Existing copy controls can stay independent of reveal state. */
actions?: ReactNode;
/** Localized interface text; missing or `undefined` keys fall back to defaultSecretValueLabels. */
labels?: Partial<SecretValueLabels>;
}
/** Explicit, transient secret display. Fetching and authorization belong to the consumer. */
@@ -25,7 +50,8 @@ export function SecretValue({ valueKey, ...props }: SecretValueProps) {
}
function SecretValueContent({ maskedValue, getValue, label = "API key", disabled = false,
errorMessage = "Could not reveal this value. Try again, or check your access.", actions, className, ...props }: Omit<SecretValueProps, "valueKey">) {
errorMessage = "Could not reveal this value. Try again, or check your access.", actions, labels: labelOverrides, className, ...props }: Omit<SecretValueProps, "valueKey">) {
const labels = resolveLabels(defaultSecretValueLabels, labelOverrides);
const id = useId();
const [secret, setSecret] = useState<string | null>(null);
const [pending, setPending] = useState(false);
@@ -63,12 +89,12 @@ function SecretValueContent({ maskedValue, getValue, label = "API key", disabled
return <div {...props} className={cn("ci-secret-value", className)} data-slot="secret-value">
<div className="ci-secret-value__row">
<code id={id} className="ci-secret-value__value ci-mask ph-no-capture" data-private="true" tabIndex={secret !== null ? 0 : undefined}
aria-label={`${label} (${secret !== null ? "revealed" : "masked"})`}>{secret ?? maskedValue}</code>
aria-label={secret !== null ? labels.revealed(label) : labels.masked(label)}>{secret ?? maskedValue}</code>
<div className="ci-secret-value__actions">
<Button type="button" variant="outline" size="sm" loading={pending} disableWhileLoading={false} disabled={disabled} aria-disabled={disabled || pending} aria-controls={id}
aria-pressed={secret !== null} onClick={() => void toggle()}>
{secret !== null ? <EyeOff aria-hidden /> : <Eye aria-hidden />}
{pending ? "Revealing…" : secret !== null ? "Hide key" : "Reveal key"}
{pending ? labels.revealing : secret !== null ? labels.hide : labels.reveal}
</Button>
{actions}
</div>

View File

@@ -0,0 +1,166 @@
"use client";
import { useEffect, useRef, useState } from "react";
import type { ComponentProps, KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";
import { cn } from "./lib/utils";
/**
* SegmentedControl — one value out of a few, shown as a capsule of segments.
*
* <SegmentedControl
* aria-label="Period"
* options={[{ value: "1d", label: "1d" }, { value: "7d", label: "7d" }]}
* value={period}
* onValueChange={setPeriod}
* />
*
* It is a `radiogroup`: the arrows move the selection, the group is one tab stop
* and each segment carries `aria-checked`. Use it when the choice changes a value
* (period, density, mode) and the content around it stays the same. When each
* choice shows a different panel, use [[tabs]] (`variant="capsule"` looks the
* same); for a form field with descriptions, use [[radio-group]].
*/
export type SegmentedControlSize = "default" | "sm";
export interface SegmentedControlOption<Value extends string = string> {
value: Value;
/** Visible text of the segment and its accessible name. */
label: ReactNode;
/** Decorative mark before the label; hidden from assistive technology. */
icon?: ReactNode;
disabled?: boolean;
}
/** A radiogroup has no visible label of its own, so one of the two is required. */
type SegmentedControlName =
| { "aria-label": string; "aria-labelledby"?: string }
| { "aria-label"?: string; "aria-labelledby": string };
export type SegmentedControlProps<Value extends string = string> = Omit<
ComponentProps<"div">,
"aria-label" | "aria-labelledby" | "children" | "defaultValue" | "onChange" | "role"
> &
SegmentedControlName & {
options: readonly SegmentedControlOption<Value>[];
value?: Value;
defaultValue?: Value;
/** Called with the new value; not called again for the segment that is already checked. */
onValueChange?: (value: Value) => void;
/** `"sm"` is the 24px segment for dense toolbars; `"default"` lines up with 36px controls. */
size?: SegmentedControlSize;
/** Disable every segment. */
disabled?: boolean;
};
/** Radio pattern: the arrows move the selection, not just the focus, and wrap around. */
function onRadioKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
// Alt/Ctrl/Cmd + arrow belong to the browser (history, word jumps).
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return;
const group = event.currentTarget;
const current = (event.target as Element).closest<HTMLButtonElement>('[role="radio"]');
const radios = Array.from(group.querySelectorAll<HTMLButtonElement>('[role="radio"]:not(:disabled)'));
const index = current ? radios.indexOf(current) : -1;
if (index === -1) return;
// Left and right follow what the eye sees, so they swap in a right-to-left group.
const inlineStep = getComputedStyle(group).direction === "rtl" ? -1 : 1;
let next = -1;
if (event.key === "ArrowDown") next = index + 1;
else if (event.key === "ArrowUp") next = index - 1;
else if (event.key === "ArrowRight") next = index + inlineStep;
else if (event.key === "ArrowLeft") next = index - inlineStep;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = radios.length - 1;
else return;
event.preventDefault();
const target = radios[(next + radios.length) % radios.length];
target.focus();
target.click();
}
/**
* A set too long for its container scrolls inside the capsule. Keep the checked segment
* fully in view there (it also grows a little when its label turns semibold), moving only
* the capsule's own scroll position, never the page.
*/
function revealSegment(segment: HTMLElement | null) {
const capsule = segment?.parentElement;
if (!segment || !capsule || capsule.scrollWidth <= capsule.clientWidth) return;
const style = getComputedStyle(capsule);
const view = capsule.getBoundingClientRect();
const box = segment.getBoundingClientRect();
const start = view.left + capsule.clientLeft + (parseFloat(style.paddingLeft) || 0);
const end = view.left + capsule.clientLeft + capsule.clientWidth - (parseFloat(style.paddingRight) || 0);
if (box.left < start) capsule.scrollLeft -= start - box.left;
else if (box.right > end) capsule.scrollLeft += box.right - end;
}
export function SegmentedControl<Value extends string = string>({
className,
options,
value: controlled,
defaultValue,
onValueChange,
size = "default",
disabled = false,
onKeyDown,
...props
}: SegmentedControlProps<Value>) {
const [uncontrolled, setUncontrolled] = useState<Value | undefined>(defaultValue);
const isControlled = controlled !== undefined;
const value = isControlled ? controlled : uncontrolled;
const checkedRef = useRef<HTMLButtonElement>(null);
// Keyed on where the checked segment sits, so options that arrive after the value still
// reveal it, while a re-render with the same options leaves the user's scroll alone.
const checkedIndex = options.findIndex((option) => option.value === value);
useEffect(() => revealSegment(checkedRef.current), [value, checkedIndex]);
function select(next: Value) {
if (next === value) return;
if (!isControlled) setUncontrolled(next);
onValueChange?.(next);
}
// Roving tab stop: the checked segment, or the first one that can take focus when
// nothing is checked (or the checked segment is disabled), so the group stays reachable.
const enabled = options.filter((option) => !disabled && !option.disabled);
const tabStop = (enabled.find((option) => option.value === value) ?? enabled[0])?.value;
return (
<div
role="radiogroup"
aria-disabled={disabled || undefined}
data-slot="segmented-control"
data-size={size}
className={cn("ci-segmented", className)}
onKeyDown={(event) => {
onKeyDown?.(event);
onRadioKeyDown(event);
}}
{...props}
>
{options.map((option) => {
const checked = option.value === value;
return (
<button
key={option.value}
ref={checked ? checkedRef : undefined}
type="button"
role="radio"
aria-checked={checked}
tabIndex={option.value === tabStop ? 0 : -1}
disabled={disabled || option.disabled}
data-slot="segmented-control-item"
data-active={checked || undefined}
className="ci-segmented__item"
onClick={() => select(option.value)}
>
{option.icon != null && <span className="ci-segmented__icon" aria-hidden="true">{option.icon}</span>}
<span className="ci-segmented__label">{option.label}</span>
</button>
);
})}
</div>
);
}

View File

@@ -0,0 +1,286 @@
"use client";
import type { ComponentProps, ReactNode } from "react";
import { AlertCircle, ArrowDown, Layers, MoreHorizontal, Pencil, Plus } from "lucide-react";
import { Badge, type BadgeTone } from "./badge";
import { Button } from "./button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "./dropdown-menu";
import { cn } from "./lib/utils";
export interface SellerCardAction {
label: string;
onSelect: () => void;
}
export interface SellerCardStatus {
label: string;
tone?: BadgeTone;
}
/** The dashboard supplies percentages and the localized description. */
export interface SellerCapUsageBarProps {
label: string;
segments: readonly number[];
forecast?: number;
calculating?: boolean;
}
interface SellerCardMetric {
label: string;
value: ReactNode;
}
export type SellerOfferVolume =
| {
kind: "capped";
label: string;
capName: string;
onCapSelect?: () => void;
usage: SellerCapUsageBarProps;
totals: readonly SellerCardMetric[];
explanation: ReactNode;
}
| {
kind: "uncapped";
onAdd?: () => void;
};
export interface SellerKeyOfferCardProps extends Omit<ComponentProps<"article">, "children"> {
provider: string;
providerMark?: ReactNode;
providerDetail: string;
privateNote?: string;
status: SellerCardStatus;
onEdit?: () => void;
onModels?: () => void;
offer: {
price: ReactNode;
detail: ReactNode;
};
volume: SellerOfferVolume;
earnings: {
label: string;
value: ReactNode;
detail: ReactNode;
models?: readonly string[];
};
capFooter: {
label: string;
name: string;
detail?: ReactNode;
action?: SellerCardAction;
};
expiry?: {
title: string;
detail: string;
};
}
export interface SellerVolumeCapCardProps extends Omit<ComponentProps<"article">, "children"> {
label: string;
name: string;
onNameSelect?: () => void;
status: SellerCardStatus;
actions?: readonly SellerCardAction[];
amount: ReactNode;
amountDetail: ReactNode;
usage: SellerCapUsageBarProps;
breakdown?: {
members: readonly SellerCardMetric[];
leftover: SellerCardMetric;
};
warning?: ReactNode;
memberLabel: string;
members: readonly string[];
dates: ReactNode;
footerAction?: SellerCardAction;
}
function SellerCapUsageBar({ label, segments, forecast = 0, calculating = false }: SellerCapUsageBarProps) {
let remaining = 100;
const widths = segments.map((segment) => {
const width = Number.isFinite(segment) ? Math.min(remaining, Math.max(0, segment)) : 0;
remaining -= width;
return width;
});
return (
<div
className="ci-seller-cap-usage"
data-calculating={calculating || undefined}
role="img"
aria-label={label}
>
{!calculating && widths.map((width, index) => (
<span aria-hidden="true" key={index} style={{ width: width + "%" }} />
))}
{!calculating && forecast > 0 && remaining > 0 && (
<span
aria-hidden="true"
className="ci-seller-cap-usage__forecast"
style={{ width: Math.min(remaining, forecast) + "%" }}
/>
)}
</div>
);
}
function OfferVolume({ volume }: { volume: SellerOfferVolume }) {
if (volume.kind === "uncapped") {
return (
<div className="ci-seller-offer-card__volume">
<small>Volume cap</small>
<h3>No volume cap</h3>
<p>This key isn’t limited by a volume cap.</p>
{volume.onAdd && (
<Button type="button" size="sm" variant="outline" onClick={volume.onAdd}>
<Plus size={14} />
Add a cap
</Button>
)}
</div>
);
}
return (
<div className="ci-seller-offer-card__volume">
<small>
{volume.label} ·{" "}
{volume.onCapSelect ? (
<button type="button" className="ci-seller-card__text-link" onClick={volume.onCapSelect}>
{volume.capName}
</button>
) : volume.capName}
</small>
<SellerCapUsageBar {...volume.usage} />
<div className="ci-seller-offer-card__totals">
{volume.totals.map(({ label, value }) => (
<span key={label}>{label} <b>{value}</b></span>
))}
</div>
<p>{volume.explanation}</p>
</div>
);
}
/** The visual summary of one seller key. Pricing, usage, and routing decisions are owned by the caller. */
export function SellerKeyOfferCard({
provider, providerMark, providerDetail, privateNote, status, onEdit, onModels, offer,
volume, earnings, capFooter, expiry, className, ...props
}: SellerKeyOfferCardProps) {
return (
<article data-ci-seller="" className={cn("ci-seller-card", "ci-seller-offer-card", className)} aria-label={provider + " key"} {...props}>
<div className="ci-seller-offer-card__header">
<div className="ci-seller-offer-card__inline">
{providerMark}
<div>
<strong>{provider}</strong>{" "}
<span className="ci-seller-card__muted">{providerDetail}</span>
{privateNote && <small className="ci-seller-offer-card__private-note">{privateNote}</small>}
</div>
</div>
<div className="ci-seller-offer-card__inline">
<Badge tone={status.tone}>{status.label}</Badge>
{onEdit && <Button type="button" size="sm" variant="outline" onClick={onEdit}><Pencil size={14} />Edit offer</Button>}
{onModels && <Button type="button" size="sm" variant="outline" onClick={onModels}><Layers size={14} />Models</Button>}
</div>
</div>
<div className="ci-seller-offer-card__body">
<div>
<small>Offer</small>
<h3>{offer.price}</h3>
<p>{offer.detail}</p>
{onEdit && (
<button type="button" className="ci-seller-card__text-link" onClick={onEdit}>
What would another price mean?
</button>
)}
</div>
<OfferVolume volume={volume} />
<div>
<small>{earnings.label}</small>
<h3>{earnings.value}</h3>
<p>{earnings.detail}</p>
{earnings.models?.map((model) => <p key={model}>{model}</p>)}
</div>
</div>
<div className="ci-seller-offer-card__footer">
<small>{capFooter.label}</small>
<strong>{capFooter.name}</strong>
{capFooter.detail && <span>{capFooter.detail}</span>}
{capFooter.action && (
<Button type="button" size="sm" variant="link" onClick={capFooter.action.onSelect}>
{capFooter.action.label}<ArrowDown size={14} />
</Button>
)}
</div>
{expiry && (
<div className="ci-seller-offer-card__expiry">
<AlertCircle size={16} />
<div><strong>{expiry.title}</strong><p>{expiry.detail}</p></div>
{onEdit && <Button type="button" size="sm" variant="outline" onClick={onEdit}>Edit offer</Button>}
</div>
)}
</article>
);
}
/** The visual summary of one volume cap. The dashboard controls cap changes and membership. */
export function SellerVolumeCapCard({
label, name, onNameSelect, status, actions, amount, amountDetail, usage, breakdown,
warning, memberLabel, members, dates, footerAction, className, ...props
}: SellerVolumeCapCardProps) {
return (
<article data-ci-seller="" className={cn("ci-seller-card", "ci-seller-cap-card", className)} tabIndex={-1} {...props}>
<header>
<div>
<small>{label}</small>
{onNameSelect ? (
<button type="button" className="ci-seller-cap-card__name" onClick={onNameSelect}>{name}</button>
) : <div className="ci-seller-cap-card__name">{name}</div>}
</div>
<Badge className="ci-seller-cap-card__status" tone={status.tone}>{status.label}</Badge>
{actions && actions.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="ghost" size="sm" aria-label={"Actions for " + name}>
<MoreHorizontal size={18} />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{actions.map(({ label, onSelect }) => (
<DropdownMenuItem key={label} onSelect={onSelect}>{label}</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
)}
</header>
<div className="ci-seller-cap-card__total">
<strong>{amount}</strong><span>{amountDetail}</span>
</div>
<SellerCapUsageBar {...usage} />
{breakdown && (
<div className="ci-seller-cap-card__breakdown">
{breakdown.members.map(({ label, value }) => (
<span key={label}><i aria-hidden="true" />{label} <b>{value}</b></span>
))}
<span>{breakdown.leftover.label} <b>{breakdown.leftover.value}</b></span>
</div>
)}
{warning && (
<div className="ci-seller-cap-card__warning" role="status">
<AlertCircle size={16} />
<span>{warning}</span>
</div>
)}
<div className="ci-seller-cap-card__members">
<small>{memberLabel}</small>
{members.map((member) => <span key={member}>{member}</span>)}
</div>
<footer>
<small>{dates}</small>
{footerAction && (
<Button type="button" size="sm" variant="outline" onClick={footerAction.onSelect}>{footerAction.label}</Button>
)}
</footer>
</article>
);
}

View File

@@ -0,0 +1,40 @@
import type { ComponentProps, ReactNode } from "react";
import { cn } from "./lib/utils";
export interface SellerEarningsMetric {
/** A unique label within this strip. */
label: string;
/** Already formatted by the caller, including currency, if applicable. */
value: ReactNode;
note: ReactNode;
}
export interface SellerEarningsSummaryStripProps extends ComponentProps<"div"> {
metrics: readonly SellerEarningsMetric[];
/** Overview uses four columns. Earnings and payments uses five. */
variant?: "overview" | "payments";
}
export function SellerEarningsSummaryStrip({
metrics,
variant = "overview",
className,
...props
}: SellerEarningsSummaryStripProps) {
return (
<div
{...props}
className={cn("ci-seller-earnings-summary-strip", className)}
data-ci-seller=""
data-variant={variant}
>
{metrics.map(({ label, value, note }) => (
<div key={label}>
<small>{label}</small>
<strong>{value}</strong>
<span>{note}</span>
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,203 @@
"use client";
import { Check, ChevronsUpDown, Clock3, Menu, Plus } from "lucide-react";
import { useState, type ReactNode, type Ref } from "react";
import { Badge } from "./badge";
import { Button } from "./button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "./dropdown-menu";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "./sheet";
export interface SellerOnboardingStep {
id: string;
label: ReactNode;
detail: ReactNode;
state?: "complete" | "pending" | "upcoming";
optionalLabel?: ReactNode;
disabled?: boolean;
}
export interface SellerOnboardingLayoutProps {
/** Slot for a banner or other app-owned chrome above the seller header. */
topBar?: ReactNode;
brand: ReactNode;
brandBadge?: ReactNode;
stepsLabel?: ReactNode;
steps: readonly SellerOnboardingStep[];
currentStep: string;
onStepSelect?: (id: string) => void;
progressLabel?: ReactNode;
railUtility?: ReactNode;
servingStatus?: {
label?: ReactNode;
title: ReactNode;
detail: ReactNode;
};
account?: {
initials: ReactNode;
name: ReactNode;
detail: ReactNode;
menu?: ReactNode;
};
children: ReactNode;
contentRef?: Ref<HTMLElement>;
backAction?: ReactNode;
actions?: ReactNode;
actionHint?: ReactNode;
navigationLabel?: string;
openNavigationLabel?: string;
navigationDescription?: ReactNode;
accountMenuLabel?: string;
}
/** Seller setup frame. Callers provide step state, forms and action handlers. */
export function SellerOnboardingLayout({
topBar,
brand,
brandBadge,
stepsLabel = "Seller setup",
steps,
currentStep,
onStepSelect,
progressLabel,
railUtility,
servingStatus,
account,
children,
contentRef,
backAction,
actions,
actionHint,
navigationLabel = "Navigation",
openNavigationLabel = "Open navigation",
navigationDescription = "Seller workspace",
accountMenuLabel = "Open account menu",
}: SellerOnboardingLayoutProps) {
const [navigationOpen, setNavigationOpen] = useState(false);
const accountDetails = account && (
<>
<span className="ci-seller-onboarding__avatar" aria-hidden="true">{account.initials}</span>
<div>
<strong>{account.name}</strong>
<small>{account.detail}</small>
</div>
</>
);
const navigation = (
<>
<p className="ci-seller-onboarding__steps-label">{stepsLabel}</p>
<nav className="ci-seller-onboarding__steps" aria-label={navigationLabel}>
{steps.map((step, index) => (
<button
type="button"
key={step.id}
aria-current={step.id === currentStep ? "step" : undefined}
data-optional={step.optionalLabel != null ? "" : undefined}
disabled={step.disabled || !onStepSelect}
onClick={() => {
onStepSelect?.(step.id);
setNavigationOpen(false);
}}
>
<span className="ci-seller-onboarding__step-marker" data-state={step.state} aria-hidden="true">
{step.state === "complete" ? <Check size={15} />
: step.state === "pending" ? <Clock3 size={15} />
: step.optionalLabel != null ? <Plus size={15} />
: index + 1}
</span>
<span>
<strong className="ci-seller-onboarding__step-title">
{step.label}
{step.optionalLabel != null && (
<Badge className="ci-seller-onboarding__step-badge" tone="neutral">{step.optionalLabel}</Badge>
)}
</strong>
<small>{step.detail}</small>
</span>
</button>
))}
</nav>
{railUtility && <div className="ci-seller-onboarding__rail-utility">{railUtility}</div>}
{servingStatus && (
<div className="ci-seller-onboarding__status">
<span>{servingStatus.label ?? "Serving status"}</span>
<strong>{servingStatus.title}</strong>
<p>{servingStatus.detail}</p>
</div>
)}
{account && (account.menu ? (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button type="button" className="ci-seller-onboarding__account" aria-label={accountMenuLabel}>
{accountDetails}
<ChevronsUpDown size={16} aria-hidden="true" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" className="ci-seller-onboarding__account-menu">
{account.menu}
</DropdownMenuContent>
</DropdownMenu>
) : (
<div className="ci-seller-onboarding__account">{accountDetails}</div>
))}
</>
);
return (
<div className="ci-seller-onboarding" data-ci-seller="">
{topBar && <div className="ci-seller-onboarding__top-bar">{topBar}</div>}
<header className="ci-seller-onboarding__brand-header">
<div>{brand}{brandBadge}</div>
{account && <small>{account.name}</small>}
</header>
<Sheet open={navigationOpen} onOpenChange={setNavigationOpen}>
<header className="ci-seller-onboarding__mobile-header">
<SheetTrigger asChild>
<Button variant="ghost" size="icon" aria-label={openNavigationLabel}>
<Menu aria-hidden="true" />
</Button>
</SheetTrigger>
{brand}
{progressLabel && <span className="ci-seller-onboarding__mobile-progress">{progressLabel}</span>}
</header>
<SheetContent side="left" className="ci-seller-onboarding__mobile-rail">
<SheetHeader>
<SheetTitle className="ci-seller-onboarding__drawer-title">{navigationLabel}</SheetTitle>
<SheetDescription>{navigationDescription}</SheetDescription>
</SheetHeader>
<div className="ci-seller-onboarding__rail-brand">{brand}{brandBadge}</div>
{navigation}
</SheetContent>
</Sheet>
<div className="ci-seller-onboarding__frame">
<aside className="ci-seller-onboarding__rail">{navigation}</aside>
<div className="ci-seller-onboarding__main">
<main className="ci-seller-onboarding__content" ref={contentRef}>{children}</main>
{(backAction || actions || actionHint) && (
<div className="ci-seller-onboarding__dock">
<footer className="ci-seller-onboarding__footer">
{backAction}
<div className="ci-seller-onboarding__actions">
{actionHint && <small>{actionHint}</small>}
{actions}
</div>
</footer>
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -6,8 +6,19 @@ import { ChevronDown } from "lucide-react";
import { SidebarMenuButton, SidebarMenuItem, useSidebar } from "./sidebar";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "./dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
/** Accessible name of the disclosure button, from the branch `label`. */
export interface SidebarBranchLabels {
expand: (label: string) => string;
collapse: (label: string) => string;
}
export const defaultSidebarBranchLabels: SidebarBranchLabels = {
expand: (label) => `Expand ${label}`,
collapse: (label) => `Collapse ${label}`,
};
export interface SidebarBranchItem {
id: string;
label: string;
@@ -29,10 +40,13 @@ export interface SidebarBranchProps {
/** Includes a selected descendant, even when filtering hides that child. */
active?: boolean;
className?: string;
/** Localized disclosure names; missing or `undefined` keys fall back to defaultSidebarBranchLabels. */
labels?: Partial<SidebarBranchLabels>;
}
/** A navigable parent with a separate disclosure; icon rails expose a menu. */
export function SidebarBranch({ label, badge, icon, link, items, open, onOpenChange, active = false, className }: SidebarBranchProps) {
export function SidebarBranch({ label, badge, icon, link, items, open, onOpenChange, active = false, className, labels: labelOverrides }: SidebarBranchProps) {
const labels = resolveLabels(defaultSidebarBranchLabels, labelOverrides);
const { state, isMobile } = useSidebar();
const submenuId = useId();
if (state === "collapsed" && !isMobile) {
@@ -67,7 +81,7 @@ export function SidebarBranch({ label, badge, icon, link, items, open, onOpenCha
<SidebarMenuButton asChild>{cloneElement(link, {}, icon, <span>{label}</span>)}</SidebarMenuButton>
{badge ? <span className="ci-sidebar__branch-badge">{badge}</span> : null}
<button type="button" className="ci-sidebar__branch-toggle"
aria-label={`${open ? "Collapse" : "Expand"} ${label}`} aria-expanded={open} aria-controls={submenuId}
aria-label={open ? labels.collapse(label) : labels.expand(label)} aria-expanded={open} aria-controls={submenuId}
onClick={() => onOpenChange(!open)}><ChevronDown aria-hidden="true" /></button>
</div>
<ul id={submenuId} className="ci-sidebar__submenu" hidden={!open} aria-label={label}>

View File

@@ -1,14 +1,16 @@
"use client";
import { cloneElement, createContext, forwardRef, isValidElement, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, version as reactVersion } from "react";
import { cloneElement, createContext, forwardRef, isValidElement, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { ComponentProps, ForwardedRef, MouseEvent as ReactMouseEvent, MutableRefObject, ReactElement, ReactNode } from "react";
import { PanelLeft } from "lucide-react";
import { ChevronDown, PanelLeft } from "lucide-react";
import { Sheet, SheetContent, SheetTitle } from "./sheet";
import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";
import { Slot } from "@radix-ui/react-slot";
import { TooltipContent, TooltipTrigger } from "./tooltip";
import { TooltipRoot } from "./lib/tooltip-root";
import { inertProps } from "./lib/inert";
import { cn } from "./lib/utils";
const DEFAULT_MOBILE_BREAKPOINT = 768;
const SUPPORTS_BOOLEAN_INERT = Number.parseInt(reactVersion, 10) >= 19;
export type SidebarState = "expanded" | "collapsed";
export type SidebarSide = "left" | "right";
@@ -28,6 +30,39 @@ export interface SidebarContextProps {
const SidebarContext = createContext<SidebarContextProps | null>(null);
const SidebarFocusContext = createContext<MutableRefObject<HTMLButtonElement | null> | null>(null);
const SidebarScopeContext = createContext<string | null>(null);
/** True while the enclosing `Sidebar` shows as the collapsed icon rail. */
const SidebarRailContext = createContext(false);
interface SidebarGroupContextValue {
open: boolean;
setOpen: (open: boolean) => void;
contentId: string;
/** On the collapsed icon rail the group shows its content and no trigger. */
rail: boolean;
}
/** Set by a collapsible `SidebarGroup`; null in a plain group. */
const SidebarGroupContext = createContext<SidebarGroupContextValue | null>(null);
const useIsomorphicLayoutEffect = typeof document === "undefined" ? useEffect : useLayoutEffect;
/**
* Hands focus to what replaced a focused control of a collapsible group. Call it from a layout
* effect cleanup of the part being removed or hidden: React runs that before the element leaves
* the document, whatever caused the change (the shortcut, a controlled `open`, a resize).
*/
function refocusInGroup(from: Element, selector: string) {
const group = from.closest(SIDEBAR_GROUP);
if (!group) return;
queueMicrotask(() => {
const active = document.activeElement;
// Focus is on another control: it moved on its own, or the element was kept. Leave it there.
if (!group.isConnected || (active && active !== document.body && active !== from)) return;
group.querySelector<HTMLElement>(selector)?.focus({ preventScroll: true });
});
}
const SIDEBAR_GROUP = '[data-slot="sidebar-group"]';
export function useSidebar() {
const context = useContext(SidebarContext);
@@ -175,13 +210,11 @@ export function Sidebar({
const mobileTriggerRef = useContext(SidebarFocusContext);
const scopeId = useContext(SidebarScopeContext);
const hiddenOffcanvas = !isMobile && collapsible === "offcanvas" && state === "collapsed";
const inertProps = hiddenOffcanvas || inertProp
? ({ inert: SUPPORTS_BOOLEAN_INERT ? true : "" } as unknown as ComponentProps<"aside">)
: {};
const rail = !isMobile && collapsible === "icon" && state === "collapsed";
const aside = (
<aside
{...props}
{...inertProps}
{...inertProps(hiddenOffcanvas || Boolean(inertProp))}
data-slot="sidebar"
data-state={isMobile || collapsible === "none" ? "expanded" : state}
data-side={side}
@@ -192,7 +225,7 @@ export function Sidebar({
aria-hidden={hiddenOffcanvas || ariaHidden || undefined}
className={cn("ci-sidebar", className)}
>
{children}
<SidebarRailContext.Provider value={rail}>{children}</SidebarRailContext.Provider>
</aside>
);
@@ -228,15 +261,129 @@ export function SidebarFooter({ className, ...props }: ComponentProps<"div">) {
export function SidebarSeparator({ className, ...props }: ComponentProps<"hr">) {
return <hr data-slot="sidebar-separator" className={cn("ci-sidebar__separator", className)} {...props} />;
}
export function SidebarGroup({ className, ...props }: ComponentProps<"section">) {
return <section data-slot="sidebar-group" className={cn("ci-sidebar__group", className)} {...props} />;
export interface SidebarGroupProps extends ComponentProps<"section"> {
/**
* Make `SidebarGroupLabel` a trigger that shows and hides `SidebarGroupContent`.
* On the collapsed icon rail the group shows its content and no trigger, as a plain group does.
*/
collapsible?: boolean;
/** Controlled open state of a collapsible group. */
open?: boolean;
/** Initial open state of an uncontrolled collapsible group. Default: open. */
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function SidebarGroupLabel({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="sidebar-group-label" className={cn("ci-sidebar__group-label", className)} {...props} />;
export function SidebarGroup({ className, collapsible = false, open: controlled, defaultOpen = true, onOpenChange, ...props }: SidebarGroupProps) {
const contentId = `${useId()}-content`;
const rail = useContext(SidebarRailContext);
const [uncontrolled, setUncontrolled] = useState(defaultOpen);
const open = controlled ?? uncontrolled;
const setOpen = useCallback((next: boolean) => {
if (controlled === undefined) setUncontrolled(next);
onOpenChange?.(next);
}, [controlled, onOpenChange]);
const group = useMemo<SidebarGroupContextValue | null>(
() => (collapsible ? { open, setOpen, contentId, rail } : null),
[collapsible, contentId, open, rail, setOpen],
);
return (
<SidebarGroupContext.Provider value={group}>
<section
data-slot="sidebar-group"
data-collapsible={collapsible || undefined}
data-state={collapsible ? (open ? "open" : "closed") : undefined}
className={cn("ci-sidebar__group", className)}
{...props}
/>
</SidebarGroupContext.Provider>
);
}
export function SidebarGroupContent({ className, ...props }: ComponentProps<"div">) {
return <div data-slot="sidebar-group-content" className={cn("ci-sidebar__group-content", className)} {...props} />;
export interface SidebarGroupLabelProps extends ComponentProps<"div"> {
/** In a collapsible group: replaces the chevron; `null` hides it. Decorative: it is hidden from assistive technology, so the trigger is named by the label alone. */
indicator?: ReactNode;
}
/** The label's button in a collapsible group. Removed on the icon rail; a focused one passes focus to the group's first item. */
function SidebarGroupTrigger({ group, indicator, children }: { group: SidebarGroupContextValue; indicator: ReactNode; children: ReactNode }) {
const { contentId } = group;
useIsomorphicLayoutEffect(() => () => {
const focused = document.activeElement;
if (focused?.getAttribute("data-slot") !== "sidebar-group-trigger" || focused.getAttribute("aria-controls") !== contentId) return;
refocusInGroup(focused, '[data-slot="sidebar-menu-button"]:not(:disabled)');
}, [contentId]);
return (
<button
type="button"
data-slot="sidebar-group-trigger"
data-state={group.open ? "open" : "closed"}
aria-expanded={group.open}
aria-controls={contentId}
className="ci-sidebar__group-trigger"
onClick={() => group.setOpen(!group.open)}
>
<span className="ci-sidebar__group-trigger-label">{children}</span>
{indicator === undefined
? <ChevronDown className="ci-sidebar__group-chevron" aria-hidden="true" />
: indicator != null && <span data-slot="sidebar-group-indicator" className="ci-sidebar__group-indicator" aria-hidden="true">{indicator}</span>}
</button>
);
}
/**
* Heading of a `SidebarGroup`. In a collapsible group its content becomes the trigger
* button (`aria-expanded`, `aria-controls`), named by that content; the props stay on the label.
*/
export function SidebarGroupLabel({ className, indicator, children, ...props }: SidebarGroupLabelProps) {
const group = useContext(SidebarGroupContext);
if (!group || group.rail) return <div data-slot="sidebar-group-label" className={cn("ci-sidebar__group-label", className)} {...props}>{children}</div>;
return (
<div data-slot="sidebar-group-label" data-collapsible="true" className={cn("ci-sidebar__group-label", className)} {...props}>
<SidebarGroupTrigger group={group} indicator={indicator}>{children}</SidebarGroupTrigger>
</div>
);
}
export interface SidebarGroupContentProps extends ComponentProps<"div"> {
/** In a collapsible group: keep closed children mounted (hidden). Default: render them only while open. */
keepMounted?: boolean;
}
/**
* The children of a collapsible group's content. When the group removes them, or hides them with
* `keepMounted`, a focused item passes focus to the group's trigger.
*/
function SidebarGroupItems({ contentId, hidden, children }: { contentId: string; hidden: boolean; children: ReactNode }) {
useIsomorphicLayoutEffect(() => () => {
// Runs when these items go away or `hidden` changes, before the content element is updated.
const focused = hidden ? null : document.activeElement;
if (focused?.closest('[data-slot="sidebar-group-content"]')?.id === contentId) refocusInGroup(focused, '[data-slot="sidebar-group-trigger"]');
}, [contentId, hidden]);
return <>{children}</>;
}
/** Body of a `SidebarGroup`, and the region a collapsible group shows and hides (it sets the `id`). */
export function SidebarGroupContent({ className, keepMounted = false, children, ...props }: SidebarGroupContentProps) {
const group = useContext(SidebarGroupContext);
if (!group) return <div data-slot="sidebar-group-content" className={cn("ci-sidebar__group-content", className)} {...props}>{children}</div>;
// On the icon rail the content is always shown, as in a plain group.
const open = group.open || group.rail;
return (
<div
{...props}
id={group.contentId}
data-slot="sidebar-group-content"
data-state={group.rail ? undefined : open ? "open" : "closed"}
hidden={!open}
className={cn("ci-sidebar__group-content", className)}
>
{open || keepMounted ? <SidebarGroupItems contentId={group.contentId} hidden={!open}>{children}</SidebarGroupItems> : null}
</div>
);
}
export function SidebarMenu({ className, ...props }: ComponentProps<"ul">) {
return <ul data-slot="sidebar-menu" className={cn("ci-sidebar__menu", className)} {...props} />;
}
@@ -250,8 +397,68 @@ export interface SidebarMenuButtonProps extends ComponentProps<"button"> {
asChild?: boolean;
}
/** What a tooltip trigger puts on its element: the handlers that drive the tooltip, and its state. */
type MenuTooltipHandlers = Pick<ComponentProps<"button">, "onPointerMove" | "onPointerLeave" | "onPointerDown" | "onFocus" | "onBlur" | "onClick">;
interface MenuTooltipState { "data-state"?: string; "aria-describedby"?: string }
interface SidebarMenuTooltipAnchorProps extends MenuTooltipHandlers, MenuTooltipState {
control: MutableRefObject<HTMLElement | null>;
handlers: MutableRefObject<MenuTooltipHandlers | null>;
setState: (update: (current: MenuTooltipState | null) => MenuTooltipState | null) => void;
}
function assignRef(ref: ForwardedRef<HTMLElement>, element: HTMLElement | null) {
if (typeof ref === "function") ref(element);
else if (ref) ref.current = element;
}
/** Handlers for the control that call whatever the mounted tooltip trigger currently has, and nothing without one. */
function delegateTo(handlers: MutableRefObject<MenuTooltipHandlers | null>): MenuTooltipHandlers {
const to = <Name extends keyof MenuTooltipHandlers>(name: Name) => ((event: never) => handlers.current?.[name]?.(event)) as MenuTooltipHandlers[Name];
return { onPointerMove: to("onPointerMove"), onPointerLeave: to("onPointerLeave"), onPointerDown: to("onPointerDown"), onFocus: to("onFocus"), onBlur: to("onBlur"), onClick: to("onClick") };
}
/**
* The rail tooltip's trigger, rendered beside the control instead of around it, so that mounting
* and unmounting the tooltip never remounts the control. It renders nothing and hands on what a
* trigger receives: the ref goes to the control's element, the handlers and the state attributes
* to `SidebarMenuButton`, which puts them on the control.
*/
const SidebarMenuTooltipAnchor = forwardRef<HTMLElement, SidebarMenuTooltipAnchorProps>(function SidebarMenuTooltipAnchor(
{ control, handlers, setState, "data-state": dataState, "aria-describedby": describedBy, onPointerMove, onPointerLeave, onPointerDown, onFocus, onBlur, onClick },
ref,
) {
const bound = useRef<{ ref: ForwardedRef<HTMLElement>; element: HTMLElement | null } | null>(null);
// After every commit: the trigger's handlers are new on each render, and an `asChild` control can change element.
useEffect(() => {
handlers.current = { onPointerMove, onPointerLeave, onPointerDown, onFocus, onBlur, onClick };
const element = control.current;
if (bound.current?.ref === ref && bound.current.element === element) return;
if (bound.current && bound.current.ref !== ref) assignRef(bound.current.ref, null);
bound.current = { ref, element };
assignRef(ref, element);
});
useEffect(() => {
// A closed tooltip is the resting state the button already renders, so it is not stored.
const next = dataState === "closed" && describedBy === undefined ? null : { "data-state": dataState, "aria-describedby": describedBy };
setState((current) => (current?.["data-state"] === next?.["data-state"] && current?.["aria-describedby"] === next?.["aria-describedby"] ? current : next));
}, [dataState, describedBy, setState]);
useEffect(() => () => {
if (bound.current) assignRef(bound.current.ref, null);
bound.current = null;
handlers.current = null;
setState(() => null);
}, [handlers, setState]);
return null;
});
export function SidebarMenuButton({ className, isActive = false, tooltip, asChild = false, children, onClick, ...props }: SidebarMenuButtonProps) {
const { state, isMobile, setOpenMobile } = useSidebar();
const tooltipActive = tooltip != null && state === "collapsed" && !isMobile;
const controlRef = useRef<HTMLElement | null>(null);
const tooltipHandlers = useRef<MenuTooltipHandlers | null>(null);
const [tooltipState, setTooltipState] = useState<MenuTooltipState | null>(null);
const classes = cn("ci-sidebar__menu-button", className);
const fallbackLabel = state === "collapsed" && !isMobile && typeof tooltip === "string" ? tooltip : undefined;
const finishInteraction = (event: ReactMouseEvent<HTMLElement>) => {
@@ -281,10 +488,24 @@ export function SidebarMenuButton({ className, isActive = false, tooltip, asChil
const hasSuppliedName = props["aria-label"] != null || props["aria-labelledby"] != null;
control = <button type="button" data-slot="sidebar-menu-button" data-active={isActive || undefined} aria-current={isActive ? "page" : undefined} aria-label={!hasSuppliedName ? fallbackLabel : undefined} className={classes} onClick={finishInteraction} {...props}>{children}</button>;
}
if (tooltip != null && state === "collapsed" && !isMobile) {
return <Tooltip><TooltipTrigger asChild>{control}</TooltipTrigger><TooltipContent side="right">{tooltip}</TooltipContent></Tooltip>;
}
return control;
if (tooltip == null) return control;
// The control keeps its place in every sidebar state; the tooltip mounts beside it on the collapsed
// rail only. Wrapping the control in the tooltip there would remount it and drop its focus.
const trigger = tooltipActive
? { "data-state": tooltipState?.["data-state"] ?? "closed", "aria-describedby": tooltipState?.["aria-describedby"], ...delegateTo(tooltipHandlers) }
: undefined;
return (
<>
<Slot ref={controlRef} {...(trigger as ComponentProps<typeof Slot> | undefined)}>{control}</Slot>
{tooltipActive ? (
// TooltipRoot joins a shared TooltipProvider when there is one, as every kit tooltip does.
<TooltipRoot>
<TooltipTrigger asChild><SidebarMenuTooltipAnchor control={controlRef} handlers={tooltipHandlers} setState={setTooltipState} /></TooltipTrigger>
<TooltipContent side="right">{tooltip}</TooltipContent>
</TooltipRoot>
) : null}
</>
);
}
export function SidebarMenuBadge({ className, ...props }: ComponentProps<"span">) {

View File

@@ -2,11 +2,11 @@
.ci-diagram-frame { position: relative; isolation: isolate; margin: 0; min-width: 0; overflow: hidden; color: var(--ci-color-heading); background: var(--ci-color-surface-subtle); border: 1px solid var(--ci-color-border); border-radius: 12px; box-shadow: 0 12px 36px -24px var(--ci-color-heading); }
.ci-diagram-frame::before { content: ""; position: absolute; inset: 0; z-index: -1; pointer-events: none; background: radial-gradient(280px circle at var(--ci-diagram-pointer-x, 50%) var(--ci-diagram-pointer-y, 50%), var(--ci-color-accent-surface-subtle), transparent 80%); opacity: .35; transition: opacity .25s; }
.ci-diagram-frame:hover::before, .ci-diagram-frame:focus-within::before { opacity: .75; }
.ci-diagram-frame-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 18px 22px; border-bottom: 1px solid var(--ci-color-border); font: 400 .625rem/1.5 var(--ci-font-mono); }
.ci-diagram-frame-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 18px 22px; border-bottom: 1px solid var(--ci-color-border); font: 400 var(--ci-font-size-3xs)/1.5 var(--ci-font-mono); }
.ci-diagram-frame-heading > :first-child { color: var(--ci-color-text-muted); }
.ci-diagram-frame-heading > :last-child { margin-left: auto; }
.ci-diagram-frame-heading > :last-child { margin-inline-start: auto; }
.ci-diagram-frame-controls { padding: 0 22px 22px; }
.ci-diagram-frame figcaption { padding: 13px 22px; border-top: 1px solid var(--ci-color-border); color: var(--ci-color-text-muted); font: 400 .625rem/1.6 var(--ci-font-mono); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-diagram-frame figcaption { padding: 13px 22px; border-top: 1px solid var(--ci-color-border); color: var(--ci-color-text-muted); font: 400 var(--ci-font-size-3xs)/1.6 var(--ci-font-mono); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-diagram { --ci-signal-on: var(--ci-lime-800); --ci-signal-packet: var(--ci-color-heading); position: relative; width: 100%; container-type: inline-size; background-image: radial-gradient(var(--ci-color-border) .65px, transparent .65px); background-size: 18px 18px; }
[data-theme="dark"] .ci-signal-diagram { --ci-signal-on: var(--ci-color-accent); --ci-signal-packet: var(--ci-color-accent); }
.ci-signal-diagram > .ci-signal-paths { position: absolute; display: block; inset: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }
@@ -34,23 +34,23 @@
.ci-signal-node[data-state="active"] .ci-signal-node-detail { color: var(--ci-neutral-950); }
.ci-signal-node[data-state="muted"] { color: var(--ci-color-text-muted); box-shadow: none; }
.ci-signal-node[data-state="blocked"] { border-style: dashed; }
.ci-signal-blocked { position: absolute; top: -7px; right: -6px; width: 18px; height: 18px; display: grid; place-items: center; border-radius: 50%; color: var(--ci-color-background); background: var(--ci-color-heading); font-size: 14px; }
.ci-signal-blocked { position: absolute; top: -7px; inset-inline-end: -6px; width: 18px; height: 18px; display: grid; place-items: center; border-radius: 50%; color: var(--ci-color-background); background: var(--ci-color-heading); font-size: 14px; }
.ci-signal-description { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
@keyframes ci-signal-travel { to { stroke-dashoffset: -100; } }
@media(max-width: 480px) {
.ci-diagram-frame-heading { padding: 15px; gap: 8px; font-size: .5rem; }
.ci-diagram-frame-controls { padding: 0 15px 18px; }
.ci-diagram-frame figcaption { padding: 12px 15px; }
.ci-signal-node { font-size: .6875rem; padding: 7px; min-height: 46px; min-width: 100px; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node-label { font-size: .6875rem; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node { font-size: var(--ci-font-size-2xs); padding: 7px; min-height: 46px; min-width: 100px; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node-label { font-size: var(--ci-font-size-2xs); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node-detail { font-size: .4375rem; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node[data-symbol] { min-height: 52px; min-width: 48px; }
.ci-signal-node[data-symbol] svg { width: 30px; height: 30px; }
}
/* Panel width matters in a product grid as much as the browser viewport. */
@container (max-width: 480px) {
.ci-signal-node { font-size: .6875rem; padding: 7px; min-height: 46px; min-width: 100px; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node-label { font-size: .6875rem; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node { font-size: var(--ci-font-size-2xs); padding: 7px; min-height: 46px; min-width: 100px; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node-label { font-size: var(--ci-font-size-2xs); font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node-detail { font-size: .4375rem; font-weight: var(--ci-font-weight-regular); line-height: var(--ci-type-caption-leading); letter-spacing: var(--ci-type-caption-tracking); }
.ci-signal-node[data-symbol] { min-height: 52px; min-width: 48px; }
.ci-signal-node[data-symbol] svg { width: 30px; height: 30px; }

View File

@@ -4,7 +4,9 @@ import { InfoTooltip } from "./info-tooltip";
import { cn } from "./lib/utils";
import { NumberTicker } from "./number-ticker";
export type StatTone = "default" | "positive" | "critical" | "warning";
export type StatTone = "default" | "positive" | "critical" | "warning" | "info" | "accent" | "muted";
/** `md` is the page summary size. `sm` is the compact size for key-value tiles inside cards and dense panels. */
export type StatSize = "sm" | "md";
export type StatAnimateFrom = "zero" | "previous";
export type StatFormat = "number" | "compact" | "currency" | "percent" | "text";
export type StatLabelVariant = "default" | "eyebrow";
@@ -21,7 +23,13 @@ interface StatBaseProps extends ComponentProps<"div"> {
/** Accessible name prefix of the info icon; the stat label is appended. Defaults to "More information". */
infoLabel?: string;
suffix?: ReactNode;
/** Colors the value. `info`, `accent` and `muted` sit next to `positive`, `critical` and `warning`. */
tone?: StatTone;
/**
* `sm` shrinks the tile: 16px value in the UI font, 12px label, tighter padding. Formatting,
* `suffix`, `hint`, `info`, `icon` and `animate` are unchanged. Omit it to follow the StatRow.
*/
size?: StatSize;
currency?: string;
/** Locale used by both static and animated number formatting. */
locale?: string;
@@ -65,6 +73,7 @@ export function Stat({
infoLabel = "More information",
suffix,
tone = "default",
size,
format = "number",
currency = "USD",
locale,
@@ -86,6 +95,7 @@ export function Stat({
<div
data-label-variant={labelVariant}
data-value-format={format}
data-size={size}
className={cn("ci-stat", `ci-stat--${tone}`, className)}
{...props}
>
@@ -124,8 +134,10 @@ export function Stat({
export interface StatRowProps extends ComponentProps<"div"> {
columns?: 2 | 3 | 4;
/** Size of every Stat inside the row. A Stat with its own `size` keeps it. */
size?: StatSize;
}
export function StatRow({ className, columns = 4, ...props }: StatRowProps) {
return <div data-columns={columns} className={cn("ci-stat-row", className)} {...props} />;
export function StatRow({ className, columns = 4, size, ...props }: StatRowProps) {
return <div data-columns={columns} data-size={size} className={cn("ci-stat-row", className)} {...props} />;
}

View File

@@ -2,6 +2,7 @@
import type { ComponentProps, ReactNode } from "react";
import { BrandLoader } from "./brand-loader";
import { inertProps } from "./lib/inert";
import { cn } from "./lib/utils";
export interface TableLoadingRegionProps extends ComponentProps<"div"> {
@@ -27,7 +28,7 @@ export function TableLoadingRegion({
data-loading={loading ? "true" : undefined}
className={cn("ci-table-loading-region", className)}
>
<div data-slot="table-loading-content" aria-busy={loading} inert={loading || undefined} aria-hidden={loading || undefined}>
<div data-slot="table-loading-content" aria-busy={loading} {...inertProps(loading)} aria-hidden={loading || undefined}>
{children}
</div>
{loading ? (

View File

@@ -0,0 +1,278 @@
import { createContext, useContext, useEffect, useLayoutEffect, useReducer, useState } from "react";
/**
* How the interactive rows of a table take keyboard focus. `"each"` makes every row its own tab
* stop. `"roving"` gives the rows one tab stop between them and moves focus with the arrow keys.
*/
export type TableRowFocus = "each" | "roving";
// React 18 warns about useLayoutEffect during server rendering.
export const useClientLayoutEffect = typeof document === "undefined" ? useEffect : useLayoutEffect;
/**
* What can be a tab stop inside a row. Deliberately wide, and not narrowed by the `tabIndex`
* getter, which answers -1 for an editing host and for media controls that Tab does stop on.
*/
const TAB_CANDIDATE_SELECTOR = [
"a[href]",
"area[href]",
"button",
"input",
"select",
"textarea",
"summary",
"iframe",
"object",
"embed",
"audio[controls]",
"video[controls]",
'[contenteditable]:not([contenteditable="false"])',
"[tabindex]",
].join(", ");
/** `Node.DOCUMENT_POSITION_PRECEDING`, spelled out because `Node` belongs to one realm. */
const DOCUMENT_POSITION_PRECEDING = 2;
/** Rows moved by Page Up and Page Down when the row or its viewport cannot be measured. */
const FALLBACK_PAGE_STEP = 10;
type TabStopListener = (isTabStop: boolean) => void;
/** The part of a keydown event the row navigation reads. */
export interface TableRowFocusKey {
key: string;
altKey: boolean;
ctrlKey: boolean;
metaKey: boolean;
shiftKey: boolean;
preventDefault: () => void;
}
/** Whether focus can land on the row: rendered, and not hidden or inert, itself or through an ancestor. */
function takesFocus(row: HTMLTableRowElement) {
if (row.closest("[hidden], [inert]")) return false;
// Both spellings of the option: `visibilityProperty` is the newer name of `checkVisibilityCSS`.
if (typeof row.checkVisibility === "function") return row.checkVisibility({ checkVisibilityCSS: true, visibilityProperty: true });
// Browsers from before checkVisibility (Safari 17.3 and older). A row without boxes is not
// rendered, unless the body has none either: then there is no layout to ask (a test DOM).
const ownerDocument = row.ownerDocument;
if (!row.getClientRects().length && ownerDocument.body.getClientRects().length) return false;
// `visibility` is inherited, so the row's own computed value also answers for its ancestors.
return (ownerDocument.defaultView?.getComputedStyle(row).visibility ?? "visible") === "visible";
}
/** Rows between the top of one screen and the top of the next, keeping one row of context. */
function pageStep(row: HTMLTableRowElement) {
const rowHeight = row.getBoundingClientRect().height;
const container = row.closest<HTMLElement>('[data-slot="table-container"]');
// A capped table scrolls its own container, under a pinned header; any other table scrolls the page.
const viewport = container && container.scrollHeight > container.clientHeight
? container.clientHeight - (row.closest("table")?.tHead?.getBoundingClientRect().height ?? 0)
: row.ownerDocument.defaultView?.innerHeight ?? 0;
if (!(rowHeight > 0) || !(viewport > 0)) return FALLBACK_PAGE_STEP;
return Math.max(1, Math.floor(viewport / rowHeight) - 1);
}
/**
* The interactive rows of one `Table rowFocus="roving"`. It decides which row is the tab stop,
* moves focus between rows, keeps the rows' own controls out of the tab order while their row is
* not the current one, and puts focus back on a row when the focused one is removed.
*/
export class TableRowFocusGroup {
private readonly rows = new Map<HTMLTableRowElement, TabStopListener>();
/** The row that last held focus, until it leaves or the selection moves while focus is elsewhere. */
private lastFocused: HTMLTableRowElement | null = null;
/** The row that currently renders `tabindex="0"`. */
private tabStop: HTMLTableRowElement | null = null;
/** Set when a row is removed with focus inside it: where it was among the rows. */
private removedWithFocus: { row: HTMLTableRowElement; index: number } | null = null;
private releaseHeldControls: (() => void) | null = null;
/** `requestSettle` asks the owning `Table` to call `settle()` once the current commit is done. */
constructor(private readonly requestSettle: () => void) {}
/**
* The rows focus can land on, in document order. Read from the DOM each time: rows can be
* moved, hidden and shown without remounting.
*/
private ordered() {
return [...this.rows.keys()].filter(takesFocus).sort((a, b) => (a.compareDocumentPosition(b) & DOCUMENT_POSITION_PRECEDING ? 1 : -1));
}
private setTabStop(next: HTMLTableRowElement | null) {
if (next === this.tabStop) return;
if (this.tabStop) this.rows.get(this.tabStop)?.(false);
if (next) this.rows.get(next)?.(true);
this.tabStop = next;
}
register(row: HTMLTableRowElement, listener: TabStopListener) {
this.rows.set(row, listener);
this.requestSettle();
return () => {
const active = row.ownerDocument.activeElement;
if (active && row.contains(active)) this.removedWithFocus = { row, index: this.ordered().indexOf(row) };
this.rows.delete(row);
if (this.lastFocused === row) this.lastFocused = null;
if (this.tabStop === row) this.tabStop = null;
// The row may stay mounted (it lost `onActivate`, or the table left roving focus).
listener(false);
this.requestSettle();
};
}
/** Focus entered the row or a control inside it: the row is the tab stop from now on. */
focused(row: HTMLTableRowElement) {
if (!this.rows.has(row)) return;
this.lastFocused = row;
this.setTabStop(row);
}
/** A row became selected or stopped being selected. */
selectionChanged(row: HTMLTableRowElement, selected: boolean) {
// A selection made while focus is elsewhere (a detail panel stepping to the next row) is where
// Tab should come back to; one made from inside the table leaves focus where the user has it.
if (selected && this.lastFocused && !this.lastFocused.contains(row.ownerDocument.activeElement)) this.lastFocused = null;
this.requestSettle();
}
/**
* Runs after every commit of the table, after rows were added, removed or reselected, and
* before each Tab. Restores focus when the focused row was removed, then points the tab stop at
* the row that last had focus, or else at the selected row, or else at the first one. A row
* that cannot take focus (hidden, not rendered) is passed over.
*/
settle() {
const rows = this.ordered();
const removed = this.removedWithFocus;
this.removedWithFocus = null;
if (removed && rows.length && !removed.row.isConnected) {
const ownerDocument = removed.row.ownerDocument;
const active = ownerDocument.activeElement;
// Only when focus really fell to the document: never take it from whatever claimed it.
if (!active || active === ownerDocument.body) rows[Math.min(Math.max(removed.index, 0), rows.length - 1)].focus();
}
const kept = this.lastFocused && rows.includes(this.lastFocused) ? this.lastFocused : null;
this.setTabStop(kept ?? rows.find((row) => row.getAttribute("aria-selected") === "true") ?? rows[0] ?? null);
}
/**
* Arrow Up and Down, Home, End, Page Up and Page Down pressed on `row`. Returns true when focus
* moved. At either end the key is left alone, so it scrolls as it would anywhere else (and can
* bring the trigger of an infinite list into view).
*/
navigate(row: HTMLTableRowElement, event: TableRowFocusKey) {
if (event.altKey || event.metaKey || event.shiftKey) return false;
const toEdge = event.key === "Home" || event.key === "End";
if (event.ctrlKey && !toEdge) return false;
if (!toEdge && !["ArrowDown", "ArrowUp", "PageDown", "PageUp"].includes(event.key)) return false;
const rows = this.ordered();
const index = rows.indexOf(row);
if (index < 0) return false;
const last = rows.length - 1;
const target = event.key === "ArrowDown" ? index + 1
: event.key === "ArrowUp" ? index - 1
: event.key === "Home" ? 0
: event.key === "End" ? last
: event.key === "PageDown" ? Math.min(last, index + pageStep(row))
: Math.max(0, index - pageStep(row));
const next = rows[target];
if (!next || next === row) return false;
event.preventDefault();
next.focus();
return true;
}
/**
* Listens for Tab on the document of the table. While the browser works out where that Tab
* goes, the controls inside every row but the current one carry `tabindex="-1"`, so sequential
* focus skips them: Tab from the row walks that row's own controls and then leaves the table,
* and Tab from outside lands on the current row. Their own `tabindex` is back before the
* keydown task ends, when focus moves or, if it does not, on the next timer. The browser still
* picks the target, so the order outside the rows is exactly its own.
*/
watchTab(container: HTMLElement) {
const ownerDocument = container.ownerDocument;
const view = ownerDocument.defaultView;
const rowOf = (start: Element | null) => {
for (let node = start; node && node !== container; node = node.parentElement) {
if (this.rows.has(node as HTMLTableRowElement)) return node as HTMLTableRowElement;
}
return null;
};
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Tab") return;
this.releaseHeldControls?.();
// A row hidden or moved without a render (a class, a media query) may hold the tab stop.
// React applies the new one before the browser acts on this key.
this.settle();
const current = rowOf(ownerDocument.activeElement) ?? this.tabStop;
// Each control with the `tabindex` attribute it had, to put back.
const held: Array<[HTMLElement, string | null]> = [];
for (const control of container.querySelectorAll<HTMLElement>(TAB_CANDIDATE_SELECTOR)) {
const tabIndex = control.getAttribute("tabindex");
// Already out of the tab order by its own attribute.
if (tabIndex !== null && Number.parseInt(tabIndex, 10) < 0) continue;
// From the parent: a row matches the selector too, and is no control of its own.
const row = rowOf(control.parentElement);
if (!row || row === current) continue;
held.push([control, tabIndex]);
}
if (!held.length) return;
for (const [control] of held) control.setAttribute("tabindex", "-1");
// Whatever writes `tabindex` on a held control from here on is the app, and its value stands.
const written = new Set<Node>();
const note = (records: MutationRecord[]) => { for (const record of records) written.add(record.target); };
const appWrites = view && typeof view.MutationObserver === "function" ? new view.MutationObserver(note) : null;
appWrites?.observe(container, { attributes: true, attributeFilter: ["tabindex"], subtree: true });
let timer: number | undefined;
const release = () => {
if (this.releaseHeldControls !== release) return;
this.releaseHeldControls = null;
if (appWrites) note(appWrites.takeRecords());
appWrites?.disconnect();
for (const [control, tabIndex] of held) {
if (written.has(control)) continue;
if (tabIndex === null) control.removeAttribute("tabindex");
else control.setAttribute("tabindex", tabIndex);
}
ownerDocument.removeEventListener("focusin", release, true);
ownerDocument.removeEventListener("focusout", release, true);
view?.clearTimeout(timer);
};
this.releaseHeldControls = release;
// The browser has chosen the target by the time either event fires.
ownerDocument.addEventListener("focusin", release, true);
ownerDocument.addEventListener("focusout", release, true);
// Tab that moves nothing (cancelled, or focus leaves for the browser's own UI).
timer = view?.setTimeout(release, 0);
};
ownerDocument.addEventListener("keydown", onKeyDown, true);
return () => {
ownerDocument.removeEventListener("keydown", onKeyDown, true);
this.releaseHeldControls?.();
};
}
}
export const TableRowFocusContext = createContext<TableRowFocusGroup | null>(null);
/** The roving group of the nearest `Table`, or null when its rows are each their own tab stop. */
export function useTableRowFocusGroup() {
return useContext(TableRowFocusContext);
}
/** Creates the group of a `Table` and keeps it settled. Returns null unless `rowFocus` is `"roving"`. */
export function useTableRowFocusProvider(rowFocus: TableRowFocus | undefined, container: HTMLElement | null) {
const roving = rowFocus === "roving";
// Rows report changes from their own effects, which can commit without Table rendering: the
// request renders it. Rows that only changed place (a sort) report nothing, so every commit of
// a roving Table settles.
const [, requestSettle] = useReducer((count: number) => count + 1, 0);
const [group] = useState(() => new TableRowFocusGroup(requestSettle));
useClientLayoutEffect(() => {
if (roving) group.settle();
});
useEffect(() => (roving && container ? group.watchTab(container) : undefined), [group, roving, container]);
return roving ? group : null;
}

View File

@@ -1,17 +1,22 @@
"use client";
import {
createContext,
useContext,
useEffect,
useId,
useMemo,
useRef,
useState,
type ComponentProps,
type KeyboardEvent,
type PointerEvent,
type ReactNode,
type RefObject,
} from "react";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
import { TableScrollAreaContext } from "./table-scroll-context";
import { TableScrollAreaContext, TableScrollAreaNameContext } from "./table-scroll-context";
type ScrollbarMetrics = {
maximum: number;
@@ -31,13 +36,40 @@ function clamp(value: number, minimum: number, maximum: number): number {
return Math.min(maximum, Math.max(minimum, value));
}
/** Interface text of the persistent scrollbar. */
export interface TableScrollAreaLabels {
/** Accessible name of the scrollbar, built from `scrollbarLabel`. */
scrollbar: (label: string) => string;
}
export const defaultTableScrollAreaLabels: TableScrollAreaLabels = {
scrollbar: (label) => `Top ${label} horizontal scrollbar`,
};
const TableScrollAreaLabelsContext = createContext(defaultTableScrollAreaLabels);
export interface TableScrollAreaLabelsProviderProps {
/** Missing or `undefined` keys keep the value of the provider above, or the English default. */
labels: Partial<TableScrollAreaLabels>;
children?: ReactNode;
}
/**
* Sets the scrollbar text once for every Table and TableScrollArea below it, so an app does not
* repeat `labels` on each table. A `labels` prop on a table still wins.
*/
export function TableScrollAreaLabelsProvider({ labels, children }: TableScrollAreaLabelsProviderProps) {
const inherited = useContext(TableScrollAreaLabelsContext);
const resolved = useMemo(() => resolveLabels(inherited, labels), [inherited, labels]);
return <TableScrollAreaLabelsContext.Provider value={resolved}>{children}</TableScrollAreaLabelsContext.Provider>;
}
function PersistentTableScrollbar({
areaRef,
label,
name,
targetId,
}: {
areaRef: RefObject<HTMLDivElement | null>;
label: string;
name: string;
targetId: string;
}) {
const targetRef = useRef<HTMLElement | null>(null);
@@ -85,9 +117,18 @@ function PersistentTableScrollbar({
const table = target.querySelector("table");
if (table) resizeObserver.observe(table);
// Cell content can widen a fixed-layout table past its container without resizing either
// observed box. The metrics decide whether the bar is a tab stop, so remeasure on content
// changes too (one layout read per batch of mutations), as Table does for its container.
const mutationObserver = typeof MutationObserver === "undefined" ? undefined : new MutationObserver(sync);
if (table) {
mutationObserver?.observe(table, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ["style", "class"] });
}
return () => {
target.removeEventListener("scroll", sync);
resizeObserver.disconnect();
mutationObserver?.disconnect();
targetRef.current = null;
};
}, [areaRef, targetId]);
@@ -162,24 +203,29 @@ function PersistentTableScrollbar({
};
};
// With nothing to scroll the bar keeps its box, so the layout does not shift, but it is neither
// a tab stop nor a scrollbar a screen reader can find. The server renders this state.
const overflowing = metrics.maximum > 0;
return (
<div
data-slot="table-scrollbar"
className="ci-table-scrollbar"
role="scrollbar"
aria-label={`Top ${label} horizontal scrollbar`}
aria-label={name}
aria-controls={targetId}
aria-orientation="horizontal"
aria-valuemin={0}
aria-valuemax={Math.round(metrics.maximum)}
aria-valuenow={Math.round(metrics.value)}
tabIndex={0}
aria-hidden={overflowing ? undefined : true}
tabIndex={overflowing ? 0 : undefined}
onKeyDown={handleKeyDown}
>
<div
ref={trackRef}
className="ci-table-scrollbar__track"
data-overflowing={metrics.maximum > 0 ? "true" : "false"}
data-overflowing={overflowing ? "true" : "false"}
onPointerDown={(event) => scrollFromTrack(event.clientX)}
>
<div
@@ -211,8 +257,13 @@ function PersistentTableScrollbar({
}
export interface TableScrollAreaProps extends ComponentProps<"div"> {
/** Accessible noun phrase used to label the persistent horizontal scrollbar. */
/**
* Accessible noun phrase used to label the persistent horizontal scrollbar. A Table inside
* with no other name also uses it for its scroll container.
*/
scrollbarLabel?: string;
/** Localized scrollbar text; missing or `undefined` keys fall back to the provider, then to defaultTableScrollAreaLabels. */
labels?: Partial<TableScrollAreaLabels>;
}
/**
@@ -222,11 +273,13 @@ export interface TableScrollAreaProps extends ComponentProps<"div"> {
export function TableScrollArea({
children,
className,
scrollbarLabel = "Table",
scrollbarLabel,
labels: labelOverrides,
...props
}: TableScrollAreaProps) {
const areaRef = useRef<HTMLDivElement>(null);
const targetId = useId();
const labels = resolveLabels(useContext(TableScrollAreaLabelsContext), labelOverrides);
return (
<div
@@ -238,10 +291,12 @@ export function TableScrollArea({
<TableScrollAreaContext.Provider value={true}>
<PersistentTableScrollbar
areaRef={areaRef}
label={scrollbarLabel}
name={labels.scrollbar(scrollbarLabel ?? "Table")}
targetId={targetId}
/>
{children}
<TableScrollAreaNameContext.Provider value={scrollbarLabel || undefined}>
{children}
</TableScrollAreaNameContext.Provider>
</TableScrollAreaContext.Provider>
</div>
);

View File

@@ -5,3 +5,13 @@ export const TableScrollAreaContext = createContext(false);
export function useInsideTableScrollArea(): boolean {
return useContext(TableScrollAreaContext);
}
/**
* The `scrollbarLabel` a consumer gave the enclosing TableScrollArea. A Table with no other name
* uses it for its scroll container; the built-in default is never passed down.
*/
export const TableScrollAreaNameContext = createContext<string | undefined>(undefined);
export function useTableScrollAreaName(): string | undefined {
return useContext(TableScrollAreaNameContext);
}

View File

@@ -1,24 +1,52 @@
"use client";
import { useEffect, useId, useState } from "react";
import type { ComponentProps, CSSProperties } from "react";
import { useCallback, useEffect, useId, useRef, useState } from "react";
import type { ComponentProps, CSSProperties, FocusEvent, KeyboardEvent, MouseEvent, MutableRefObject, Ref } from "react";
import { ExternalLink } from "lucide-react";
import { cn } from "./lib/utils";
import { TableRowFocusContext, useClientLayoutEffect, useTableRowFocusGroup, useTableRowFocusProvider, type TableRowFocus } from "./table-row-focus";
import { TableLoadingRegion, type TableLoadingRegionProps } from "./table-loading";
import { TableScrollArea } from "./table-scroll-area";
import { useInsideTableScrollArea } from "./table-scroll-context";
import { TableScrollArea, type TableScrollAreaLabels } from "./table-scroll-area";
import { useInsideTableScrollArea, useTableScrollAreaName } from "./table-scroll-context";
export type TableDensity = "compact" | "default" | "comfortable";
export type TableVariant = "bordered" | "plain";
export interface TableProps extends ComponentProps<"table"> {
containerClassName?: string;
/**
* Row height, cell padding and text size of the header and body cells. Each value sets the
* `--ci-table-cell-height`, `--ci-table-cell-padding-block`, `--ci-table-cell-padding-inline`
* and `--ci-table-font-size` tokens on the container. Omitted, the table follows the tokens of
* its context, which are the `"default"` sizes when nothing sets them.
*/
density?: TableDensity;
/**
* `"plain"` drops the container's border, radius and background, for a table whose host (a
* `Card`, a panel) already draws the frame. Defaults to `"bordered"`.
*/
variant?: TableVariant;
/** Three-column settings rows: description, estimate, and control. Stacks below 640px. */
mobileLayout?: "default" | "settings";
/** Show the default axis overlay while the consumer fetches new rows. */
loading?: boolean;
loadingLabel?: string;
loadingIndicator?: TableLoadingRegionProps["loadingIndicator"];
/** Accessible noun phrase used for the persistent horizontal scrollbar. */
/**
* Accessible noun phrase used for the persistent horizontal scrollbar. It also names the scroll
* container while the table overflows, when nothing listed under `scrollLabel` does.
*/
scrollbarLabel?: string;
/**
* Localized text of the persistent scrollbar this table creates. A table inside a
* `TableScrollArea` draws no scrollbar of its own, so this has no effect there: pass `labels`
* to that area.
*/
labels?: Partial<TableScrollAreaLabels>;
/**
* Set false to use the browser's native horizontal scrollbar only. Defaults to true, or to
* false when `maxHeight` is set, because a capped table keeps its native scrollbars in view.
* false when `maxHeight` or `fill` is set, because a bounded table keeps its native scrollbars
* in view.
*/
persistentScrollbars?: boolean;
/**
@@ -26,19 +54,36 @@ export interface TableProps extends ComponentProps<"table"> {
* it, under a header row that stays in view, and the container takes focus while it overflows.
*/
maxHeight?: string | number;
/**
* How the rows that take `onActivate` receive keyboard focus. `"each"` (the default) makes every
* such row a tab stop. `"roving"` gives them one tab stop between them: Tab enters on the row
* that last had focus (or else the selected row, or else the first), Arrow Up and Down, Home,
* End, Page Up and Page Down move focus between rows, and Tab again goes through the controls
* of that row and leaves the table. The table keeps its table semantics.
*/
rowFocus?: TableRowFocus;
/**
* Fill a height-constrained parent: the scroll container takes the block size its parent gives
* it, and the rows scroll inside it exactly as under `maxHeight`. The parent needs a definite
* height (a fixed one, or one it gets as a flex or grid item); without it the table keeps its
* own height. `maxHeight` is ignored next to `fill`: to cap a filled table, cap its parent.
*/
fill?: boolean;
/**
* Accessible name of the scroll container while the table overflows. When omitted, the
* container is named by the table caption, then by the table's own `aria-labelledby` or
* `aria-label`. With none of these it still becomes focusable, but stays unnamed.
* `aria-label`, then by `scrollbarLabel` (its own, or the one of an enclosing `TableScrollArea`).
* With none of these it still becomes focusable, but stays unnamed.
*/
scrollLabel?: string;
}
/**
* Tracks whether the table container scrolls and which caption names it. Takes the container
* node (from a callback ref) so a replaced container is observed again.
* node (from a callback ref) so a replaced container is observed again, and the density, which
* resizes the cells from an attribute of the container that no observer watches.
*/
function useScrollContainer(container: HTMLDivElement | null, fallbackCaptionId: string) {
function useScrollContainer(container: HTMLDivElement | null, fallbackCaptionId: string, density?: TableDensity) {
const [overflowing, setOverflowing] = useState(false);
const [captionId, setCaptionId] = useState<string>();
@@ -80,7 +125,7 @@ function useScrollContainer(container: HTMLDivElement | null, fallbackCaptionId:
mutationObserver?.disconnect();
if (!hasResizeObserver) window.removeEventListener("resize", measure);
};
}, [container, fallbackCaptionId]);
}, [container, fallbackCaptionId, density]);
return { overflowing, captionId };
}
@@ -88,18 +133,27 @@ function useScrollContainer(container: HTMLDivElement | null, fallbackCaptionId:
export function Table({
className,
containerClassName,
scrollbarLabel = "Table",
density,
variant,
mobileLayout = "default",
scrollbarLabel,
labels,
maxHeight,
persistentScrollbars = maxHeight === undefined,
fill,
persistentScrollbars = maxHeight === undefined && !fill,
scrollLabel,
loading,
loadingLabel,
loadingIndicator,
rowFocus,
...props
}: TableProps) {
const insideScrollArea = useInsideTableScrollArea();
const [container, setContainer] = useState<HTMLDivElement | null>(null);
const { overflowing, captionId } = useScrollContainer(container, useId());
const { overflowing, captionId } = useScrollContainer(container, useId(), density);
// Only a label the consumer passed counts: the built-in scrollbar default never becomes a name.
const areaName = useTableScrollAreaName();
const scrollbarName = scrollbarLabel || areaName;
// Keyboard users can only scroll an overflowing container if it takes focus (WCAG 2.1.1).
const name = scrollLabel
? { "aria-label": scrollLabel }
@@ -109,27 +163,39 @@ export function Table({
? { "aria-labelledby": props["aria-labelledby"] }
: props["aria-label"]
? { "aria-label": props["aria-label"] }
: undefined;
: scrollbarName
? { "aria-label": scrollbarName }
: undefined;
const scrollProps = overflowing ? { tabIndex: 0, ...(name ? { role: "region", ...name } : {}) } : {};
const capProps = maxHeight === undefined ? {} : {
// A fill container is bounded by its parent, so it is marked capped as well and gets the same
// scrolling and pinned header. Its cap is "none", whatever maxHeight says and whatever a capped
// table around it would let it inherit.
const capProps = maxHeight === undefined && !fill ? {} : {
"data-capped": "",
style: { "--ci-table-max-height": typeof maxHeight === "number" ? `${maxHeight}px` : maxHeight } as CSSProperties,
"data-fill": fill || undefined,
style: { "--ci-table-max-height": fill ? "none" : typeof maxHeight === "number" ? `${maxHeight}px` : maxHeight } as CSSProperties,
};
const rowFocusGroup = useTableRowFocusProvider(rowFocus, container);
const table = (
<div
ref={setContainer}
data-slot="table-container"
data-mobile-layout={mobileLayout === "default" ? undefined : mobileLayout}
data-overflowing={overflowing || undefined}
data-density={density}
data-variant={variant === "plain" ? variant : undefined}
className={cn("ci-table-container", containerClassName)}
{...capProps}
{...scrollProps}
>
<table data-slot="table" className={cn("ci-table", className)} {...props} />
<TableRowFocusContext.Provider value={rowFocusGroup}>
<table data-slot="table" data-row-focus={rowFocusGroup ? "roving" : undefined} className={cn("ci-table", className)} {...props} />
</TableRowFocusContext.Provider>
</div>
);
const content = !persistentScrollbars || insideScrollArea
? table
: <TableScrollArea scrollbarLabel={scrollbarLabel}>{table}</TableScrollArea>;
: <TableScrollArea scrollbarLabel={scrollbarLabel} labels={labels}>{table}</TableScrollArea>;
// Keep the original DOM for consumers without asynchronous data.
if (loading === undefined) return content;
return (
@@ -151,45 +217,190 @@ export function TableFooter({ className, ...props }: ComponentProps<"tfoot">) {
return <tfoot data-slot="table-footer" className={cn("ci-table__footer", className)} {...props} />;
}
export function TableRow({ className, ...props }: ComponentProps<"tr">) {
return <tr data-slot="table-row" className={cn("ci-table__row", className)} {...props} />;
export type { TableRowFocus };
/** The event that activated a row: its click, or the keydown of Enter or Space. */
export type TableRowActivateEvent = MouseEvent<HTMLTableRowElement> | KeyboardEvent<HTMLTableRowElement>;
export interface TableRowProps extends ComponentProps<"tr"> {
/**
* Makes the row interactive. It becomes a tab stop (`tabIndex` 0 unless you pass one; inside a
* `Table rowFocus="roving"` the rows share one tab stop and the arrow keys move between them) and
* `onActivate` runs on a click and on Enter or Space while the row itself has focus. It does not
* run for an event that comes from a control inside the row (a button, a link, a field,
* anything in the tab order or with a widget role), for an event that reaches the row through
* a portal, for a click that ends a text selection in the row, or after your own `onClick` or
* `onKeyDown` called `preventDefault()`.
*/
onActivate?: (event: TableRowActivateEvent) => void;
/**
* Marks the row as selected (`aria-selected="true"` and `data-state="selected"`). Pass `false`
* on the other rows of a table whose rows can be selected, so each one states
* `aria-selected="false"`; leave it out where selection does not apply.
*/
selected?: boolean;
}
export type TableStickyEdge = "end";
/** Controls that handle their own clicks and keys inside an interactive row. */
const ROW_CONTROL_SELECTOR = [
"a[href]",
"area[href]",
"button",
"input",
"select",
"textarea",
"summary",
"label",
"audio[controls]",
"video[controls]",
'[contenteditable]:not([contenteditable="false"])',
// tabindex="-1" marks a target for programmatic focus (a cell, a region), not a control.
'[tabindex]:not([tabindex="-1"])',
...["button", "link", "checkbox", "radio", "switch", "tab", "option", "menuitem", "menuitemcheckbox", "menuitemradio", "combobox", "listbox", "slider", "spinbutton", "textbox", "searchbox", "treeitem"]
.map((role) => `[role="${role}"]`),
].join(", ");
export interface TableHeadProps extends ComponentProps<"th"> {
/** True when the click belongs to the row: not to a control inside it, a portal or a text selection. */
function isRowClick(event: MouseEvent<HTMLTableRowElement>) {
const row = event.currentTarget;
const target = event.target;
// The constructors of the row's own document: a table rendered into an iframe is another realm.
const view = row.ownerDocument.defaultView;
// React bubbles events from a portal (a menu, a dialog) to the row that rendered it.
if (!view || !(target instanceof view.Node) || !row.contains(target)) return false;
const control = (target instanceof view.Element ? target : target.parentElement)?.closest(ROW_CONTROL_SELECTOR);
// The row itself and its focusable scroll container also match the selector.
if (control && control !== row && row.contains(control)) return false;
// A drag that selected text in the row ends with a click on it.
const selection = row.ownerDocument.getSelection();
return !selection || selection.isCollapsed || !(row.contains(selection.anchorNode) || row.contains(selection.focusNode));
}
/**
* The row's part in the roving focus of its `Table`. Returns null for a row that keeps its own
* tab stop: outside `rowFocus="roving"`, without `onActivate`, or with a `tabIndex` of its own.
*/
function useRovingRow(interactive: boolean, tabIndex: number | undefined, selected: boolean, props: Pick<TableRowProps, "ref">) {
const group = useTableRowFocusGroup();
const roving = group && interactive && tabIndex === undefined ? group : null;
// Read only where it is used: before React 19 `ref` is not a prop of a function component.
const consumerRef = roving ? props.ref as Ref<HTMLTableRowElement> | undefined : undefined;
const node = useRef<HTMLTableRowElement | null>(null);
const [isTabStop, setIsTabStop] = useState(false);
const wasSelected = useRef(selected);
useClientLayoutEffect(() => (roving && node.current ? roving.register(node.current, setIsTabStop) : undefined), [roving]);
useClientLayoutEffect(() => {
if (roving && node.current && selected !== wasSelected.current) roving.selectionChanged(node.current, selected);
wasSelected.current = selected;
}, [roving, selected]);
// The row needs its own node, and a `ref` you pass (a prop since React 19) still gets it.
const ref = useCallback((element: HTMLTableRowElement | null) => {
node.current = element;
if (typeof consumerRef !== "function") {
if (consumerRef) (consumerRef as MutableRefObject<HTMLTableRowElement | null>).current = element;
return undefined;
}
// Since React 19 a callback ref may return its own cleanup, which then replaces the null call.
const cleanup: unknown = consumerRef(element);
return typeof cleanup === "function" ? () => { node.current = null; (cleanup as () => void)(); } : undefined;
}, [consumerRef]);
return roving ? { group: roving, ref, tabIndex: isTabStop ? 0 : -1 } : null;
}
export function TableRow({ className, onActivate, selected, onClick, onKeyDown, onFocus, tabIndex, ...props }: TableRowProps) {
const roving = useRovingRow(
Boolean(onActivate),
tabIndex,
selected ?? (props["aria-selected"] === true || props["aria-selected"] === "true"),
props,
);
return (
<tr
data-slot="table-row"
data-interactive={onActivate ? "" : undefined}
className={cn("ci-table__row", className)}
tabIndex={tabIndex ?? roving?.tabIndex ?? (onActivate ? 0 : undefined)}
{...props}
{...(roving ? { ref: roving.ref } : undefined)}
{...(selected === undefined ? undefined : { "aria-selected": selected })}
{...(selected ? { "data-state": "selected" } : undefined)}
onFocus={roving ? (event: FocusEvent<HTMLTableRowElement>) => {
onFocus?.(event);
// Focus on the row or on a control inside it, not in a portal the row rendered.
// Your onFocus may have moved the focus to another row: only the row that still holds it is recorded.
const row = event.currentTarget;
if (row.contains(event.target) && row.contains(row.ownerDocument.activeElement)) roving.group.focused(row);
} : onFocus}
onClick={onActivate ? (event) => {
onClick?.(event);
if (event.defaultPrevented || !isRowClick(event)) return;
onActivate(event);
} : onClick}
onKeyDown={onActivate ? (event) => {
onKeyDown?.(event);
// Keys pressed on a control inside the row, or in a portal, belong to that control.
if (event.defaultPrevented || event.target !== event.currentTarget) return;
if (roving?.group.navigate(event.currentTarget, event)) return;
if (event.key !== "Enter" && event.key !== " ") return;
// Space would scroll the page, also while it is held down.
event.preventDefault();
if (!event.repeat) onActivate(event);
} : onKeyDown}
/>
);
}
export type TableStickyEdge = "start" | "end";
export type TableCellAlign = "start" | "center" | "end";
/** Layout props shared by `TableHead` and `TableCell`. */
interface TableCellLayoutProps {
/** Pins the cell to the inline start or end edge of the scroll container. */
sticky?: TableStickyEdge;
/**
* Inline alignment of the content, following the writing direction. Wins over the alignment
* that `numeric` or `action` imply. Replaces the deprecated HTML `align` attribute.
*/
align?: TableCellAlign;
/** A column of numbers: end-aligned, with tabular digits. */
numeric?: boolean;
/** The narrow, centered column for one row action (an icon button or a `TableActionLink`). */
action?: boolean;
}
export function TableHead({ className, sticky, ...props }: TableHeadProps) {
function cellLayoutClasses(block: "ci-table__head" | "ci-table__cell", { sticky, align, numeric, action }: TableCellLayoutProps) {
return [
numeric && `${block}--numeric`,
action && `${block}--action`,
align && `${block}--${align}`,
sticky && `${block}--sticky-${sticky}`,
];
}
export interface TableHeadProps extends Omit<ComponentProps<"th">, "align">, TableCellLayoutProps {}
export function TableHead({ className, sticky, align, numeric, action, ...props }: TableHeadProps) {
return (
<th
data-slot="table-head"
data-sticky={sticky}
className={cn(
"ci-table__head",
sticky === "end" && "ci-table__head--sticky-end",
className,
)}
className={cn("ci-table__head", ...cellLayoutClasses("ci-table__head", { sticky, align, numeric, action }), className)}
{...props}
/>
);
}
export interface TableCellProps extends ComponentProps<"td"> {
sticky?: TableStickyEdge;
}
export interface TableCellProps extends Omit<ComponentProps<"td">, "align">, TableCellLayoutProps {}
export function TableCell({ className, sticky, ...props }: TableCellProps) {
export function TableCell({ className, sticky, align, numeric, action, ...props }: TableCellProps) {
return (
<td
data-slot="table-cell"
data-sticky={sticky}
className={cn(
"ci-table__cell",
sticky === "end" && "ci-table__cell--sticky-end",
className,
)}
className={cn("ci-table__cell", ...cellLayoutClasses("ci-table__cell", { sticky, align, numeric, action }), className)}
{...props}
/>
);

View File

@@ -5,10 +5,19 @@ import { cn } from "./lib/utils";
export interface TextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {
/** Shows the error border (also triggered by aria-invalid). */
error?: boolean;
/**
* Sets the value in the kit code font (`--ci-font-code`) at the size, leading and tab width of
* `CodePreview`, for JSON, code and lists of keys. Also turns `spellCheck`, `autoCapitalize` and
* `autoCorrect` off; pass any of them to turn it back on.
*/
mono?: boolean;
}
// Text assistance meant for prose, which only gets in the way of a key or a snippet.
const monoDefaults = { spellCheck: false, autoCapitalize: "none", autoCorrect: "off" } as const;
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
function Textarea({ className, error, ...props }, ref) {
function Textarea({ className, error, mono, ...props }, ref) {
return (
<textarea
ref={ref}
@@ -16,8 +25,10 @@ export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
className={cn(
"ci-textarea",
error && "ci-textarea--error",
mono && "ci-textarea--mono",
className,
)}
{...(mono ? monoDefaults : undefined)}
{...props}
/>
);

View File

@@ -2,6 +2,7 @@
import { forwardRef, useState } from "react";
import type { ButtonHTMLAttributes, ReactNode } from "react";
import type { BadgeChartTone, BadgeTone } from "./badge";
import { cn } from "./lib/utils";
export type ToggleChipSize = "sm" | "md";
@@ -15,6 +16,12 @@ export interface ToggleChipProps extends Omit<ButtonHTMLAttributes<HTMLButtonEle
/** Trailing count, e.g. matching rows. Part of the accessible name. */
count?: ReactNode;
size?: ToggleChipSize;
/**
* Colours the pressed state with a Badge tone (ink, border and tint) instead of the
* active-control colours. The unpressed chip does not change. Keep the label: the
* tone never carries the meaning alone.
*/
tone?: BadgeTone | BadgeChartTone;
}
/** A pill toggle button (`aria-pressed`) for filter and selection chips. */
@@ -26,6 +33,7 @@ export const ToggleChip = forwardRef<HTMLButtonElement, ToggleChipProps>(functio
icon,
count,
size = "md",
tone,
children,
onClick,
type = "button",
@@ -41,6 +49,7 @@ export const ToggleChip = forwardRef<HTMLButtonElement, ToggleChipProps>(functio
data-slot="toggle-chip"
data-state={pressed ? "on" : "off"}
data-size={size}
data-tone={tone}
className={cn("ci-toggle-chip", className)}
onClick={(event) => {
onClick?.(event);

View File

@@ -141,6 +141,8 @@ export const ciTokens = {
display: '"Switzer", -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif',
mono: '"Switzer", -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif',
size: {
10: "0.625rem",
11: "0.6875rem",
12: "0.75rem",
14: "0.875rem",
16: "1rem",
@@ -194,6 +196,7 @@ export const ciTokens = {
full: "9999px",
},
size: {
controlXs: "1.5rem",
controlSm: "2rem",
controlMd: "2.25rem",
controlLg: "2.5rem",
@@ -253,6 +256,13 @@ export const ciTokenReferences = {
live: "var(--ci-color-live)",
focus: "var(--ci-color-focus)",
},
/** Stroke of a flow-canvas connector, per state; 3:1 or better on the canvas and every content surface. */
flowEdge: {
active: "var(--ci-flow-edge-active)",
warning: "var(--ci-flow-edge-warning)",
error: "var(--ci-flow-edge-error)",
idle: "var(--ci-flow-edge-idle)",
},
font: {
ui: "var(--ci-font-ui)",
display: "var(--ci-font-display)",
@@ -262,6 +272,7 @@ export const ciTokenReferences = {
radius: {
control: "var(--ci-radius-control)",
surface: "var(--ci-radius-surface)",
surfaceNested: "var(--ci-radius-surface-nested)",
pill: "var(--ci-radius-pill)",
},
} as const;

View File

@@ -1,9 +1,13 @@
"use client";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { forwardRef } from "react";
import { forwardRef, useCallback } from "react";
import type { ComponentProps, ReactNode } from "react";
import { isKeyboardNavigationFocus, watchKeyboardNavigation } from "./lib/keyboard-focus";
import { cn } from "./lib/utils";
import { TooltipRoot } from "./lib/tooltip-root";
export { TooltipProvider, type TooltipProviderProps } from "./lib/tooltip-root";
export type TooltipSide = NonNullable<ComponentProps<typeof TooltipPrimitive.Content>["side"]>;
export type TooltipAlign = NonNullable<ComponentProps<typeof TooltipPrimitive.Content>["align"]>;
@@ -12,6 +16,7 @@ export interface TooltipProps extends ComponentProps<"span"> {
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Delay before opening, in ms. Defaults to 300, or to the TooltipProvider's delay under one. */
delayDuration?: number;
disableHoverableContent?: boolean;
children?: ReactNode;
@@ -22,32 +27,54 @@ export const Tooltip = forwardRef<HTMLSpanElement, TooltipProps>(function Toolti
open,
defaultOpen,
onOpenChange,
delayDuration = 300,
delayDuration,
disableHoverableContent,
children,
...props
}, ref) {
return (
<span ref={ref} className={cn("ci-tooltip", className)} {...props}>
<TooltipPrimitive.Provider delayDuration={delayDuration}>
<TooltipPrimitive.Root
open={open}
defaultOpen={defaultOpen}
onOpenChange={onOpenChange}
delayDuration={delayDuration}
disableHoverableContent={disableHoverableContent}
>
{children}
</TooltipPrimitive.Root>
</TooltipPrimitive.Provider>
<TooltipRoot
open={open}
defaultOpen={defaultOpen}
onOpenChange={onOpenChange}
delayDuration={delayDuration}
disableHoverableContent={disableHoverableContent}
>
{children}
</TooltipRoot>
</span>
);
});
export interface TooltipTriggerProps extends ComponentProps<typeof TooltipPrimitive.Trigger> {}
export const TooltipTrigger = forwardRef<HTMLButtonElement, TooltipTriggerProps>(function TooltipTrigger(props, ref) {
return <TooltipPrimitive.Trigger ref={ref} data-slot="tooltip-trigger" {...props} />;
/**
* Opens the tooltip on hover and on a focus the user moved there with the keyboard (Tab, the
* arrows, Home, End, PageUp, PageDown). A focus moved by code, such as a dialog focusing its first
* control or handing focus back to its opener, leaves it closed, so it cannot take that dialog's Escape.
*/
export const TooltipTrigger = forwardRef<HTMLButtonElement, TooltipTriggerProps>(function TooltipTrigger({ onFocus, ...props }, ref) {
// Listen in the trigger's own document (an iframe has its own) from mount, before the first
// key: the first focus is already too late to tell how it came.
const attach = useCallback((element: HTMLButtonElement | null) => {
if (element) watchKeyboardNavigation(element.ownerDocument);
// React 19 runs the cleanup a callback ref returns on unmount, in place of calling it with null.
if (typeof ref === "function") return ref(element);
if (ref) ref.current = element;
}, [ref]);
return (
<TooltipPrimitive.Trigger
ref={attach}
data-slot="tooltip-trigger"
onFocus={(event) => {
onFocus?.(event);
// Radix opens the tooltip in its own focus handler, which it skips for a default-prevented event.
if (!isKeyboardNavigationFocus(event.currentTarget.ownerDocument)) event.preventDefault();
}}
{...props}
/>
);
});
export interface TooltipContentProps extends ComponentProps<typeof TooltipPrimitive.Content> {

View File

@@ -7,6 +7,7 @@ import { Card } from "./card";
import { Skeleton } from "./skeleton";
import { Table } from "./table";
import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";
import { resolveLabels } from "./lib/labels";
import { cn } from "./lib/utils";
/** Values are already formatted by the dashboard. Null means unavailable, never zero. */
@@ -39,6 +40,22 @@ export function UsageDrilldownHeader({ eyebrow, title, status, description, endp
</div>;
}
/** Interface text of UsageRequestIdentity. `help` stays a separate prop. */
export interface UsageRequestIdentityLabels {
requestId: string;
/** Copy button accessible name. */
copy: string;
/** Copy button accessible name and status after a copy. */
copied: string;
/** Help button accessible name. */
about: string;
}
export const defaultUsageRequestIdentityLabels: UsageRequestIdentityLabels = {
requestId: "Request ID",
copy: "Copy request ID",
copied: "Request ID copied",
about: "About request ID",
};
export interface UsageRequestIdentityProps extends ComponentProps<"div"> {
requestId: string;
/** Clipboard access, success and failure state remain controlled by the caller. */
@@ -47,14 +64,17 @@ export interface UsageRequestIdentityProps extends ComponentProps<"div"> {
copyError?: ReactNode;
help?: ReactNode;
timestamp?: ReactNode;
/** Localized interface text; missing or `undefined` keys fall back to defaultUsageRequestIdentityLabels. */
labels?: Partial<UsageRequestIdentityLabels>;
}
export function UsageRequestIdentity({ requestId, onCopy, copied = false, copyError, help = "Include this ID when contacting support so we can locate this exact request.", timestamp, className, ...props }: UsageRequestIdentityProps) {
export function UsageRequestIdentity({ requestId, onCopy, copied = false, copyError, help = "Include this ID when contacting support so we can locate this exact request.", timestamp, labels: labelOverrides, className, ...props }: UsageRequestIdentityProps) {
const labels = resolveLabels(defaultUsageRequestIdentityLabels, labelOverrides);
return <div data-slot="usage-request-identity" className={cn("ci-usage-request-identity", className)} {...props}>
<span className="ci-usage-request-identity__label"><Hash size={14} aria-hidden="true" />Request ID</span><code>{requestId}</code>
{onCopy && <Button type="button" variant="ghost" size="icon-xs" aria-label={copied ? "Request ID copied" : "Copy request ID"} onClick={onCopy}>{copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}</Button>}
{help != null && <UsageInfoTooltip label="About request ID">{help}</UsageInfoTooltip>}
<span className="ci-usage-request-identity__label"><Hash size={14} aria-hidden="true" />{labels.requestId}</span><code>{requestId}</code>
{onCopy && <Button type="button" variant="ghost" size="icon-xs" aria-label={copied ? labels.copied : labels.copy} onClick={onCopy}>{copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}</Button>}
{help != null && <UsageInfoTooltip label={labels.about}>{help}</UsageInfoTooltip>}
{timestamp != null && <span className="ci-usage-request-identity__timestamp">{timestamp}</span>}
<span className="ci-usage-request-identity__feedback" role="status">{copyError ?? (copied ? "Request ID copied" : null)}</span>
<span className="ci-usage-request-identity__feedback" role="status">{copyError ?? (copied ? labels.copied : null)}</span>
</div>;
}
@@ -68,12 +88,26 @@ export interface UsageReceiptRow {
strong?: boolean;
tone?: "default" | "muted" | "positive";
}
function ReceiptRow({ label, value, help, helpLabel, indent, strong, tone = "default" }: UsageReceiptRow) {
function ReceiptRow({ label, value, help, helpLabel, indent, strong, tone = "default", about }: UsageReceiptRow & { about: (label?: string) => string }) {
return <div className={cn("ci-usage-receipt__row", indent && "ci-usage-receipt__row--indent", strong && "ci-usage-receipt__row--strong")}>
<dt>{label}{help != null && <UsageInfoTooltip label={helpLabel ?? `About ${typeof label === "string" ? label.toLowerCase() : "this amount"}`}>{help}</UsageInfoTooltip>}</dt>
<dt>{label}{help != null && <UsageInfoTooltip label={helpLabel ?? about(typeof label === "string" ? label : undefined)}>{help}</UsageInfoTooltip>}</dt>
<span className="ci-usage-receipt__leader" aria-hidden="true" /><dd data-tone={tone}>{value ?? "—"}</dd>
</div>;
}
/** Interface text of UsageCostBreakdown. `title` and `label` stay separate props. */
export interface UsageCostBreakdownLabels {
/** Heading of the optimization rows. */
optimizations: string;
/** Help button name of the retention line. */
aboutRetention: string;
/** Help button name of a row without `helpLabel`; `label` is the row label when it is a string. */
about: (label?: string) => string;
}
export const defaultUsageCostBreakdownLabels: UsageCostBreakdownLabels = {
optimizations: "Optimizations",
aboutRetention: "About data retention",
about: (label) => `About ${label ? label.toLowerCase() : "this amount"}`,
};
export interface UsageCostBreakdownProps extends Omit<ComponentProps<"div">, "title"> {
title?: ReactNode;
badge?: ReactNode;
@@ -86,17 +120,20 @@ export interface UsageCostBreakdownProps extends Omit<ComponentProps<"div">, "ti
retention?: ReactNode;
retentionHelp?: ReactNode;
label?: string;
/** Localized interface text; missing or `undefined` keys fall back to defaultUsageCostBreakdownLabels. */
labels?: Partial<UsageCostBreakdownLabels>;
}
/** Receipt presentation only: no currency conversion, discount calculation or clamping. */
export function UsageCostBreakdown({ title = "Cost breakdown", badge, rows, optimizations, optimizationTotal, totals, note, retention, retentionHelp, label = "Savings breakdown for this request", className, ...props }: UsageCostBreakdownProps) {
export function UsageCostBreakdown({ title = "Cost breakdown", badge, rows, optimizations, optimizationTotal, totals, note, retention, retentionHelp, label = "Savings breakdown for this request", labels: labelOverrides, className, ...props }: UsageCostBreakdownProps) {
const labels = resolveLabels(defaultUsageCostBreakdownLabels, labelOverrides);
return <Card data-slot="usage-cost-breakdown" aria-label={label} className={cn("ci-usage-receipt", className)} {...props}>
<div className="ci-usage-receipt__heading"><h3><ReceiptText aria-hidden="true" />{title}</h3>{badge}</div>
<dl className="ci-usage-receipt__lines">{rows.map(row => <ReceiptRow key={row.id} {...row} />)}</dl>
{optimizations && optimizations.length > 0 && <><p className="ci-usage-receipt__group-label">Optimizations</p><dl className="ci-usage-receipt__lines">{optimizations.map(row => <ReceiptRow key={row.id} {...row} indent />)}</dl></>}
{optimizationTotal && <dl className="ci-usage-receipt__lines"><ReceiptRow {...optimizationTotal} /></dl>}
<dl className="ci-usage-receipt__totals">{totals.map(row => <ReceiptRow key={row.id} {...row} strong />)}</dl>
<dl className="ci-usage-receipt__lines">{rows.map(row => <ReceiptRow key={row.id} {...row} about={labels.about} />)}</dl>
{optimizations && optimizations.length > 0 && <><p className="ci-usage-receipt__group-label">{labels.optimizations}</p><dl className="ci-usage-receipt__lines">{optimizations.map(row => <ReceiptRow key={row.id} {...row} indent about={labels.about} />)}</dl></>}
{optimizationTotal && <dl className="ci-usage-receipt__lines"><ReceiptRow {...optimizationTotal} about={labels.about} /></dl>}
<dl className="ci-usage-receipt__totals">{totals.map(row => <ReceiptRow key={row.id} {...row} strong about={labels.about} />)}</dl>
{note != null && <p className="ci-usage-receipt__note">{note}</p>}
{retention != null && <div className="ci-usage-receipt__retention"><Shield aria-hidden="true" />{retention}{retentionHelp != null && <UsageInfoTooltip label="About data retention">{retentionHelp}</UsageInfoTooltip>}</div>}
{retention != null && <div className="ci-usage-receipt__retention"><Shield aria-hidden="true" />{retention}{retentionHelp != null && <UsageInfoTooltip label={labels.aboutRetention}>{retentionHelp}</UsageInfoTooltip>}</div>}
</Card>;
}
@@ -107,22 +144,51 @@ export interface UsageTokenUsageProps extends ComponentProps<"div"> {
cachedInput?: UsageDetailValue;
showOriginal?: boolean;
showCached?: boolean;
/** Localized interface text; missing or `undefined` keys fall back to defaultUsageTokenUsageLabels. */
labels?: Partial<UsageTokenUsageLabels>;
}
const tokenHelp = {
original: "Prompt tokens recorded before request optimization.",
input: "Prompt tokens recorded for the model request after processing. This can differ from the original count because of formatting or token accounting.",
cached: "Cached input is included in sent-to-model input tokens. Do not add it to the total again.",
output: "Completion tokens reported for the generated response.",
/** Interface text of UsageTokenUsage: the title, the four rows and their help. */
export interface UsageTokenUsageLabels {
title: string;
original: string;
input: string;
cached: string;
output: string;
originalHelp: string;
inputHelp: string;
cachedHelp: string;
outputHelp: string;
/** Help button name of the original, input and output rows, from the row label. */
about: (label: string) => string;
/** Help button name of the cached row. */
aboutCached: string;
/** Sentence added to a row's help when its value is null. */
unavailable: string;
}
export const defaultUsageTokenUsageLabels: UsageTokenUsageLabels = {
title: "Token usage",
original: "Original input",
input: "Sent to model",
cached: "Of which cached",
output: "Output",
originalHelp: "Prompt tokens recorded before request optimization.",
inputHelp: "Prompt tokens recorded for the model request after processing. This can differ from the original count because of formatting or token accounting.",
cachedHelp: "Cached input is included in sent-to-model input tokens. Do not add it to the total again.",
outputHelp: "Completion tokens reported for the generated response.",
about: (label) => `About ${label.toLowerCase()}`,
aboutCached: "About cached input",
unavailable: "This value is unavailable; it does not mean zero.",
};
export function UsageTokenUsage({ originalInput, input, output, cachedInput, showOriginal = true, showCached = false, className, ...props }: UsageTokenUsageProps) {
export function UsageTokenUsage({ originalInput, input, output, cachedInput, showOriginal = true, showCached = false, labels: labelOverrides, className, ...props }: UsageTokenUsageProps) {
const labels = resolveLabels(defaultUsageTokenUsageLabels, labelOverrides);
const rows = [
...(showOriginal ? [{ id: "original", label: "Original input", value: originalInput, help: tokenHelp.original }] : []),
{ id: "input", label: "Sent to model", value: input, help: tokenHelp.input },
...(showCached || cachedInput !== undefined ? [{ id: "cached", label: "Of which cached", value: cachedInput, help: tokenHelp.cached }] : []),
{ id: "output", label: "Output", value: output, help: tokenHelp.output },
...(showOriginal ? [{ id: "original", label: labels.original, value: originalInput, help: labels.originalHelp }] : []),
{ id: "input", label: labels.input, value: input, help: labels.inputHelp },
...(showCached || cachedInput !== undefined ? [{ id: "cached", label: labels.cached, value: cachedInput, help: labels.cachedHelp }] : []),
{ id: "output", label: labels.output, value: output, help: labels.outputHelp },
];
return <Card data-slot="usage-token-usage" className={cn("ci-usage-section", className)} title={<h3 className="ci-usage-section__title"><Layers3 aria-hidden="true" />Token usage</h3>} {...props}>
<dl className="ci-usage-token-rows">{rows.map(row => <div key={row.id} className={cn("ci-usage-token-row", row.id === "cached" && "ci-usage-token-row--cached")}><dt>{row.label}<UsageInfoTooltip label={`About ${row.id === "cached" ? "cached input" : row.label.toLowerCase()}`}>{row.help}{row.value == null && " This value is unavailable; it does not mean zero."}</UsageInfoTooltip></dt><dd>{row.value ?? "—"}</dd></div>)}</dl>
return <Card data-slot="usage-token-usage" className={cn("ci-usage-section", className)} title={<h3 className="ci-usage-section__title"><Layers3 aria-hidden="true" />{labels.title}</h3>} {...props}>
<dl className="ci-usage-token-rows">{rows.map(row => <div key={row.id} className={cn("ci-usage-token-row", row.id === "cached" && "ci-usage-token-row--cached")}><dt>{row.label}<UsageInfoTooltip label={row.id === "cached" ? labels.aboutCached : labels.about(row.label)}>{row.help}{row.value == null && ` ${labels.unavailable}`}</UsageInfoTooltip></dt><dd>{row.value ?? "—"}</dd></div>)}</dl>
</Card>;
}
@@ -140,17 +206,23 @@ export interface UsageDetailSectionProps extends Omit<ComponentProps<"div">, "ti
description?: ReactNode;
rows: UsageDetailRow[];
secondaryRows?: UsageDetailRow[];
/** Help button name of a row without `helpLabel`; `label` is the row label when it is a string. Defaults to "About …". */
aboutLabel?: (label?: string) => string;
}
function DetailRows({ rows }: { rows: UsageDetailRow[] }) {
return <dl className="ci-usage-detail-rows">{rows.map(row => <div key={row.id}><dt>{row.icon}{row.label}{row.help != null && <UsageInfoTooltip label={row.helpLabel ?? `About ${typeof row.label === "string" ? row.label.toLowerCase() : "this detail"}`}>{row.help}</UsageInfoTooltip>}</dt><dd>{row.value ?? "—"}</dd></div>)}</dl>;
const defaultUsageDetailAboutLabel = (label?: string) => `About ${label ? label.toLowerCase() : "this detail"}`;
function DetailRows({ rows, about }: { rows: UsageDetailRow[]; about: (label?: string) => string }) {
return <dl className="ci-usage-detail-rows">{rows.map(row => <div key={row.id}><dt>{row.icon}{row.label}{row.help != null && <UsageInfoTooltip label={row.helpLabel ?? about(typeof row.label === "string" ? row.label : undefined)}>{row.help}</UsageInfoTooltip>}</dt><dd>{row.value ?? "—"}</dd></div>)}</dl>;
}
/** Also supports approved optional Pricing rows. Caller supplies customer-safe fields. */
export function UsageDetailSection({ title, icon, description, rows, secondaryRows, className, ...props }: UsageDetailSectionProps) {
return <Card data-slot="usage-detail-section" className={cn("ci-usage-section", className)} title={<h3 className="ci-usage-section__title">{icon}{title}</h3>} description={description} {...props}><DetailRows rows={rows} />{secondaryRows && secondaryRows.length > 0 && <div className="ci-usage-detail-rows__secondary"><DetailRows rows={secondaryRows} /></div>}</Card>;
export function UsageDetailSection({ title, icon, description, rows, secondaryRows, aboutLabel = defaultUsageDetailAboutLabel, className, ...props }: UsageDetailSectionProps) {
return <Card data-slot="usage-detail-section" className={cn("ci-usage-section", className)} title={<h3 className="ci-usage-section__title">{icon}{title}</h3>} description={description} {...props}><DetailRows rows={rows} about={aboutLabel} />{secondaryRows && secondaryRows.length > 0 && <div className="ci-usage-detail-rows__secondary"><DetailRows rows={secondaryRows} about={aboutLabel} /></div>}</Card>;
}
export type UsageTimingDeliveryProps = Omit<UsageDetailSectionProps, "title" | "icon">;
export function UsageTimingDelivery(props: UsageTimingDeliveryProps) {
return <UsageDetailSection title="Timing & delivery" icon={<Timer aria-hidden="true" />} {...props} />;
export type UsageTimingDeliveryProps = Omit<UsageDetailSectionProps, "title" | "icon"> & {
/** Section heading. Defaults to "Timing & delivery". */
title?: ReactNode;
};
export function UsageTimingDelivery({ title = "Timing & delivery", ...props }: UsageTimingDeliveryProps) {
return <UsageDetailSection title={title} icon={<Timer aria-hidden="true" />} {...props} />;
}
export interface UsageModelRow {
@@ -162,13 +234,31 @@ export interface UsageModelRow {
onSelect?: () => void;
selectLabel?: string;
}
/** Interface text of UsageModelsUsed: the title (also the table name) and the column headers. */
export interface UsageModelsUsedLabels {
title: string;
model: string;
requests: string;
spend: string;
total: string;
}
export const defaultUsageModelsUsedLabels: UsageModelsUsedLabels = {
title: "Models used",
model: "Model",
requests: "Requests",
spend: "Spend",
total: "Total",
};
export interface UsageModelsUsedProps extends ComponentProps<"div"> {
models: UsageModelRow[];
total?: { requests: UsageDetailValue; spend: UsageDetailValue };
/** Localized interface text; missing or `undefined` keys fall back to defaultUsageModelsUsedLabels. */
labels?: Partial<UsageModelsUsedLabels>;
}
export function UsageModelsUsed({ models, total, className, ...props }: UsageModelsUsedProps) {
return <Card data-slot="usage-models-used" className={cn("ci-usage-section", className)} title={<h3 className="ci-usage-section__title"><Boxes aria-hidden="true" />Models used</h3>} {...props}>
<div className="ci-usage-models-scroll"><Table className="ci-usage-models" containerClassName="ci-usage-models-container" scrollbarLabel="Models used" aria-label="Models used"><thead><tr><th scope="col">Model</th><th scope="col">Requests</th><th scope="col">Spend</th></tr></thead><tbody>{models.map(model => <tr key={model.id}><th scope="row">{model.onSelect ? <Button variant="ghost" size="sm" aria-label={model.selectLabel} onClick={model.onSelect}>{model.model}</Button> : model.model}</th><td>{model.requests ?? "—"}</td><td>{model.spend ?? "—"}</td></tr>)}</tbody>{total && <tfoot><tr><th scope="row">Total</th><td>{total.requests ?? "—"}</td><td>{total.spend ?? "—"}</td></tr></tfoot>}</Table></div>
export function UsageModelsUsed({ models, total, labels: labelOverrides, className, ...props }: UsageModelsUsedProps) {
const labels = resolveLabels(defaultUsageModelsUsedLabels, labelOverrides);
return <Card data-slot="usage-models-used" className={cn("ci-usage-section", className)} title={<h3 className="ci-usage-section__title"><Boxes aria-hidden="true" />{labels.title}</h3>} {...props}>
<div className="ci-usage-models-scroll"><Table className="ci-usage-models" containerClassName="ci-usage-models-container" scrollbarLabel={labels.title} aria-label={labels.title}><thead><tr><th scope="col">{labels.model}</th><th scope="col">{labels.requests}</th><th scope="col">{labels.spend}</th></tr></thead><tbody>{models.map(model => <tr key={model.id}><th scope="row">{model.onSelect ? <Button variant="ghost" size="sm" aria-label={model.selectLabel} onClick={model.onSelect}>{model.model}</Button> : model.model}</th><td>{model.requests ?? "—"}</td><td>{model.spend ?? "—"}</td></tr>)}</tbody>{total && <tfoot><tr><th scope="row">{labels.total}</th><td>{total.requests ?? "—"}</td><td>{total.spend ?? "—"}</td></tr></tfoot>}</Table></div>
</Card>;
}

View File

@@ -0,0 +1,29 @@
/* Placeholder decoration lives behind native text so selection, IME and caret remain native. */
.ci-variable-textarea { position: relative; min-width: 0; background: var(--ci-field-bg); border-radius: var(--ci-radius-control); }
.ci-variable-textarea__layer {
position: absolute; inset: 0; box-sizing: border-box; overflow: hidden; pointer-events: none;
border: var(--ci-border-default) solid transparent; border-radius: var(--ci-radius-control);
padding: var(--ci-space-3) var(--ci-space-4);
font: var(--ci-font-weight-regular) var(--ci-font-size-sm) / var(--ci-line-height-ui) var(--ci-font-ui);
line-height: var(--ci-type-data-leading); letter-spacing: var(--ci-type-data-tracking);
white-space: pre-wrap; overflow-wrap: break-word; word-break: normal; color: transparent;
}
/* `mono` sets the textarea in the code font. The layer repeats the same declarations as
.ci-textarea--mono in ci-ui.css, so each highlight stays under its text. */
.ci-variable-textarea__layer--mono {
font-family: var(--ci-font-code);
font-size: var(--ci-font-size-xs);
line-height: var(--ci-type-reading-leading);
font-variant-numeric: tabular-nums;
font-variant-ligatures: none;
tab-size: 2;
}
.ci-variable-textarea__layer[dir="auto"] { unicode-bidi: plaintext; }
.ci-variable-textarea__layer mark { background: var(--ci-chart-6-subtle); color: transparent; border-radius: 3px; padding: 0; font: inherit; letter-spacing: inherit; }
.ci-variable-textarea__input { position: relative; background: transparent; caret-color: var(--ci-field-fg); }
.ci-variable-textarea__input::selection { background: var(--ci-color-accent); color: var(--ci-color-accent-foreground); }
.ci-variable-textarea[data-disabled] .ci-variable-textarea__layer { opacity: .56; }
@media (forced-colors: active) {
.ci-variable-textarea__layer { display: none; }
.ci-variable-textarea__input { background: Field; color: FieldText; }
}

Some files were not shown because too many files have changed in this diff Show More