Choose, drop, or paste files using UI SDK File Input.
Default
Upload project files
All file types · 21 MB / file · 2/10
- Mobile app.fig13 MB Uploading Uploading
- Design system.sketch8.5 MB Completed Completed
Single File
Attach your portfolio
.pdf · 5.2 MB / file · 0/1
Error
Review your uploads
All file types · 21 MB / file · 1/10
- Project reference.pdf2 MB Connection interrupted Connection interrupted
Disabled
Uploads are paused
All file types · 21 MB / file · 0/10
Purpose
A file upload control lets people choose or drop files and see what happens next, including progress, errors, and retry options.
Parts & Composition
Use FileUpload with FileUploadHeader, FileUploadBody, and FileUploadFooter for the upload card. Its rows display app-owned upload statuses and actions. Keep the original selected File in each row’s source property so the SDK can stay in sync with row removal.
API & Props
| Part | Purpose |
|---|---|
FileInput | Root (variant: plain | card, value, defaultValue, onValueChange, onReject, accept, multiple, directory, minSize, maxSize, maxFiles, validate, disabled, controller). |
FileInputTrigger, FileInputDropzone | Picker button or dropzone (variant: button | dropzone), plus target and pasteTarget drop/paste handling. |
FileInputList, FileInputItem, FileInputItemRemove | File list with useSlidingHighlight row feedback and per-item remove actions. |
FileUpload, FileUploadHeader, FileUploadBody, FileUploadFooter, FileUploadClose | Card upload surface (separator default false on header, true on footer; FileUploadClose positioned at end-2.5 top-2.5). |
See the UI SDK File Input reference for upstream options on SDK parts. Wrapper-specific props are listed above.
Common props in detail
| Prop / part | Purpose |
|---|---|
size on FileInput or FileUpload | xs, sm, md (default), or lg. Adjusts typography, gaps, and the upload card’s region insets. |
value / defaultValue / onValueChange | Control or initialize the full File array. Update app rows from the next selection. |
accept / multiple / directory | Configure the browser picker. Validate incoming files again in the app and on the server. |
onReject | Use the rejection callback to show why a file could not be added. |
Controlled values are File[] and onValueChange reports the full selection. createFileInputController() opens the picker or manages files programmatically.
Theming, Layout & Responsiveness
FileInput (variant="card") and FileUpload use bg-card, border-border, rounded-lg, shadow-sm, and surfacePadding. FileUploadHeader (separator={false}) and FileUploadFooter (separator={true}) use surfaceRegionInset, surfaceHeaderRadius, and surfaceFooterRadius. FileUploadClose renders a ghost Button at end-2.5 top-2.5.
Motion & Accessibility
The shared highlight follows pointer and keyboard focus across file rows. Remove and retry buttons appear on hover, focus-within, or coarse touch pointers.
Arrow keys move between files in FileInputList, Delete/Backspace removes the focused file, and live announcements report additions and rejections.
Guidance for Coding Agents
Use the command in the Install tab, then read this Info page before composing the component.
Use FileInput for selection, validation, and file removal. Keep the original File with each upload row and let the app manage network progress, cancellation, and retry. Validate again on the server.
Start from the closest Preview → Usage example and use this page’s API table for component parts and options. For inherited props, callbacks, keyboard behavior, and rendering options, consult UI SDK File Input.
CLI installation
bunx --bun shadcn@latest add https://ui.devvarena.com/api/r/file-upload'use client';
import {
formatFileSize,
relativePath,
FileInput as SDKFileInput,
FileInputDropzone as SDKFileInputDropzone,
FileInputItem as SDKFileInputItem,
FileInputItemRemove as SDKFileInputItemRemove,
FileInputList as SDKFileInputList,
FileInputTrigger as SDKFileInputTrigger,
} from '@ui-sdk/react/file-input';
import { cva } from 'class-variance-authority';
import {
Box,
CloudUpload,
Database,
File,
FileArchive,
FileAudio,
FileCode,
FileImage,
FileSpreadsheet,
FileTerminal,
FileText,
FileType as FileTypeIcon,
FileVideo,
Palette,
Presentation,
RotateCcw,
Trash2,
X,
} from 'lucide-react';
import {
type ComponentProps,
createContext,
type MouseEvent,
useCallback,
useContext,
useId,
useMemo,
useState,
} from 'react';
import { Alert, AlertContent, AlertIcon, AlertTitle } from '@/components/devvarena-ui/alert';
import { Badge } from '@/components/devvarena-ui/badge';
import { Button, buttonVariants } from '@/components/devvarena-ui/button';
import { Separator } from '@/components/devvarena-ui/separator';
import { useSlidingHighlight } from '@/hooks/use-sliding-highlight';
import {
concentricRadius,
controlTextSizes,
focusRing,
partClass,
type StandardControlSize,
slidingHighlight,
surfaceBodyPadding,
surfaceFooterRadius,
surfaceHeaderRadius,
surfacePadding,
surfaceRegionInset,
} from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
import {
defaultLabels,
EMPTY_FILES,
type FileType,
type FileUploadFile,
type FileUploadRejection,
getFileType,
rejectionReasons,
uploadBadgeStatus,
} from './file-types';
const fileInputVariants = cva('relative grid w-full min-w-0', {
variants: {
variant: {
plain: '',
card: cn(
'rounded-lg border border-border bg-card text-card-foreground shadow-sm',
surfacePadding,
),
},
size: {
xs: `${controlTextSizes.xs} gap-2 [--surface-padding:1.3rem]`,
sm: `${controlTextSizes.sm} gap-2.5 [--surface-padding:1.35rem]`,
md: `${controlTextSizes.md} gap-3 [--surface-padding:1.5rem]`,
lg: `${controlTextSizes.lg} gap-4 [--surface-padding:1.75rem]`,
} satisfies Record<StandardControlSize, string>,
},
defaultVariants: { variant: 'plain', size: 'md' },
});
type FileInputProps = ComponentProps<typeof SDKFileInput> & {
variant?: 'plain' | 'card';
size?: StandardControlSize;
};
function FileInput({ className, variant = 'plain', size = 'md', ...props }: FileInputProps) {
return (
<SDKFileInput
{...props}
data-variant={variant}
data-size={size}
className={partClass(fileInputVariants({ variant, size }), className)}
/>
);
}
function FileInputDropzone({ className, ...props }: ComponentProps<typeof SDKFileInputDropzone>) {
return (
<SDKFileInputDropzone
{...props}
className={partClass(
'grid min-w-0 gap-3 rounded-lg border border-dashed border-border bg-muted/30 p-1 transition-colors data-drag-accept:border-primary data-drag-accept:bg-primary/10 data-drag-reject:border-destructive data-drag-reject:bg-destructive/10 data-disabled:opacity-50 motion-reduce:transition-none',
className,
)}
/>
);
}
type FileInputTriggerProps = ComponentProps<typeof SDKFileInputTrigger> & {
variant?: 'button' | 'dropzone';
};
function FileInputTrigger({
className,
variant = 'button',
children,
...props
}: FileInputTriggerProps) {
return (
<SDKFileInputTrigger
{...props}
className={partClass(
variant === 'dropzone'
? cn(
`grid w-full cursor-pointer justify-items-center gap-2 ${concentricRadius} px-4 py-6 text-center hover:bg-muted/60 focus-visible:ring-inset`,
focusRing,
)
: buttonVariants({ variant: 'outline' }),
className,
)}
>
{children ??
(variant === 'dropzone' ? (
<>
<CloudUpload aria-hidden="true" className="size-7 text-muted-foreground" />
<span className="font-medium">Drop files here or browse</span>
</>
) : (
'Browse files'
))}
</SDKFileInputTrigger>
);
}
function FileInputList({
className,
slidingHighlight: animatedHighlight = true,
children,
...props
}: ComponentProps<typeof SDKFileInputList> & { slidingHighlight?: boolean }) {
const { containerRef, highlightStyle } = useSlidingHighlight({
itemSelector: '[data-slot="file-input-item"]:not([data-disabled])',
disabled: !animatedHighlight,
});
return (
<div
ref={containerRef}
data-sliding-highlight={animatedHighlight || undefined}
className="group/file-input-list relative isolate min-w-0 has-[[data-slot=file-input-list]:empty]:hidden"
>
{animatedHighlight && (
<span aria-hidden="true" style={highlightStyle} className={slidingHighlight} />
)}
<SDKFileInputList
{...props}
className={partClass('grid min-w-0 gap-1 empty:hidden', className)}
>
{children}
</SDKFileInputList>
</div>
);
}
function FileInputItem({ className, children, ...props }: ComponentProps<typeof SDKFileInputItem>) {
return (
<SDKFileInputItem
{...props}
className={partClass(
`relative flex min-w-0 items-center gap-3 ${concentricRadius} border border-transparent px-2 py-1.5 outline-none group-not-data-sliding-highlight/file-input-list:hover:bg-muted/60 group-not-data-sliding-highlight/file-input-list:focus-visible:bg-muted/60 data-disabled:opacity-50`,
className,
)}
>
{children ??
(({ file }) => (
<>
<span
className="inline-grid size-8 shrink-0 place-items-center rounded-lg bg-muted text-muted-foreground"
aria-hidden="true"
>
<FileText className="size-4" />
</span>
<span className="grid min-w-0 flex-1 gap-0.5">
<span className="truncate font-medium">{relativePath(file)}</span>
<span className="text-xs text-muted-foreground">{formatFileSize(file.size)}</span>
</span>
<FileInputItemRemove />
</>
))}
</SDKFileInputItem>
);
}
function FileInputItemRemove({
className,
children = <X aria-hidden="true" />,
...props
}: ComponentProps<typeof SDKFileInputItemRemove>) {
return (
<SDKFileInputItemRemove
{...props}
className={partClass(buttonVariants({ variant: 'ghost', size: 'icon-xs' }), className)}
>
{children}
</SDKFileInputItemRemove>
);
}
type FileUploadProps = Omit<
FileInputProps,
'value' | 'defaultValue' | 'onValueChange' | 'onReject'
> & {
files?: readonly FileUploadFile[];
onFilesAdded: (files: File[]) => void;
onFilesRejected?: (rejections: FileUploadRejection[]) => void;
onRemove?: (id: string) => void;
onRetry?: (id: string) => void;
accept?: string;
maxSize?: number;
maxFiles?: number;
multiple?: boolean;
disabled?: boolean;
labels?: Partial<typeof defaultLabels>;
};
type UploadContextValue = {
files: readonly FileUploadFile[];
accept?: FileInputProps['accept'];
byteLimit: number;
limit: number;
multiple: boolean;
disabled: boolean;
unavailable: boolean;
text: typeof defaultLabels;
errors: string[];
showError: boolean;
dismissError: () => void;
onRemove?: (id: string) => void;
onRetry?: (id: string) => void;
};
const UploadContext = createContext<UploadContextValue | null>(null);
const ItemContext = createContext<{
file: FileUploadFile;
remove: (event: MouseEvent<HTMLElement>) => void;
} | null>(null);
function useUpload() {
const context = useContext(UploadContext);
if (!context) throw new Error('File Upload parts must be inside FileUpload.');
return context;
}
function useUploadItem() {
const context = useContext(ItemContext);
if (!context) throw new Error('File Upload item parts must be inside FileUploadItem.');
return context;
}
function FileUpload({
files = EMPTY_FILES,
onFilesAdded,
onFilesRejected,
onRemove,
onRetry,
accept,
maxSize = 20 * 1024 * 1024,
maxFiles = 10,
multiple = true,
disabled = false,
labels,
validate,
variant = 'card',
children,
...props
}: FileUploadProps) {
const [errors, setErrors] = useState<string[]>([]);
const errorId = useId();
const text = useMemo(() => ({ ...defaultLabels, ...labels }), [labels]);
const selected = files.flatMap(({ source }) => (source ? [source] : []));
const limit = Math.min(maxFiles, multiple ? maxFiles : 1);
const unavailable = disabled || files.length >= limit;
const contextValue = useMemo(
() => ({
files,
accept,
byteLimit: maxSize,
limit,
multiple,
disabled,
unavailable,
text,
errors,
showError: errors.length > 0,
dismissError: () => setErrors([]),
onRemove,
onRetry,
}),
[
files,
accept,
maxSize,
limit,
multiple,
disabled,
unavailable,
text,
errors,
onRemove,
onRetry,
],
);
return (
<UploadContext value={contextValue}>
<FileInput
{...props}
variant={variant}
className={partClass('block max-w-lg', props.className)}
accept={accept}
maxSize={maxSize}
maxFiles={Math.max(0, limit - files.length + selected.length)}
multiple={multiple}
disabled={unavailable}
value={selected}
validate={(file) =>
files.some((existing) => existing.name === file.name && existing.size === file.size)
? 'duplicate'
: validate?.(file)
}
onValueChange={(_, details) => {
setErrors([]);
if (details.added.length) onFilesAdded(details.added);
}}
onReject={(rejected) => {
const rejections = rejected.flatMap(({ file, reasons }) =>
reasons.flatMap((reason) => {
const mapped = rejectionReasons[reason];
return mapped ? [{ file, reason: mapped }] : [];
}),
);
const messages = rejected.flatMap(({ reasons }) =>
reasons.map((reason) => {
const mapped = rejectionReasons[reason];
return mapped ? text[`${mapped}Error`] : reason;
}),
);
setErrors([...new Set(messages)]);
if (rejections.length) onFilesRejected?.(rejections);
}}
render={props.render ?? <section />}
>
{(state) => (
<>
{typeof children === 'function' ? children(state) : children}
<div id={errorId} role="alert" aria-atomic="true" className="sr-only">
{errors.join(' ')}
</div>
</>
)}
</FileInput>
</UploadContext>
);
}
function FileUploadDropzone({ className, ...props }: ComponentProps<typeof SDKFileInputDropzone>) {
return (
<SDKFileInputDropzone
{...props}
className={partClass(
'group/upload relative rounded-lg border-2 ring-3 ring-background/50 border-dashed bg-muted/50 bg-linear-to-br from-background/60 via-card/30 to-muted/40 outline-none transition-[background-color,border-color,box-shadow] duration-200 data-drag-accept:border-primary data-drag-accept:bg-accent data-drag-reject:border-destructive motion-reduce:transition-none',
className,
)}
/>
);
}
function FileUploadTrigger({ className, ...props }: ComponentProps<typeof SDKFileInputTrigger>) {
const { errors } = useUpload();
return (
<SDKFileInputTrigger
{...props}
aria-invalid={props['aria-invalid'] ?? (errors.length > 0 || undefined)}
className={partClass(
'flex w-full min-h-48 flex-col items-center justify-center gap-4 rounded-[max(0px,calc(var(--radius-lg,0.5rem)-2px))] px-4 py-6 text-center outline-none md:min-h-52 cursor-pointer data-disabled:cursor-not-allowed data-disabled:opacity-60',
className,
)}
/>
);
}
function FileUploadBody({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="file-upload-body"
className={cn(surfaceRegionInset, surfaceBodyPadding, 'min-w-0', className)}
/>
);
}
function FileUploadFooter({
separator = true,
className,
children,
...props
}: ComponentProps<'footer'> & { separator?: boolean }) {
return (
<footer
{...props}
data-slot="file-upload-footer"
className={cn(
surfaceRegionInset,
surfaceFooterRadius,
'relative text-xs text-muted-foreground empty:hidden',
className,
)}
>
{separator && children != null ? (
<Separator className="absolute inset-x-0 top-0 w-auto" />
) : null}
{children}
</footer>
);
}
function FileUploadHeader({
separator = false,
className,
children,
...props
}: ComponentProps<'div'> & { separator?: boolean }) {
return (
<div
{...props}
data-slot="file-upload-header"
className={cn(
'relative [&.sticky]:top-0 flex items-start gap-2',
surfaceHeaderRadius,
surfaceRegionInset,
className,
)}
>
{children}
{separator ? <Separator className="absolute inset-x-0 bottom-0 w-auto" /> : null}
</div>
);
}
function FileUploadIcon({ className, children, ...props }: ComponentProps<'span'>) {
return (
<span
aria-hidden="true"
{...props}
data-slot="file-upload-icon"
className={cn(
'inline-flex size-5 shrink-0 items-center justify-center text-muted-foreground [&>svg]:size-full',
className,
)}
>
{children ?? <CloudUpload />}
</span>
);
}
function FileUploadTitle({
as: Heading = 'h3',
className,
...props
}: ComponentProps<'h3'> & { as?: 'h2' | 'h3' | 'h4' }) {
return (
<Heading
{...props}
data-slot="file-upload-title"
className={cn(
'm-0 flex items-center gap-2.5 text-xl font-semibold tracking-tight',
className,
)}
/>
);
}
function FileUploadDescription({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="file-upload-description"
className={cn('mt-1 text-sm leading-relaxed text-muted-foreground', className)}
/>
);
}
function FileUploadClose({ className, children, ...props }: ComponentProps<typeof Button>) {
const { text } = useUpload();
return (
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={text.close}
{...props}
data-slot="file-upload-close"
className={cn(
'absolute end-2.5 top-2.5 z-10 text-muted-foreground hover:text-foreground',
className,
)}
>
{children ?? <X aria-hidden="true" />}
</Button>
);
}
function FileUploadGraphic({ className, ...props }: ComponentProps<'span'>) {
return (
<span
aria-hidden="true"
{...props}
data-slot="file-upload-illustration"
className={cn(
'relative flex h-36 w-52 max-w-full items-center justify-center [&>svg]:h-full [&>svg]:w-full transition-transform duration-200 motion-reduce:transition-none',
'motion-safe:group-data-dragging/upload:-translate-y-1',
className,
)}
/>
);
}
function FileUploadPrompt({ className, children, ...props }: ComponentProps<'span'>) {
const { unavailable, text } = useUpload();
return (
<span
{...props}
data-slot="file-upload-prompt"
className={cn('flex flex-col gap-1', className)}
>
{children ?? (
<>
<span className="text-sm font-medium">
{unavailable ? (
text.disabled
) : (
<>
<span className="group-data-dragging/upload:hidden">{text.drop}</span>
<span className="hidden group-data-dragging/upload:inline">{text.drag}</span>
</>
)}
</span>
<span
className={cn(
'inline-block self-center text-sm text-muted-foreground underline decoration-border underline-offset-4',
!unavailable &&
'motion-safe:group-hover/upload:shimmer motion-safe:group-hover/upload:shimmer-once motion-safe:group-hover/upload:shimmer-duration-1000 motion-safe:group-focus-within/upload:shimmer motion-safe:group-focus-within/upload:shimmer-once motion-safe:group-focus-within/upload:shimmer-duration-1000',
)}
>
{text.browse}
</span>
</>
)}
</span>
);
}
function FileUploadError({ className, children, ...props }: ComponentProps<'div'>) {
const { errors, showError, dismissError } = useUpload();
const errorSummary = errors.join(' ');
if (!children && (!showError || !errorSummary)) return null;
return (
<div {...props} className={className}>
{children ??
(showError && errorSummary ? (
<Alert
tone="warning"
variant="soft"
size="sm"
duration={4000}
onOpenChange={(open) => {
if (!open) dismissError();
}}
role="presentation"
>
<AlertIcon />
<AlertContent>
<AlertTitle>{errorSummary}</AlertTitle>
</AlertContent>
</Alert>
) : null)}
</div>
);
}
function FileUploadHint({ className, children, ...props }: ComponentProps<'p'>) {
const { accept, byteLimit, files, limit, multiple } = useUpload();
return (
<p
{...props}
data-slot="file-upload-hint"
className={cn(
'mb-0 mt-1 break-words text-xs leading-relaxed text-muted-foreground',
className,
)}
>
{children ?? (
<>
{accept || 'All file types'} · {formatFileSize(byteLimit)} / file · {files.length}/
{multiple ? limit : Math.min(limit, 1)}
</>
)}
</p>
);
}
function FileUploadList({ className, ...props }: ComponentProps<'ul'>) {
const { disabled, files } = useUpload();
const { containerRef, highlightStyle } = useSlidingHighlight({ disabled });
return (
<div
ref={containerRef}
className={cn(
'relative isolate -mx-3 transition-[margin-top] duration-200 motion-reduce:transition-none',
files.length ? 'mt-6' : 'mt-0',
)}
>
<span
aria-hidden="true"
data-slot="file-upload-row-highlight"
style={highlightStyle}
className={slidingHighlight}
/>
<ul
{...props}
data-slot="file-upload-list"
className={cn('m-0 flex list-none flex-col p-0', className)}
/>
</div>
);
}
function FileUploadItem({
file,
className,
children,
onAnimationEnd,
...props
}: ComponentProps<'li'> & { file: FileUploadFile }) {
const { onRemove } = useUpload();
const remove = useCallback(
(event: MouseEvent<HTMLElement>) => {
if (!onRemove) return;
if (file.status === 'uploading') {
onRemove(file.id);
return;
}
const li = event.currentTarget.closest<HTMLElement>('[data-slot="file-upload-item"]');
if (li?.hasAttribute('data-exiting')) return;
if (!li || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
onRemove(file.id);
return;
}
li.setAttribute('data-exiting', '');
li.removeAttribute('data-highlight-item');
li.inert = true;
li.dispatchEvent(new PointerEvent('pointerout', { bubbles: true }));
},
[file.id, file.status, onRemove],
);
const itemValue = useMemo(() => ({ file, remove }), [file, remove]);
return (
<ItemContext value={itemValue}>
<li
{...props}
data-slot="file-upload-item"
data-highlight-item=""
onAnimationEnd={(event) => {
onAnimationEnd?.(event);
if (
event.target instanceof HTMLElement &&
event.target.dataset.slot === 'file-upload-item-body' &&
event.target.parentElement?.parentElement === event.currentTarget &&
event.currentTarget.hasAttribute('data-exiting')
)
onRemove?.(file.id);
}}
className={cn(
'group/row grid min-w-0 grid-rows-[1fr] duration-300 ease-out data-exiting:transition-[grid-template-rows] data-exiting:grid-rows-[0fr] motion-reduce:transition-none',
className,
)}
>
<div className="min-h-0 overflow-hidden">
<div
data-slot="file-upload-item-body"
className={`flex min-w-0 items-start gap-3 ${concentricRadius} p-3 opacity-100 blur-none transition-[opacity,filter] duration-300 ease-out starting:opacity-0 motion-safe:starting:blur-[6px] group-data-exiting/row:animate-out group-data-exiting/row:fade-out-0 group-data-exiting/row:blur-out-[6px] group-data-exiting/row:duration-300 group-data-exiting/row:fill-mode-both motion-reduce:group-data-exiting/row:duration-[1ms] motion-reduce:group-data-exiting/row:[--tw-exit-blur:0px] motion-reduce:transition-none motion-reduce:blur-none`}
>
{children}
</div>
</div>
</li>
</ItemContext>
);
}
const fileTypeIcons = {
file: File,
image: FileImage,
video: FileVideo,
audio: FileAudio,
pdf: FileText,
document: FileText,
text: FileText,
spreadsheet: FileSpreadsheet,
presentation: Presentation,
archive: FileArchive,
code: FileCode,
design: Palette,
font: FileTypeIcon,
model: Box,
database: Database,
executable: FileTerminal,
} satisfies Record<FileType, typeof File>;
function FileUploadItemPreview({ className, children, ...props }: ComponentProps<'span'>) {
const { file } = useUploadItem();
const Icon = fileTypeIcons[getFileType(file.name, file.type)];
return (
<span
aria-hidden="true"
{...props}
data-slot="file-upload-item-preview"
className={cn(
'flex size-10 shrink-0 items-center justify-center rounded-lg border border-border bg-muted/30 text-muted-foreground [&>svg]:size-5',
className,
)}
>
{children ?? file.icon ?? <Icon />}
</span>
);
}
function FileUploadItemContent({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="file-upload-item-content"
className={cn('min-w-0 flex-1', className)}
/>
);
}
function FileUploadItemName({ className, children, ...props }: ComponentProps<'div'>) {
const { file } = useUploadItem();
return (
<div
{...props}
data-slot="file-upload-item-name"
className={cn('break-words text-sm font-medium leading-snug', className)}
>
{children ?? file.name}
</div>
);
}
function FileUploadItemSize({ className, children, ...props }: ComponentProps<'span'>) {
const { file } = useUploadItem();
return (
<span {...props} data-slot="file-upload-item-size" className={className}>
{children ?? formatFileSize(file.size)}
</span>
);
}
function FileUploadItemStatus({ children, ...props }: ComponentProps<typeof Badge>) {
const { file } = useUploadItem();
const { text } = useUpload();
return (
<Badge
status={uploadBadgeStatus[file.status]}
size="sm"
animated={file.status === 'uploading'}
{...props}
>
{children ?? (file.status === 'error' ? file.error || text.error : text[file.status])}
</Badge>
);
}
function FileUploadItemActions({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="file-upload-item-actions"
className={cn('flex shrink-0 items-center gap-1', className)}
/>
);
}
function FileUploadRemove({
className,
children,
onClick,
disabled,
...props
}: ComponentProps<typeof Button>) {
const { file, remove } = useUploadItem();
const upload = useUpload();
if (!upload.onRemove) return null;
return (
<Button
type="button"
variant="destructive-soft"
size="icon-xs"
{...props}
disabled={upload.disabled || disabled}
aria-label={
props['aria-label'] ??
`${file.status === 'uploading' ? upload.text.cancel : upload.text.remove}: ${file.name}`
}
data-slot="file-upload-remove"
onClick={(event, details) => {
const result = onClick?.(event, details);
if (!event.defaultPrevented && !upload.disabled && !disabled) remove(event);
return result;
}}
className={cn(
'pointer-events-none opacity-0 transition-opacity duration-150 motion-reduce:transition-none focus-visible:pointer-events-auto focus-visible:opacity-100 group-focus-within/row:pointer-events-auto group-focus-within/row:opacity-100 group-hover/row:pointer-events-auto group-hover/row:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100',
className,
)}
>
{children ??
(file.status === 'uploading' ? (
<X aria-hidden="true" className="size-4" />
) : (
<Trash2 aria-hidden="true" className="size-4" />
))}
</Button>
);
}
function FileUploadRetry({
className,
children,
onClick,
disabled,
...props
}: ComponentProps<typeof Button>) {
const { file } = useUploadItem();
const upload = useUpload();
if (!upload.onRetry || file.status !== 'error') return null;
return (
<Button
type="button"
variant="ghost"
size="icon-sm"
{...props}
disabled={upload.disabled || disabled}
aria-label={props['aria-label'] ?? `${upload.text.retry}: ${file.name}`}
data-slot="file-upload-retry"
onClick={(event, details) => {
const result = onClick?.(event, details);
if (!event.defaultPrevented && !upload.disabled && !disabled) upload.onRetry?.(file.id);
return result;
}}
className={cn('text-muted-foreground', className)}
>
{children ?? <RotateCcw aria-hidden="true" className="size-4" />}
</Button>
);
}
export type { FileInputOptions, FileInputValueChangeDetails } from '@ui-sdk/core/file-input';
export type { FileRejection } from '@ui-sdk/react/file-input';
export { createFileInputController, formatFileSize, relativePath } from '@ui-sdk/react/file-input';
export {
FileInput,
FileInputDropzone,
FileInputItem,
FileInputItemRemove,
FileInputList,
FileInputTrigger,
FileUpload,
FileUploadBody,
FileUploadClose,
FileUploadDescription,
FileUploadDropzone,
FileUploadError,
type FileUploadFile,
FileUploadFooter,
FileUploadGraphic,
FileUploadHeader,
FileUploadHint,
FileUploadIcon,
FileUploadItem,
FileUploadItemActions,
FileUploadItemContent,
FileUploadItemName,
FileUploadItemPreview,
FileUploadItemSize,
FileUploadItemStatus,
FileUploadList,
FileUploadPrompt,
type FileUploadRejection,
FileUploadRemove,
FileUploadRetry,
FileUploadTitle,
FileUploadTrigger,
};
import type { ReactNode } from 'react';
/** Visual classification only; never use this to validate file safety or contents. */
const fileExtensionGroups = {
image: 'jpg jpeg jfif png gif webp avif heic heif bmp tif tiff ico svg raw cr2 nef dng',
video: 'mp4 m4v mov webm mkv avi wmv flv mpg mpeg 3gp ogv ts mts m2ts',
audio: 'mp3 wav ogg oga opus aac m4a flac aiff aif wma mid midi amr',
pdf: 'pdf',
document: 'doc docx odt rtf pages epub mobi azw azw3',
text: 'txt md markdown rst log tex',
spreadsheet: 'xls xlsx xlsm xlsb csv tsv ods numbers',
presentation: 'ppt pptx pps ppsx odp key',
archive: 'zip rar 7z tar gz gzip bz2 xz zst tgz cab iso dmg',
code: 'js jsx ts tsx mjs cjs html htm css scss sass less json jsonc xml yaml yml toml ini env py ipynb java kt kts c h cpp hpp cs go rs rb php swift sh bash zsh ps1 bat vue svelte graphql gql wasm',
design: 'fig sketch xd psd psb ai eps indd afdesign afphoto afpub xcf procreate',
font: 'ttf otf woff woff2 eot',
model: 'obj fbx gltf glb stl blend 3ds dae usdz step stp dwg dxf',
database: 'sql sqlite sqlite3 db mdb accdb parquet arrow',
executable: 'exe msi app apk aab deb rpm pkg bin dll so dylib',
} as const;
type FileType = keyof typeof fileExtensionGroups | 'file';
const extensionTypes = new Map<string, FileType>(
Object.entries(fileExtensionGroups).flatMap(([type, names]) =>
names.split(' ').map((name) => [name, type as FileType] as const),
),
);
const mimeTypes: Record<string, FileType> = {
'application/pdf': 'pdf',
'application/msword': 'document',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'document',
'application/vnd.oasis.opendocument.text': 'document',
'application/vnd.ms-excel': 'spreadsheet',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'spreadsheet',
'text/csv': 'spreadsheet',
'application/vnd.ms-powerpoint': 'presentation',
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'presentation',
'application/zip': 'archive',
'application/x-7z-compressed': 'archive',
'application/gzip': 'archive',
'application/json': 'code',
'application/xml': 'code',
'text/html': 'code',
'text/css': 'code',
};
function getFileType(name: string, mimeType = ''): FileType {
const extension = name.includes('.') ? name.split('.').pop()?.toLowerCase() : undefined;
const known = extension ? extensionTypes.get(extension) : undefined;
if (known) return known;
const mime = mimeType.split(';', 1)[0].trim().toLowerCase();
if (mimeTypes[mime]) return mimeTypes[mime];
if (mime.startsWith('image/')) return 'image';
if (mime.startsWith('video/')) return 'video';
if (mime.startsWith('audio/')) return 'audio';
if (mime.startsWith('font/')) return 'font';
if (mime.startsWith('text/')) return 'text';
return 'file';
}
type FileUploadFile = {
id: string;
source?: File;
name: string;
/** Optional MIME type, used when the filename extension is unknown. */
type?: string;
size: number;
status: 'queued' | 'uploading' | 'complete' | 'error';
error?: string;
icon?: ReactNode;
};
type FileUploadRejection = {
file: File;
reason: 'type' | 'size' | 'count' | 'duplicate';
};
const EMPTY_FILES: readonly FileUploadFile[] = [];
const uploadBadgeStatus = {
queued: 'warning',
uploading: 'progress',
complete: 'success',
error: 'error',
} as const;
const defaultLabels = {
drop: 'Drop files here',
browse: 'or browse files',
drag: 'Release to add your files',
disabled: 'File selection unavailable',
queued: 'Ready to upload',
uploading: 'Uploading',
complete: 'Completed',
error: 'Upload failed',
remove: 'Remove',
cancel: 'Cancel upload',
close: 'Close file upload',
retry: 'Retry',
typeError: 'Some files have an unsupported format.',
sizeError: 'Some files exceed the size limit.',
countError: 'The file limit has been reached.',
duplicateError: 'Some files are already in the list.',
};
const rejectionReasons: Record<string, FileUploadRejection['reason']> = {
'file-type': 'type',
'file-too-large': 'size',
'file-too-small': 'size',
'too-many-files': 'count',
duplicate: 'duplicate',
};
export type { FileType, FileUploadFile, FileUploadRejection };
export { defaultLabels, EMPTY_FILES, getFileType, rejectionReasons, uploadBadgeStatus };
'use client';
import { cva, type VariantProps } from 'class-variance-authority';
import { Bell, CircleCheck, CircleX, TriangleAlert, X } from 'lucide-react';
import {
type ComponentProps,
createContext,
useCallback,
useContext,
useEffect,
useEffectEvent,
useMemo,
useState,
} from 'react';
import { Button, type ButtonProps } from '@/components/devvarena-ui/button';
import { controlTextSizes, surfaceRegionInset } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
const tones = {
neutral: {
icon: <Bell />,
className:
'[--notice-color:var(--muted-foreground)] [--notice-fill:var(--muted-foreground)] [--notice-ink:var(--background)]',
},
info: {
icon: <Bell />,
className:
'[--notice-color:var(--status-info,var(--color-blue-600))] dark:[--notice-color:var(--status-info,var(--color-blue-400))] [--notice-fill:var(--status-info,var(--color-blue-500))] [--notice-ink:white]',
},
success: {
icon: <CircleCheck />,
className:
'[--notice-color:var(--status-success,var(--color-green-700))] dark:[--notice-color:var(--status-success,var(--color-green-400))] [--notice-fill:var(--status-success,var(--color-green-500))] [--notice-ink:white]',
},
warning: {
icon: <TriangleAlert />,
className:
'[--notice-color:var(--status-pending,var(--color-yellow-800))] dark:[--notice-color:var(--status-pending,var(--color-yellow-300))] [--notice-fill:var(--status-pending,var(--color-yellow-400))] [--notice-ink:white]',
},
error: {
icon: <CircleX />,
className:
'[--notice-color:var(--status-error,var(--color-red-600))] dark:[--notice-color:var(--status-error,var(--color-red-400))] [--notice-fill:var(--status-error,var(--color-red-500))] [--notice-ink:white]',
},
} as const;
const alertVariants = cva(
'group/alert relative isolate grid h-auto w-full min-w-0 grid-cols-[minmax(0,1fr)] items-start gap-3 rounded-lg ring-1 ring-border bg-card text-card-foreground has-[>[data-slot=alert-icon]]:grid-cols-[auto_minmax(0,1fr)] has-[>[data-slot=alert-close]]:pe-14 md:has-[>[data-slot=alert-close]]:pe-12 md:has-[>[data-slot=alert-actions]]:grid-cols-[minmax(0,1fr)_auto] md:has-[>[data-slot=alert-icon]]:has-[>[data-slot=alert-actions]]:grid-cols-[auto_minmax(0,1fr)_auto] opacity-100 blur-none [interpolate-size:allow-keywords] [transition-behavior:allow-discrete] transition-[display,opacity,filter] duration-250 ease-out starting:opacity-0 motion-safe:starting:blur-[6px] [&[hidden]]:hidden [&[hidden]]:h-0 [&[hidden]]:overflow-hidden [&[hidden]]:gap-0 [&[hidden]]:ring-0 [&[hidden]]:p-0 [&[hidden]]:opacity-0 motion-safe:[&[hidden]]:blur-[6px] [&[hidden]]:transition-[display,height,padding,gap,opacity,filter] motion-reduce:transition-none motion-reduce:blur-none',
{
variants: {
variant: {
outline: '',
soft: '[--notice-soft-surface:color-mix(in_oklab,var(--notice-fill)_8%,var(--card))] ring-2 [--notice-soft-edge:color-mix(in_oklab,var(--notice-soft-surface)_30%,white)] dark:[--notice-soft-surface:color-mix(in_oklab,var(--notice-fill)_12%,var(--card))] dark:[--notice-soft-edge:color-mix(in_oklab,var(--notice-soft-surface)_78%,black)] ring-[var(--notice-soft-edge)] bg-[var(--notice-soft-surface)]',
stripe:
'ring-[color-mix(in_oklab,var(--notice-color)_18%,var(--border))] bg-[color-mix(in_oklab,var(--notice-fill)_4%,var(--card))] before:pointer-events-none before:absolute before:inset-y-3 before:start-3 before:w-0.5 before:rounded-full before:bg-[var(--notice-color)]',
accent:
'bg-[linear-gradient(110deg,color-mix(in_oklab,var(--notice-fill)_12%,var(--card)),var(--card)_55%)] rtl:bg-[linear-gradient(250deg,color-mix(in_oklab,var(--notice-fill)_12%,var(--card)),var(--card)_55%)]',
},
size: {
xs: [
controlTextSizes.xs,
'[--surface-padding:1.3rem] [--notice-icon-size:1rem] [--notice-glyph-size:1rem] gap-2 has-[>[data-slot=alert-close]]:min-h-10',
],
sm: [
controlTextSizes.sm,
'[--surface-padding:1.125rem] [--notice-icon-size:1.125rem] [--notice-glyph-size:1.125rem] gap-2 has-[>[data-slot=alert-close]]:min-h-10',
],
md: [
controlTextSizes.md,
'[--surface-padding:1.5rem] [--notice-icon-size:2.5rem] [--notice-glyph-size:1.25rem]',
],
lg: [
controlTextSizes.lg,
'[--surface-padding:1.75rem] [--notice-icon-size:2.5rem] [--notice-glyph-size:1.25rem]',
],
},
},
compoundVariants: [
{ variant: 'stripe', size: ['xs', 'sm'], className: 'before:inset-y-2 before:start-2' },
],
defaultVariants: { variant: 'outline', size: 'md' },
},
);
type NoticeTone = keyof typeof tones;
const NoticeContext = createContext<{
tone: NoticeTone;
plainIcon: boolean;
close: () => void;
} | null>(null);
function useNotice() {
const context = useContext(NoticeContext);
if (!context) throw new Error('Alert parts must be inside Alert.');
return context;
}
type AlertProps = Omit<ComponentProps<'div'>, 'hidden'> &
VariantProps<typeof alertVariants> & {
tone?: NoticeTone;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Persistent by default. A positive duration dismisses after idle milliseconds. */
duration?: number;
};
/** Inline feedback, not a toast manager. CSS owns motion; the optional timer owns visibility. */
function Alert({
tone = 'neutral',
variant = 'outline',
size: sizeProp,
open,
defaultOpen = true,
onOpenChange,
duration = 0,
className,
children,
role = tone === 'error' ? 'alert' : 'status',
'aria-atomic': atomic = true,
onPointerEnter,
onPointerLeave,
onFocusCapture,
onBlurCapture,
...props
}: AlertProps) {
const size = sizeProp ?? 'md';
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [paused, setPaused] = useState(false);
const visible = open ?? internalOpen;
const timed = Number.isFinite(duration) && duration > 0;
const close = useCallback(() => {
if (!visible) return;
if (open === undefined) setInternalOpen(false);
onOpenChange?.(false);
setPaused(false);
}, [visible, open, onOpenChange]);
const expire = useEffectEvent(close);
useEffect(() => {
if (!visible || paused || !timed) return;
const timer = window.setTimeout(expire, duration);
return () => window.clearTimeout(timer);
}, [visible, paused, duration, timed]);
const plainIcon = variant === 'stripe' || size === 'xs' || size === 'sm';
const noticeValue = useMemo(() => ({ tone, plainIcon, close }), [tone, plainIcon, close]);
return (
<NoticeContext.Provider value={noticeValue}>
<div
{...props}
role={role}
aria-atomic={atomic}
hidden={!visible}
inert={!visible || undefined}
data-slot="alert"
data-tone={tone}
data-size={size}
data-variant={variant}
className={cn(
alertVariants({ variant, size }),
surfaceRegionInset,
tones[tone].className,
variant === 'stripe' && 'ps-7',
className,
)}
onPointerEnter={(event) => {
onPointerEnter?.(event);
if (timed && !event.defaultPrevented && event.pointerType !== 'touch') setPaused(true);
}}
onPointerLeave={(event) => {
onPointerLeave?.(event);
if (!event.defaultPrevented)
setPaused(
timed &&
event.currentTarget.contains(event.currentTarget.ownerDocument.activeElement),
);
}}
onFocusCapture={(event) => {
onFocusCapture?.(event);
if (timed && !event.defaultPrevented) setPaused(true);
}}
onBlurCapture={(event) => {
onBlurCapture?.(event);
if (!event.defaultPrevented && !event.currentTarget.contains(event.relatedTarget))
setPaused(timed && event.currentTarget.matches(':hover'));
}}
>
{children}
</div>
</NoticeContext.Provider>
);
}
function AlertIcon({ className, children, ...props }: ComponentProps<'div'>) {
const { tone, plainIcon } = useNotice();
return (
<div
aria-hidden="true"
{...props}
data-slot="alert-icon"
className={cn(
'col-start-1 row-start-1 flex shrink-0 items-center justify-center [&>svg]:size-[var(--notice-glyph-size)]',
plainIcon
? 'size-[var(--notice-glyph-size)] text-[var(--notice-color)]'
: [
'size-[var(--notice-icon-size)] rounded-lg ring-1 ring-border bg-[color-mix(in_oklab,var(--notice-fill)_10%,var(--card))] text-[var(--notice-color)]',
'group-data-[variant=outline]/alert:bg-[var(--notice-fill)] group-data-[variant=outline]/alert:text-[var(--notice-ink)] group-data-[variant=accent]/alert:bg-[var(--notice-fill)] group-data-[variant=accent]/alert:text-[var(--notice-ink)]',
'group-data-[variant=outline]/alert:ring-[color-mix(in_oklab,var(--notice-fill)_30%,white)] group-data-[variant=accent]/alert:ring-[color-mix(in_oklab,var(--notice-fill)_30%,white)]',
'group-data-[variant=outline]/alert:shadow-[inset_0_1px_0_rgb(255_255_255/0.22),inset_0_-1px_0_color-mix(in_oklab,var(--notice-fill)_12%,transparent),0_1px_2px_color-mix(in_oklab,var(--notice-fill)_12%,transparent)] group-data-[variant=accent]/alert:shadow-[inset_0_1px_0_rgb(255_255_255/0.22),inset_0_-1px_0_color-mix(in_oklab,var(--notice-fill)_12%,transparent),0_1px_2px_color-mix(in_oklab,var(--notice-fill)_12%,transparent)]',
'dark:group-data-[variant=outline]/alert:ring-[color-mix(in_oklab,var(--notice-fill),black_25%)] dark:group-data-[variant=accent]/alert:ring-[color-mix(in_oklab,var(--notice-fill),black_25%)]',
'dark:group-data-[variant=outline]/alert:shadow-[inset_0_1px_0_rgb(255_255_255/0.2),inset_0_-1px_0_rgb(0_0_0/0.1),0_1px_2px_rgb(0_0_0/0.12)] dark:group-data-[variant=accent]/alert:shadow-[inset_0_1px_0_rgb(255_255_255/0.2),inset_0_-1px_0_rgb(0_0_0/0.1),0_1px_2px_rgb(0_0_0/0.12)]',
'group-data-[variant=soft]/alert:ring-0 group-data-[variant=soft]/alert:bg-card group-data-[variant=soft]/alert:shadow-[inset_0_1px_0_rgb(255_255_255/0.14),0_1px_2px_color-mix(in_oklab,var(--notice-fill)_10%,transparent)] dark:group-data-[variant=soft]/alert:shadow-[inset_0_1px_0_rgb(255_255_255/0.08),0_1px_2px_rgb(0_0_0/0.12)]',
],
className,
)}
>
{children === undefined ? tones[tone].icon : children}
</div>
);
}
function AlertContent({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="alert-content"
className={cn(
'col-start-1 row-start-1 flex min-w-0 flex-col gap-1 group-has-[[data-slot=alert-icon]]/alert:col-start-2',
className,
)}
/>
);
}
function AlertTitle({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="alert-title"
className={cn('font-semibold leading-snug [overflow-wrap:anywhere]', className)}
/>
);
}
function AlertDescription({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="alert-description"
className={cn(
'leading-relaxed text-muted-foreground [overflow-wrap:anywhere] [&_a]:text-foreground [&_a]:underline [&_a]:underline-offset-4',
className,
)}
/>
);
}
function AlertActions({ className, ...props }: ComponentProps<'div'>) {
return (
<div
{...props}
data-slot="alert-actions"
className={cn(
'col-start-1 row-start-2 flex min-w-0 flex-wrap items-center gap-2 group-has-[[data-slot=alert-icon]]/alert:col-start-2 md:col-start-2 md:row-start-1 md:self-center md:group-has-[[data-slot=alert-icon]]/alert:col-start-3',
className,
)}
/>
);
}
const closeIcon = <X aria-hidden="true" />;
function AlertClose({
className,
children,
onClick,
variant = 'ghost',
size = 'icon-xs',
'aria-label': label = 'Dismiss notice',
...props
}: ButtonProps) {
const { close } = useNotice();
return (
<Button
{...props}
type="button"
variant={variant}
size={size}
aria-label={label}
data-slot="alert-close"
onClick={(event, details) => {
const result = onClick?.(event, details);
if (!event.defaultPrevented) close();
return result;
}}
className={cn(
'absolute end-2.5 top-2.5 z-10 text-muted-foreground hover:text-foreground',
className,
)}
>
{children ?? closeIcon}
</Button>
);
}
export { Alert, AlertActions, AlertClose, AlertContent, AlertDescription, AlertIcon, AlertTitle };
import { mergeProps, type RenderProp, renderElement } from '@ui-sdk/react/primitive';
import { cva, type VariantProps } from 'class-variance-authority';
import { Bell, CircleCheck, CircleDashed, CircleX, TriangleAlert } from 'lucide-react';
import type { ComponentProps, ReactNode } from 'react';
import { ValueTransition } from '@/hooks/use-value-transition';
import { compactControlMinHeights, controlTextSizes } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
/** Label (`--badge-color`), fill, and ink align with Alert tone tokens. */
const statuses = {
neutral: {
label: 'Status',
className:
'[--badge-color:var(--muted-foreground)] [--badge-fill:var(--muted-foreground)] [--badge-ink:white]',
},
info: {
label: 'Info',
icon: Bell,
className:
'[--badge-color:var(--status-info,var(--color-blue-600))] dark:[--badge-color:var(--status-info,var(--color-blue-400))] [--badge-fill:var(--status-info,var(--color-blue-500))] [--badge-ink:white]',
},
progress: {
label: 'In progress',
icon: CircleDashed,
className:
'[--badge-color:var(--status-progress,var(--color-violet-600))] dark:[--badge-color:var(--status-progress,var(--color-violet-400))] [--badge-fill:var(--status-progress,var(--color-violet-500))] [--badge-ink:white]',
},
warning: {
label: 'Warning',
icon: TriangleAlert,
className:
'[--badge-color:var(--status-warning,var(--status-pending,var(--color-yellow-800)))] dark:[--badge-color:var(--status-warning,var(--status-pending,var(--color-yellow-300)))] [--badge-fill:var(--status-warning,var(--status-pending,var(--color-yellow-500)))] [--badge-ink:white]',
},
success: {
label: 'Success',
icon: CircleCheck,
className:
'[--badge-color:var(--status-success,var(--color-green-700))] dark:[--badge-color:var(--status-success,var(--color-green-400))] [--badge-fill:var(--status-success,var(--color-green-500))] [--badge-ink:white]',
},
error: {
label: 'Error',
icon: CircleX,
className:
'[--badge-color:var(--status-error,var(--color-red-600))] dark:[--badge-color:var(--status-error,var(--color-red-400))] [--badge-fill:var(--status-error,var(--color-red-500))] [--badge-ink:white]',
},
} as const;
const badgeShadow =
'shadow-[inset_0_1px_0_rgb(255_255_255/0.45),0_1px_1.5px_rgb(0_0_0/0.14)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.22),0_1px_2px_rgb(0_0_0/0.4)]';
const badgeVariants = cva(
'group/badge inline-flex w-fit max-w-full min-w-0 items-center justify-center rounded-sm border border-transparent font-medium tracking-normal whitespace-normal select-none transition-[background-color,border-color,box-shadow,filter,translate] duration-150 ease-out [a&,button&]:cursor-pointer [a&,button&]:touch-manipulation motion-safe:[a&,button&]:active:translate-y-px motion-reduce:transition-none',
{
variants: {
status: {
neutral: statuses.neutral.className,
info: statuses.info.className,
progress: statuses.progress.className,
warning: statuses.warning.className,
success: statuses.success.className,
error: statuses.error.className,
},
variant: {
soft: '[--badge-tone:var(--badge-fill,var(--badge-color))] bg-[color-mix(in_oklab,var(--badge-tone)_10%,transparent)] dark:bg-[color-mix(in_oklab,var(--badge-tone)_16%,transparent)] text-[color:var(--badge-color)]',
outline:
'[--badge-tone:var(--badge-fill,var(--badge-color))] border-[color-mix(in_oklab,var(--badge-tone)_32%,var(--border))] bg-transparent text-[color:var(--badge-color)]',
solid: `[--badge-tone:var(--badge-fill,var(--badge-color))] border-[color-mix(in_oklab,var(--badge-tone),black_12%)] bg-[var(--badge-tone)] text-[color:var(--badge-ink,white)] ${badgeShadow}`,
},
size: {
xs: `${compactControlMinHeights.xs} ${controlTextSizes.xs} gap-1 px-1.5 leading-none [&_[data-slot=badge-icon]]:size-2.5`,
sm: `${compactControlMinHeights.sm} ${controlTextSizes.sm} gap-1 px-2 py-0.5 leading-none [&_[data-slot=badge-icon]]:size-3`,
md: `${compactControlMinHeights.md} text-xs gap-1.5 px-2 py-0.5 leading-none [&_[data-slot=badge-icon]]:size-3.5`,
lg: `${compactControlMinHeights.lg} ${controlTextSizes.lg} gap-2 px-3 py-1 leading-snug [&_[data-slot=badge-icon]]:size-4`,
},
},
compoundVariants: [
{
status: 'neutral',
variant: 'solid',
className: 'border-border bg-muted text-muted-foreground',
},
],
defaultVariants: { status: 'neutral', variant: 'soft', size: 'md' },
},
);
type BadgeStatus = keyof typeof statuses;
type BadgeSize = NonNullable<VariantProps<typeof badgeVariants>['size']>;
type BadgeVariant = NonNullable<VariantProps<typeof badgeVariants>['variant']>;
type BadgeState = { slot: 'badge'; status: BadgeStatus; variant: BadgeVariant; size: BadgeSize };
type BadgeProps = ComponentProps<'span'> &
Omit<VariantProps<typeof badgeVariants>, 'status' | 'size' | 'variant'> & {
/** Semantic status preset for its label, icon, and theme color. */
status?: BadgeStatus;
/** Override the preset icon. Pass null or false to omit it. */
icon?: ReactNode;
/** Place the icon before or after the label. */
iconPosition?: 'start' | 'end';
/** Rotate the preset icon, typically for the progress status. */
animated?: boolean;
size?: BadgeSize;
variant?: BadgeVariant;
/** Render the badge as another element, such as an anchor or button. */
render?: RenderProp<BadgeState>;
};
function Badge({
status = 'neutral',
variant = 'soft',
size = 'md',
icon,
iconPosition = 'start',
animated = false,
children,
className,
render,
...props
}: BadgeProps) {
const preset = statuses[status];
const DefaultIcon = 'icon' in preset ? preset.icon : null;
const content = icon !== undefined ? icon : DefaultIcon ? <DefaultIcon /> : null;
const label = children ?? preset.label;
const displayedLabel =
typeof label === 'string' || typeof label === 'number' ? (
<ValueTransition
value={label}
className="min-w-0 max-w-full flex-wrap [overflow-wrap:anywhere]"
/>
) : (
label
);
const indicator =
content === null || content === false ? null : (
<span
aria-hidden="true"
data-slot="badge-icon"
className={cn(
'inline-flex shrink-0 items-center justify-center [&>svg]:size-full [&>svg]:stroke-[1.75]',
animated &&
icon === undefined &&
DefaultIcon &&
'motion-safe:animate-spin motion-safe:[animation-duration:1.6s]',
)}
>
{content}
</span>
);
const state: BadgeState = { slot: 'badge', status, variant, size };
return renderElement(
'span',
mergeProps(props, {
'data-slot': 'badge',
'data-status': status,
'data-variant': variant,
'data-size': size,
className: cn(badgeVariants({ status, variant, size }), className),
children: (
<>
{iconPosition === 'start' && indicator}
<span data-slot="badge-label" className="min-w-0 [overflow-wrap:anywhere]">
{displayedLabel}
</span>
{iconPosition === 'end' && indicator}
</>
),
}),
render,
state,
);
}
export { Badge, type BadgeProps, type BadgeSize, type BadgeStatus, badgeVariants };
import type { ButtonOptions } from '@ui-sdk/core/button';
import { Button as ButtonPrimitive } from '@ui-sdk/react/button';
import { cva, type VariantProps } from 'class-variance-authority';
import { Loader2 } from 'lucide-react';
import type { ComponentProps, ReactNode } from 'react';
import { controlHeights, controlTextSizes, focusRing } from '@/lib/devvarena-ui';
import { cn } from '@/lib/utils';
/*
* Clean tactile button surfaces with a subtle top highlight, contact shadow,
* and 2% press scale using pure Tailwind/theme tokens.
*/
const flatPress = 'motion-safe:not-data-disabled:not-data-pending:active:scale-[0.985]';
const activeInsetShadow =
'active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.12),0_1px_2px_rgb(0_0_0/0.06)] dark:active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.18),0_1px_2px_rgb(0_0_0/0.1)]';
const tactileFilled =
'bg-[linear-gradient(180deg,rgb(255_255_255/0.16),rgb(255_255_255/0)_75%)] shadow-[inset_0_1.5px_0_rgb(255_255_255/0.22),inset_0_-1px_0_rgb(0_0_0/0.12),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] active:shadow-[inset_0_1px_3px_rgb(0_0_0/0.18),0_1px_2px_rgb(0_0_0/0.1)]';
const tactileNeutral = `bg-[linear-gradient(180deg,rgb(255_255_255/0.35),transparent_48%,rgb(0_0_0/0.025)_100%)] shadow-[inset_0_1px_0_rgb(255_255_255/0.65),inset_0_-1px_0_rgb(0_0_0/0.06),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] dark:bg-[linear-gradient(180deg,rgb(255_255_255/0.06),transparent_48%,rgb(0_0_0/0.12)_100%)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.1),inset_0_-1px_0_rgb(0_0_0/0.12),0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)] ${activeInsetShadow}`;
/** Surface map for button variants, shared with Toggle, Tabs, Radio, Checkbox, and Switch. */
const buttonSurfaces = {
primary: `border-[color-mix(in_oklch,var(--primary),black_8%)] bg-primary text-primary-foreground ${tactileFilled} ${flatPress}`,
secondary: ` bg-popover text-popover-foreground border-[color-mix(in_oklch,var(--muted),black_5%)] ${tactileNeutral} ${flatPress}`,
outline: `border-input bg-accent/10 text-foreground shadow-sm hover:text-accent-foreground ${activeInsetShadow} ${flatPress}`,
ghost: `border-transparent text-foreground hover:bg-muted ${activeInsetShadow} ${flatPress}`,
destructive: `border-[color-mix(in_oklch,var(--destructive),black_8%)] bg-destructive text-[color:var(--destructive-foreground,white)] ${tactileFilled} ${flatPress}`,
tertiary: `border-transparent bg-accent text-accent-foreground ${activeInsetShadow} ${flatPress}`,
'destructive-soft': `border-transparent bg-destructive/10 text-destructive dark:bg-destructive/20 ${activeInsetShadow} ${flatPress}`,
link: 'border-transparent text-primary underline-offset-4 hover:underline',
} as const;
type ButtonVariant = keyof typeof buttonSurfaces;
const buttonBase = cva(
[
// layout
'group/button relative isolate inline-flex shrink-0 items-center justify-center whitespace-nowrap rounded-lg border text-sm font-medium',
// interaction
'cursor-pointer select-none touch-manipulation',
'transition-[background-color,border-color,box-shadow,translate,scale,filter] duration-150 ease-out motion-reduce:transition-none',
focusRing,
// 44px touch target on coarse pointers without changing the visual size
'[@media(pointer:coarse)]:after:absolute [@media(pointer:coarse)]:after:inset-1/2 [@media(pointer:coarse)]:after:min-h-11 [@media(pointer:coarse)]:after:min-w-11 [@media(pointer:coarse)]:after:-translate-1/2',
// states
'disabled:cursor-not-allowed aria-disabled:opacity-50 data-disabled:cursor-not-allowed data-disabled:opacity-50 data-pending:cursor-wait',
// icons
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-(--icon-size,1rem) [&>span:has(>svg):not([class*='size-'])]:size-(--icon-size,1rem)",
],
{
variants: {
size: {
md: `${controlHeights.md} ${controlTextSizes.md} gap-2 px-4 [--icon-size:1.2rem]`,
xs: `${controlHeights.xs} ${controlTextSizes.xs} gap-1 px-2.5 [--icon-size:0.875rem]`,
sm: `${controlHeights.sm} ${controlTextSizes.sm} gap-1.5 px-3 [--icon-size:1rem]`,
lg: `${controlHeights.lg} ${controlTextSizes.lg} gap-2 px-6 [--icon-size:1.25rem]`,
icon: `${controlHeights.md} aspect-square [--icon-size:1.2rem]`,
'icon-xs': `${controlHeights.xs} aspect-square [--icon-size:0.875rem]`,
'icon-sm': `${controlHeights.sm} aspect-square [--icon-size:1rem]`,
'icon-lg': `${controlHeights.lg} aspect-square [--icon-size:1.25rem]`,
},
},
defaultVariants: { size: 'md' },
},
);
type ButtonVariantProps = VariantProps<typeof buttonBase> & {
variant?: ButtonVariant;
};
function buttonVariants({
variant = 'primary',
size,
className,
}: ButtonVariantProps & { className?: string } = {}) {
return cn(buttonBase({ size }), buttonSurfaces[variant], className);
}
type ButtonProps = Omit<
ComponentProps<typeof ButtonPrimitive>,
keyof ButtonOptions | 'className' | 'children'
> &
ButtonOptions &
ButtonVariantProps & {
children?: ReactNode;
className?: string;
/** Prevent repeated activation and display an inline spinner without replacing the label. */
loading?: boolean;
};
const spinner = (
<Loader2
aria-hidden="true"
data-slot="spinner"
className="hidden size-(--icon-size,1rem) animate-spin in-data-pending:inline-block in-data-loading:inline-block motion-reduce:animate-none"
/>
);
function Button({
className,
variant = 'primary',
size = 'md',
loading = false,
disabled,
children,
'aria-busy': ariaBusy,
...props
}: ButtonProps) {
return (
<ButtonPrimitive
{...props}
className={buttonVariants({ variant, size, className })}
data-size={size}
data-variant={variant}
data-loading={loading || undefined}
disabled={disabled || loading}
aria-busy={loading || ariaBusy}
>
{spinner}
{children}
</ButtonPrimitive>
);
}
export { Button, type ButtonProps, type ButtonVariant, buttonSurfaces, buttonVariants };
import { Separator as SDKSeparator } from '@ui-sdk/react/separator';
import type { ComponentProps } from 'react';
import { partClass } from '@/lib/devvarena-ui';
type SeparatorProps = ComponentProps<typeof SDKSeparator> & { variant?: 'fade' | 'solid' };
/** Theme-derived fading rule built on `@ui-sdk/react/separator`. */
function Separator({
orientation = 'horizontal',
decorative = true,
variant = 'fade',
className,
...props
}: SeparatorProps) {
return (
<SDKSeparator
{...props}
orientation={orientation}
decorative={decorative}
data-variant={variant}
className={partClass(
'pointer-events-none shrink-0',
orientation === 'horizontal' ? 'h-px w-full' : 'w-px self-stretch',
variant === 'solid'
? 'bg-[var(--separator-color,var(--border))]'
: orientation === 'horizontal'
? 'bg-[linear-gradient(to_right,transparent,var(--separator-color,var(--border))_18%,var(--separator-color,var(--border))_82%,transparent)]'
: 'bg-[linear-gradient(to_bottom,transparent,var(--separator-color,var(--border))_18%,var(--separator-color,var(--border))_82%,transparent)]',
className,
)}
/>
);
}
export type { SeparatorProps };
export { Separator };
'use client';
import { type CSSProperties, useCallback, useMemo } from 'react';
export type UseSlidingHighlightOptions = {
/** Mark eligible descendants with this selector. */
itemSelector?: string;
/** Resolve a row when the primitive focuses its parent instead of the row itself. */
focusItemSelector?: string;
disabled?: boolean;
/** Follow a primitive-owned state attribute on eligible items. */
activeAttribute?: string;
};
function highlightProperties(activeAttribute?: string) {
const prefix = activeAttribute ? `--sliding-highlight-${activeAttribute}` : '--sliding-highlight';
return {
left: `${prefix}-left`,
top: `${prefix}-top`,
width: `${prefix}-width`,
height: `${prefix}-height`,
opacity: `${prefix}-opacity`,
};
}
type Clipper = { el: Element; x: boolean; y: boolean };
/** Decorative hover/focus feedback; zero React state or useEffect. */
export function useSlidingHighlight({
itemSelector = '[data-highlight-item]',
focusItemSelector,
disabled = false,
activeAttribute,
}: UseSlidingHighlightOptions = {}) {
const properties = useMemo(() => highlightProperties(activeAttribute), [activeAttribute]);
const highlightStyle = useMemo<CSSProperties>(
() => ({
position: 'absolute',
top: 0,
left: 0,
width: `var(${properties.width}, 0px)`,
height: `var(${properties.height}, 0px)`,
transform: `translate3d(var(${properties.left}, 0px), var(${properties.top}, 0px), 0)`,
opacity: `var(${properties.opacity}, 0)`,
pointerEvents: 'none',
}),
[properties],
);
const containerRef = useCallback(
(container: HTMLElement | null) => {
if (!container || disabled) return;
const activeSelector = activeAttribute ? `${itemSelector}[${activeAttribute}]` : null;
const style = container.style;
let hovered: HTMLElement | null = null;
let focused: HTMLElement | null = null;
let observed: HTMLElement | null = null;
let clippers: Clipper[] = [];
let visible: boolean | null = null;
let pLeft = NaN;
let pTop = NaN;
let pWidth = NaN;
let pHeight = NaN;
const findItem = (target: EventTarget | null) => {
const item = target instanceof Element ? target.closest<HTMLElement>(itemSelector) : null;
return item && item !== container && container.contains(item) ? item : null;
};
// Programmatic/pointer focus must not pin a popover's initially focused row.
const findFocusedItem = (target: EventTarget | null) => {
if (!(target instanceof Element) || !target.matches(':focus-visible')) return null;
const inner = focusItemSelector ? target.querySelector(focusItemSelector) : null;
return findItem(inner ?? target);
};
const setVisible = (next: boolean) => {
if (visible === next) return;
visible = next;
style.setProperty(properties.opacity, next ? '1' : '0');
};
// Runs only when the tracked item changes, so getComputedStyle is not called per frame.
const track = (item: HTMLElement | null) => {
if (observed === item) return;
if (observed) resize?.unobserve(observed);
if (item) resize?.observe(item);
observed = item;
clippers = [];
for (let el = item?.parentElement; el && el !== container; el = el.parentElement) {
const { overflowX, overflowY } = getComputedStyle(el);
const x = overflowX !== 'visible';
const y = overflowY !== 'visible';
if (x || y) clippers.push({ el, x, y });
}
};
const measure = () => {
const item = activeSelector
? container.querySelector<HTMLElement>(activeSelector)
: focused?.matches(itemSelector) && container.contains(focused)
? focused
: hovered;
const valid = item && container.contains(item) && item.matches(itemSelector);
track(valid ? item : null);
if (!valid) return setVisible(false);
const outer = container.getBoundingClientRect();
const inner = item.getBoundingClientRect();
if (!outer.width || !outer.height || !inner.width || !inner.height) {
return setVisible(false);
}
let { left: cLeft, top: cTop, right: cRight, bottom: cBottom } = inner;
for (const { el, x, y } of clippers) {
const r = el.getBoundingClientRect();
if (x) {
cLeft = Math.max(cLeft, r.left);
cRight = Math.min(cRight, r.right);
}
if (y) {
cTop = Math.max(cTop, r.top);
cBottom = Math.min(cBottom, r.bottom);
}
}
if (cRight <= cLeft || cBottom <= cTop) return setVisible(false);
const scaleX = container.offsetWidth / outer.width;
const scaleY = container.offsetHeight / outer.height;
const left = (cLeft - outer.left) * scaleX - container.clientLeft + container.scrollLeft;
const top = (cTop - outer.top) * scaleY - container.clientTop + container.scrollTop;
const width = (cRight - cLeft) * scaleX;
const height = (cBottom - cTop) * scaleY;
if (left !== pLeft) {
pLeft = left;
style.setProperty(properties.left, `${left}px`);
}
if (top !== pTop) {
pTop = top;
style.setProperty(properties.top, `${top}px`);
}
if (width !== pWidth) {
pWidth = width;
style.setProperty(properties.width, `${width}px`);
}
if (height !== pHeight) {
pHeight = height;
style.setProperty(properties.height, `${height}px`);
}
setVisible(true);
};
const resize = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
const mutation = new MutationObserver(measure);
const onPointer = (e: PointerEvent) => {
if (e.pointerType === 'touch') return;
const next = findItem(e.type === 'pointerout' ? e.relatedTarget : e.target);
if (next === hovered) return;
hovered = next;
measure();
};
const onPointerLeave = (e: PointerEvent) => {
if (e.pointerType === 'touch') return;
hovered = null;
measure();
};
const onFocus = (e: FocusEvent) => {
focused = findFocusedItem(e.type === 'focusin' ? e.target : e.relatedTarget);
measure();
};
resize?.observe(container);
mutation.observe(container, {
childList: true,
subtree: true,
...(activeAttribute && {
attributeFilter: [activeAttribute, 'data-disabled', 'aria-disabled'],
}),
});
container.addEventListener('scroll', measure, { capture: true, passive: true });
if (!activeSelector) {
focused = findFocusedItem(document.activeElement);
container.addEventListener('pointerover', onPointer);
container.addEventListener('pointermove', onPointer);
container.addEventListener('pointerout', onPointer);
container.addEventListener('pointerleave', onPointerLeave);
container.addEventListener('pointercancel', onPointerLeave);
container.addEventListener('focusin', onFocus);
container.addEventListener('focusout', onFocus);
}
measure();
return () => {
resize?.disconnect();
mutation.disconnect();
container.removeEventListener('scroll', measure, true);
if (!activeSelector) {
container.removeEventListener('pointerover', onPointer);
container.removeEventListener('pointermove', onPointer);
container.removeEventListener('pointerout', onPointer);
container.removeEventListener('pointerleave', onPointerLeave);
container.removeEventListener('pointercancel', onPointerLeave);
container.removeEventListener('focusin', onFocus);
container.removeEventListener('focusout', onFocus);
}
for (const v of Object.values(properties)) style.removeProperty(v);
};
},
[itemSelector, focusItemSelector, disabled, activeAttribute, properties],
);
return { containerRef, highlightStyle };
}
import { cn } from '@/lib/utils';
type ClassValue = string | false | null | undefined;
type PartClassValue<State> = ClassValue | ((state: State) => ClassValue);
/** Composes static class names and UI-SDK state class functions into a single `className` prop. */
export function partClass<State>(...parts: PartClassValue<State>[]) {
if (parts.some((part) => typeof part === 'function')) {
return (state: State) =>
cn(...parts.map((part) => (typeof part === 'function' ? part(state) : part)));
}
return cn(...(parts as ClassValue[]));
}
export const surfacePadding = 'p-1 [--surface-padding:1.5rem] [--concentric-inset:0.25rem]';
export const surfaceRegionInset = 'p-[calc(var(--surface-padding,1rem)-0.5rem)]';
export const surfaceHeaderRadius = 'rounded-t-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
export const surfaceFooterRadius = 'rounded-b-[max(0px,calc(var(--radius-lg,0.5rem)-0.25rem))]';
/** Concentric inner radius (`outer - inset`); set `[--concentric-inset:0.125rem]` on `p-0.5` rails (defaults to `0.25rem` for `p-1`). */
export const concentricRadius =
'rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))]';
export const surfaceBodyPadding =
'py-[max(0px,calc(var(--surface-padding,1rem)-1rem))] has-[>[data-slot=list]:not([data-variant=plain])]:p-0 has-[>[data-slot=list-items-container]]:p-0';
export type StandardControlSize = 'xs' | 'sm' | 'md' | 'lg';
/** Standard control heights (`28px / 32px / 40px / 48px`) for buttons, inputs, selects, tabs, and sliders. */
export const controlHeights = {
xs: 'h-7',
sm: 'h-8',
md: 'h-10',
lg: 'h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard minimum control heights (`28px / 32px / 40px / 48px`) for expandable controls and menu items. */
export const controlMinHeights = {
xs: 'min-h-7',
sm: 'min-h-8',
md: 'min-h-10',
lg: 'min-h-12',
} as const satisfies Record<StandardControlSize, string>;
/** Standard control text sizes (`xs / xs / sm / base`) paired with `StandardControlSize`. */
export const controlTextSizes = {
xs: 'text-xs',
sm: 'text-xs',
md: 'text-sm',
lg: 'text-base',
} as const satisfies Record<StandardControlSize, string>;
/** Compact control heights (`1.25rem / 1.3rem / 1.625rem / 1.75rem`), one step smaller than standard, for switches and compact controls. */
export const compactControlHeights = {
xs: 'h-[1.3rem]',
sm: 'h-[1.4rem]',
md: 'h-[1.5rem]',
lg: 'h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Compact minimum control heights (`1rem / 1.25rem / 1.5rem / 1.75rem`) for badges and tooltips. */
export const compactControlMinHeights = {
xs: 'min-h-[1.3rem]',
sm: 'min-h-[1.4rem]',
md: 'min-h-[1.5rem]',
lg: 'min-h-[1.6rem]',
} as const satisfies Record<StandardControlSize, string>;
/** Universal keyboard focus + invalid ring/border styles shared across controls. */
export const focusRing =
'touch-manipulation outline-none focus-visible:border-ring/30 transition-ring focus-visible:ring-3 focus-visible:ring-ring/15 focus-visible:brightness-[0.97] dark:focus-visible:brightness-[1.15] has-[:focus-visible]:border-ring/30 has-[:focus-visible]:ring-3 has-[:focus-visible]:ring-ring/15 has-[:focus-visible]:brightness-[0.97] dark:has-[:focus-visible]:brightness-[1.15] data-active:border-ring/30 data-active:ring-3 data-active:ring-ring/15 data-active:brightness-[0.97] dark:data-active:brightness-[1.15] data-open:border-ring/30 data-open:ring-3 data-open:ring-ring/15 data-open:brightness-[0.97] dark:data-open:brightness-[1.15] data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/25 data-invalid:border-destructive data-invalid:ring-3 data-invalid:ring-destructive/25 has-[[data-invalid]]:border-destructive has-[[data-invalid]]:ring-3 has-[[data-invalid]]:ring-destructive/25 group-aria-invalid/control:border-destructive group-aria-invalid/control:ring-3 group-aria-invalid/control:ring-destructive/25 group-data-invalid/control:border-destructive group-data-invalid/control:ring-3 group-data-invalid/control:ring-destructive/25 group-has-[input[aria-invalid=true]]/control:border-destructive group-has-[input[aria-invalid=true]]/control:ring-3 group-has-[input[aria-invalid=true]]/control:ring-destructive/25 hover:brightness-[0.97] dark:hover:brightness-[1.15]';
/** Shared sliding highlight indicator base (pointer-safe, concentric inner radius inside rounded-lg containers, 200ms transition). */
export const slidingHighlight =
'pointer-events-none -z-10 rounded-[max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem)))] bg-primary/10 [clip-path:inset(0px_round_max(0px,calc(var(--radius-lg,0.5rem)-var(--concentric-inset,0.25rem))))] transition-[transform,width,height,opacity] duration-200 ease-out motion-reduce:transition-none';
export const textFieldSurfaces = {
filled: 'border-input bg-card text-card-foreground',
outline: 'border-input bg-transparent text-foreground dark:bg-transparent',
ghost: 'border-transparent bg-muted text-foreground shadow-none',
underline:
'rounded-none border-0 border-b-2 border-input bg-transparent px-0 text-foreground shadow-none focus-visible:border-ring focus-visible:ring-0 aria-invalid:ring-0 data-invalid:ring-0 dark:bg-transparent',
} as const;
export const textFieldUnderlineMotion =
'border-transparent! bg-origin-border bg-bottom bg-no-repeat [--underline-color:var(--primary)] [background-image:linear-gradient(var(--underline-color),var(--underline-color)),linear-gradient(var(--input),var(--input))] [background-size:0%_2px,100%_2px] focus:[background-size:100%_2px,100%_2px] aria-invalid:[--underline-color:var(--destructive)] data-invalid:[--underline-color:var(--destructive)] transition-[border-color,background-color,box-shadow,filter,background-size] duration-200 motion-reduce:transition-none';
/** Generic balanced icon & floating-label layout tokens shared across all text-field sizes. */
export const textFieldLayout = {
icon: 'size-4',
iconStart: 'start-3',
iconEnd: 'end-3',
padStart: 'ps-9',
padEnd: 'pe-9',
underlinePadStart: 'ps-7',
underlinePadEnd: 'pe-7',
floatingStart: 'start-2.5',
floatingWithIcon: 'start-8',
floatingUnderlineIcon: 'start-6',
} as const;
export const textFieldLabelSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
/** Clamps per-grapheme wave delay (ms) so total staggering stays within 300ms. */
export function clampWaveDelay(waveDelay: number, count: number): number {
return Math.max(
0,
Math.min(Number.isFinite(waveDelay) ? waveDelay : 24, 80, 300 / Math.max(1, count - 1)),
);
}
/** Shared scale/color transition for floating labels inside a `group/field` wrapper. */
export const textFieldLabelMotion =
'inline-block origin-left backdrop-blur-xs transition-[scale,color] duration-200 ease-out group-has-[input:focus]/field:scale-85 group-has-[input:not(:placeholder-shown)]/field:scale-85 rtl:origin-right motion-reduce:transition-none';
/** Resolves start/end padding for a text field when a leading or trailing icon is present. */
export function getTextFieldIconPadding(iconPosition: 'start' | 'end', underline: boolean): string {
if (iconPosition === 'start') {
return underline ? textFieldLayout.underlinePadStart : textFieldLayout.padStart;
}
return underline ? textFieldLayout.underlinePadEnd : textFieldLayout.padEnd;
}
/** Shared per-grapheme ripple transition for wave labels inside a `group/field` wrapper. */
export const textFieldWaveMotion =
'inline-block origin-left backdrop-blur-xs transition-[translate,scale,color] duration-200 ease-out group-has-[input:focus]/field:-translate-y-5 group-has-[input:focus]/field:scale-85 group-has-[input:focus]/field:text-primary group-has-[input:not(:placeholder-shown)]/field:-translate-y-5 group-has-[input:not(:placeholder-shown)]/field:scale-85 group-has-[input[aria-invalid=true]]/field:text-destructive rtl:origin-right motion-reduce:transition-none';