File Upload
Two file upload patterns: an attachment workspace for mixed files, links, audio and media, plus a progress queue with retry and removal.
Attachment Upload
attachment-upload.tsxA mixed attachment workspace with a dropzone, staggered file and image rows, animated upload, success, failure, retry and removal feedback, shared-layout image previews, and an audio waveform.
Attachments:
- launch-brief.pdfUpload failed31 MB
- orange-flowers.jpg9.3 MB
- 0:120:48
"use client";
import { useEffect, useRef, useState } from "react";
import {
AttachmentUpload,
type AttachmentUploadItem,
} from "@/components/motion/attachment-upload";
const INITIAL_ITEMS: AttachmentUploadItem[] = [
{
id: "brief",
name: "launch-brief.pdf",
kind: "file",
size: 32_400_000,
href: "data:application/pdf,beUI%20launch%20brief",
status: "failed",
error: "Upload failed",
},
{
id: "flowers",
name: "orange-flowers.jpg",
kind: "image",
size: 9_800_000,
previewUrl:
"https://images.unsplash.com/photo-1490750967868-88aa4486c946?auto=format&fit=crop&w=1200&q=85",
},
{
id: "voice-note",
name: "launch-note.m4a",
kind: "audio",
currentTime: 12,
duration: 48,
},
];
export function AttachmentUploadPreview() {
const [items, setItems] = useState(INITIAL_ITEMS);
const [playingId, setPlayingId] = useState<string>();
const retryTimersRef = useRef<number[]>([]);
useEffect(
() => () => {
for (const timer of retryTimersRef.current) {
window.clearTimeout(timer);
}
},
[],
);
useEffect(() => {
if (!playingId) return;
const timer = window.setInterval(() => {
setItems((current) =>
current.map((item) => {
if (item.id !== playingId || !item.duration) return item;
const nextTime = Math.min(
item.duration,
(item.currentTime ?? 0) + 1,
);
return { ...item, currentTime: nextTime };
}),
);
}, 1000);
return () => window.clearInterval(timer);
}, [playingId]);
useEffect(() => {
if (!playingId) return;
const playingItem = items.find((item) => item.id === playingId);
if (
playingItem?.duration &&
(playingItem.currentTime ?? 0) >= playingItem.duration
) {
setPlayingId(undefined);
}
}, [items, playingId]);
return (
<div className="w-full max-w-2xl px-3 py-6 sm:px-6">
<AttachmentUpload
value={items}
onValueChange={setItems}
onRetry={(retryItem) => {
setItems((current) =>
current.map((item) =>
item.id === retryItem.id
? { ...item, status: "uploading", error: undefined }
: item,
),
);
const completeTimer = window.setTimeout(() => {
setItems((current) =>
current.map((item) =>
item.id === retryItem.id
? { ...item, status: "complete" }
: item,
),
);
}, 900);
const readyTimer = window.setTimeout(() => {
setItems((current) =>
current.map((item) =>
item.id === retryItem.id
? { ...item, status: "idle" }
: item,
),
);
}, 1900);
retryTimersRef.current.push(completeTimer, readyTimer);
}}
playingId={playingId}
onAudioToggle={(item) => {
setPlayingId((current) =>
current === item.id ? undefined : item.id,
);
}}
attachmentsLabel="Attachments:"
/>
</div>
);
}
"use client";
// beui.dev/components/blocks/file-upload
import {
AlertCircle,
Check,
ExternalLink,
FileImage,
Link as LinkIcon,
LoaderCircle,
Mic,
Paperclip,
Pause,
Play,
RotateCcw,
Upload,
X,
} from "lucide-react";
import {
AnimatePresence,
LayoutGroup,
motion,
useReducedMotion,
} from "motion/react";
import {
useCallback,
useEffect,
useId,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { Tooltip } from "@/components/motion/tooltip";
import {
EASE_OUT,
SPRING_LAYOUT,
SPRING_PRESS,
} from "@/lib/ease";
import { PresenceGate } from "@/lib/presence-gate";
import { cn } from "@/lib/utils";
export type AttachmentUploadKind = "file" | "link" | "image" | "audio";
export type AttachmentRejectReason = "too-large" | "max-files";
export type AttachmentUploadStatus =
| "idle"
| "uploading"
| "complete"
| "failed";
export type AttachmentUploadItem = {
id: string;
name: string;
kind: AttachmentUploadKind;
size?: number;
href?: string;
previewUrl?: string;
currentTime?: number;
duration?: number;
status?: AttachmentUploadStatus;
error?: string;
file?: File;
};
export type AttachmentUploadClassNames = {
dropzone?: string;
list?: string;
row?: string;
};
export interface AttachmentUploadProps {
value?: AttachmentUploadItem[];
defaultValue?: AttachmentUploadItem[];
onValueChange?: (items: AttachmentUploadItem[]) => void;
onFilesAdded?: (items: AttachmentUploadItem[], files: File[]) => void;
onFilesRejected?: (files: File[], reason: AttachmentRejectReason) => void;
onRemove?: (item: AttachmentUploadItem) => void;
onRetry?: (item: AttachmentUploadItem) => void;
playingId?: string;
onAudioToggle?: (item: AttachmentUploadItem) => void;
accept?: string;
multiple?: boolean;
maxFiles?: number;
maxFileSize?: number;
disabled?: boolean;
title?: string;
description?: string;
attachmentsLabel?: string;
className?: string;
classNames?: AttachmentUploadClassNames;
}
const ITEM_TRANSITION = { duration: 0.2, ease: EASE_OUT } as const;
const DEFAULT_MAX_FILE_SIZE = 500 * 1024 * 1024;
const UPLOAD_PROGRESS_MS = 900;
const UPLOAD_COMPLETE_HOLD_MS = 1000;
const REMOVE_PENDING_MS = 420;
const WAVEFORM_BARS = [
18, 31, 24, 39, 30, 43, 27, 18, 9, 29, 38, 24, 34, 18, 26, 37, 21, 14,
7, 11, 22, 35, 18, 26, 41, 29, 17, 33,
].map((height, index) => ({ id: `wave-${index}-${height}`, height }));
function useControllableList<T>({
value,
defaultValue,
onValueChange,
}: {
value?: T[];
defaultValue?: T[];
onValueChange?: (items: T[]) => void;
}) {
const [internalValue, setInternalValue] = useState(defaultValue ?? []);
const controlled = value !== undefined;
const items = value ?? internalValue;
const setItems = useCallback(
(next: T[]) => {
if (!controlled) setInternalValue(next);
onValueChange?.(next);
},
[controlled, onValueChange],
);
return [items, setItems] as const;
}
function formatBytes(bytes: number | undefined) {
if (bytes === undefined || !Number.isFinite(bytes) || bytes <= 0) {
return null;
}
const units = ["B", "KB", "MB", "GB"];
const exponent = Math.min(
Math.floor(Math.log(bytes) / Math.log(1024)),
units.length - 1,
);
const value = bytes / 1024 ** exponent;
return `${value >= 10 || exponent === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[exponent]}`;
}
function formatDuration(seconds: number | undefined) {
const safeSeconds = Math.max(0, Math.round(seconds ?? 0));
const minutes = Math.floor(safeSeconds / 60);
return `${minutes}:${String(safeSeconds % 60).padStart(2, "0")}`;
}
function formatMaxSize(bytes: number) {
const megabytes = bytes / (1024 * 1024);
return `${Number.isInteger(megabytes) ? megabytes : megabytes.toFixed(1)} MB`;
}
function inferKind(file: File): AttachmentUploadKind {
if (file.type.startsWith("image/")) return "image";
if (file.type.startsWith("audio/")) return "audio";
return "file";
}
function AttachmentIcon({ kind }: { kind: AttachmentUploadKind }) {
if (kind === "link") return <LinkIcon className="size-4" />;
if (kind === "image") return <FileImage className="size-4" />;
if (kind === "audio") return <Mic className="size-4" />;
return <Paperclip className="size-4" />;
}
function imageSource(item: AttachmentUploadItem) {
if (item.kind !== "image") return undefined;
return item.previewUrl ?? item.href;
}
type RowActionState =
| "idle"
| "uploading"
| "complete"
| "failed"
| "removing";
function RowAction({
label,
onClick,
state,
retryable = false,
reduce = false,
}: {
label: string;
onClick: () => void;
state: RowActionState;
retryable?: boolean;
reduce?: boolean;
}) {
if (state === "uploading") {
return <span aria-hidden="true" className="size-9 shrink-0" />;
}
if (state === "complete") {
return (
<Tooltip content="Upload complete" side="top" delay={100}>
<motion.span
role="status"
aria-label={`Upload complete for ${label}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.75 }}
animate={{ opacity: 1, scale: 1 }}
transition={ITEM_TRANSITION}
className="grid size-9 shrink-0 place-items-center rounded-xl text-emerald-600 dark:text-emerald-400"
>
<Check className="size-4" />
</motion.span>
</Tooltip>
);
}
if (state === "removing") {
return (
<Tooltip content="Removing attachment" side="top" delay={100}>
<span
role="status"
aria-label={`Removing ${label}`}
className="grid size-9 shrink-0 place-items-center rounded-xl text-muted-foreground"
>
<motion.span
animate={reduce ? undefined : { rotate: 360 }}
transition={{
duration: 0.7,
ease: "linear",
repeat: Infinity,
}}
className="grid place-items-center"
>
<LoaderCircle className="size-4" />
</motion.span>
</span>
</Tooltip>
);
}
if (state === "failed") {
if (!retryable) {
return (
<Tooltip content="Upload failed" side="top" delay={100}>
<span
role="status"
aria-label={`Upload failed for ${label}`}
className="grid size-9 shrink-0 place-items-center rounded-xl text-destructive"
>
<AlertCircle className="size-4" />
</span>
</Tooltip>
);
}
return (
<Tooltip content="Retry upload" side="top" delay={100}>
<motion.button
type="button"
aria-label={`Retry ${label}`}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-xl text-destructive outline-none transition-colors hover:bg-destructive/10 focus-visible:ring-2 focus-visible:ring-ring"
>
<RotateCcw className="size-4" />
</motion.button>
</Tooltip>
);
}
return (
<Tooltip content="Remove attachment" side="top" delay={100}>
<motion.button
type="button"
aria-label={`Remove ${label}`}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-xl text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-4" />
</motion.button>
</Tooltip>
);
}
function ImageThumbnail({
item,
layoutId,
onPreview,
reduce,
}: {
item: AttachmentUploadItem;
layoutId?: string;
onPreview: (item: AttachmentUploadItem) => void;
reduce: boolean;
}) {
const src = imageSource(item);
if (!src) {
return (
<span
aria-hidden="true"
className="grid size-8 shrink-0 place-items-center rounded-lg bg-muted text-muted-foreground"
>
<FileImage className="size-4" />
</span>
);
}
return (
<Tooltip
side="top"
delay={160}
className="rounded-xl p-1 shadow-xl"
content={
<span className="block w-32">
{/* biome-ignore lint/performance/noImgElement: Blob and remote previews keep this registry component framework-agnostic. */}
<img
src={src}
alt=""
className="h-20 w-full rounded-lg object-cover"
/>
<span className="block px-1 pb-0.5 pt-1 text-center text-[10px] font-medium text-muted-foreground">
Click to preview
</span>
</span>
}
>
<motion.button
type="button"
aria-label={`Preview ${item.name}`}
onClick={(event) => {
event.currentTarget.blur();
onPreview(item);
}}
whileTap={reduce ? undefined : { scale: 0.94 }}
transition={SPRING_PRESS}
className="group/image relative size-9 shrink-0 overflow-hidden rounded-[10px] bg-muted outline-none ring-1 ring-border/70 focus-visible:ring-2 focus-visible:ring-ring"
>
{/* biome-ignore lint/performance/noImgElement: Motion layout requires the image element and portable blob URLs. */}
<motion.img
layoutId={layoutId}
src={src}
alt=""
className="size-full object-cover"
transition={{ layout: SPRING_LAYOUT }}
/>
</motion.button>
</Tooltip>
);
}
function ImagePreviewDialog({
item,
layoutId,
onClose,
reduce,
}: {
item: AttachmentUploadItem | null;
layoutId?: string;
onClose: () => void;
reduce: boolean;
}) {
const closeRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!item) return;
const previousFocus =
document.activeElement instanceof HTMLElement
? document.activeElement
: null;
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
closeRef.current?.focus();
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") onClose();
if (event.key === "Tab") {
event.preventDefault();
closeRef.current?.focus();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
document.body.style.overflow = previousOverflow;
previousFocus?.focus();
};
}, [item, onClose]);
if (typeof document === "undefined") return null;
const src = item ? imageSource(item) : undefined;
const content =
item && src ? (
// The wrapper carries no box: both children are `fixed` and resolve
// against the viewport themselves. The scrim spans the viewport edges but
// paints a colour, and the layer that centres the image is inset off every
// edge. `PresenceGate` releases interaction in the same commit that starts
// the exit.
<PresenceGate>
{({ isPresent, gate }) => (
<div
inert={!isPresent}
className="pointer-events-none fixed left-0 top-0 z-[10000] size-0"
>
<motion.button
type="button"
aria-label="Close image preview"
tabIndex={-1}
className="pointer-events-auto fixed inset-0 size-full cursor-default bg-black/45 backdrop-blur-xl"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={{ duration: reduce ? 0.1 : 0.2, ease: EASE_OUT }}
{...gate}
onClick={onClose}
/>
<div className="fixed inset-4 flex items-center justify-center sm:inset-8">
<motion.div
role="dialog"
aria-modal="true"
aria-label={`Preview of ${item.name}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={ITEM_TRANSITION}
{...gate}
className="pointer-events-auto relative"
>
{/* biome-ignore lint/performance/noImgElement: Motion layout requires the image element and portable blob URLs. */}
<motion.img
layoutId={reduce ? undefined : layoutId}
src={src}
alt={item.name}
className="max-h-[90vh] max-w-[90vw] rounded-2xl object-contain shadow-2xl"
transition={{ layout: SPRING_LAYOUT }}
/>
<motion.button
ref={closeRef}
type="button"
aria-label="Close image preview"
onClick={onClose}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={
reduce ? undefined : { opacity: 0, scale: 0.8 }
}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="absolute -right-3 -top-3 grid size-9 place-items-center rounded-full bg-background text-foreground shadow-xl outline-none ring-1 ring-border/70 transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-4" />
</motion.button>
</motion.div>
</div>
</div>
)}
</PresenceGate>
) : null;
return createPortal(
reduce ? content : <AnimatePresence>{content}</AnimatePresence>,
document.body,
);
}
function AttachmentRow({
item,
playing,
uploading,
uploadComplete,
failed,
removing,
arrivalIndex,
imageLayoutId,
onAudioToggle,
onImagePreview,
onRemove,
onRetry,
reduce,
className,
}: {
item: AttachmentUploadItem;
playing: boolean;
uploading: boolean;
uploadComplete: boolean;
failed: boolean;
removing: boolean;
arrivalIndex: number;
imageLayoutId?: string;
onAudioToggle?: (item: AttachmentUploadItem) => void;
onImagePreview: (item: AttachmentUploadItem) => void;
onRemove: (item: AttachmentUploadItem) => void;
onRetry?: (item: AttachmentUploadItem) => void;
reduce: boolean;
className?: string;
}) {
const size = formatBytes(item.size);
const progress =
item.duration && item.duration > 0
? Math.min(1, Math.max(0, (item.currentTime ?? 0) / item.duration))
: 0;
const actionState: RowActionState = removing
? "removing"
: uploading
? "uploading"
: uploadComplete
? "complete"
: failed
? "failed"
: "idle";
const arrivalDelay = Math.min(Math.max(arrivalIndex, 0), 5) * 0.055;
const rowTransition =
!reduce && arrivalIndex >= 0
? {
...SPRING_LAYOUT,
delay: arrivalDelay,
opacity: {
duration: 0.16,
ease: EASE_OUT,
delay: arrivalDelay,
},
}
: ITEM_TRANSITION;
const showUploadProgress = uploading || uploadComplete;
const uploadProgress = (
<motion.span
role="progressbar"
aria-label={`Uploading ${item.name}`}
className="pointer-events-none absolute inset-0 -z-10 origin-left bg-emerald-400/25 dark:bg-emerald-500/20"
initial={{ opacity: 1, scaleX: 0 }}
animate={{ opacity: 1, scaleX: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={{
duration: reduce ? 0.1 : UPLOAD_PROGRESS_MS / 1000,
ease: EASE_OUT,
}}
/>
);
return (
<motion.li
layout={!reduce}
initial={
reduce
? { opacity: 0 }
: arrivalIndex >= 0
? { opacity: 0, y: -16, scale: 0.985 }
: { opacity: 0, y: 6 }
}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={reduce ? undefined : { opacity: 0, y: -4 }}
transition={rowTransition}
className={cn(
"flex min-h-14 items-center gap-1 rounded-2xl bg-muted/70 p-1",
className,
)}
>
<div className="relative isolate flex min-w-0 flex-1 items-center gap-3 self-stretch overflow-hidden rounded-xl bg-background px-2 py-1">
{failed ? (
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 -z-10 bg-destructive/10"
/>
) : null}
{item.kind === "image" ? (
<ImageThumbnail
item={item}
layoutId={imageLayoutId}
onPreview={onImagePreview}
reduce={reduce}
/>
) : (
<span
aria-hidden="true"
className="grid size-7 shrink-0 place-items-center text-muted-foreground"
>
<AttachmentIcon kind={item.kind} />
</span>
)}
{item.kind === "audio" ? (
<>
<span className="w-9 shrink-0 text-xs tabular-nums text-muted-foreground">
{formatDuration(item.currentTime)}
</span>
<span
aria-hidden="true"
className="flex h-11 min-w-0 flex-1 items-center gap-[3px] overflow-hidden"
>
{WAVEFORM_BARS.map((bar, index) => (
<motion.span
key={bar.id}
className={cn(
"w-[3px] shrink-0 rounded-full",
index / WAVEFORM_BARS.length <= progress
? "bg-foreground"
: "bg-muted-foreground/35",
)}
style={{ height: bar.height }}
animate={
reduce || !playing
? undefined
: { scaleY: [0.72, 1, 0.78] }
}
transition={{
duration: 0.55,
ease: EASE_OUT,
repeat: Infinity,
delay: index * 0.018,
}}
/>
))}
</span>
<span className="w-9 shrink-0 text-right text-xs tabular-nums text-muted-foreground">
{formatDuration(item.duration)}
</span>
<motion.button
type="button"
aria-label={`${playing ? "Pause" : "Play"} ${item.name}`}
onClick={() => onAudioToggle?.(item)}
whileTap={{ scale: 0.94 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-full bg-foreground text-background outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<AnimatePresence mode="wait" initial={false}>
<motion.span
key={playing ? "pause" : "play"}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
transition={ITEM_TRANSITION}
>
{playing ? (
<Pause className="size-4 fill-current" />
) : (
<Play className="size-4 translate-x-px fill-current" />
)}
</motion.span>
</AnimatePresence>
</motion.button>
</>
) : (
<>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-foreground">
{item.name}
</span>
{failed ? (
<span className="block truncate text-[11px] text-destructive">
{item.error ?? "Upload failed"}
</span>
) : null}
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{item.kind === "link" ? "Web" : size}
</span>
{item.kind === "link" && item.href ? (
<a
href={item.href}
target="_blank"
rel="noreferrer noopener"
aria-label={`Open ${item.name}`}
className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<ExternalLink className="size-4" />
</a>
) : null}
</>
)}
{reduce ? (
showUploadProgress ? (
uploadProgress
) : null
) : (
<AnimatePresence>
{showUploadProgress ? uploadProgress : null}
</AnimatePresence>
)}
</div>
<RowAction
label={item.name}
onClick={() => {
if (actionState === "failed") {
onRetry?.(item);
return;
}
onRemove(item);
}}
state={actionState}
retryable={onRetry !== undefined}
reduce={reduce}
/>
</motion.li>
);
}
export function AttachmentUpload({
value,
defaultValue,
onValueChange,
onFilesAdded,
onFilesRejected,
onRemove,
onRetry,
playingId,
onAudioToggle,
accept,
multiple = true,
maxFiles = 12,
maxFileSize = DEFAULT_MAX_FILE_SIZE,
disabled = false,
title = "Drag and drop or browse files",
description,
attachmentsLabel = "Attachments",
className,
classNames,
}: AttachmentUploadProps) {
const inputId = useId();
const inputRef = useRef<HTMLInputElement>(null);
const dragDepthRef = useRef(0);
const ownedUrlsRef = useRef(new Set<string>());
const lifecycleTimersRef = useRef(
new Set<ReturnType<typeof setTimeout>>(),
);
const reduce = useReducedMotion() ?? false;
const [dragging, setDragging] = useState(false);
const [previewItem, setPreviewItem] =
useState<AttachmentUploadItem | null>(null);
const [uploadingIds, setUploadingIds] = useState<Set<string>>(
() => new Set(),
);
const [uploadCompleteIds, setUploadCompleteIds] = useState<Set<string>>(
() => new Set(),
);
const [removingIds, setRemovingIds] = useState<Set<string>>(
() => new Set(),
);
const [items, setItems] = useControllableList({
value,
defaultValue,
onValueChange,
});
const itemsRef = useRef(items);
itemsRef.current = items;
useEffect(
() => () => {
for (const url of ownedUrlsRef.current) URL.revokeObjectURL(url);
ownedUrlsRef.current.clear();
for (const timer of lifecycleTimersRef.current) {
clearTimeout(timer);
}
lifecycleTimersRef.current.clear();
},
[],
);
const maxReached = items.length >= maxFiles;
const scheduleLifecycle = useCallback(
(callback: () => void, delay: number) => {
const timer = setTimeout(() => {
lifecycleTimersRef.current.delete(timer);
callback();
}, delay);
lifecycleTimersRef.current.add(timer);
},
[],
);
const addFiles = useCallback(
(incomingFiles: File[]) => {
if (disabled || incomingFiles.length === 0) return;
const availableSlots = Math.max(0, maxFiles - items.length);
if (availableSlots === 0) {
onFilesRejected?.(incomingFiles, "max-files");
return;
}
const selectedFiles = incomingFiles.slice(
0,
multiple ? availableSlots : Math.min(1, availableSlots),
);
const oversized = selectedFiles.filter(
(file) => file.size > maxFileSize,
);
const accepted = selectedFiles.filter(
(file) => file.size <= maxFileSize,
);
if (oversized.length > 0) onFilesRejected?.(oversized, "too-large");
if (incomingFiles.length > selectedFiles.length) {
onFilesRejected?.(incomingFiles.slice(selectedFiles.length), "max-files");
}
const added = accepted.map((file, index) => {
const kind = inferKind(file);
const objectUrl = URL.createObjectURL(file);
ownedUrlsRef.current.add(objectUrl);
return {
id: `${Date.now()}-${index}-${file.name}`,
name: file.name,
kind,
size: file.size,
previewUrl: kind === "image" ? objectUrl : undefined,
href: objectUrl,
currentTime: kind === "audio" ? 0 : undefined,
duration: kind === "audio" ? 0 : undefined,
file,
};
});
if (added.length === 0) return;
setItems([...items, ...added]);
const addedIds = added.map((item) => item.id);
setUploadingIds((current) => new Set([...current, ...addedIds]));
scheduleLifecycle(
() => {
setUploadingIds((current) => {
const next = new Set(current);
for (const id of addedIds) next.delete(id);
return next;
});
setUploadCompleteIds(
(current) => new Set([...current, ...addedIds]),
);
scheduleLifecycle(() => {
setUploadCompleteIds((current) => {
const next = new Set(current);
for (const id of addedIds) next.delete(id);
return next;
});
}, UPLOAD_COMPLETE_HOLD_MS);
},
reduce ? 140 : UPLOAD_PROGRESS_MS,
);
onFilesAdded?.(added, accepted);
},
[
disabled,
items,
maxFileSize,
maxFiles,
multiple,
onFilesAdded,
onFilesRejected,
reduce,
scheduleLifecycle,
setItems,
],
);
const finalizeRemove = useCallback(
(item: AttachmentUploadItem) => {
const ownedUrl = [item.previewUrl, item.href].find(
(url): url is string =>
url !== undefined && ownedUrlsRef.current.has(url),
);
if (ownedUrl) {
URL.revokeObjectURL(ownedUrl);
ownedUrlsRef.current.delete(ownedUrl);
}
setPreviewItem((current) =>
current?.id === item.id ? null : current,
);
setUploadingIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
setUploadCompleteIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
setItems(itemsRef.current.filter((entry) => entry.id !== item.id));
onRemove?.(item);
},
[onRemove, setItems],
);
const requestRemove = useCallback(
(item: AttachmentUploadItem) => {
if (removingIds.has(item.id)) return;
setRemovingIds((current) => new Set(current).add(item.id));
scheduleLifecycle(
() => {
finalizeRemove(item);
setRemovingIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
},
reduce ? 140 : REMOVE_PENDING_MS,
);
},
[
finalizeRemove,
reduce,
removingIds,
scheduleLifecycle,
],
);
const resetDrag = useCallback(() => {
dragDepthRef.current = 0;
setDragging(false);
}, []);
const closePreview = useCallback(() => setPreviewItem(null), []);
useEffect(() => {
if (
previewItem &&
!items.some((item) => item.id === previewItem.id)
) {
setPreviewItem(null);
}
}, [items, previewItem]);
const uploadOrder = Array.from(uploadingIds);
const previewLayoutId = previewItem
? `attachment-image-${previewItem.id}`
: undefined;
return (
<LayoutGroup id={inputId}>
<div className={cn("w-full", className)}>
<input
ref={inputRef}
id={inputId}
type="file"
aria-label="Upload attachments"
accept={accept}
multiple={multiple}
disabled={disabled || maxReached}
tabIndex={-1}
className="sr-only"
onChange={(event) => {
addFiles(Array.from(event.currentTarget.files ?? []));
event.currentTarget.value = "";
}}
/>
<motion.button
type="button"
disabled={disabled || maxReached}
data-dragging={dragging}
animate={
reduce
? undefined
: { scale: dragging ? 1.006 : 1 }
}
whileTap={reduce ? undefined : { scale: 0.995 }}
transition={SPRING_PRESS}
onClick={() => inputRef.current?.click()}
onDragEnter={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current += 1;
setDragging(true);
}}
onDragOver={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
setDragging(true);
}}
onDragLeave={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) setDragging(false);
}}
onDrop={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
resetDrag();
addFiles(Array.from(event.dataTransfer.files));
}}
className={cn(
"group relative isolate flex min-h-52 w-full flex-col items-center justify-center overflow-hidden rounded-[2rem] bg-muted/65 p-2 text-center outline-none",
"transition-colors duration-200 hover:bg-muted/85",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"data-[dragging=true]:bg-muted",
"disabled:pointer-events-none disabled:opacity-55",
classNames?.dropzone,
)}
>
<span
aria-hidden="true"
className="absolute inset-2 -z-10 rounded-[1.5rem] border border-dashed border-muted-foreground/25 bg-background transition-[border-color,background-color] duration-200 group-hover:border-muted-foreground/45 group-data-[dragging=true]:border-foreground/65 group-data-[dragging=true]:bg-muted/20"
/>
<motion.span
aria-hidden="true"
animate={
reduce
? undefined
: {
y: dragging ? -4 : 0,
scale: dragging ? 1.08 : 1,
}
}
transition={ITEM_TRANSITION}
className="mb-3 grid size-11 place-items-center rounded-2xl bg-muted text-foreground transition-colors duration-200 group-hover:bg-muted/80 group-data-[dragging=true]:bg-foreground group-data-[dragging=true]:text-background"
>
<Upload className="size-[18px]" />
</motion.span>
<span className="text-sm font-semibold tracking-[-0.01em] text-foreground">
{maxReached ? "Attachment limit reached" : title}
</span>
<span className="mt-1 text-xs leading-5 text-muted-foreground">
{maxReached
? `${items.length} of ${maxFiles} attachments added`
: description ?? `Maximum ${formatMaxSize(maxFileSize)} file size`}
</span>
</motion.button>
{items.length > 0 ? (
<section className="mt-8" aria-labelledby={`${inputId}-attachments`}>
<h3
id={`${inputId}-attachments`}
className="text-sm font-semibold text-foreground"
>
{attachmentsLabel}
</h3>
{items.length > 0 ? (
<ul className={cn("mt-3 space-y-2", classNames?.list)}>
<AnimatePresence initial={uploadOrder.length > 0}>
{items.map((item) => (
<AttachmentRow
key={item.id}
item={item}
playing={playingId === item.id}
uploading={
uploadingIds.has(item.id) ||
item.status === "uploading"
}
uploadComplete={
uploadCompleteIds.has(item.id) ||
item.status === "complete"
}
failed={item.status === "failed"}
removing={removingIds.has(item.id)}
arrivalIndex={uploadOrder.indexOf(item.id)}
imageLayoutId={
reduce ? undefined : `attachment-image-${item.id}`
}
onAudioToggle={onAudioToggle}
onImagePreview={setPreviewItem}
onRemove={requestRemove}
onRetry={onRetry}
reduce={reduce}
className={classNames?.row}
/>
))}
</AnimatePresence>
</ul>
) : null}
</section>
) : null}
<ImagePreviewDialog
item={previewItem}
layoutId={reduce ? undefined : previewLayoutId}
onClose={closePreview}
reduce={reduce}
/>
</div>
</LayoutGroup>
);
}
Install
shadcn init? You are set. Theme setupInstall dependencies
npm i @floating-ui/dom clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
"use client";
import { useIsPresent } from "motion/react";
import type { ReactNode } from "react";
export interface PresenceGateRenderProps {
/**
* False from the render that starts the exit animation onward. An overlay
* kept in the tree by `AnimatePresence` is still the topmost thing on the
* page, so anything it decides from `open` alone stays true for the whole
* exit — this is the boolean that already knows the overlay is leaving.
*/
isPresent: boolean;
/**
* Spread onto every layer that takes pointer events while the overlay is
* open. Interaction releases in the same commit that starts the exit while
* the visual exit keeps playing: pointer events stop landing, and `inert`
* drops the subtree from focus order, from tab order and from the
* accessibility tree — an exiting dialog is not a dialog you can still type
* into. A layer that never takes pointer events (a wrapper that only centres
* the panel) takes `inert={!isPresent}` alone, so its own
* `pointer-events-none` is not overwritten.
*/
gate: {
inert: boolean;
style: { pointerEvents: "auto" | "none" };
};
}
export interface PresenceGateProps {
children: (props: PresenceGateRenderProps) => ReactNode;
}
/**
* Reads the presence of the subtree it renders and hands it down.
*
* `useIsPresent` only answers inside the `AnimatePresence` subtree, and the
* components that own an overlay render the `AnimatePresence` themselves, so
* the boolean has to be read one component further down: this is that
* component, and the render prop is how it reaches the layers.
*/
export function PresenceGate({ children }: PresenceGateProps) {
const isPresent = useIsPresent();
return children({
isPresent,
gate: {
inert: !isPresent,
style: { pointerEvents: isPresent ? "auto" : "none" },
},
});
}
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { type RefObject, useEffect } from "react";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Return true for an outside target that should *not* dismiss. Must be stable. */
ignore?: (target: Element) => boolean;
}
/**
* What every currently open dismiss scope counts as inside itself. A consumed
* dismissal reads this to tell a stray gesture from one that belongs to an
* overlay in front of it: overlays have no shared z-order to consult, but the
* one the gesture landed in has said as much by registering it.
*/
const openScopes = new Set<(target: Element) => boolean>();
function claimedByAnotherScope(
self: (target: Element) => boolean,
target: Element,
) {
for (const scope of openScopes) {
if (scope !== self && scope(target)) return true;
}
return false;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over. `onDismiss` and `ignore` must be stable (wrap in
* useCallback) so the listeners aren't re-bound every render while open.
*/
export function useDismiss(
open: boolean,
onDismiss: () => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
ignore,
}: DismissOptions = {},
) {
useEffect(() => {
if (!open) return;
const inside = (target: Element) =>
Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));
const onKey = (event: KeyboardEvent) => {
if (dismissOnEscape && event.key === "Escape") onDismiss();
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside one that is also open: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !claimedByAnotherScope(inside, target)) {
consumeActivation(event);
}
onDismiss();
};
openScopes.add(inside);
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer, true);
return () => {
openScopes.delete(inside);
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
};
}, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);
}
"use client";
import { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks — is this pointer
* resting on the surface or pressing it — and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap — the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter — mounted under
* the cursor, say — still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control — and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away — `pointercancel`, no click
* ever — and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
Copy the source code
"use client";
// beui.dev/components/blocks/file-upload
import {
AlertCircle,
Check,
ExternalLink,
FileImage,
Link as LinkIcon,
LoaderCircle,
Mic,
Paperclip,
Pause,
Play,
RotateCcw,
Upload,
X,
} from "lucide-react";
import {
AnimatePresence,
LayoutGroup,
motion,
useReducedMotion,
} from "motion/react";
import {
useCallback,
useEffect,
useId,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { Tooltip } from "@/components/motion/tooltip";
import {
EASE_OUT,
SPRING_LAYOUT,
SPRING_PRESS,
} from "@/lib/ease";
import { PresenceGate } from "@/lib/presence-gate";
import { cn } from "@/lib/utils";
export type AttachmentUploadKind = "file" | "link" | "image" | "audio";
export type AttachmentRejectReason = "too-large" | "max-files";
export type AttachmentUploadStatus =
| "idle"
| "uploading"
| "complete"
| "failed";
export type AttachmentUploadItem = {
id: string;
name: string;
kind: AttachmentUploadKind;
size?: number;
href?: string;
previewUrl?: string;
currentTime?: number;
duration?: number;
status?: AttachmentUploadStatus;
error?: string;
file?: File;
};
export type AttachmentUploadClassNames = {
dropzone?: string;
list?: string;
row?: string;
};
export interface AttachmentUploadProps {
value?: AttachmentUploadItem[];
defaultValue?: AttachmentUploadItem[];
onValueChange?: (items: AttachmentUploadItem[]) => void;
onFilesAdded?: (items: AttachmentUploadItem[], files: File[]) => void;
onFilesRejected?: (files: File[], reason: AttachmentRejectReason) => void;
onRemove?: (item: AttachmentUploadItem) => void;
onRetry?: (item: AttachmentUploadItem) => void;
playingId?: string;
onAudioToggle?: (item: AttachmentUploadItem) => void;
accept?: string;
multiple?: boolean;
maxFiles?: number;
maxFileSize?: number;
disabled?: boolean;
title?: string;
description?: string;
attachmentsLabel?: string;
className?: string;
classNames?: AttachmentUploadClassNames;
}
const ITEM_TRANSITION = { duration: 0.2, ease: EASE_OUT } as const;
const DEFAULT_MAX_FILE_SIZE = 500 * 1024 * 1024;
const UPLOAD_PROGRESS_MS = 900;
const UPLOAD_COMPLETE_HOLD_MS = 1000;
const REMOVE_PENDING_MS = 420;
const WAVEFORM_BARS = [
18, 31, 24, 39, 30, 43, 27, 18, 9, 29, 38, 24, 34, 18, 26, 37, 21, 14,
7, 11, 22, 35, 18, 26, 41, 29, 17, 33,
].map((height, index) => ({ id: `wave-${index}-${height}`, height }));
function useControllableList<T>({
value,
defaultValue,
onValueChange,
}: {
value?: T[];
defaultValue?: T[];
onValueChange?: (items: T[]) => void;
}) {
const [internalValue, setInternalValue] = useState(defaultValue ?? []);
const controlled = value !== undefined;
const items = value ?? internalValue;
const setItems = useCallback(
(next: T[]) => {
if (!controlled) setInternalValue(next);
onValueChange?.(next);
},
[controlled, onValueChange],
);
return [items, setItems] as const;
}
function formatBytes(bytes: number | undefined) {
if (bytes === undefined || !Number.isFinite(bytes) || bytes <= 0) {
return null;
}
const units = ["B", "KB", "MB", "GB"];
const exponent = Math.min(
Math.floor(Math.log(bytes) / Math.log(1024)),
units.length - 1,
);
const value = bytes / 1024 ** exponent;
return `${value >= 10 || exponent === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[exponent]}`;
}
function formatDuration(seconds: number | undefined) {
const safeSeconds = Math.max(0, Math.round(seconds ?? 0));
const minutes = Math.floor(safeSeconds / 60);
return `${minutes}:${String(safeSeconds % 60).padStart(2, "0")}`;
}
function formatMaxSize(bytes: number) {
const megabytes = bytes / (1024 * 1024);
return `${Number.isInteger(megabytes) ? megabytes : megabytes.toFixed(1)} MB`;
}
function inferKind(file: File): AttachmentUploadKind {
if (file.type.startsWith("image/")) return "image";
if (file.type.startsWith("audio/")) return "audio";
return "file";
}
function AttachmentIcon({ kind }: { kind: AttachmentUploadKind }) {
if (kind === "link") return <LinkIcon className="size-4" />;
if (kind === "image") return <FileImage className="size-4" />;
if (kind === "audio") return <Mic className="size-4" />;
return <Paperclip className="size-4" />;
}
function imageSource(item: AttachmentUploadItem) {
if (item.kind !== "image") return undefined;
return item.previewUrl ?? item.href;
}
type RowActionState =
| "idle"
| "uploading"
| "complete"
| "failed"
| "removing";
function RowAction({
label,
onClick,
state,
retryable = false,
reduce = false,
}: {
label: string;
onClick: () => void;
state: RowActionState;
retryable?: boolean;
reduce?: boolean;
}) {
if (state === "uploading") {
return <span aria-hidden="true" className="size-9 shrink-0" />;
}
if (state === "complete") {
return (
<Tooltip content="Upload complete" side="top" delay={100}>
<motion.span
role="status"
aria-label={`Upload complete for ${label}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.75 }}
animate={{ opacity: 1, scale: 1 }}
transition={ITEM_TRANSITION}
className="grid size-9 shrink-0 place-items-center rounded-xl text-emerald-600 dark:text-emerald-400"
>
<Check className="size-4" />
</motion.span>
</Tooltip>
);
}
if (state === "removing") {
return (
<Tooltip content="Removing attachment" side="top" delay={100}>
<span
role="status"
aria-label={`Removing ${label}`}
className="grid size-9 shrink-0 place-items-center rounded-xl text-muted-foreground"
>
<motion.span
animate={reduce ? undefined : { rotate: 360 }}
transition={{
duration: 0.7,
ease: "linear",
repeat: Infinity,
}}
className="grid place-items-center"
>
<LoaderCircle className="size-4" />
</motion.span>
</span>
</Tooltip>
);
}
if (state === "failed") {
if (!retryable) {
return (
<Tooltip content="Upload failed" side="top" delay={100}>
<span
role="status"
aria-label={`Upload failed for ${label}`}
className="grid size-9 shrink-0 place-items-center rounded-xl text-destructive"
>
<AlertCircle className="size-4" />
</span>
</Tooltip>
);
}
return (
<Tooltip content="Retry upload" side="top" delay={100}>
<motion.button
type="button"
aria-label={`Retry ${label}`}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-xl text-destructive outline-none transition-colors hover:bg-destructive/10 focus-visible:ring-2 focus-visible:ring-ring"
>
<RotateCcw className="size-4" />
</motion.button>
</Tooltip>
);
}
return (
<Tooltip content="Remove attachment" side="top" delay={100}>
<motion.button
type="button"
aria-label={`Remove ${label}`}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-xl text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-4" />
</motion.button>
</Tooltip>
);
}
function ImageThumbnail({
item,
layoutId,
onPreview,
reduce,
}: {
item: AttachmentUploadItem;
layoutId?: string;
onPreview: (item: AttachmentUploadItem) => void;
reduce: boolean;
}) {
const src = imageSource(item);
if (!src) {
return (
<span
aria-hidden="true"
className="grid size-8 shrink-0 place-items-center rounded-lg bg-muted text-muted-foreground"
>
<FileImage className="size-4" />
</span>
);
}
return (
<Tooltip
side="top"
delay={160}
className="rounded-xl p-1 shadow-xl"
content={
<span className="block w-32">
{/* biome-ignore lint/performance/noImgElement: Blob and remote previews keep this registry component framework-agnostic. */}
<img
src={src}
alt=""
className="h-20 w-full rounded-lg object-cover"
/>
<span className="block px-1 pb-0.5 pt-1 text-center text-[10px] font-medium text-muted-foreground">
Click to preview
</span>
</span>
}
>
<motion.button
type="button"
aria-label={`Preview ${item.name}`}
onClick={(event) => {
event.currentTarget.blur();
onPreview(item);
}}
whileTap={reduce ? undefined : { scale: 0.94 }}
transition={SPRING_PRESS}
className="group/image relative size-9 shrink-0 overflow-hidden rounded-[10px] bg-muted outline-none ring-1 ring-border/70 focus-visible:ring-2 focus-visible:ring-ring"
>
{/* biome-ignore lint/performance/noImgElement: Motion layout requires the image element and portable blob URLs. */}
<motion.img
layoutId={layoutId}
src={src}
alt=""
className="size-full object-cover"
transition={{ layout: SPRING_LAYOUT }}
/>
</motion.button>
</Tooltip>
);
}
function ImagePreviewDialog({
item,
layoutId,
onClose,
reduce,
}: {
item: AttachmentUploadItem | null;
layoutId?: string;
onClose: () => void;
reduce: boolean;
}) {
const closeRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!item) return;
const previousFocus =
document.activeElement instanceof HTMLElement
? document.activeElement
: null;
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
closeRef.current?.focus();
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") onClose();
if (event.key === "Tab") {
event.preventDefault();
closeRef.current?.focus();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
document.body.style.overflow = previousOverflow;
previousFocus?.focus();
};
}, [item, onClose]);
if (typeof document === "undefined") return null;
const src = item ? imageSource(item) : undefined;
const content =
item && src ? (
// The wrapper carries no box: both children are `fixed` and resolve
// against the viewport themselves. The scrim spans the viewport edges but
// paints a colour, and the layer that centres the image is inset off every
// edge. `PresenceGate` releases interaction in the same commit that starts
// the exit.
<PresenceGate>
{({ isPresent, gate }) => (
<div
inert={!isPresent}
className="pointer-events-none fixed left-0 top-0 z-[10000] size-0"
>
<motion.button
type="button"
aria-label="Close image preview"
tabIndex={-1}
className="pointer-events-auto fixed inset-0 size-full cursor-default bg-black/45 backdrop-blur-xl"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={{ duration: reduce ? 0.1 : 0.2, ease: EASE_OUT }}
{...gate}
onClick={onClose}
/>
<div className="fixed inset-4 flex items-center justify-center sm:inset-8">
<motion.div
role="dialog"
aria-modal="true"
aria-label={`Preview of ${item.name}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={ITEM_TRANSITION}
{...gate}
className="pointer-events-auto relative"
>
{/* biome-ignore lint/performance/noImgElement: Motion layout requires the image element and portable blob URLs. */}
<motion.img
layoutId={reduce ? undefined : layoutId}
src={src}
alt={item.name}
className="max-h-[90vh] max-w-[90vw] rounded-2xl object-contain shadow-2xl"
transition={{ layout: SPRING_LAYOUT }}
/>
<motion.button
ref={closeRef}
type="button"
aria-label="Close image preview"
onClick={onClose}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={
reduce ? undefined : { opacity: 0, scale: 0.8 }
}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="absolute -right-3 -top-3 grid size-9 place-items-center rounded-full bg-background text-foreground shadow-xl outline-none ring-1 ring-border/70 transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-4" />
</motion.button>
</motion.div>
</div>
</div>
)}
</PresenceGate>
) : null;
return createPortal(
reduce ? content : <AnimatePresence>{content}</AnimatePresence>,
document.body,
);
}
function AttachmentRow({
item,
playing,
uploading,
uploadComplete,
failed,
removing,
arrivalIndex,
imageLayoutId,
onAudioToggle,
onImagePreview,
onRemove,
onRetry,
reduce,
className,
}: {
item: AttachmentUploadItem;
playing: boolean;
uploading: boolean;
uploadComplete: boolean;
failed: boolean;
removing: boolean;
arrivalIndex: number;
imageLayoutId?: string;
onAudioToggle?: (item: AttachmentUploadItem) => void;
onImagePreview: (item: AttachmentUploadItem) => void;
onRemove: (item: AttachmentUploadItem) => void;
onRetry?: (item: AttachmentUploadItem) => void;
reduce: boolean;
className?: string;
}) {
const size = formatBytes(item.size);
const progress =
item.duration && item.duration > 0
? Math.min(1, Math.max(0, (item.currentTime ?? 0) / item.duration))
: 0;
const actionState: RowActionState = removing
? "removing"
: uploading
? "uploading"
: uploadComplete
? "complete"
: failed
? "failed"
: "idle";
const arrivalDelay = Math.min(Math.max(arrivalIndex, 0), 5) * 0.055;
const rowTransition =
!reduce && arrivalIndex >= 0
? {
...SPRING_LAYOUT,
delay: arrivalDelay,
opacity: {
duration: 0.16,
ease: EASE_OUT,
delay: arrivalDelay,
},
}
: ITEM_TRANSITION;
const showUploadProgress = uploading || uploadComplete;
const uploadProgress = (
<motion.span
role="progressbar"
aria-label={`Uploading ${item.name}`}
className="pointer-events-none absolute inset-0 -z-10 origin-left bg-emerald-400/25 dark:bg-emerald-500/20"
initial={{ opacity: 1, scaleX: 0 }}
animate={{ opacity: 1, scaleX: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={{
duration: reduce ? 0.1 : UPLOAD_PROGRESS_MS / 1000,
ease: EASE_OUT,
}}
/>
);
return (
<motion.li
layout={!reduce}
initial={
reduce
? { opacity: 0 }
: arrivalIndex >= 0
? { opacity: 0, y: -16, scale: 0.985 }
: { opacity: 0, y: 6 }
}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={reduce ? undefined : { opacity: 0, y: -4 }}
transition={rowTransition}
className={cn(
"flex min-h-14 items-center gap-1 rounded-2xl bg-muted/70 p-1",
className,
)}
>
<div className="relative isolate flex min-w-0 flex-1 items-center gap-3 self-stretch overflow-hidden rounded-xl bg-background px-2 py-1">
{failed ? (
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 -z-10 bg-destructive/10"
/>
) : null}
{item.kind === "image" ? (
<ImageThumbnail
item={item}
layoutId={imageLayoutId}
onPreview={onImagePreview}
reduce={reduce}
/>
) : (
<span
aria-hidden="true"
className="grid size-7 shrink-0 place-items-center text-muted-foreground"
>
<AttachmentIcon kind={item.kind} />
</span>
)}
{item.kind === "audio" ? (
<>
<span className="w-9 shrink-0 text-xs tabular-nums text-muted-foreground">
{formatDuration(item.currentTime)}
</span>
<span
aria-hidden="true"
className="flex h-11 min-w-0 flex-1 items-center gap-[3px] overflow-hidden"
>
{WAVEFORM_BARS.map((bar, index) => (
<motion.span
key={bar.id}
className={cn(
"w-[3px] shrink-0 rounded-full",
index / WAVEFORM_BARS.length <= progress
? "bg-foreground"
: "bg-muted-foreground/35",
)}
style={{ height: bar.height }}
animate={
reduce || !playing
? undefined
: { scaleY: [0.72, 1, 0.78] }
}
transition={{
duration: 0.55,
ease: EASE_OUT,
repeat: Infinity,
delay: index * 0.018,
}}
/>
))}
</span>
<span className="w-9 shrink-0 text-right text-xs tabular-nums text-muted-foreground">
{formatDuration(item.duration)}
</span>
<motion.button
type="button"
aria-label={`${playing ? "Pause" : "Play"} ${item.name}`}
onClick={() => onAudioToggle?.(item)}
whileTap={{ scale: 0.94 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-full bg-foreground text-background outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<AnimatePresence mode="wait" initial={false}>
<motion.span
key={playing ? "pause" : "play"}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
transition={ITEM_TRANSITION}
>
{playing ? (
<Pause className="size-4 fill-current" />
) : (
<Play className="size-4 translate-x-px fill-current" />
)}
</motion.span>
</AnimatePresence>
</motion.button>
</>
) : (
<>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-foreground">
{item.name}
</span>
{failed ? (
<span className="block truncate text-[11px] text-destructive">
{item.error ?? "Upload failed"}
</span>
) : null}
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{item.kind === "link" ? "Web" : size}
</span>
{item.kind === "link" && item.href ? (
<a
href={item.href}
target="_blank"
rel="noreferrer noopener"
aria-label={`Open ${item.name}`}
className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<ExternalLink className="size-4" />
</a>
) : null}
</>
)}
{reduce ? (
showUploadProgress ? (
uploadProgress
) : null
) : (
<AnimatePresence>
{showUploadProgress ? uploadProgress : null}
</AnimatePresence>
)}
</div>
<RowAction
label={item.name}
onClick={() => {
if (actionState === "failed") {
onRetry?.(item);
return;
}
onRemove(item);
}}
state={actionState}
retryable={onRetry !== undefined}
reduce={reduce}
/>
</motion.li>
);
}
export function AttachmentUpload({
value,
defaultValue,
onValueChange,
onFilesAdded,
onFilesRejected,
onRemove,
onRetry,
playingId,
onAudioToggle,
accept,
multiple = true,
maxFiles = 12,
maxFileSize = DEFAULT_MAX_FILE_SIZE,
disabled = false,
title = "Drag and drop or browse files",
description,
attachmentsLabel = "Attachments",
className,
classNames,
}: AttachmentUploadProps) {
const inputId = useId();
const inputRef = useRef<HTMLInputElement>(null);
const dragDepthRef = useRef(0);
const ownedUrlsRef = useRef(new Set<string>());
const lifecycleTimersRef = useRef(
new Set<ReturnType<typeof setTimeout>>(),
);
const reduce = useReducedMotion() ?? false;
const [dragging, setDragging] = useState(false);
const [previewItem, setPreviewItem] =
useState<AttachmentUploadItem | null>(null);
const [uploadingIds, setUploadingIds] = useState<Set<string>>(
() => new Set(),
);
const [uploadCompleteIds, setUploadCompleteIds] = useState<Set<string>>(
() => new Set(),
);
const [removingIds, setRemovingIds] = useState<Set<string>>(
() => new Set(),
);
const [items, setItems] = useControllableList({
value,
defaultValue,
onValueChange,
});
const itemsRef = useRef(items);
itemsRef.current = items;
useEffect(
() => () => {
for (const url of ownedUrlsRef.current) URL.revokeObjectURL(url);
ownedUrlsRef.current.clear();
for (const timer of lifecycleTimersRef.current) {
clearTimeout(timer);
}
lifecycleTimersRef.current.clear();
},
[],
);
const maxReached = items.length >= maxFiles;
const scheduleLifecycle = useCallback(
(callback: () => void, delay: number) => {
const timer = setTimeout(() => {
lifecycleTimersRef.current.delete(timer);
callback();
}, delay);
lifecycleTimersRef.current.add(timer);
},
[],
);
const addFiles = useCallback(
(incomingFiles: File[]) => {
if (disabled || incomingFiles.length === 0) return;
const availableSlots = Math.max(0, maxFiles - items.length);
if (availableSlots === 0) {
onFilesRejected?.(incomingFiles, "max-files");
return;
}
const selectedFiles = incomingFiles.slice(
0,
multiple ? availableSlots : Math.min(1, availableSlots),
);
const oversized = selectedFiles.filter(
(file) => file.size > maxFileSize,
);
const accepted = selectedFiles.filter(
(file) => file.size <= maxFileSize,
);
if (oversized.length > 0) onFilesRejected?.(oversized, "too-large");
if (incomingFiles.length > selectedFiles.length) {
onFilesRejected?.(incomingFiles.slice(selectedFiles.length), "max-files");
}
const added = accepted.map((file, index) => {
const kind = inferKind(file);
const objectUrl = URL.createObjectURL(file);
ownedUrlsRef.current.add(objectUrl);
return {
id: `${Date.now()}-${index}-${file.name}`,
name: file.name,
kind,
size: file.size,
previewUrl: kind === "image" ? objectUrl : undefined,
href: objectUrl,
currentTime: kind === "audio" ? 0 : undefined,
duration: kind === "audio" ? 0 : undefined,
file,
};
});
if (added.length === 0) return;
setItems([...items, ...added]);
const addedIds = added.map((item) => item.id);
setUploadingIds((current) => new Set([...current, ...addedIds]));
scheduleLifecycle(
() => {
setUploadingIds((current) => {
const next = new Set(current);
for (const id of addedIds) next.delete(id);
return next;
});
setUploadCompleteIds(
(current) => new Set([...current, ...addedIds]),
);
scheduleLifecycle(() => {
setUploadCompleteIds((current) => {
const next = new Set(current);
for (const id of addedIds) next.delete(id);
return next;
});
}, UPLOAD_COMPLETE_HOLD_MS);
},
reduce ? 140 : UPLOAD_PROGRESS_MS,
);
onFilesAdded?.(added, accepted);
},
[
disabled,
items,
maxFileSize,
maxFiles,
multiple,
onFilesAdded,
onFilesRejected,
reduce,
scheduleLifecycle,
setItems,
],
);
const finalizeRemove = useCallback(
(item: AttachmentUploadItem) => {
const ownedUrl = [item.previewUrl, item.href].find(
(url): url is string =>
url !== undefined && ownedUrlsRef.current.has(url),
);
if (ownedUrl) {
URL.revokeObjectURL(ownedUrl);
ownedUrlsRef.current.delete(ownedUrl);
}
setPreviewItem((current) =>
current?.id === item.id ? null : current,
);
setUploadingIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
setUploadCompleteIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
setItems(itemsRef.current.filter((entry) => entry.id !== item.id));
onRemove?.(item);
},
[onRemove, setItems],
);
const requestRemove = useCallback(
(item: AttachmentUploadItem) => {
if (removingIds.has(item.id)) return;
setRemovingIds((current) => new Set(current).add(item.id));
scheduleLifecycle(
() => {
finalizeRemove(item);
setRemovingIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
},
reduce ? 140 : REMOVE_PENDING_MS,
);
},
[
finalizeRemove,
reduce,
removingIds,
scheduleLifecycle,
],
);
const resetDrag = useCallback(() => {
dragDepthRef.current = 0;
setDragging(false);
}, []);
const closePreview = useCallback(() => setPreviewItem(null), []);
useEffect(() => {
if (
previewItem &&
!items.some((item) => item.id === previewItem.id)
) {
setPreviewItem(null);
}
}, [items, previewItem]);
const uploadOrder = Array.from(uploadingIds);
const previewLayoutId = previewItem
? `attachment-image-${previewItem.id}`
: undefined;
return (
<LayoutGroup id={inputId}>
<div className={cn("w-full", className)}>
<input
ref={inputRef}
id={inputId}
type="file"
aria-label="Upload attachments"
accept={accept}
multiple={multiple}
disabled={disabled || maxReached}
tabIndex={-1}
className="sr-only"
onChange={(event) => {
addFiles(Array.from(event.currentTarget.files ?? []));
event.currentTarget.value = "";
}}
/>
<motion.button
type="button"
disabled={disabled || maxReached}
data-dragging={dragging}
animate={
reduce
? undefined
: { scale: dragging ? 1.006 : 1 }
}
whileTap={reduce ? undefined : { scale: 0.995 }}
transition={SPRING_PRESS}
onClick={() => inputRef.current?.click()}
onDragEnter={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current += 1;
setDragging(true);
}}
onDragOver={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
setDragging(true);
}}
onDragLeave={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) setDragging(false);
}}
onDrop={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
resetDrag();
addFiles(Array.from(event.dataTransfer.files));
}}
className={cn(
"group relative isolate flex min-h-52 w-full flex-col items-center justify-center overflow-hidden rounded-[2rem] bg-muted/65 p-2 text-center outline-none",
"transition-colors duration-200 hover:bg-muted/85",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"data-[dragging=true]:bg-muted",
"disabled:pointer-events-none disabled:opacity-55",
classNames?.dropzone,
)}
>
<span
aria-hidden="true"
className="absolute inset-2 -z-10 rounded-[1.5rem] border border-dashed border-muted-foreground/25 bg-background transition-[border-color,background-color] duration-200 group-hover:border-muted-foreground/45 group-data-[dragging=true]:border-foreground/65 group-data-[dragging=true]:bg-muted/20"
/>
<motion.span
aria-hidden="true"
animate={
reduce
? undefined
: {
y: dragging ? -4 : 0,
scale: dragging ? 1.08 : 1,
}
}
transition={ITEM_TRANSITION}
className="mb-3 grid size-11 place-items-center rounded-2xl bg-muted text-foreground transition-colors duration-200 group-hover:bg-muted/80 group-data-[dragging=true]:bg-foreground group-data-[dragging=true]:text-background"
>
<Upload className="size-[18px]" />
</motion.span>
<span className="text-sm font-semibold tracking-[-0.01em] text-foreground">
{maxReached ? "Attachment limit reached" : title}
</span>
<span className="mt-1 text-xs leading-5 text-muted-foreground">
{maxReached
? `${items.length} of ${maxFiles} attachments added`
: description ?? `Maximum ${formatMaxSize(maxFileSize)} file size`}
</span>
</motion.button>
{items.length > 0 ? (
<section className="mt-8" aria-labelledby={`${inputId}-attachments`}>
<h3
id={`${inputId}-attachments`}
className="text-sm font-semibold text-foreground"
>
{attachmentsLabel}
</h3>
{items.length > 0 ? (
<ul className={cn("mt-3 space-y-2", classNames?.list)}>
<AnimatePresence initial={uploadOrder.length > 0}>
{items.map((item) => (
<AttachmentRow
key={item.id}
item={item}
playing={playingId === item.id}
uploading={
uploadingIds.has(item.id) ||
item.status === "uploading"
}
uploadComplete={
uploadCompleteIds.has(item.id) ||
item.status === "complete"
}
failed={item.status === "failed"}
removing={removingIds.has(item.id)}
arrivalIndex={uploadOrder.indexOf(item.id)}
imageLayoutId={
reduce ? undefined : `attachment-image-${item.id}`
}
onAudioToggle={onAudioToggle}
onImagePreview={setPreviewItem}
onRemove={requestRemove}
onRetry={onRetry}
reduce={reduce}
className={classNames?.row}
/>
))}
</AnimatePresence>
</ul>
) : null}
</section>
) : null}
<ImagePreviewDialog
item={previewItem}
layoutId={reduce ? undefined : previewLayoutId}
onClose={closePreview}
reduce={reduce}
/>
</div>
</LayoutGroup>
);
}
"use client";
import { AnimatePresence } from "motion/react";
import {
type ComponentProps,
type PointerEvent as ReactPointerEvent,
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { TooltipSurface } from "@/components/motion/tooltip-surface";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { cn } from "@/lib/utils";
import { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from "./tooltip/grace";
import { TooltipArrow, TooltipPositioner } from "./tooltip/positioner";
import {
type TooltipAlign,
type TooltipAnchor,
type TooltipPoint,
type TooltipSide,
useTooltipPointer,
} from "./tooltip/use-position";
export type { TooltipAlign, TooltipSide };
/* -------------------------------------------------------------------------- */
/* Provider */
/* -------------------------------------------------------------------------- */
interface TooltipTiming {
/** Delay before a hover opens a tooltip (ms). */
delay: number;
/** Delay before a tooltip closes once the pointer has left it (ms). */
closeDelay: number;
/** After one tooltip closes, others open instantly for this long (ms). */
skipDelay: number;
}
const TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });
export interface TooltipProviderProps extends Partial<TooltipTiming> {
children: ReactNode;
}
/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */
export function TooltipProvider({ children, ...timing }: TooltipProviderProps) {
const parent = useContext(TimingContext);
const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =
timing;
const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);
return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
// Moving along a toolbar should feel instant after the first label, and only
// one label may show at a time: a keyboard-focused control and a hovered one
// would otherwise both claim the screen.
let lastClosedAt = 0;
let current: { close: () => void } | null = null;
function isEmpty(content: ReactNode) {
return content == null || content === false || content === "";
}
interface TooltipContextValue {
open: boolean;
contentId: string;
labelId: string;
asLabel: boolean;
empty: boolean;
followCursor: boolean;
anchor: TooltipAnchor | null;
/** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */
triggered: boolean;
floatingRef: RefObject<HTMLSpanElement | null>;
pointer: ReturnType<typeof useTooltipPointer>;
setTrigger: (element: TooltipAnchor | null) => void;
setEmpty: (empty: boolean) => void;
close: () => void;
onContentEnter: () => void;
onContentLeave: (event: ReactPointerEvent) => void;
}
const TooltipContext = createContext<TooltipContextValue | null>(null);
function useTooltipContext(part: string) {
const context = useContext(TooltipContext);
if (!context) throw new Error(`${part} must be used inside <Tooltip>`);
return context;
}
export interface TooltipRootProps {
children?: ReactNode;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Delay before showing on hover (ms). Keyboard focus shows immediately. */
delay?: number;
/** Delay before hiding once the pointer has left (ms). */
closeDelay?: number;
/** Never show, e.g. while the label it carries is already visible. */
disabled?: boolean;
/**
* Use the tooltip as the trigger's accessible name rather than its
* description. For icon-only controls whose only label is the tooltip.
*/
asLabel?: boolean;
/** Follow real pointer coordinates; keyboard focus still uses the anchor. */
followCursor?: boolean;
/** Existing anchor for controlled integrations such as chart cells. */
anchorRef?: RefObject<TooltipAnchor | null>;
/** Id of the tooltip surface, for anchors that reference it themselves. */
id?: string;
}
function TooltipRoot({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
delay: delayProp,
closeDelay: closeDelayProp,
disabled = false,
asLabel = false,
followCursor = false,
anchorRef,
id,
initialEmpty = false,
}: TooltipRootProps & { initialEmpty?: boolean }) {
const timing = useContext(TimingContext);
const delay = delayProp ?? timing.delay;
const closeDelay = closeDelayProp ?? timing.closeDelay;
const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
const open = controlledOpen ?? uncontrolledOpen;
const [empty, setEmpty] = useState(initialEmpty);
const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);
const [external, setExternal] = useState<TooltipAnchor | null>(null);
const anchor = anchorRef ? external : trigger;
const generatedId = useId();
const contentId = id ?? `${generatedId}-content`;
const labelId = `${generatedId}-label`;
const floatingRef = useRef<HTMLSpanElement | null>(null);
const anchorObject = useRef<TooltipAnchor | null>(null);
const pointer = useTooltipPointer(anchor, followCursor);
// An external ref can attach after this component renders; read it once it has.
useLayoutEffect(() => {
if (!anchorRef) return;
const element = anchorRef.current ?? null;
if (element !== external) setExternal(element);
});
// Everything the event listeners read, current without re-binding them.
const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });
useLayoutEffect(() => {
anchorObject.current = anchor;
latest.current = {
open,
delay,
closeDelay,
disabled,
empty,
onOpenChange,
controlled: controlledOpen !== undefined,
};
});
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const grace = useRef<(() => void) | null>(null);
const self = useRef<{ close: () => void }>({ close: () => {} });
const clearTimers = useCallback(() => {
if (openTimer.current) clearTimeout(openTimer.current);
if (closeTimer.current) clearTimeout(closeTimer.current);
openTimer.current = null;
closeTimer.current = null;
}, []);
const stopGrace = useCallback(() => {
grace.current?.();
grace.current = null;
}, []);
// Only a real change reaches the consumer: a pointer leaving a closed
// tooltip is not news.
const commit = useCallback((next: boolean) => {
if (latest.current.open === next) return;
if (!latest.current.controlled) setUncontrolledOpen(next);
latest.current.onOpenChange?.(next);
}, []);
const openNow = useCallback(() => {
clearTimers();
stopGrace();
if (latest.current.disabled || latest.current.empty) return;
if (current && current !== self.current) current.close();
current = self.current;
commit(true);
}, [clearTimers, stopGrace, commit]);
const close = useCallback(() => {
clearTimers();
stopGrace();
if (latest.current.open) lastClosedAt = Date.now();
if (current === self.current) current = null;
commit(false);
}, [clearTimers, stopGrace, commit]);
useLayoutEffect(() => {
self.current.close = close;
}, [close]);
const requestOpen = useCallback(() => {
clearTimers();
if (latest.current.open || latest.current.disabled || latest.current.empty) return;
const warm = Date.now() - lastClosedAt < timing.skipDelay;
if (warm || latest.current.delay <= 0) openNow();
else openTimer.current = setTimeout(openNow, latest.current.delay);
}, [clearTimers, openNow, timing.skipDelay]);
const requestClose = useCallback(() => {
clearTimers();
if (latest.current.closeDelay > 0) {
closeTimer.current = setTimeout(close, latest.current.closeDelay);
} else close();
}, [clearTimers, close]);
// Hold the label open while the pointer crosses from one box toward the other.
const startGrace = useCallback(
(exit: TooltipPoint, from: Element, to: Element | null) => {
stopGrace();
if (!to) return requestClose();
const target = to.getBoundingClientRect();
const origin = from.getBoundingClientRect();
const corridor = graceArea(exit, target);
const onMove = (event: PointerEvent) => {
const point = { x: event.clientX, y: event.clientY };
if (inBox(point, target) || inBox(point, origin)) return;
if (!inPolygon(point, corridor)) requestClose();
};
document.addEventListener("pointermove", onMove);
grace.current = () => document.removeEventListener("pointermove", onMove);
},
[stopGrace, requestClose],
);
const hover = useHoverGesture();
const tap = useTapGesture<boolean>();
// Listeners go on the trigger itself rather than on cloned props, so a
// component that owns its own handlers keeps them, and no wrapper element
// sits between the control and its layout.
useEffect(() => {
if (anchorRef || !trigger) return;
watchModality();
// A mouse press dismisses the label and keeps it away until the pointer
// leaves; hovering a control you just clicked should not bring it back.
let suppressed = false;
// Focus that came from the keyboard holds the label open on its own.
let keyboardFocus = false;
const onEnter = (event: PointerEvent) => {
if (!hover.enter(event)) return;
stopGrace();
if (closeTimer.current) clearTimeout(closeTimer.current);
if (!suppressed) requestOpen();
};
const onLeave = (event: PointerEvent) => {
if (!hover.leave(event)) return;
suppressed = false;
if (keyboardFocus) return;
if (openTimer.current) {
clearTimers();
return;
}
if (latest.current.open && !followCursor) {
startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);
} else requestClose();
};
const onDown = (event: PointerEvent) => {
tap.start(event, latest.current.open);
if (event.pointerType === "mouse") {
suppressed = true;
close();
}
};
// A finger never hovers, and Safari does not focus a button on tap either,
// so the label is only reachable if the tap itself toggles it. The click
// carries no pointerType; the pointerdown before it says whether it was a
// tap, and keyboard activation has none at all.
const onClick = () => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) close();
else openNow();
};
const onKey = () => tap.drop();
const onFocusIn = () => {
if (!focusFromKeyboard()) return;
keyboardFocus = true;
openNow();
};
const onFocusOut = (event: FocusEvent) => {
if (trigger.contains(event.relatedTarget as Node | null)) return;
keyboardFocus = false;
close();
};
// Both element kinds dispatch the same events; one type keeps the listeners typed.
const el = trigger as HTMLElement;
el.addEventListener("pointerenter", onEnter);
el.addEventListener("pointerleave", onLeave);
el.addEventListener("pointerdown", onDown);
el.addEventListener("pointercancel", tap.drop);
el.addEventListener("click", onClick);
el.addEventListener("keydown", onKey);
el.addEventListener("focusin", onFocusIn);
el.addEventListener("focusout", onFocusOut);
return () => {
el.removeEventListener("pointerenter", onEnter);
el.removeEventListener("pointerleave", onLeave);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointercancel", tap.drop);
el.removeEventListener("click", onClick);
el.removeEventListener("keydown", onKey);
el.removeEventListener("focusin", onFocusIn);
el.removeEventListener("focusout", onFocusOut);
};
}, [
anchorRef,
trigger,
followCursor,
hover,
tap,
requestOpen,
requestClose,
openNow,
close,
clearTimers,
stopGrace,
startGrace,
]);
// While open, a trigger that turns disabled loses focus without a blur event,
// and a window that loses focus never reports the pointer leaving.
useEffect(() => {
if (!open || anchorRef || !trigger) return;
const observer = new MutationObserver(() => {
if (trigger.matches(":disabled, [aria-disabled='true']")) close();
});
observer.observe(trigger, { attributes: true, attributeFilter: ["disabled", "aria-disabled"] });
window.addEventListener("blur", close);
return () => {
observer.disconnect();
window.removeEventListener("blur", close);
};
}, [open, anchorRef, trigger, close]);
// A chart drives its own open state and swaps content as it goes; only a
// trigger-owned label closes itself for having nothing to say.
useEffect(() => {
if (disabled || (empty && !anchorRef)) close();
}, [disabled, empty, anchorRef, close]);
useEffect(
() => () => {
clearTimers();
stopGrace();
if (current === self.current) current = null;
},
[clearTimers, stopGrace],
);
const insideTooltip = useCallback(
(target: Element) => Boolean(floatingRef.current?.contains(target)),
[],
);
// ...and closed by the next tap that lands somewhere else, or Escape. The
// label covers nothing interactive, so that tap passes through to what it hit.
useDismiss(open, close, anchorObject, { ignore: insideTooltip });
const onContentEnter = useCallback(() => {
stopGrace();
clearTimers();
}, [stopGrace, clearTimers]);
const onContentLeave = useCallback(
(event: ReactPointerEvent) => {
const floating = floatingRef.current;
if (!floating) return;
if (anchorRef) {
// Bridge the small gap back onto a chart; it reopens on its own terms.
clearTimers();
closeTimer.current = setTimeout(close, 100);
return;
}
startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);
},
[anchorRef, clearTimers, close, startGrace],
);
const value = useMemo<TooltipContextValue>(
() => ({
open,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
triggered: !anchorRef,
floatingRef,
pointer,
setTrigger,
setEmpty,
close,
onContentEnter,
onContentLeave,
}),
[
open,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
anchorRef,
pointer,
close,
onContentEnter,
onContentLeave,
],
);
return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Trigger */
/* -------------------------------------------------------------------------- */
function mergeIds(...ids: unknown[]) {
return ids.filter((value) => typeof value === "string" && value).join(" ") || undefined;
}
function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) (ref as { current: T | null }).current = value;
}
export interface TooltipTriggerProps extends ComponentProps<"button"> {
/** Use the single child element as the trigger instead of rendering a button. */
asChild?: boolean;
}
export function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {
const { open, contentId, labelId, asLabel, empty, setTrigger } =
useTooltipContext("TooltipTrigger");
const child = asChild && isValidElement(children) ? children : null;
const childProps = (child?.props ?? props) as Record<string, unknown>;
const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;
const attached = useRef<TooltipAnchor | null>(null);
const setRef = useCallback(
(element: TooltipAnchor | null) => {
attached.current = element;
setTrigger(element);
assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);
},
[setTrigger, childRef, ref],
);
useEffect(() => {
if (process.env.NODE_ENV !== "production" && child && !attached.current) {
console.warn(
"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.",
);
}
}, [child]);
const aria = asLabel
? {
"aria-labelledby": empty
? (childProps["aria-labelledby"] as string | undefined)
: labelId,
}
: {
"aria-describedby": mergeIds(
childProps["aria-describedby"],
open && !empty ? contentId : undefined,
),
};
if (asChild) {
if (!child) return children;
return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });
}
return (
<button
type="button"
data-state={open ? "open" : "closed"}
{...props}
ref={setRef as Ref<HTMLButtonElement>}
{...aria}
>
{children}
</button>
);
}
/* -------------------------------------------------------------------------- */
/* Content */
/* -------------------------------------------------------------------------- */
export interface TooltipContentProps {
children?: ReactNode;
side?: TooltipSide;
align?: TooltipAlign;
/** Gap between anchor and tooltip (px). */
sideOffset?: number;
/** Draw an arrow pointing at the anchor. */
arrow?: boolean;
/** Point within the anchor, as fractions of its rendered width and height. */
anchorPoint?: TooltipPoint;
className?: string;
}
export function TooltipContent({
children,
side = "top",
align = "center",
sideOffset,
arrow = false,
anchorPoint,
className,
}: TooltipContentProps) {
const {
open,
contentId,
labelId,
asLabel,
followCursor,
anchor,
floatingRef,
pointer,
setEmpty,
close,
onContentEnter,
onContentLeave,
} = useTooltipContext("TooltipContent");
const empty = isEmpty(children);
const arrowRef = useRef<SVGSVGElement | null>(null);
useLayoutEffect(() => {
setEmpty(empty);
}, [empty, setEmpty]);
if (typeof document === "undefined") return null;
return createPortal(
<>
{/* The name has to exist while the label is closed, so it lives apart from the surface. */}
{asLabel && !empty ? (
<span id={labelId} hidden>
{children}
</span>
) : null}
<AnimatePresence>
{open && !empty ? (
<TooltipPositioner
key="tooltip"
anchor={anchor}
floatingRef={floatingRef}
arrowRef={arrow ? arrowRef : undefined}
anchorPoint={anchorPoint}
followCursor={followCursor}
side={side}
align={align}
sideOffset={sideOffset}
onDismiss={close}
pointer={pointer}
>
{(positioned, isPresent, placedSide) => (
<TooltipSurface
id={asLabel ? undefined : contentId}
aria-hidden={asLabel || undefined}
ready={positioned}
onPointerEnter={onContentEnter}
onPointerLeave={onContentLeave}
style={{ pointerEvents: isPresent && !followCursor ? "auto" : "none" }}
className={cn(
"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words",
arrow && "relative",
className,
)}
>
{children}
{arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}
</TooltipSurface>
)}
</TooltipPositioner>
) : null}
</AnimatePresence>
</>,
document.body,
);
}
/* -------------------------------------------------------------------------- */
/* Tooltip (root, or one-line shorthand when given `content`) */
/* -------------------------------------------------------------------------- */
export interface TooltipProps
extends TooltipRootProps,
Omit<TooltipContentProps, "children" | "className"> {
/**
* Shorthand: the tooltip's content. With it, `children` is the trigger
* element; without it, compose `TooltipTrigger` and `TooltipContent`.
*/
content?: ReactNode;
/** Shorthand only: classes for the tooltip surface. */
className?: string;
}
export function Tooltip(props: TooltipProps) {
if (!("content" in props)) return <TooltipRoot {...props} />;
const {
content,
children,
side,
align,
sideOffset,
arrow,
anchorPoint,
className,
...root
} = props;
if (!root.anchorRef && !isValidElement(children)) return children ?? null;
return (
<TooltipRoot {...root} initialEmpty={isEmpty(content)}>
{isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}
<TooltipContent
side={side}
align={align}
sideOffset={sideOffset}
arrow={arrow}
anchorPoint={anchorPoint}
className={className}
>
{content}
</TooltipContent>
</TooltipRoot>
);
}
type Point = { x: number; y: number };
type Box = { left: number; top: number; right: number; bottom: number };
/**
* The corridor a pointer may cross between the trigger and the open tooltip
* without closing it: the convex hull of where it left and the box it is
* heading for. A fixed timeout either cuts a slow diagonal move short or keeps
* the label alive after the pointer has plainly gone elsewhere; this follows
* the path itself.
*/
export function graceArea(exit: Point, target: Box): Point[] {
// A few pixels either side of the exit point give the corridor some width at
// its narrow end, so a hand that drifts sideways while it moves stays inside.
const pad = 5;
return hull([
{ x: exit.x - pad, y: exit.y - pad },
{ x: exit.x + pad, y: exit.y - pad },
{ x: exit.x - pad, y: exit.y + pad },
{ x: exit.x + pad, y: exit.y + pad },
{ x: target.left, y: target.top },
{ x: target.right, y: target.top },
{ x: target.right, y: target.bottom },
{ x: target.left, y: target.bottom },
]);
}
export function inBox(point: Point, box: Box) {
return (
point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom
);
}
export function inPolygon(point: Point, polygon: Point[]) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const a = polygon[i];
const b = polygon[j];
if (
a.y > point.y !== b.y > point.y &&
point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x
) {
inside = !inside;
}
}
return inside;
}
// Monotone chain; the corridor is always convex, so a hull is all it needs.
function hull(points: Point[]) {
const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);
const cross = (o: Point, a: Point, b: Point) =>
(a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower: Point[] = [];
for (const p of sorted) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
}
const upper: Point[] = [];
for (let i = sorted.length - 1; i >= 0; i--) {
const p = sorted[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
/**
* How the user last reached for the page. A focus that a mouse press caused is
* not a request to read the label: the pointer is already on the control and
* hovering showed it. A focus that followed a key — Tab, or a roving arrow key
* moving focus in script — is the only way a keyboard user sees it at all.
*/
let modality: "keyboard" | "pointer" = "keyboard";
let listening = false;
export function watchModality() {
if (listening || typeof window === "undefined") return;
listening = true;
window.addEventListener("keydown", () => (modality = "keyboard"), true);
window.addEventListener("pointerdown", () => (modality = "pointer"), true);
}
export function focusFromKeyboard() {
return modality === "keyboard";
}
"use client";
import { useIsPresent } from "motion/react";
import { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from "react";
import { type TooltipSide, useTooltipPosition } from "./use-position";
type PositionProps = Parameters<typeof useTooltipPosition>[0];
/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */
export function TooltipPositioner({
children,
...position
}: Omit<PositionProps, "open" | "onPosition"> & {
children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;
}) {
const present = useIsPresent();
const [ready, setReady] = useState(false);
const [side, setSide] = useState<TooltipSide>(position.side);
const onPosition = useCallback((placed: TooltipSide) => {
setReady(true);
setSide(placed);
}, []);
useTooltipPosition({ ...position, open: present, onPosition });
return (
<span
ref={position.floatingRef}
inert={!present}
aria-hidden={!present || undefined}
className="pointer-events-none fixed left-0 top-0 z-[9999] w-max"
style={{ visibility: "hidden", maxWidth: "calc(100vw - 16px)" }}
>
{children(ready, present, side)}
</span>
);
}
// Each arrow is a 12px box whose base sits on the surface's inner border edge,
// so its fill covers the border beneath it and only the two outer edges stroke.
const ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {
top: { path: "M0 6L6 12L12 6", style: { top: "calc(100% - 6px)" } },
bottom: { path: "M0 6L6 0L12 6", style: { bottom: "calc(100% - 6px)" } },
left: { path: "M6 0L12 6L6 12", style: { left: "calc(100% - 6px)" } },
right: { path: "M6 0L0 6L6 12", style: { right: "calc(100% - 6px)" } },
};
export function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {
const { path, style } = ARROW[side];
return (
<svg
ref={ref}
aria-hidden="true"
width="12"
height="12"
viewBox="0 0 12 12"
className="pointer-events-none absolute overflow-visible"
style={style}
>
<path d={`${path}Z`} style={{ fill: "var(--tooltip-arrow-fill, transparent)" }} />
<path
d={path}
fill="none"
strokeWidth="1"
style={{ stroke: "var(--tooltip-arrow-stroke, transparent)" }}
/>
</svg>
);
}
"use client";
import {
arrow as arrowMiddleware,
autoUpdate,
computePosition,
flip,
hide,
offset,
type Placement,
shift,
type VirtualElement,
} from "@floating-ui/dom";
import { type RefObject, useCallback, useLayoutEffect, useRef } from "react";
export type TooltipSide = "top" | "right" | "bottom" | "left";
export type TooltipAlign = "start" | "center" | "end";
export type TooltipPoint = { x: number; y: number };
export type TooltipAnchor = HTMLElement | SVGElement;
const ORIGIN: Record<TooltipSide, string> = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */
export function useTooltipPosition({
open,
anchor,
floatingRef,
arrowRef,
anchorPoint,
followCursor,
side,
align,
sideOffset,
onDismiss,
onPosition,
pointer,
}: {
open: boolean;
anchor: TooltipAnchor | null;
floatingRef: RefObject<HTMLSpanElement | null>;
arrowRef?: RefObject<SVGSVGElement | null>;
anchorPoint?: TooltipPoint;
followCursor: boolean;
side: TooltipSide;
align: TooltipAlign;
sideOffset?: number;
onDismiss: () => void;
onPosition: (side: TooltipSide) => void;
pointer: ReturnType<typeof useTooltipPointer>;
}) {
const { cursor, onMove } = pointer;
const preferred: Placement = align === "center" ? side : `${side}-${align}`;
const cursorSide = useRef<Placement | null>(null);
useLayoutEffect(() => {
cursorSide.current = open ? preferred : null;
}, [open, preferred]);
const frame = useRef<number | null>(null);
const version = useRef(0);
const update = useRef<() => void>(() => {});
const schedule = useCallback(() => {
// Invalidate older async calculations as soon as new geometry is requested.
version.current++;
if (frame.current !== null) return;
frame.current = requestAnimationFrame(() => {
frame.current = null;
update.current();
});
}, []);
useLayoutEffect(() => {
onMove.current = schedule;
return () => {
onMove.current = null;
};
}, [onMove, schedule]);
const pointX = anchorPoint?.x;
const pointY = anchorPoint?.y;
// Latest committed inputs are read without recreating observers for every period/content update.
useLayoutEffect(() => {
update.current = () => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const revision = ++version.current;
const currentCursor = followCursor ? cursor.current : null;
const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;
const reference: Element | VirtualElement = virtual
? {
contextElement: anchor,
getBoundingClientRect: () => {
const rect = anchor.getBoundingClientRect();
const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);
const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);
return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };
},
}
: anchor;
const arrowElement = arrowRef?.current ?? null;
void computePosition(reference, floating, {
strategy: "fixed",
placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,
middleware: [
offset(sideOffset ?? (currentCursor ? 12 : 8)),
flip({ padding: 8 }),
shift({ padding: 8 }),
...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),
// A label left floating over whatever scrolled into its trigger's place
// describes nothing there. Points inside a chart move with the chart.
...(virtual ? [] : [hide({ strategy: "referenceHidden" })]),
],
}).then(({ x, y, placement, middlewareData }) => {
if (version.current !== revision || !floating.isConnected) return;
// Hold the chosen side for this hover session. Crossing a flip threshold
// repeatedly must not bounce the surface above and below the pointer.
if (currentCursor) cursorSide.current = placement;
else cursorSide.current = null;
const placedSide = placement.split("-")[0] as TooltipSide;
const dpr = window.devicePixelRatio || 1;
floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;
floating.style.setProperty("--tooltip-origin", ORIGIN[placedSide]);
// A box with no size has no clipped state to report, only a missing layout.
const box = anchor.getBoundingClientRect();
const clipped =
Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);
floating.style.visibility = clipped ? "hidden" : "visible";
floating.dataset.placement = placement;
const surface = arrowElement?.parentElement;
if (arrowElement && surface) {
// Measured against the positioner, drawn inside the surface's border.
const { x: ax, y: ay } = middlewareData.arrow ?? {};
if (ax != null) arrowElement.style.left = `${ax - surface.clientLeft}px`;
if (ay != null) arrowElement.style.top = `${ay - surface.clientTop}px`;
// Paint with whatever the surface resolved to, so a restyled tooltip
// keeps a matching arrow without a second set of classes.
const style = getComputedStyle(surface);
arrowElement.style.setProperty("--tooltip-arrow-fill", style.backgroundColor);
arrowElement.style.setProperty("--tooltip-arrow-stroke", style.borderTopColor);
}
onPosition(placedSide);
});
};
if (open) schedule();
}, [
open,
anchor,
floatingRef,
arrowRef,
followCursor,
pointX,
pointY,
preferred,
sideOffset,
schedule,
onPosition,
cursor,
]);
useLayoutEffect(() => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const stop = autoUpdate(anchor, floating, schedule);
const onScroll = () => {
// A stationary pointer no longer describes the same chart point after scrolling.
if (followCursor && cursor.current) onDismiss();
};
window.addEventListener("scroll", onScroll, true);
return () => {
stop();
window.removeEventListener("scroll", onScroll, true);
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
frame.current = null;
};
}, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);
useLayoutEffect(
() => () => {
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
},
[],
);
}
/** Pointer lifetime belongs to the anchor, including the opening delay. */
export function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {
const cursor = useRef<TooltipPoint | null>(null);
const onMove = useRef<(() => void) | null>(null);
const pointerFocus = useRef(false);
useLayoutEffect(() => {
if (!anchor || !followCursor) return;
const point = (event: PointerEvent) => {
if (event.type === "pointermove" && event.pointerType === "touch" && !event.buttons) return;
cursor.current = { x: event.clientX, y: event.clientY };
if (event.type === "pointerdown") pointerFocus.current = true;
onMove.current?.();
};
const keyboard = () => {
cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const focus = () => {
if (!pointerFocus.current) cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const leave = () => {
cursor.current = null;
};
anchor.addEventListener("pointerenter", point as EventListener, { passive: true });
anchor.addEventListener("pointermove", point as EventListener, { passive: true });
anchor.addEventListener("pointerdown", point as EventListener, { passive: true });
anchor.addEventListener("pointerleave", leave);
anchor.addEventListener("pointercancel", leave);
anchor.addEventListener("keydown", keyboard);
anchor.addEventListener("focusin", focus);
return () => {
cursor.current = null;
anchor.removeEventListener("pointerenter", point as EventListener);
anchor.removeEventListener("pointermove", point as EventListener);
anchor.removeEventListener("pointerdown", point as EventListener);
anchor.removeEventListener("pointerleave", leave);
anchor.removeEventListener("pointercancel", leave);
anchor.removeEventListener("keydown", keyboard);
anchor.removeEventListener("focusin", focus);
};
}, [anchor, followCursor]);
return { cursor, onMove };
}
"use client";
import { motion, useReducedMotion } from "motion/react";
import type { ComponentProps, ReactNode, Ref } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
/** Presentation only: the unanimated parent owns measurement and positioning. */
export function TooltipSurface({
children,
side: _side = "top",
className,
ref,
ready = true,
style,
...props
}: Omit<ComponentProps<typeof motion.span>, "children"> & {
children?: ReactNode;
/** Start the entrance only after the positioning layer has been measured. */
ready?: boolean;
side?: "top" | "right" | "bottom" | "left";
ref?: Ref<HTMLSpanElement>;
}) {
const reduce = useReducedMotion();
const closed = { opacity: 0, scale: reduce ? 1 : 0.94 };
return (
<motion.span
ref={ref}
role="tooltip"
initial={closed}
animate={{
...(ready ? { opacity: 1, scale: 1 } : closed),
transition: { duration: 0.18, ease: EASE_OUT },
}}
exit={{ ...closed, transition: { duration: 0.12, ease: EASE_OUT } }}
style={{ transformOrigin: "var(--tooltip-origin, center)", ...style }}
className={cn(
"block whitespace-nowrap rounded-lg border border-border bg-background px-2.5 py-1 text-xs font-medium text-foreground shadow-lg",
className,
)}
{...props}
>
{children}
</motion.span>
);
}
API Reference
value?AttachmentUploadItem[]—defaultValue?AttachmentUploadItem[]—onValueChange?((items: AttachmentUploadItem[]) => void)—onFilesAdded?((items: AttachmentUploadItem[], files: File[]) => void)—onFilesRejected?((files: File[], reason: AttachmentRejectReason) => void)—onRemove?((item: AttachmentUploadItem) => void)—onRetry?((item: AttachmentUploadItem) => void)—playingId?string—onAudioToggle?((item: AttachmentUploadItem) => void)—accept?string—multiple?booleantruemaxFiles?number12maxFileSize?number500 * 1024 * 1024disabled?booleanfalsetitle?stringDrag and drop or browse filesdescription?string—attachmentsLabel?stringAttachmentsclassName?string—classNames?AttachmentUploadClassNames—Upload Queue
file-upload.tsxA drag-and-drop upload queue with progress rows, upload states, retry, and removal.
Upload package
1 of 3 files ready
brand-assets.zip
ZIP · 18 MB
Uploadedrelease-cut.mov
MOV · 80 MB
Uploadingvendor-contract.pdf
PDF · 2.7 MB · Connection lost
Failed
"use client";
import { RotateCcw } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
FileUpload,
type FileUploadItem,
type FileUploadVariant,
} from "@/components/motion/file-upload";
const initialItems: FileUploadItem[] = [
{
id: "brand-assets",
name: "brand-assets.zip",
size: 18_400_000,
type: "application/zip",
progress: 100,
status: "success",
},
{
id: "release-video",
name: "release-cut.mov",
size: 84_200_000,
type: "video/quicktime",
progress: 58,
status: "uploading",
},
{
id: "contracts",
name: "vendor-contract.pdf",
size: 2_800_000,
type: "application/pdf",
progress: 32,
status: "error",
error: "Connection lost",
},
];
const variants: { id: FileUploadVariant; label: string }[] = [
{ id: "centered", label: "Centered" },
{ id: "default", label: "Row" },
];
export function FileUploadPreview() {
const [items, setItems] = useState(initialItems);
const [variant, setVariant] = useState<FileUploadVariant>("centered");
const timersRef = useRef<Map<string, ReturnType<typeof setInterval>>>(
new Map(),
);
const stopUpload = useCallback((id: string) => {
const timer = timersRef.current.get(id);
if (!timer) return;
clearInterval(timer);
timersRef.current.delete(id);
}, []);
const startUpload = useCallback(
(id: string) => {
stopUpload(id);
const timer = setInterval(() => {
setItems((current) => {
const target = current.find((item) => item.id === id);
if (target?.status !== "uploading") {
stopUpload(id);
return current;
}
const nextProgress = Math.min(
100,
(target.progress ?? 0) + 7 + Math.random() * 12,
);
if (nextProgress >= 100) {
stopUpload(id);
}
return current.map((item) =>
item.id === id
? {
...item,
progress: nextProgress,
status: nextProgress >= 100 ? "success" : "uploading",
}
: item,
);
});
}, 520);
timersRef.current.set(id, timer);
},
[stopUpload],
);
useEffect(() => {
startUpload("release-video");
return () => {
for (const timer of timersRef.current.values()) {
clearInterval(timer);
}
timersRef.current.clear();
};
}, [startUpload]);
return (
<div className="flex min-h-[30rem] w-full items-center justify-center">
<div className="w-full max-w-md rounded-[2rem] border border-border bg-background p-3">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2 px-1">
<div>
<p className="text-sm font-semibold text-foreground">
Upload package
</p>
<p className="text-xs text-muted-foreground">
{items.filter((item) => item.status === "success").length} of{" "}
{items.length} files ready
</p>
</div>
<div className="flex items-center gap-1.5">
<div className="flex rounded-full border border-border bg-muted p-1">
{variants.map((entry) => {
const selected = entry.id === variant;
return (
<button
key={entry.id}
type="button"
onClick={() => setVariant(entry.id)}
data-selected={selected}
className="h-7 rounded-full px-3 text-xs font-medium text-muted-foreground transition-[background-color,color,transform] duration-150 hover:text-foreground active:scale-95 data-[selected=true]:bg-background data-[selected=true]:text-foreground"
>
{entry.label}
</button>
);
})}
</div>
<button
type="button"
onClick={() => {
for (const item of items) {
stopUpload(item.id);
}
setItems(initialItems);
startUpload("release-video");
}}
className="grid h-9 w-9 place-items-center rounded-full border border-border text-muted-foreground transition-colors hover:text-foreground active:scale-95"
aria-label="Reset upload queue"
>
<RotateCcw className="h-3.5 w-3.5" />
</button>
</div>
</div>
<FileUpload
value={items}
variant={variant}
onValueChange={setItems}
onFilesAdded={(added) => {
for (const item of added) {
startUpload(item.id);
}
}}
onRetry={(item) => startUpload(item.id)}
onRemove={(item) => stopUpload(item.id)}
maxFiles={5}
title={variant === "centered" ? "Drop files to upload" : "Drop release files"}
description="PDF, images, video or zipped assets"
/>
</div>
</div>
);
}
"use client";
// beui.dev/components/blocks/file-upload
import {
AlertCircle,
CheckCircle2,
FileArchive,
FileAudio,
FileCode2,
FileIcon,
FileImage,
FileSpreadsheet,
FileText,
FileVideo,
Loader2,
RotateCcw,
UploadCloud,
X,
} from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useCallback, useId, useRef, useState } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type FileUploadStatus = "queued" | "uploading" | "success" | "error";
export type FileUploadVariant = "default" | "centered";
export type FileUploadItem = {
id: string;
name: string;
size: number;
type?: string;
progress?: number;
status?: FileUploadStatus;
error?: string;
file?: File;
};
export type FileUploadClassNames = {
root?: string;
dropzone?: string;
queue?: string;
item?: string;
leading?: string;
content?: string;
name?: string;
meta?: string;
progress?: string;
action?: string;
};
export interface FileUploadProps {
value?: FileUploadItem[];
defaultValue?: FileUploadItem[];
onValueChange?: (items: FileUploadItem[]) => void;
onFilesAdded?: (items: FileUploadItem[], files: File[]) => void;
onRemove?: (item: FileUploadItem) => void;
onRetry?: (item: FileUploadItem) => void;
accept?: string;
multiple?: boolean;
maxFiles?: number;
disabled?: boolean;
variant?: FileUploadVariant;
title?: string;
description?: string;
browseLabel?: string;
className?: string;
classNames?: FileUploadClassNames;
}
const ROW_TRANSITION = { duration: 0.22, ease: EASE_OUT } as const;
const FAST_TRANSITION = { duration: 0.16, ease: EASE_OUT } as const;
const STATUS_LABEL: Record<FileUploadStatus, string> = {
queued: "Queued",
uploading: "Uploading",
success: "Uploaded",
error: "Failed",
};
const STATUS_TONE: Record<FileUploadStatus, string> = {
queued: "text-muted-foreground",
uploading: "text-foreground",
success: "text-emerald-600 dark:text-emerald-400",
error: "text-destructive",
};
function useControllableUpload({
value,
defaultValue,
onValueChange,
}: {
value?: FileUploadItem[];
defaultValue?: FileUploadItem[];
onValueChange?: (items: FileUploadItem[]) => void;
}) {
const [internalValue, setInternalValue] = useState(defaultValue ?? []);
const isControlled = value !== undefined;
const items = value ?? internalValue;
const setItems = useCallback(
(next: FileUploadItem[]) => {
if (!isControlled) {
setInternalValue(next);
}
onValueChange?.(next);
},
[isControlled, onValueChange],
);
return [items, setItems] as const;
}
function clampProgress(value: number | undefined, status: FileUploadStatus) {
if (status === "success") return 100;
if (value === undefined || Number.isNaN(value)) return 0;
return Math.max(0, Math.min(100, value));
}
function formatBytes(bytes: number) {
if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const exponent = Math.min(
Math.floor(Math.log(bytes) / Math.log(1024)),
units.length - 1,
);
const value = bytes / 1024 ** exponent;
return `${value >= 10 || exponent === 0 ? value.toFixed(0) : value.toFixed(1)} ${
units[exponent]
}`;
}
function fileKind(item: FileUploadItem) {
const extension = item.name.includes(".")
? item.name.split(".").pop()
: undefined;
if (extension) return extension.toUpperCase();
if (item.type) return item.type.split("/").pop()?.toUpperCase();
return "FILE";
}
function getFileIcon(item: FileUploadItem) {
const extension = item.name.includes(".")
? item.name.split(".").pop()?.toLowerCase()
: undefined;
const type = item.type ?? "";
if (type.startsWith("image/")) return FileImage;
if (type.startsWith("video/")) return FileVideo;
if (type.startsWith("audio/")) return FileAudio;
if (
type.includes("zip") ||
type.includes("compressed") ||
["zip", "rar", "7z", "tar", "gz"].includes(extension ?? "")
) {
return FileArchive;
}
if (
type.includes("spreadsheet") ||
type.includes("excel") ||
["csv", "xls", "xlsx"].includes(extension ?? "")
) {
return FileSpreadsheet;
}
if (
type.includes("pdf") ||
type.startsWith("text/") ||
["pdf", "doc", "docx", "md", "txt"].includes(extension ?? "")
) {
return FileText;
}
if (
[
"css",
"html",
"js",
"jsx",
"json",
"mdx",
"ts",
"tsx",
"xml",
"yaml",
"yml",
].includes(extension ?? "")
) {
return FileCode2;
}
return FileIcon;
}
export function createFileUploadItem(file: File, index = 0): FileUploadItem {
return {
id: `${Date.now()}-${index}-${file.name}`,
name: file.name,
size: file.size,
type: file.type,
progress: 0,
status: "uploading",
file,
};
}
function StatusIcon({
status,
reduce,
}: {
status: FileUploadStatus;
reduce: boolean;
}) {
const iconClassName = "h-4 w-4";
return (
<AnimatePresence mode="wait" initial={false}>
<motion.span
key={status}
initial={
reduce
? { opacity: 0 }
: { opacity: 0, transform: "translateY(4px)" }
}
animate={{ opacity: 1, transform: "translateY(0px)" }}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, transform: "translateY(-4px)" }
}
transition={FAST_TRANSITION}
className={cn("grid h-6 w-6 place-items-center", STATUS_TONE[status])}
>
{status === "success" ? (
<CheckCircle2 className={iconClassName} />
) : status === "error" ? (
<AlertCircle className={iconClassName} />
) : status === "uploading" ? (
<Loader2
className={cn(
iconClassName,
"animate-spin",
reduce && "animate-none",
)}
/>
) : (
<FileIcon className={iconClassName} />
)}
<span className="sr-only">{STATUS_LABEL[status]}</span>
</motion.span>
</AnimatePresence>
);
}
function FileUploadRow({
item,
onRemove,
onRetry,
classNames,
}: {
item: FileUploadItem;
onRemove: (item: FileUploadItem) => void;
onRetry: (item: FileUploadItem) => void;
classNames?: FileUploadClassNames;
}) {
const reduce = useReducedMotion() ?? false;
const status = item.status ?? "queued";
const progress = clampProgress(item.progress, status);
const progressRatio = progress / 100;
const showProgress = status === "uploading" || status === "success";
const LeadingIcon = getFileIcon(item);
return (
<motion.li
layout={!reduce}
initial={
reduce ? { opacity: 0 } : { opacity: 0, transform: "translateY(8px)" }
}
animate={{ opacity: 1, transform: "translateY(0px)" }}
exit={
reduce ? { opacity: 0 } : { opacity: 0, transform: "translateY(-6px)" }
}
transition={ROW_TRANSITION}
className={cn(
"relative overflow-hidden rounded-2xl border border-border bg-background p-3",
classNames?.item,
)}
>
<div className="flex items-center gap-3">
<div
className={cn(
"grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-muted text-muted-foreground",
classNames?.leading,
)}
>
<LeadingIcon className="h-5 w-5" />
</div>
<div className={cn("min-w-0 flex-1", classNames?.content)}>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p
className={cn(
"truncate text-sm font-medium text-foreground",
classNames?.name,
)}
>
{item.name}
</p>
<p
className={cn(
"mt-0.5 text-xs text-muted-foreground",
classNames?.meta,
)}
>
{fileKind(item)} · {formatBytes(item.size)}
{status === "error" && item.error ? ` · ${item.error}` : null}
</p>
</div>
<div className="flex shrink-0 items-center gap-1">
<StatusIcon status={status} reduce={reduce} />
{status === "error" ? (
<button
type="button"
onClick={() => onRetry(item)}
aria-label={`Retry ${item.name}`}
className={cn(
"grid h-7 w-7 place-items-center rounded-full text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground active:scale-95",
classNames?.action,
)}
>
<RotateCcw className="h-3.5 w-3.5" />
</button>
) : null}
<button
type="button"
onClick={() => onRemove(item)}
aria-label={`Remove ${item.name}`}
className={cn(
"grid h-7 w-7 place-items-center rounded-full text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground active:scale-95",
classNames?.action,
)}
>
<X className="h-3.5 w-3.5" />
</button>
</div>
</div>
{showProgress ? (
<div
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(progress)}
aria-label={`${item.name} upload progress`}
className={cn(
"mt-3 h-1.5 overflow-hidden rounded-full bg-muted",
classNames?.progress,
)}
>
<motion.div
className={cn(
"h-full rounded-full",
status === "success"
? "bg-emerald-500"
: "bg-foreground",
)}
style={{
transformOrigin: "left",
transform: reduce ? `scaleX(${progressRatio})` : undefined,
}}
initial={false}
animate={
reduce ? undefined : { transform: `scaleX(${progressRatio})` }
}
transition={{ duration: 0.28, ease: EASE_OUT }}
/>
</div>
) : null}
</div>
</div>
</motion.li>
);
}
export function FileUpload({
value,
defaultValue,
onValueChange,
onFilesAdded,
onRemove,
onRetry,
accept,
multiple = true,
maxFiles,
disabled = false,
variant = "default",
title = "Drop files here",
description = "Add files to the upload queue",
browseLabel = "Browse",
className,
classNames,
}: FileUploadProps) {
const inputId = useId();
const inputRef = useRef<HTMLInputElement>(null);
const dragDepthRef = useRef(0);
const reduce = useReducedMotion() ?? false;
const [items, setItems] = useControllableUpload({
value,
defaultValue,
onValueChange,
});
const [dragging, setDragging] = useState(false);
const commit = useCallback(
(next: FileUploadItem[]) => {
setItems(next);
},
[setItems],
);
const addFiles = useCallback(
(incomingFiles: File[]) => {
if (disabled || incomingFiles.length === 0) return;
const remainingSlots =
maxFiles === undefined ? incomingFiles.length : maxFiles - items.length;
if (remainingSlots <= 0) return;
const files = incomingFiles.slice(
0,
multiple ? remainingSlots : Math.min(1, remainingSlots),
);
const added = files.map((file, index) => createFileUploadItem(file, index));
if (added.length === 0) return;
commit([...items, ...added]);
onFilesAdded?.(added, files);
},
[commit, disabled, items, maxFiles, multiple, onFilesAdded],
);
const removeItem = useCallback(
(item: FileUploadItem) => {
commit(items.filter((entry) => entry.id !== item.id));
onRemove?.(item);
},
[commit, items, onRemove],
);
const retryItem = useCallback(
(item: FileUploadItem) => {
const retryingItem = {
...item,
error: undefined,
progress: 0,
status: "uploading" as const,
};
commit(
items.map((entry) => (entry.id === item.id ? retryingItem : entry)),
);
onRetry?.(retryingItem);
},
[commit, items, onRetry],
);
const resetDrag = useCallback(() => {
dragDepthRef.current = 0;
setDragging(false);
}, []);
const maxReached = maxFiles !== undefined && items.length >= maxFiles;
const centered = variant === "centered";
return (
<div className={cn("w-full space-y-3", className, classNames?.root)}>
<input
ref={inputRef}
id={inputId}
type="file"
aria-label="Upload files"
accept={accept}
multiple={multiple}
disabled={disabled || maxReached}
tabIndex={-1}
className="sr-only"
onChange={(event) => {
addFiles(Array.from(event.currentTarget.files ?? []));
event.currentTarget.value = "";
}}
/>
<button
type="button"
disabled={disabled || maxReached}
data-dragging={dragging}
onClick={() => inputRef.current?.click()}
onDragEnter={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current += 1;
setDragging(true);
}}
onDragOver={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
setDragging(true);
}}
onDragLeave={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) setDragging(false);
}}
onDrop={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
resetDrag();
addFiles(Array.from(event.dataTransfer.files));
}}
className={cn(
"group relative flex w-full overflow-hidden rounded-3xl border border-dashed border-border bg-background outline-none",
"transition-[border-color,transform] duration-200 active:scale-[0.99]",
"hover:border-foreground/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"data-[dragging=true]:border-foreground",
"disabled:pointer-events-none disabled:opacity-55",
centered
? "min-h-56 flex-col items-center justify-center gap-3 p-7 text-center"
: "items-center gap-4 p-5 text-left",
classNames?.dropzone,
)}
>
<motion.span
aria-hidden="true"
className={cn(
"grid shrink-0 place-items-center bg-muted text-foreground",
centered
? "h-16 w-16 rounded-[1.35rem] border border-border"
: "h-14 w-14 rounded-[1.25rem]",
)}
animate={
reduce
? undefined
: {
transform: dragging
? "translateY(-2px)"
: "translateY(0px)",
}
}
transition={FAST_TRANSITION}
>
<UploadCloud className={centered ? "h-7 w-7" : "h-6 w-6"} />
</motion.span>
<span className={cn("min-w-0", centered ? "max-w-xs" : "flex-1")}>
<span
className={cn(
"block font-semibold text-foreground",
centered ? "text-base" : "text-sm",
)}
>
{maxReached ? "Upload limit reached" : title}
</span>
<span
className={cn(
"block text-xs text-muted-foreground",
centered ? "mt-1 leading-5" : "mt-0.5",
)}
>
{maxReached
? `${items.length} of ${maxFiles} files added`
: description}
</span>
</span>
<span
className={cn(
"shrink-0 rounded-full border border-border text-xs font-medium text-foreground transition-colors duration-150 group-hover:bg-muted",
centered ? "mt-1 px-4 py-2" : "px-3.5 py-2",
)}
>
{browseLabel}
</span>
</button>
<ul className={cn("space-y-2", classNames?.queue)}>
<AnimatePresence initial={false}>
{items.map((item) => (
<FileUploadRow
key={item.id}
item={item}
onRemove={removeItem}
onRetry={retryItem}
classNames={classNames}
/>
))}
</AnimatePresence>
</ul>
</div>
);
}
Install
shadcn init? You are set. Theme setupInstall dependencies
npm i @floating-ui/dom clsx lucide-react motion tailwind-mergeAdd util files
// Shared motion tokens. Easing curves mirror the CSS custom properties in
// globals.css; springs are the canonical physics used across components.
// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;
export const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;
/** CSS string form of EASE_OUT for inline style transitions. */
export const EASE_OUT_CSS = "cubic-bezier(0.16, 1, 0.3, 1)";
/** Press feedback on buttons and other tappable surfaces. */
export const SPRING_PRESS = {
type: "spring",
stiffness: 500,
damping: 30,
mass: 0.6,
} as const;
/** Content swaps — label/icon slots trading places inside a control. */
export const SPRING_SWAP = {
type: "spring",
stiffness: 460,
damping: 30,
mass: 0.55,
} as const;
/** Overlay panel entrances — modals and sheets summoned by pointer. */
export const SPRING_PANEL = {
type: "spring",
stiffness: 420,
damping: 40,
mass: 0.5,
} as const;
/** Shared-layout glides — pills, indicators and panels morphing between positions. */
export const SPRING_LAYOUT = {
type: "spring",
stiffness: 360,
damping: 32,
mass: 0.6,
} as const;
/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */
export const SPRING_MOUSE = {
stiffness: 200,
damping: 15,
mass: 0.3,
} as const;
/** Dragged handles and fills (sliders) — critically damped `useSpring` config,
* so the value follows the pointer butterily and never rebounds off an end. */
export const SPRING_GLIDE = {
stiffness: 700,
damping: 50,
mass: 0.5,
} as const;
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
"use client";
import { useIsPresent } from "motion/react";
import type { ReactNode } from "react";
export interface PresenceGateRenderProps {
/**
* False from the render that starts the exit animation onward. An overlay
* kept in the tree by `AnimatePresence` is still the topmost thing on the
* page, so anything it decides from `open` alone stays true for the whole
* exit — this is the boolean that already knows the overlay is leaving.
*/
isPresent: boolean;
/**
* Spread onto every layer that takes pointer events while the overlay is
* open. Interaction releases in the same commit that starts the exit while
* the visual exit keeps playing: pointer events stop landing, and `inert`
* drops the subtree from focus order, from tab order and from the
* accessibility tree — an exiting dialog is not a dialog you can still type
* into. A layer that never takes pointer events (a wrapper that only centres
* the panel) takes `inert={!isPresent}` alone, so its own
* `pointer-events-none` is not overwritten.
*/
gate: {
inert: boolean;
style: { pointerEvents: "auto" | "none" };
};
}
export interface PresenceGateProps {
children: (props: PresenceGateRenderProps) => ReactNode;
}
/**
* Reads the presence of the subtree it renders and hands it down.
*
* `useIsPresent` only answers inside the `AnimatePresence` subtree, and the
* components that own an overlay render the `AnimatePresence` themselves, so
* the boolean has to be read one component further down: this is that
* component, and the render prop is how it reaches the layers.
*/
export function PresenceGate({ children }: PresenceGateProps) {
const isPresent = useIsPresent();
return children({
isPresent,
gate: {
inert: !isPresent,
style: { pointerEvents: isPresent ? "auto" : "none" },
},
});
}
"use client";
import { type RefObject, useEffect } from "react";
/**
* What the dismissing gesture does to the control it landed on.
*
* `"pass-through"` is the platform norm (native popover light-dismiss): the
* tap closes the overlay *and* activates whatever was under it. Use
* `"consume"` where the open overlay sits over or beside controls that would
* be costly to trigger by accident — the dismissal then swallows the
* activation too, so the gesture only closes.
*/
export type DismissBehavior = "pass-through" | "consume";
export interface DismissOptions {
/** Default `"pass-through"`. */
behavior?: DismissBehavior;
/** Dismiss on Escape as well. Default true. */
escape?: boolean;
/** Return true for an outside target that should *not* dismiss. Must be stable. */
ignore?: (target: Element) => boolean;
}
/**
* What every currently open dismiss scope counts as inside itself. A consumed
* dismissal reads this to tell a stray gesture from one that belongs to an
* overlay in front of it: overlays have no shared z-order to consult, but the
* one the gesture landed in has said as much by registering it.
*/
const openScopes = new Set<(target: Element) => boolean>();
function claimedByAnotherScope(
self: (target: Element) => boolean,
target: Element,
) {
for (const scope of openScopes) {
if (scope !== self && scope(target)) return true;
}
return false;
}
// preventDefault on pointerdown does not suppress the click that follows, so
// consuming a gesture means swallowing that click itself. The swallower
// deliberately outlives the effect that installed it — the dismissal it
// belongs to has already unmounted or re-rendered by the time the click lands.
// It releases on that click, or on the next gesture if the pointer is dragged
// away and no click ever arrives, so it can never eat a later one. A keydown
// releases it too: a gesture that ends with neither a click nor a cancel would
// otherwise leave it armed, and the click Enter synthesizes on some focused
// control is not the one this dismissal was owed.
function consumeActivation(source: Event) {
const swallow = (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
release();
};
const restart = (event: Event) => {
if (event !== source) release();
};
const release = () => {
window.removeEventListener("click", swallow, true);
window.removeEventListener("pointerdown", restart, true);
window.removeEventListener("pointercancel", restart, true);
window.removeEventListener("keydown", release, true);
};
window.addEventListener("click", swallow, true);
window.addEventListener("pointerdown", restart, true);
window.addEventListener("pointercancel", restart, true);
window.addEventListener("keydown", release, true);
}
/**
* Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`
* for `ref` when what counts as inside isn't one element, and say so with
* `ignore` instead.
*
* The pointerdown listener is capture-phase: a bubble-phase one is blinded by
* any handler in between that stops propagation, and an overlay cannot know
* what it is layered over. `onDismiss` and `ignore` must be stable (wrap in
* useCallback) so the listeners aren't re-bound every render while open.
*/
export function useDismiss(
open: boolean,
onDismiss: () => void,
ref: RefObject<HTMLElement | SVGElement | null> | null,
{
behavior = "pass-through",
escape: dismissOnEscape = true,
ignore,
}: DismissOptions = {},
) {
useEffect(() => {
if (!open) return;
const inside = (target: Element) =>
Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));
const onKey = (event: KeyboardEvent) => {
if (dismissOnEscape && event.key === "Escape") onDismiss();
};
const onPointer = (event: PointerEvent) => {
const target = event.target as Element | null;
if (!target || inside(target)) return;
// Outside this overlay, but inside one that is also open: the gesture is
// that overlay's to answer, and swallowing its click from behind would
// cost the user the control they actually aimed at.
if (behavior === "consume" && !claimedByAnotherScope(inside, target)) {
consumeActivation(event);
}
onDismiss();
};
openScopes.add(inside);
window.addEventListener("keydown", onKey);
window.addEventListener("pointerdown", onPointer, true);
return () => {
openScopes.delete(inside);
window.removeEventListener("keydown", onKey);
window.removeEventListener("pointerdown", onPointer, true);
};
}, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);
}
"use client";
import { useMemo, useRef } from "react";
import { isHoveringPointer } from "@/lib/touch";
interface BoundaryEvent {
pointerId: number;
pointerType: string;
buttons: number;
}
export interface HoverGesture {
/** True when this enter starts a hover: the pointer arrived resting, not pressing. */
enter: (event: BoundaryEvent) => boolean;
/** True when this leave ends a hover that entered as one. */
leave: (event: BoundaryEvent) => boolean;
}
/**
* Pairs a surface's enter with its leave, per pointer.
*
* `isHoveringPointer` answers the question the *enter* asks — is this pointer
* resting on the surface or pressing it — and both boundary cases go wrong if
* the leave is asked the same question again:
*
* - A pen with no hover never rests. It arrives in contact, taps, and the spec
* then requires its boundary events after `pointerup`, so the leave carries
* `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid
* the tap — the panel the pen had just opened closed under it.
* - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.
* Skipping teardown there strands the surface open: the release happens
* outside, and no second leave ever comes.
*
* So the state a hover holds is released by the pointer that took it, whatever
* the buttons say at the boundary, and a pointer that arrived in contact never
* took it in the first place. Contact is the exception tracked here, not
* hover: a leave from a pointer this surface never saw enter — mounted under
* the cursor, say — still counts, since the alternative is state with no way
* out.
*/
export function useHoverGesture(): HoverGesture {
const contact = useRef(new Set<number>());
return useMemo(
() => ({
enter: (event) => {
if (isHoveringPointer(event)) {
contact.current.delete(event.pointerId);
return true;
}
contact.current.add(event.pointerId);
return false;
},
leave: (event) => {
const arrivedInContact = contact.current.delete(event.pointerId);
return !arrivedInContact && event.pointerType !== "touch";
},
}),
[],
);
}
"use client";
import { useMemo, useRef } from "react";
/** What a pointerdown recorded, read back by the click that ends its gesture. */
export interface TapRecord<S> {
/** Which input started the gesture. */
pointerType: string;
/** What the surface was showing when it started. */
state: S;
}
export interface TapGesture<S> {
/** Record the gesture a pointerdown starts, with the state it starts in. */
start: (event: { pointerType: string }, state: S) => void;
/** Read the record and clear it. `null` when no pointer is behind this click. */
take: () => TapRecord<S> | null;
/** Drop the record: this gesture will never spend it on a click. */
drop: () => void;
}
/**
* The pointer gesture behind a click, recorded where the click cannot report
* it. A `click` carries no `pointerType` in the engines that matter, so the
* `pointerdown` before it is the only thing that says which input activated
* the control — and whether one did at all, since keyboard activation
* synthesizes a click with no pointer behind it.
*
* State goes in with the record because a click reports that no better: a
* browser that focuses a control on contact can open the very panel the tap
* was meant to open, and reading "is it open" at click time then undoes it.
* What the gesture started against is what it acts on.
*
* The record is spent by one click and dropped by everything else, because a
* record that outlives its gesture is worse than none:
*
* - A scroll or an OS gesture takes the touch away — `pointercancel`, no click
* ever — and the finger would sit in the record until some later click.
* - That later click is often `Enter` on a keyboard, which arrives with no
* pointerdown of its own and would inherit the abandoned finger. A keydown
* is the start of a keyboard activation and never part of a tap, so it drops
* the record too.
*
* Both ends have to be wired by the surface: `drop` on `onPointerCancel` and
* on `onKeyDown`.
*/
export function useTapGesture<S>(): TapGesture<S> {
const record = useRef<TapRecord<S> | null>(null);
return useMemo(
() => ({
start: (event, state) => {
record.current = { pointerType: event.pointerType, state };
},
take: () => {
const spent = record.current;
record.current = null;
return spent;
},
drop: () => {
record.current = null;
},
}),
[],
);
}
// Shared touch primitives. iOS and iPadOS run their own gestures on top of the
// page — the long-press selection callout and the selection it drags in with
// it — and they win: once the platform claims a touch it cancels ours
// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own
// their gesture have to opt out.
//
// What the two classes below cover, precisely:
// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:
// it is not a property other engines have, so it is inert everywhere else.
// - `user-select: none` stops the long-press selection on every engine,
// Android included, and stops a drag from painting a selection under the
// cursor. It is inherited, so it reaches every descendant — which is why the
// two classes differ only in whether they apply it unconditionally.
// What neither covers:
// - Chrome for Android's long-press menu on a link or an image. No CSS
// suppresses it; a gesture surface that wraps one needs its own
// `onContextMenu` with `preventDefault()`.
// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is
// not inherited and plain divs and buttons are not drag sources, so setting
// it on the surface does nothing — the child itself needs `draggable={false}`.
/**
* Classes for a surface that *is* the control: a thumb, a drum, a stage, a
* handle, a hold button. Selection is suppressed on every input, because a
* drag that highlights the control's own label is wrong on a mouse too.
* Compose with `touch-none` when the surface also owns the scroll axis — leave
* it off when the page must still scroll from there.
*/
export const TOUCH_GESTURE_CLASS = "select-none [-webkit-touch-callout:none]";
/**
* The same opt-out for a gesture surface that wraps content the consumer owns:
* a scroller, a context-menu trigger, a sheet header, a list row. Selection is
* suppressed only where the platform runs its own press gestures — a coarse
* pointer — so a mouse user can still select and copy that content. If the
* gesture itself would paint a selection under the cursor, add `select-none`
* for the duration of the gesture rather than reaching for
* `TOUCH_GESTURE_CLASS`.
*
* `pointer: coarse` describes the *primary* pointer and nothing else, so a
* hybrid machine reads it wrong in both directions: a tablet with a mouse
* plugged in keeps touch as primary and loses mouse selection, and a laptop
* with a touchscreen keeps the mouse as primary and leaves selection live
* under a finger. No media query can answer per interaction — the query is
* about the device, and the question is about the gesture in progress. The
* default stays here because it is right on the machines that are one thing or
* the other, and losing a selection is a nuisance; where the miss costs a
* *gesture* instead, the surface pairs it with `holdSelection` on the press.
*/
export const TOUCH_GESTURE_CONTENT_CLASS =
"[-webkit-touch-callout:none] pointer-coarse:select-none";
/**
* Suppress selection on `element` for as long as a gesture is running on it,
* whatever the primary pointer of the machine happens to be. Returns the
* release. Inline, so it wins over the class above and is gone again the
* moment the gesture ends.
*
* For the press gestures a native selection would otherwise steal — a
* long-press that opens a menu. Elsewhere prefer the classes: a surface that
* takes selection away for the whole session is a surface whose text nobody
* can copy.
*/
export function holdSelection(element: HTMLElement) {
element.style.setProperty("user-select", "none");
element.style.setProperty("-webkit-user-select", "none");
return () => {
element.style.removeProperty("user-select");
element.style.removeProperty("-webkit-user-select");
};
}
/**
* Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer
* is already gone by the time the handler runs — routine on iOS, where the
* system can claim the touch first — and an uncaught throw takes the rest of
* the handler, the gesture included, down with it. Touch pointers carry
* implicit capture anyway, so losing it is never fatal.
*/
export function capturePointer(element: Element, pointerId: number) {
try {
element.setPointerCapture(pointerId);
} catch {
// Pointer is no longer active — implicit capture still applies on touch.
}
}
/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */
export function releasePointer(element: Element, pointerId: number) {
try {
if (element.hasPointerCapture(pointerId)) {
element.releasePointerCapture(pointerId);
}
} catch {
// Capture was already dropped by the browser.
}
}
/**
* Whether this event came from a pointer that is *hovering*: not a touch, and
* not currently pressed. Which input the user is holding right now is not
* something a device capability can answer — a touchscreen laptop hovers and
* taps, and iPadOS reports a fine hovering pointer for a finger — so both
* paths stay live and each handler branches on the event it was given.
*
* A pen resting on the glass is making contact, not hovering: `buttons` is the
* tell, and it sends a pen tap down the same route a finger takes.
*
* This answers what an *enter* asks. A leave is the other half of a pair and
* has to be read against the enter that started it — `useHoverGesture` in
* `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it
* rather than asking this question twice.
*/
export const isHoveringPointer = (event: {
pointerType: string;
buttons: number;
}) => event.pointerType !== "touch" && event.buttons === 0;
Copy the source code
"use client";
// beui.dev/components/blocks/file-upload
import {
AlertCircle,
CheckCircle2,
FileArchive,
FileAudio,
FileCode2,
FileIcon,
FileImage,
FileSpreadsheet,
FileText,
FileVideo,
Loader2,
RotateCcw,
UploadCloud,
X,
} from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useCallback, useId, useRef, useState } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
export type FileUploadStatus = "queued" | "uploading" | "success" | "error";
export type FileUploadVariant = "default" | "centered";
export type FileUploadItem = {
id: string;
name: string;
size: number;
type?: string;
progress?: number;
status?: FileUploadStatus;
error?: string;
file?: File;
};
export type FileUploadClassNames = {
root?: string;
dropzone?: string;
queue?: string;
item?: string;
leading?: string;
content?: string;
name?: string;
meta?: string;
progress?: string;
action?: string;
};
export interface FileUploadProps {
value?: FileUploadItem[];
defaultValue?: FileUploadItem[];
onValueChange?: (items: FileUploadItem[]) => void;
onFilesAdded?: (items: FileUploadItem[], files: File[]) => void;
onRemove?: (item: FileUploadItem) => void;
onRetry?: (item: FileUploadItem) => void;
accept?: string;
multiple?: boolean;
maxFiles?: number;
disabled?: boolean;
variant?: FileUploadVariant;
title?: string;
description?: string;
browseLabel?: string;
className?: string;
classNames?: FileUploadClassNames;
}
const ROW_TRANSITION = { duration: 0.22, ease: EASE_OUT } as const;
const FAST_TRANSITION = { duration: 0.16, ease: EASE_OUT } as const;
const STATUS_LABEL: Record<FileUploadStatus, string> = {
queued: "Queued",
uploading: "Uploading",
success: "Uploaded",
error: "Failed",
};
const STATUS_TONE: Record<FileUploadStatus, string> = {
queued: "text-muted-foreground",
uploading: "text-foreground",
success: "text-emerald-600 dark:text-emerald-400",
error: "text-destructive",
};
function useControllableUpload({
value,
defaultValue,
onValueChange,
}: {
value?: FileUploadItem[];
defaultValue?: FileUploadItem[];
onValueChange?: (items: FileUploadItem[]) => void;
}) {
const [internalValue, setInternalValue] = useState(defaultValue ?? []);
const isControlled = value !== undefined;
const items = value ?? internalValue;
const setItems = useCallback(
(next: FileUploadItem[]) => {
if (!isControlled) {
setInternalValue(next);
}
onValueChange?.(next);
},
[isControlled, onValueChange],
);
return [items, setItems] as const;
}
function clampProgress(value: number | undefined, status: FileUploadStatus) {
if (status === "success") return 100;
if (value === undefined || Number.isNaN(value)) return 0;
return Math.max(0, Math.min(100, value));
}
function formatBytes(bytes: number) {
if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const exponent = Math.min(
Math.floor(Math.log(bytes) / Math.log(1024)),
units.length - 1,
);
const value = bytes / 1024 ** exponent;
return `${value >= 10 || exponent === 0 ? value.toFixed(0) : value.toFixed(1)} ${
units[exponent]
}`;
}
function fileKind(item: FileUploadItem) {
const extension = item.name.includes(".")
? item.name.split(".").pop()
: undefined;
if (extension) return extension.toUpperCase();
if (item.type) return item.type.split("/").pop()?.toUpperCase();
return "FILE";
}
function getFileIcon(item: FileUploadItem) {
const extension = item.name.includes(".")
? item.name.split(".").pop()?.toLowerCase()
: undefined;
const type = item.type ?? "";
if (type.startsWith("image/")) return FileImage;
if (type.startsWith("video/")) return FileVideo;
if (type.startsWith("audio/")) return FileAudio;
if (
type.includes("zip") ||
type.includes("compressed") ||
["zip", "rar", "7z", "tar", "gz"].includes(extension ?? "")
) {
return FileArchive;
}
if (
type.includes("spreadsheet") ||
type.includes("excel") ||
["csv", "xls", "xlsx"].includes(extension ?? "")
) {
return FileSpreadsheet;
}
if (
type.includes("pdf") ||
type.startsWith("text/") ||
["pdf", "doc", "docx", "md", "txt"].includes(extension ?? "")
) {
return FileText;
}
if (
[
"css",
"html",
"js",
"jsx",
"json",
"mdx",
"ts",
"tsx",
"xml",
"yaml",
"yml",
].includes(extension ?? "")
) {
return FileCode2;
}
return FileIcon;
}
export function createFileUploadItem(file: File, index = 0): FileUploadItem {
return {
id: `${Date.now()}-${index}-${file.name}`,
name: file.name,
size: file.size,
type: file.type,
progress: 0,
status: "uploading",
file,
};
}
function StatusIcon({
status,
reduce,
}: {
status: FileUploadStatus;
reduce: boolean;
}) {
const iconClassName = "h-4 w-4";
return (
<AnimatePresence mode="wait" initial={false}>
<motion.span
key={status}
initial={
reduce
? { opacity: 0 }
: { opacity: 0, transform: "translateY(4px)" }
}
animate={{ opacity: 1, transform: "translateY(0px)" }}
exit={
reduce
? { opacity: 0 }
: { opacity: 0, transform: "translateY(-4px)" }
}
transition={FAST_TRANSITION}
className={cn("grid h-6 w-6 place-items-center", STATUS_TONE[status])}
>
{status === "success" ? (
<CheckCircle2 className={iconClassName} />
) : status === "error" ? (
<AlertCircle className={iconClassName} />
) : status === "uploading" ? (
<Loader2
className={cn(
iconClassName,
"animate-spin",
reduce && "animate-none",
)}
/>
) : (
<FileIcon className={iconClassName} />
)}
<span className="sr-only">{STATUS_LABEL[status]}</span>
</motion.span>
</AnimatePresence>
);
}
function FileUploadRow({
item,
onRemove,
onRetry,
classNames,
}: {
item: FileUploadItem;
onRemove: (item: FileUploadItem) => void;
onRetry: (item: FileUploadItem) => void;
classNames?: FileUploadClassNames;
}) {
const reduce = useReducedMotion() ?? false;
const status = item.status ?? "queued";
const progress = clampProgress(item.progress, status);
const progressRatio = progress / 100;
const showProgress = status === "uploading" || status === "success";
const LeadingIcon = getFileIcon(item);
return (
<motion.li
layout={!reduce}
initial={
reduce ? { opacity: 0 } : { opacity: 0, transform: "translateY(8px)" }
}
animate={{ opacity: 1, transform: "translateY(0px)" }}
exit={
reduce ? { opacity: 0 } : { opacity: 0, transform: "translateY(-6px)" }
}
transition={ROW_TRANSITION}
className={cn(
"relative overflow-hidden rounded-2xl border border-border bg-background p-3",
classNames?.item,
)}
>
<div className="flex items-center gap-3">
<div
className={cn(
"grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-muted text-muted-foreground",
classNames?.leading,
)}
>
<LeadingIcon className="h-5 w-5" />
</div>
<div className={cn("min-w-0 flex-1", classNames?.content)}>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p
className={cn(
"truncate text-sm font-medium text-foreground",
classNames?.name,
)}
>
{item.name}
</p>
<p
className={cn(
"mt-0.5 text-xs text-muted-foreground",
classNames?.meta,
)}
>
{fileKind(item)} · {formatBytes(item.size)}
{status === "error" && item.error ? ` · ${item.error}` : null}
</p>
</div>
<div className="flex shrink-0 items-center gap-1">
<StatusIcon status={status} reduce={reduce} />
{status === "error" ? (
<button
type="button"
onClick={() => onRetry(item)}
aria-label={`Retry ${item.name}`}
className={cn(
"grid h-7 w-7 place-items-center rounded-full text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground active:scale-95",
classNames?.action,
)}
>
<RotateCcw className="h-3.5 w-3.5" />
</button>
) : null}
<button
type="button"
onClick={() => onRemove(item)}
aria-label={`Remove ${item.name}`}
className={cn(
"grid h-7 w-7 place-items-center rounded-full text-muted-foreground transition-colors duration-150 hover:bg-muted hover:text-foreground active:scale-95",
classNames?.action,
)}
>
<X className="h-3.5 w-3.5" />
</button>
</div>
</div>
{showProgress ? (
<div
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={Math.round(progress)}
aria-label={`${item.name} upload progress`}
className={cn(
"mt-3 h-1.5 overflow-hidden rounded-full bg-muted",
classNames?.progress,
)}
>
<motion.div
className={cn(
"h-full rounded-full",
status === "success"
? "bg-emerald-500"
: "bg-foreground",
)}
style={{
transformOrigin: "left",
transform: reduce ? `scaleX(${progressRatio})` : undefined,
}}
initial={false}
animate={
reduce ? undefined : { transform: `scaleX(${progressRatio})` }
}
transition={{ duration: 0.28, ease: EASE_OUT }}
/>
</div>
) : null}
</div>
</div>
</motion.li>
);
}
export function FileUpload({
value,
defaultValue,
onValueChange,
onFilesAdded,
onRemove,
onRetry,
accept,
multiple = true,
maxFiles,
disabled = false,
variant = "default",
title = "Drop files here",
description = "Add files to the upload queue",
browseLabel = "Browse",
className,
classNames,
}: FileUploadProps) {
const inputId = useId();
const inputRef = useRef<HTMLInputElement>(null);
const dragDepthRef = useRef(0);
const reduce = useReducedMotion() ?? false;
const [items, setItems] = useControllableUpload({
value,
defaultValue,
onValueChange,
});
const [dragging, setDragging] = useState(false);
const commit = useCallback(
(next: FileUploadItem[]) => {
setItems(next);
},
[setItems],
);
const addFiles = useCallback(
(incomingFiles: File[]) => {
if (disabled || incomingFiles.length === 0) return;
const remainingSlots =
maxFiles === undefined ? incomingFiles.length : maxFiles - items.length;
if (remainingSlots <= 0) return;
const files = incomingFiles.slice(
0,
multiple ? remainingSlots : Math.min(1, remainingSlots),
);
const added = files.map((file, index) => createFileUploadItem(file, index));
if (added.length === 0) return;
commit([...items, ...added]);
onFilesAdded?.(added, files);
},
[commit, disabled, items, maxFiles, multiple, onFilesAdded],
);
const removeItem = useCallback(
(item: FileUploadItem) => {
commit(items.filter((entry) => entry.id !== item.id));
onRemove?.(item);
},
[commit, items, onRemove],
);
const retryItem = useCallback(
(item: FileUploadItem) => {
const retryingItem = {
...item,
error: undefined,
progress: 0,
status: "uploading" as const,
};
commit(
items.map((entry) => (entry.id === item.id ? retryingItem : entry)),
);
onRetry?.(retryingItem);
},
[commit, items, onRetry],
);
const resetDrag = useCallback(() => {
dragDepthRef.current = 0;
setDragging(false);
}, []);
const maxReached = maxFiles !== undefined && items.length >= maxFiles;
const centered = variant === "centered";
return (
<div className={cn("w-full space-y-3", className, classNames?.root)}>
<input
ref={inputRef}
id={inputId}
type="file"
aria-label="Upload files"
accept={accept}
multiple={multiple}
disabled={disabled || maxReached}
tabIndex={-1}
className="sr-only"
onChange={(event) => {
addFiles(Array.from(event.currentTarget.files ?? []));
event.currentTarget.value = "";
}}
/>
<button
type="button"
disabled={disabled || maxReached}
data-dragging={dragging}
onClick={() => inputRef.current?.click()}
onDragEnter={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current += 1;
setDragging(true);
}}
onDragOver={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
setDragging(true);
}}
onDragLeave={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) setDragging(false);
}}
onDrop={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
resetDrag();
addFiles(Array.from(event.dataTransfer.files));
}}
className={cn(
"group relative flex w-full overflow-hidden rounded-3xl border border-dashed border-border bg-background outline-none",
"transition-[border-color,transform] duration-200 active:scale-[0.99]",
"hover:border-foreground/40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"data-[dragging=true]:border-foreground",
"disabled:pointer-events-none disabled:opacity-55",
centered
? "min-h-56 flex-col items-center justify-center gap-3 p-7 text-center"
: "items-center gap-4 p-5 text-left",
classNames?.dropzone,
)}
>
<motion.span
aria-hidden="true"
className={cn(
"grid shrink-0 place-items-center bg-muted text-foreground",
centered
? "h-16 w-16 rounded-[1.35rem] border border-border"
: "h-14 w-14 rounded-[1.25rem]",
)}
animate={
reduce
? undefined
: {
transform: dragging
? "translateY(-2px)"
: "translateY(0px)",
}
}
transition={FAST_TRANSITION}
>
<UploadCloud className={centered ? "h-7 w-7" : "h-6 w-6"} />
</motion.span>
<span className={cn("min-w-0", centered ? "max-w-xs" : "flex-1")}>
<span
className={cn(
"block font-semibold text-foreground",
centered ? "text-base" : "text-sm",
)}
>
{maxReached ? "Upload limit reached" : title}
</span>
<span
className={cn(
"block text-xs text-muted-foreground",
centered ? "mt-1 leading-5" : "mt-0.5",
)}
>
{maxReached
? `${items.length} of ${maxFiles} files added`
: description}
</span>
</span>
<span
className={cn(
"shrink-0 rounded-full border border-border text-xs font-medium text-foreground transition-colors duration-150 group-hover:bg-muted",
centered ? "mt-1 px-4 py-2" : "px-3.5 py-2",
)}
>
{browseLabel}
</span>
</button>
<ul className={cn("space-y-2", classNames?.queue)}>
<AnimatePresence initial={false}>
{items.map((item) => (
<FileUploadRow
key={item.id}
item={item}
onRemove={removeItem}
onRetry={retryItem}
classNames={classNames}
/>
))}
</AnimatePresence>
</ul>
</div>
);
}
"use client";
// beui.dev/components/blocks/file-upload
import {
AlertCircle,
Check,
ExternalLink,
FileImage,
Link as LinkIcon,
LoaderCircle,
Mic,
Paperclip,
Pause,
Play,
RotateCcw,
Upload,
X,
} from "lucide-react";
import {
AnimatePresence,
LayoutGroup,
motion,
useReducedMotion,
} from "motion/react";
import {
useCallback,
useEffect,
useId,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { Tooltip } from "@/components/motion/tooltip";
import {
EASE_OUT,
SPRING_LAYOUT,
SPRING_PRESS,
} from "@/lib/ease";
import { PresenceGate } from "@/lib/presence-gate";
import { cn } from "@/lib/utils";
export type AttachmentUploadKind = "file" | "link" | "image" | "audio";
export type AttachmentRejectReason = "too-large" | "max-files";
export type AttachmentUploadStatus =
| "idle"
| "uploading"
| "complete"
| "failed";
export type AttachmentUploadItem = {
id: string;
name: string;
kind: AttachmentUploadKind;
size?: number;
href?: string;
previewUrl?: string;
currentTime?: number;
duration?: number;
status?: AttachmentUploadStatus;
error?: string;
file?: File;
};
export type AttachmentUploadClassNames = {
dropzone?: string;
list?: string;
row?: string;
};
export interface AttachmentUploadProps {
value?: AttachmentUploadItem[];
defaultValue?: AttachmentUploadItem[];
onValueChange?: (items: AttachmentUploadItem[]) => void;
onFilesAdded?: (items: AttachmentUploadItem[], files: File[]) => void;
onFilesRejected?: (files: File[], reason: AttachmentRejectReason) => void;
onRemove?: (item: AttachmentUploadItem) => void;
onRetry?: (item: AttachmentUploadItem) => void;
playingId?: string;
onAudioToggle?: (item: AttachmentUploadItem) => void;
accept?: string;
multiple?: boolean;
maxFiles?: number;
maxFileSize?: number;
disabled?: boolean;
title?: string;
description?: string;
attachmentsLabel?: string;
className?: string;
classNames?: AttachmentUploadClassNames;
}
const ITEM_TRANSITION = { duration: 0.2, ease: EASE_OUT } as const;
const DEFAULT_MAX_FILE_SIZE = 500 * 1024 * 1024;
const UPLOAD_PROGRESS_MS = 900;
const UPLOAD_COMPLETE_HOLD_MS = 1000;
const REMOVE_PENDING_MS = 420;
const WAVEFORM_BARS = [
18, 31, 24, 39, 30, 43, 27, 18, 9, 29, 38, 24, 34, 18, 26, 37, 21, 14,
7, 11, 22, 35, 18, 26, 41, 29, 17, 33,
].map((height, index) => ({ id: `wave-${index}-${height}`, height }));
function useControllableList<T>({
value,
defaultValue,
onValueChange,
}: {
value?: T[];
defaultValue?: T[];
onValueChange?: (items: T[]) => void;
}) {
const [internalValue, setInternalValue] = useState(defaultValue ?? []);
const controlled = value !== undefined;
const items = value ?? internalValue;
const setItems = useCallback(
(next: T[]) => {
if (!controlled) setInternalValue(next);
onValueChange?.(next);
},
[controlled, onValueChange],
);
return [items, setItems] as const;
}
function formatBytes(bytes: number | undefined) {
if (bytes === undefined || !Number.isFinite(bytes) || bytes <= 0) {
return null;
}
const units = ["B", "KB", "MB", "GB"];
const exponent = Math.min(
Math.floor(Math.log(bytes) / Math.log(1024)),
units.length - 1,
);
const value = bytes / 1024 ** exponent;
return `${value >= 10 || exponent === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[exponent]}`;
}
function formatDuration(seconds: number | undefined) {
const safeSeconds = Math.max(0, Math.round(seconds ?? 0));
const minutes = Math.floor(safeSeconds / 60);
return `${minutes}:${String(safeSeconds % 60).padStart(2, "0")}`;
}
function formatMaxSize(bytes: number) {
const megabytes = bytes / (1024 * 1024);
return `${Number.isInteger(megabytes) ? megabytes : megabytes.toFixed(1)} MB`;
}
function inferKind(file: File): AttachmentUploadKind {
if (file.type.startsWith("image/")) return "image";
if (file.type.startsWith("audio/")) return "audio";
return "file";
}
function AttachmentIcon({ kind }: { kind: AttachmentUploadKind }) {
if (kind === "link") return <LinkIcon className="size-4" />;
if (kind === "image") return <FileImage className="size-4" />;
if (kind === "audio") return <Mic className="size-4" />;
return <Paperclip className="size-4" />;
}
function imageSource(item: AttachmentUploadItem) {
if (item.kind !== "image") return undefined;
return item.previewUrl ?? item.href;
}
type RowActionState =
| "idle"
| "uploading"
| "complete"
| "failed"
| "removing";
function RowAction({
label,
onClick,
state,
retryable = false,
reduce = false,
}: {
label: string;
onClick: () => void;
state: RowActionState;
retryable?: boolean;
reduce?: boolean;
}) {
if (state === "uploading") {
return <span aria-hidden="true" className="size-9 shrink-0" />;
}
if (state === "complete") {
return (
<Tooltip content="Upload complete" side="top" delay={100}>
<motion.span
role="status"
aria-label={`Upload complete for ${label}`}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.75 }}
animate={{ opacity: 1, scale: 1 }}
transition={ITEM_TRANSITION}
className="grid size-9 shrink-0 place-items-center rounded-xl text-emerald-600 dark:text-emerald-400"
>
<Check className="size-4" />
</motion.span>
</Tooltip>
);
}
if (state === "removing") {
return (
<Tooltip content="Removing attachment" side="top" delay={100}>
<span
role="status"
aria-label={`Removing ${label}`}
className="grid size-9 shrink-0 place-items-center rounded-xl text-muted-foreground"
>
<motion.span
animate={reduce ? undefined : { rotate: 360 }}
transition={{
duration: 0.7,
ease: "linear",
repeat: Infinity,
}}
className="grid place-items-center"
>
<LoaderCircle className="size-4" />
</motion.span>
</span>
</Tooltip>
);
}
if (state === "failed") {
if (!retryable) {
return (
<Tooltip content="Upload failed" side="top" delay={100}>
<span
role="status"
aria-label={`Upload failed for ${label}`}
className="grid size-9 shrink-0 place-items-center rounded-xl text-destructive"
>
<AlertCircle className="size-4" />
</span>
</Tooltip>
);
}
return (
<Tooltip content="Retry upload" side="top" delay={100}>
<motion.button
type="button"
aria-label={`Retry ${label}`}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-xl text-destructive outline-none transition-colors hover:bg-destructive/10 focus-visible:ring-2 focus-visible:ring-ring"
>
<RotateCcw className="size-4" />
</motion.button>
</Tooltip>
);
}
return (
<Tooltip content="Remove attachment" side="top" delay={100}>
<motion.button
type="button"
aria-label={`Remove ${label}`}
onClick={onClick}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-xl text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-4" />
</motion.button>
</Tooltip>
);
}
function ImageThumbnail({
item,
layoutId,
onPreview,
reduce,
}: {
item: AttachmentUploadItem;
layoutId?: string;
onPreview: (item: AttachmentUploadItem) => void;
reduce: boolean;
}) {
const src = imageSource(item);
if (!src) {
return (
<span
aria-hidden="true"
className="grid size-8 shrink-0 place-items-center rounded-lg bg-muted text-muted-foreground"
>
<FileImage className="size-4" />
</span>
);
}
return (
<Tooltip
side="top"
delay={160}
className="rounded-xl p-1 shadow-xl"
content={
<span className="block w-32">
{/* biome-ignore lint/performance/noImgElement: Blob and remote previews keep this registry component framework-agnostic. */}
<img
src={src}
alt=""
className="h-20 w-full rounded-lg object-cover"
/>
<span className="block px-1 pb-0.5 pt-1 text-center text-[10px] font-medium text-muted-foreground">
Click to preview
</span>
</span>
}
>
<motion.button
type="button"
aria-label={`Preview ${item.name}`}
onClick={(event) => {
event.currentTarget.blur();
onPreview(item);
}}
whileTap={reduce ? undefined : { scale: 0.94 }}
transition={SPRING_PRESS}
className="group/image relative size-9 shrink-0 overflow-hidden rounded-[10px] bg-muted outline-none ring-1 ring-border/70 focus-visible:ring-2 focus-visible:ring-ring"
>
{/* biome-ignore lint/performance/noImgElement: Motion layout requires the image element and portable blob URLs. */}
<motion.img
layoutId={layoutId}
src={src}
alt=""
className="size-full object-cover"
transition={{ layout: SPRING_LAYOUT }}
/>
</motion.button>
</Tooltip>
);
}
function ImagePreviewDialog({
item,
layoutId,
onClose,
reduce,
}: {
item: AttachmentUploadItem | null;
layoutId?: string;
onClose: () => void;
reduce: boolean;
}) {
const closeRef = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!item) return;
const previousFocus =
document.activeElement instanceof HTMLElement
? document.activeElement
: null;
const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
closeRef.current?.focus();
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") onClose();
if (event.key === "Tab") {
event.preventDefault();
closeRef.current?.focus();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
document.body.style.overflow = previousOverflow;
previousFocus?.focus();
};
}, [item, onClose]);
if (typeof document === "undefined") return null;
const src = item ? imageSource(item) : undefined;
const content =
item && src ? (
// The wrapper carries no box: both children are `fixed` and resolve
// against the viewport themselves. The scrim spans the viewport edges but
// paints a colour, and the layer that centres the image is inset off every
// edge. `PresenceGate` releases interaction in the same commit that starts
// the exit.
<PresenceGate>
{({ isPresent, gate }) => (
<div
inert={!isPresent}
className="pointer-events-none fixed left-0 top-0 z-[10000] size-0"
>
<motion.button
type="button"
aria-label="Close image preview"
tabIndex={-1}
className="pointer-events-auto fixed inset-0 size-full cursor-default bg-black/45 backdrop-blur-xl"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={{ duration: reduce ? 0.1 : 0.2, ease: EASE_OUT }}
{...gate}
onClick={onClose}
/>
<div className="fixed inset-4 flex items-center justify-center sm:inset-8">
<motion.div
role="dialog"
aria-modal="true"
aria-label={`Preview of ${item.name}`}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={ITEM_TRANSITION}
{...gate}
className="pointer-events-auto relative"
>
{/* biome-ignore lint/performance/noImgElement: Motion layout requires the image element and portable blob URLs. */}
<motion.img
layoutId={reduce ? undefined : layoutId}
src={src}
alt={item.name}
className="max-h-[90vh] max-w-[90vw] rounded-2xl object-contain shadow-2xl"
transition={{ layout: SPRING_LAYOUT }}
/>
<motion.button
ref={closeRef}
type="button"
aria-label="Close image preview"
onClick={onClose}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={
reduce ? undefined : { opacity: 0, scale: 0.8 }
}
whileTap={reduce ? undefined : { scale: 0.92 }}
transition={SPRING_PRESS}
className="absolute -right-3 -top-3 grid size-9 place-items-center rounded-full bg-background text-foreground shadow-xl outline-none ring-1 ring-border/70 transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
>
<X className="size-4" />
</motion.button>
</motion.div>
</div>
</div>
)}
</PresenceGate>
) : null;
return createPortal(
reduce ? content : <AnimatePresence>{content}</AnimatePresence>,
document.body,
);
}
function AttachmentRow({
item,
playing,
uploading,
uploadComplete,
failed,
removing,
arrivalIndex,
imageLayoutId,
onAudioToggle,
onImagePreview,
onRemove,
onRetry,
reduce,
className,
}: {
item: AttachmentUploadItem;
playing: boolean;
uploading: boolean;
uploadComplete: boolean;
failed: boolean;
removing: boolean;
arrivalIndex: number;
imageLayoutId?: string;
onAudioToggle?: (item: AttachmentUploadItem) => void;
onImagePreview: (item: AttachmentUploadItem) => void;
onRemove: (item: AttachmentUploadItem) => void;
onRetry?: (item: AttachmentUploadItem) => void;
reduce: boolean;
className?: string;
}) {
const size = formatBytes(item.size);
const progress =
item.duration && item.duration > 0
? Math.min(1, Math.max(0, (item.currentTime ?? 0) / item.duration))
: 0;
const actionState: RowActionState = removing
? "removing"
: uploading
? "uploading"
: uploadComplete
? "complete"
: failed
? "failed"
: "idle";
const arrivalDelay = Math.min(Math.max(arrivalIndex, 0), 5) * 0.055;
const rowTransition =
!reduce && arrivalIndex >= 0
? {
...SPRING_LAYOUT,
delay: arrivalDelay,
opacity: {
duration: 0.16,
ease: EASE_OUT,
delay: arrivalDelay,
},
}
: ITEM_TRANSITION;
const showUploadProgress = uploading || uploadComplete;
const uploadProgress = (
<motion.span
role="progressbar"
aria-label={`Uploading ${item.name}`}
className="pointer-events-none absolute inset-0 -z-10 origin-left bg-emerald-400/25 dark:bg-emerald-500/20"
initial={{ opacity: 1, scaleX: 0 }}
animate={{ opacity: 1, scaleX: 1 }}
exit={reduce ? undefined : { opacity: 0 }}
transition={{
duration: reduce ? 0.1 : UPLOAD_PROGRESS_MS / 1000,
ease: EASE_OUT,
}}
/>
);
return (
<motion.li
layout={!reduce}
initial={
reduce
? { opacity: 0 }
: arrivalIndex >= 0
? { opacity: 0, y: -16, scale: 0.985 }
: { opacity: 0, y: 6 }
}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={reduce ? undefined : { opacity: 0, y: -4 }}
transition={rowTransition}
className={cn(
"flex min-h-14 items-center gap-1 rounded-2xl bg-muted/70 p-1",
className,
)}
>
<div className="relative isolate flex min-w-0 flex-1 items-center gap-3 self-stretch overflow-hidden rounded-xl bg-background px-2 py-1">
{failed ? (
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 -z-10 bg-destructive/10"
/>
) : null}
{item.kind === "image" ? (
<ImageThumbnail
item={item}
layoutId={imageLayoutId}
onPreview={onImagePreview}
reduce={reduce}
/>
) : (
<span
aria-hidden="true"
className="grid size-7 shrink-0 place-items-center text-muted-foreground"
>
<AttachmentIcon kind={item.kind} />
</span>
)}
{item.kind === "audio" ? (
<>
<span className="w-9 shrink-0 text-xs tabular-nums text-muted-foreground">
{formatDuration(item.currentTime)}
</span>
<span
aria-hidden="true"
className="flex h-11 min-w-0 flex-1 items-center gap-[3px] overflow-hidden"
>
{WAVEFORM_BARS.map((bar, index) => (
<motion.span
key={bar.id}
className={cn(
"w-[3px] shrink-0 rounded-full",
index / WAVEFORM_BARS.length <= progress
? "bg-foreground"
: "bg-muted-foreground/35",
)}
style={{ height: bar.height }}
animate={
reduce || !playing
? undefined
: { scaleY: [0.72, 1, 0.78] }
}
transition={{
duration: 0.55,
ease: EASE_OUT,
repeat: Infinity,
delay: index * 0.018,
}}
/>
))}
</span>
<span className="w-9 shrink-0 text-right text-xs tabular-nums text-muted-foreground">
{formatDuration(item.duration)}
</span>
<motion.button
type="button"
aria-label={`${playing ? "Pause" : "Play"} ${item.name}`}
onClick={() => onAudioToggle?.(item)}
whileTap={{ scale: 0.94 }}
transition={SPRING_PRESS}
className="grid size-9 shrink-0 place-items-center rounded-full bg-foreground text-background outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<AnimatePresence mode="wait" initial={false}>
<motion.span
key={playing ? "pause" : "play"}
initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8 }}
transition={ITEM_TRANSITION}
>
{playing ? (
<Pause className="size-4 fill-current" />
) : (
<Play className="size-4 translate-x-px fill-current" />
)}
</motion.span>
</AnimatePresence>
</motion.button>
</>
) : (
<>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-foreground">
{item.name}
</span>
{failed ? (
<span className="block truncate text-[11px] text-destructive">
{item.error ?? "Upload failed"}
</span>
) : null}
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{item.kind === "link" ? "Web" : size}
</span>
{item.kind === "link" && item.href ? (
<a
href={item.href}
target="_blank"
rel="noreferrer noopener"
aria-label={`Open ${item.name}`}
className="grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<ExternalLink className="size-4" />
</a>
) : null}
</>
)}
{reduce ? (
showUploadProgress ? (
uploadProgress
) : null
) : (
<AnimatePresence>
{showUploadProgress ? uploadProgress : null}
</AnimatePresence>
)}
</div>
<RowAction
label={item.name}
onClick={() => {
if (actionState === "failed") {
onRetry?.(item);
return;
}
onRemove(item);
}}
state={actionState}
retryable={onRetry !== undefined}
reduce={reduce}
/>
</motion.li>
);
}
export function AttachmentUpload({
value,
defaultValue,
onValueChange,
onFilesAdded,
onFilesRejected,
onRemove,
onRetry,
playingId,
onAudioToggle,
accept,
multiple = true,
maxFiles = 12,
maxFileSize = DEFAULT_MAX_FILE_SIZE,
disabled = false,
title = "Drag and drop or browse files",
description,
attachmentsLabel = "Attachments",
className,
classNames,
}: AttachmentUploadProps) {
const inputId = useId();
const inputRef = useRef<HTMLInputElement>(null);
const dragDepthRef = useRef(0);
const ownedUrlsRef = useRef(new Set<string>());
const lifecycleTimersRef = useRef(
new Set<ReturnType<typeof setTimeout>>(),
);
const reduce = useReducedMotion() ?? false;
const [dragging, setDragging] = useState(false);
const [previewItem, setPreviewItem] =
useState<AttachmentUploadItem | null>(null);
const [uploadingIds, setUploadingIds] = useState<Set<string>>(
() => new Set(),
);
const [uploadCompleteIds, setUploadCompleteIds] = useState<Set<string>>(
() => new Set(),
);
const [removingIds, setRemovingIds] = useState<Set<string>>(
() => new Set(),
);
const [items, setItems] = useControllableList({
value,
defaultValue,
onValueChange,
});
const itemsRef = useRef(items);
itemsRef.current = items;
useEffect(
() => () => {
for (const url of ownedUrlsRef.current) URL.revokeObjectURL(url);
ownedUrlsRef.current.clear();
for (const timer of lifecycleTimersRef.current) {
clearTimeout(timer);
}
lifecycleTimersRef.current.clear();
},
[],
);
const maxReached = items.length >= maxFiles;
const scheduleLifecycle = useCallback(
(callback: () => void, delay: number) => {
const timer = setTimeout(() => {
lifecycleTimersRef.current.delete(timer);
callback();
}, delay);
lifecycleTimersRef.current.add(timer);
},
[],
);
const addFiles = useCallback(
(incomingFiles: File[]) => {
if (disabled || incomingFiles.length === 0) return;
const availableSlots = Math.max(0, maxFiles - items.length);
if (availableSlots === 0) {
onFilesRejected?.(incomingFiles, "max-files");
return;
}
const selectedFiles = incomingFiles.slice(
0,
multiple ? availableSlots : Math.min(1, availableSlots),
);
const oversized = selectedFiles.filter(
(file) => file.size > maxFileSize,
);
const accepted = selectedFiles.filter(
(file) => file.size <= maxFileSize,
);
if (oversized.length > 0) onFilesRejected?.(oversized, "too-large");
if (incomingFiles.length > selectedFiles.length) {
onFilesRejected?.(incomingFiles.slice(selectedFiles.length), "max-files");
}
const added = accepted.map((file, index) => {
const kind = inferKind(file);
const objectUrl = URL.createObjectURL(file);
ownedUrlsRef.current.add(objectUrl);
return {
id: `${Date.now()}-${index}-${file.name}`,
name: file.name,
kind,
size: file.size,
previewUrl: kind === "image" ? objectUrl : undefined,
href: objectUrl,
currentTime: kind === "audio" ? 0 : undefined,
duration: kind === "audio" ? 0 : undefined,
file,
};
});
if (added.length === 0) return;
setItems([...items, ...added]);
const addedIds = added.map((item) => item.id);
setUploadingIds((current) => new Set([...current, ...addedIds]));
scheduleLifecycle(
() => {
setUploadingIds((current) => {
const next = new Set(current);
for (const id of addedIds) next.delete(id);
return next;
});
setUploadCompleteIds(
(current) => new Set([...current, ...addedIds]),
);
scheduleLifecycle(() => {
setUploadCompleteIds((current) => {
const next = new Set(current);
for (const id of addedIds) next.delete(id);
return next;
});
}, UPLOAD_COMPLETE_HOLD_MS);
},
reduce ? 140 : UPLOAD_PROGRESS_MS,
);
onFilesAdded?.(added, accepted);
},
[
disabled,
items,
maxFileSize,
maxFiles,
multiple,
onFilesAdded,
onFilesRejected,
reduce,
scheduleLifecycle,
setItems,
],
);
const finalizeRemove = useCallback(
(item: AttachmentUploadItem) => {
const ownedUrl = [item.previewUrl, item.href].find(
(url): url is string =>
url !== undefined && ownedUrlsRef.current.has(url),
);
if (ownedUrl) {
URL.revokeObjectURL(ownedUrl);
ownedUrlsRef.current.delete(ownedUrl);
}
setPreviewItem((current) =>
current?.id === item.id ? null : current,
);
setUploadingIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
setUploadCompleteIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
setItems(itemsRef.current.filter((entry) => entry.id !== item.id));
onRemove?.(item);
},
[onRemove, setItems],
);
const requestRemove = useCallback(
(item: AttachmentUploadItem) => {
if (removingIds.has(item.id)) return;
setRemovingIds((current) => new Set(current).add(item.id));
scheduleLifecycle(
() => {
finalizeRemove(item);
setRemovingIds((current) => {
const next = new Set(current);
next.delete(item.id);
return next;
});
},
reduce ? 140 : REMOVE_PENDING_MS,
);
},
[
finalizeRemove,
reduce,
removingIds,
scheduleLifecycle,
],
);
const resetDrag = useCallback(() => {
dragDepthRef.current = 0;
setDragging(false);
}, []);
const closePreview = useCallback(() => setPreviewItem(null), []);
useEffect(() => {
if (
previewItem &&
!items.some((item) => item.id === previewItem.id)
) {
setPreviewItem(null);
}
}, [items, previewItem]);
const uploadOrder = Array.from(uploadingIds);
const previewLayoutId = previewItem
? `attachment-image-${previewItem.id}`
: undefined;
return (
<LayoutGroup id={inputId}>
<div className={cn("w-full", className)}>
<input
ref={inputRef}
id={inputId}
type="file"
aria-label="Upload attachments"
accept={accept}
multiple={multiple}
disabled={disabled || maxReached}
tabIndex={-1}
className="sr-only"
onChange={(event) => {
addFiles(Array.from(event.currentTarget.files ?? []));
event.currentTarget.value = "";
}}
/>
<motion.button
type="button"
disabled={disabled || maxReached}
data-dragging={dragging}
animate={
reduce
? undefined
: { scale: dragging ? 1.006 : 1 }
}
whileTap={reduce ? undefined : { scale: 0.995 }}
transition={SPRING_PRESS}
onClick={() => inputRef.current?.click()}
onDragEnter={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current += 1;
setDragging(true);
}}
onDragOver={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
setDragging(true);
}}
onDragLeave={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) setDragging(false);
}}
onDrop={(event) => {
if (disabled || maxReached) return;
event.preventDefault();
resetDrag();
addFiles(Array.from(event.dataTransfer.files));
}}
className={cn(
"group relative isolate flex min-h-52 w-full flex-col items-center justify-center overflow-hidden rounded-[2rem] bg-muted/65 p-2 text-center outline-none",
"transition-colors duration-200 hover:bg-muted/85",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
"data-[dragging=true]:bg-muted",
"disabled:pointer-events-none disabled:opacity-55",
classNames?.dropzone,
)}
>
<span
aria-hidden="true"
className="absolute inset-2 -z-10 rounded-[1.5rem] border border-dashed border-muted-foreground/25 bg-background transition-[border-color,background-color] duration-200 group-hover:border-muted-foreground/45 group-data-[dragging=true]:border-foreground/65 group-data-[dragging=true]:bg-muted/20"
/>
<motion.span
aria-hidden="true"
animate={
reduce
? undefined
: {
y: dragging ? -4 : 0,
scale: dragging ? 1.08 : 1,
}
}
transition={ITEM_TRANSITION}
className="mb-3 grid size-11 place-items-center rounded-2xl bg-muted text-foreground transition-colors duration-200 group-hover:bg-muted/80 group-data-[dragging=true]:bg-foreground group-data-[dragging=true]:text-background"
>
<Upload className="size-[18px]" />
</motion.span>
<span className="text-sm font-semibold tracking-[-0.01em] text-foreground">
{maxReached ? "Attachment limit reached" : title}
</span>
<span className="mt-1 text-xs leading-5 text-muted-foreground">
{maxReached
? `${items.length} of ${maxFiles} attachments added`
: description ?? `Maximum ${formatMaxSize(maxFileSize)} file size`}
</span>
</motion.button>
{items.length > 0 ? (
<section className="mt-8" aria-labelledby={`${inputId}-attachments`}>
<h3
id={`${inputId}-attachments`}
className="text-sm font-semibold text-foreground"
>
{attachmentsLabel}
</h3>
{items.length > 0 ? (
<ul className={cn("mt-3 space-y-2", classNames?.list)}>
<AnimatePresence initial={uploadOrder.length > 0}>
{items.map((item) => (
<AttachmentRow
key={item.id}
item={item}
playing={playingId === item.id}
uploading={
uploadingIds.has(item.id) ||
item.status === "uploading"
}
uploadComplete={
uploadCompleteIds.has(item.id) ||
item.status === "complete"
}
failed={item.status === "failed"}
removing={removingIds.has(item.id)}
arrivalIndex={uploadOrder.indexOf(item.id)}
imageLayoutId={
reduce ? undefined : `attachment-image-${item.id}`
}
onAudioToggle={onAudioToggle}
onImagePreview={setPreviewItem}
onRemove={requestRemove}
onRetry={onRetry}
reduce={reduce}
className={classNames?.row}
/>
))}
</AnimatePresence>
</ul>
) : null}
</section>
) : null}
<ImagePreviewDialog
item={previewItem}
layoutId={reduce ? undefined : previewLayoutId}
onClose={closePreview}
reduce={reduce}
/>
</div>
</LayoutGroup>
);
}
"use client";
import { AnimatePresence } from "motion/react";
import {
type ComponentProps,
type PointerEvent as ReactPointerEvent,
cloneElement,
createContext,
isValidElement,
type ReactElement,
type ReactNode,
type Ref,
type RefObject,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { createPortal } from "react-dom";
import { TooltipSurface } from "@/components/motion/tooltip-surface";
import { useDismiss } from "@/lib/hooks/use-dismiss";
import { useHoverGesture } from "@/lib/hooks/use-hover-gesture";
import { useTapGesture } from "@/lib/hooks/use-tap-gesture";
import { cn } from "@/lib/utils";
import { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from "./tooltip/grace";
import { TooltipArrow, TooltipPositioner } from "./tooltip/positioner";
import {
type TooltipAlign,
type TooltipAnchor,
type TooltipPoint,
type TooltipSide,
useTooltipPointer,
} from "./tooltip/use-position";
export type { TooltipAlign, TooltipSide };
/* -------------------------------------------------------------------------- */
/* Provider */
/* -------------------------------------------------------------------------- */
interface TooltipTiming {
/** Delay before a hover opens a tooltip (ms). */
delay: number;
/** Delay before a tooltip closes once the pointer has left it (ms). */
closeDelay: number;
/** After one tooltip closes, others open instantly for this long (ms). */
skipDelay: number;
}
const TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });
export interface TooltipProviderProps extends Partial<TooltipTiming> {
children: ReactNode;
}
/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */
export function TooltipProvider({ children, ...timing }: TooltipProviderProps) {
const parent = useContext(TimingContext);
const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =
timing;
const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);
return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Root */
/* -------------------------------------------------------------------------- */
// Moving along a toolbar should feel instant after the first label, and only
// one label may show at a time: a keyboard-focused control and a hovered one
// would otherwise both claim the screen.
let lastClosedAt = 0;
let current: { close: () => void } | null = null;
function isEmpty(content: ReactNode) {
return content == null || content === false || content === "";
}
interface TooltipContextValue {
open: boolean;
contentId: string;
labelId: string;
asLabel: boolean;
empty: boolean;
followCursor: boolean;
anchor: TooltipAnchor | null;
/** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */
triggered: boolean;
floatingRef: RefObject<HTMLSpanElement | null>;
pointer: ReturnType<typeof useTooltipPointer>;
setTrigger: (element: TooltipAnchor | null) => void;
setEmpty: (empty: boolean) => void;
close: () => void;
onContentEnter: () => void;
onContentLeave: (event: ReactPointerEvent) => void;
}
const TooltipContext = createContext<TooltipContextValue | null>(null);
function useTooltipContext(part: string) {
const context = useContext(TooltipContext);
if (!context) throw new Error(`${part} must be used inside <Tooltip>`);
return context;
}
export interface TooltipRootProps {
children?: ReactNode;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Delay before showing on hover (ms). Keyboard focus shows immediately. */
delay?: number;
/** Delay before hiding once the pointer has left (ms). */
closeDelay?: number;
/** Never show, e.g. while the label it carries is already visible. */
disabled?: boolean;
/**
* Use the tooltip as the trigger's accessible name rather than its
* description. For icon-only controls whose only label is the tooltip.
*/
asLabel?: boolean;
/** Follow real pointer coordinates; keyboard focus still uses the anchor. */
followCursor?: boolean;
/** Existing anchor for controlled integrations such as chart cells. */
anchorRef?: RefObject<TooltipAnchor | null>;
/** Id of the tooltip surface, for anchors that reference it themselves. */
id?: string;
}
function TooltipRoot({
children,
open: controlledOpen,
defaultOpen = false,
onOpenChange,
delay: delayProp,
closeDelay: closeDelayProp,
disabled = false,
asLabel = false,
followCursor = false,
anchorRef,
id,
initialEmpty = false,
}: TooltipRootProps & { initialEmpty?: boolean }) {
const timing = useContext(TimingContext);
const delay = delayProp ?? timing.delay;
const closeDelay = closeDelayProp ?? timing.closeDelay;
const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
const open = controlledOpen ?? uncontrolledOpen;
const [empty, setEmpty] = useState(initialEmpty);
const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);
const [external, setExternal] = useState<TooltipAnchor | null>(null);
const anchor = anchorRef ? external : trigger;
const generatedId = useId();
const contentId = id ?? `${generatedId}-content`;
const labelId = `${generatedId}-label`;
const floatingRef = useRef<HTMLSpanElement | null>(null);
const anchorObject = useRef<TooltipAnchor | null>(null);
const pointer = useTooltipPointer(anchor, followCursor);
// An external ref can attach after this component renders; read it once it has.
useLayoutEffect(() => {
if (!anchorRef) return;
const element = anchorRef.current ?? null;
if (element !== external) setExternal(element);
});
// Everything the event listeners read, current without re-binding them.
const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });
useLayoutEffect(() => {
anchorObject.current = anchor;
latest.current = {
open,
delay,
closeDelay,
disabled,
empty,
onOpenChange,
controlled: controlledOpen !== undefined,
};
});
const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const grace = useRef<(() => void) | null>(null);
const self = useRef<{ close: () => void }>({ close: () => {} });
const clearTimers = useCallback(() => {
if (openTimer.current) clearTimeout(openTimer.current);
if (closeTimer.current) clearTimeout(closeTimer.current);
openTimer.current = null;
closeTimer.current = null;
}, []);
const stopGrace = useCallback(() => {
grace.current?.();
grace.current = null;
}, []);
// Only a real change reaches the consumer: a pointer leaving a closed
// tooltip is not news.
const commit = useCallback((next: boolean) => {
if (latest.current.open === next) return;
if (!latest.current.controlled) setUncontrolledOpen(next);
latest.current.onOpenChange?.(next);
}, []);
const openNow = useCallback(() => {
clearTimers();
stopGrace();
if (latest.current.disabled || latest.current.empty) return;
if (current && current !== self.current) current.close();
current = self.current;
commit(true);
}, [clearTimers, stopGrace, commit]);
const close = useCallback(() => {
clearTimers();
stopGrace();
if (latest.current.open) lastClosedAt = Date.now();
if (current === self.current) current = null;
commit(false);
}, [clearTimers, stopGrace, commit]);
useLayoutEffect(() => {
self.current.close = close;
}, [close]);
const requestOpen = useCallback(() => {
clearTimers();
if (latest.current.open || latest.current.disabled || latest.current.empty) return;
const warm = Date.now() - lastClosedAt < timing.skipDelay;
if (warm || latest.current.delay <= 0) openNow();
else openTimer.current = setTimeout(openNow, latest.current.delay);
}, [clearTimers, openNow, timing.skipDelay]);
const requestClose = useCallback(() => {
clearTimers();
if (latest.current.closeDelay > 0) {
closeTimer.current = setTimeout(close, latest.current.closeDelay);
} else close();
}, [clearTimers, close]);
// Hold the label open while the pointer crosses from one box toward the other.
const startGrace = useCallback(
(exit: TooltipPoint, from: Element, to: Element | null) => {
stopGrace();
if (!to) return requestClose();
const target = to.getBoundingClientRect();
const origin = from.getBoundingClientRect();
const corridor = graceArea(exit, target);
const onMove = (event: PointerEvent) => {
const point = { x: event.clientX, y: event.clientY };
if (inBox(point, target) || inBox(point, origin)) return;
if (!inPolygon(point, corridor)) requestClose();
};
document.addEventListener("pointermove", onMove);
grace.current = () => document.removeEventListener("pointermove", onMove);
},
[stopGrace, requestClose],
);
const hover = useHoverGesture();
const tap = useTapGesture<boolean>();
// Listeners go on the trigger itself rather than on cloned props, so a
// component that owns its own handlers keeps them, and no wrapper element
// sits between the control and its layout.
useEffect(() => {
if (anchorRef || !trigger) return;
watchModality();
// A mouse press dismisses the label and keeps it away until the pointer
// leaves; hovering a control you just clicked should not bring it back.
let suppressed = false;
// Focus that came from the keyboard holds the label open on its own.
let keyboardFocus = false;
const onEnter = (event: PointerEvent) => {
if (!hover.enter(event)) return;
stopGrace();
if (closeTimer.current) clearTimeout(closeTimer.current);
if (!suppressed) requestOpen();
};
const onLeave = (event: PointerEvent) => {
if (!hover.leave(event)) return;
suppressed = false;
if (keyboardFocus) return;
if (openTimer.current) {
clearTimers();
return;
}
if (latest.current.open && !followCursor) {
startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);
} else requestClose();
};
const onDown = (event: PointerEvent) => {
tap.start(event, latest.current.open);
if (event.pointerType === "mouse") {
suppressed = true;
close();
}
};
// A finger never hovers, and Safari does not focus a button on tap either,
// so the label is only reachable if the tap itself toggles it. The click
// carries no pointerType; the pointerdown before it says whether it was a
// tap, and keyboard activation has none at all.
const onClick = () => {
const gesture = tap.take();
if (!gesture || gesture.pointerType === "mouse") return;
if (gesture.state) close();
else openNow();
};
const onKey = () => tap.drop();
const onFocusIn = () => {
if (!focusFromKeyboard()) return;
keyboardFocus = true;
openNow();
};
const onFocusOut = (event: FocusEvent) => {
if (trigger.contains(event.relatedTarget as Node | null)) return;
keyboardFocus = false;
close();
};
// Both element kinds dispatch the same events; one type keeps the listeners typed.
const el = trigger as HTMLElement;
el.addEventListener("pointerenter", onEnter);
el.addEventListener("pointerleave", onLeave);
el.addEventListener("pointerdown", onDown);
el.addEventListener("pointercancel", tap.drop);
el.addEventListener("click", onClick);
el.addEventListener("keydown", onKey);
el.addEventListener("focusin", onFocusIn);
el.addEventListener("focusout", onFocusOut);
return () => {
el.removeEventListener("pointerenter", onEnter);
el.removeEventListener("pointerleave", onLeave);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointercancel", tap.drop);
el.removeEventListener("click", onClick);
el.removeEventListener("keydown", onKey);
el.removeEventListener("focusin", onFocusIn);
el.removeEventListener("focusout", onFocusOut);
};
}, [
anchorRef,
trigger,
followCursor,
hover,
tap,
requestOpen,
requestClose,
openNow,
close,
clearTimers,
stopGrace,
startGrace,
]);
// While open, a trigger that turns disabled loses focus without a blur event,
// and a window that loses focus never reports the pointer leaving.
useEffect(() => {
if (!open || anchorRef || !trigger) return;
const observer = new MutationObserver(() => {
if (trigger.matches(":disabled, [aria-disabled='true']")) close();
});
observer.observe(trigger, { attributes: true, attributeFilter: ["disabled", "aria-disabled"] });
window.addEventListener("blur", close);
return () => {
observer.disconnect();
window.removeEventListener("blur", close);
};
}, [open, anchorRef, trigger, close]);
// A chart drives its own open state and swaps content as it goes; only a
// trigger-owned label closes itself for having nothing to say.
useEffect(() => {
if (disabled || (empty && !anchorRef)) close();
}, [disabled, empty, anchorRef, close]);
useEffect(
() => () => {
clearTimers();
stopGrace();
if (current === self.current) current = null;
},
[clearTimers, stopGrace],
);
const insideTooltip = useCallback(
(target: Element) => Boolean(floatingRef.current?.contains(target)),
[],
);
// ...and closed by the next tap that lands somewhere else, or Escape. The
// label covers nothing interactive, so that tap passes through to what it hit.
useDismiss(open, close, anchorObject, { ignore: insideTooltip });
const onContentEnter = useCallback(() => {
stopGrace();
clearTimers();
}, [stopGrace, clearTimers]);
const onContentLeave = useCallback(
(event: ReactPointerEvent) => {
const floating = floatingRef.current;
if (!floating) return;
if (anchorRef) {
// Bridge the small gap back onto a chart; it reopens on its own terms.
clearTimers();
closeTimer.current = setTimeout(close, 100);
return;
}
startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);
},
[anchorRef, clearTimers, close, startGrace],
);
const value = useMemo<TooltipContextValue>(
() => ({
open,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
triggered: !anchorRef,
floatingRef,
pointer,
setTrigger,
setEmpty,
close,
onContentEnter,
onContentLeave,
}),
[
open,
contentId,
labelId,
asLabel,
empty,
followCursor,
anchor,
anchorRef,
pointer,
close,
onContentEnter,
onContentLeave,
],
);
return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;
}
/* -------------------------------------------------------------------------- */
/* Trigger */
/* -------------------------------------------------------------------------- */
function mergeIds(...ids: unknown[]) {
return ids.filter((value) => typeof value === "string" && value).join(" ") || undefined;
}
function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
if (typeof ref === "function") ref(value);
else if (ref) (ref as { current: T | null }).current = value;
}
export interface TooltipTriggerProps extends ComponentProps<"button"> {
/** Use the single child element as the trigger instead of rendering a button. */
asChild?: boolean;
}
export function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {
const { open, contentId, labelId, asLabel, empty, setTrigger } =
useTooltipContext("TooltipTrigger");
const child = asChild && isValidElement(children) ? children : null;
const childProps = (child?.props ?? props) as Record<string, unknown>;
const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;
const attached = useRef<TooltipAnchor | null>(null);
const setRef = useCallback(
(element: TooltipAnchor | null) => {
attached.current = element;
setTrigger(element);
assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);
},
[setTrigger, childRef, ref],
);
useEffect(() => {
if (process.env.NODE_ENV !== "production" && child && !attached.current) {
console.warn(
"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.",
);
}
}, [child]);
const aria = asLabel
? {
"aria-labelledby": empty
? (childProps["aria-labelledby"] as string | undefined)
: labelId,
}
: {
"aria-describedby": mergeIds(
childProps["aria-describedby"],
open && !empty ? contentId : undefined,
),
};
if (asChild) {
if (!child) return children;
return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });
}
return (
<button
type="button"
data-state={open ? "open" : "closed"}
{...props}
ref={setRef as Ref<HTMLButtonElement>}
{...aria}
>
{children}
</button>
);
}
/* -------------------------------------------------------------------------- */
/* Content */
/* -------------------------------------------------------------------------- */
export interface TooltipContentProps {
children?: ReactNode;
side?: TooltipSide;
align?: TooltipAlign;
/** Gap between anchor and tooltip (px). */
sideOffset?: number;
/** Draw an arrow pointing at the anchor. */
arrow?: boolean;
/** Point within the anchor, as fractions of its rendered width and height. */
anchorPoint?: TooltipPoint;
className?: string;
}
export function TooltipContent({
children,
side = "top",
align = "center",
sideOffset,
arrow = false,
anchorPoint,
className,
}: TooltipContentProps) {
const {
open,
contentId,
labelId,
asLabel,
followCursor,
anchor,
floatingRef,
pointer,
setEmpty,
close,
onContentEnter,
onContentLeave,
} = useTooltipContext("TooltipContent");
const empty = isEmpty(children);
const arrowRef = useRef<SVGSVGElement | null>(null);
useLayoutEffect(() => {
setEmpty(empty);
}, [empty, setEmpty]);
if (typeof document === "undefined") return null;
return createPortal(
<>
{/* The name has to exist while the label is closed, so it lives apart from the surface. */}
{asLabel && !empty ? (
<span id={labelId} hidden>
{children}
</span>
) : null}
<AnimatePresence>
{open && !empty ? (
<TooltipPositioner
key="tooltip"
anchor={anchor}
floatingRef={floatingRef}
arrowRef={arrow ? arrowRef : undefined}
anchorPoint={anchorPoint}
followCursor={followCursor}
side={side}
align={align}
sideOffset={sideOffset}
onDismiss={close}
pointer={pointer}
>
{(positioned, isPresent, placedSide) => (
<TooltipSurface
id={asLabel ? undefined : contentId}
aria-hidden={asLabel || undefined}
ready={positioned}
onPointerEnter={onContentEnter}
onPointerLeave={onContentLeave}
style={{ pointerEvents: isPresent && !followCursor ? "auto" : "none" }}
className={cn(
"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words",
arrow && "relative",
className,
)}
>
{children}
{arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}
</TooltipSurface>
)}
</TooltipPositioner>
) : null}
</AnimatePresence>
</>,
document.body,
);
}
/* -------------------------------------------------------------------------- */
/* Tooltip (root, or one-line shorthand when given `content`) */
/* -------------------------------------------------------------------------- */
export interface TooltipProps
extends TooltipRootProps,
Omit<TooltipContentProps, "children" | "className"> {
/**
* Shorthand: the tooltip's content. With it, `children` is the trigger
* element; without it, compose `TooltipTrigger` and `TooltipContent`.
*/
content?: ReactNode;
/** Shorthand only: classes for the tooltip surface. */
className?: string;
}
export function Tooltip(props: TooltipProps) {
if (!("content" in props)) return <TooltipRoot {...props} />;
const {
content,
children,
side,
align,
sideOffset,
arrow,
anchorPoint,
className,
...root
} = props;
if (!root.anchorRef && !isValidElement(children)) return children ?? null;
return (
<TooltipRoot {...root} initialEmpty={isEmpty(content)}>
{isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}
<TooltipContent
side={side}
align={align}
sideOffset={sideOffset}
arrow={arrow}
anchorPoint={anchorPoint}
className={className}
>
{content}
</TooltipContent>
</TooltipRoot>
);
}
type Point = { x: number; y: number };
type Box = { left: number; top: number; right: number; bottom: number };
/**
* The corridor a pointer may cross between the trigger and the open tooltip
* without closing it: the convex hull of where it left and the box it is
* heading for. A fixed timeout either cuts a slow diagonal move short or keeps
* the label alive after the pointer has plainly gone elsewhere; this follows
* the path itself.
*/
export function graceArea(exit: Point, target: Box): Point[] {
// A few pixels either side of the exit point give the corridor some width at
// its narrow end, so a hand that drifts sideways while it moves stays inside.
const pad = 5;
return hull([
{ x: exit.x - pad, y: exit.y - pad },
{ x: exit.x + pad, y: exit.y - pad },
{ x: exit.x - pad, y: exit.y + pad },
{ x: exit.x + pad, y: exit.y + pad },
{ x: target.left, y: target.top },
{ x: target.right, y: target.top },
{ x: target.right, y: target.bottom },
{ x: target.left, y: target.bottom },
]);
}
export function inBox(point: Point, box: Box) {
return (
point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom
);
}
export function inPolygon(point: Point, polygon: Point[]) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const a = polygon[i];
const b = polygon[j];
if (
a.y > point.y !== b.y > point.y &&
point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x
) {
inside = !inside;
}
}
return inside;
}
// Monotone chain; the corridor is always convex, so a hull is all it needs.
function hull(points: Point[]) {
const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);
const cross = (o: Point, a: Point, b: Point) =>
(a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
const lower: Point[] = [];
for (const p of sorted) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
}
const upper: Point[] = [];
for (let i = sorted.length - 1; i >= 0; i--) {
const p = sorted[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
lower.pop();
upper.pop();
return lower.concat(upper);
}
/**
* How the user last reached for the page. A focus that a mouse press caused is
* not a request to read the label: the pointer is already on the control and
* hovering showed it. A focus that followed a key — Tab, or a roving arrow key
* moving focus in script — is the only way a keyboard user sees it at all.
*/
let modality: "keyboard" | "pointer" = "keyboard";
let listening = false;
export function watchModality() {
if (listening || typeof window === "undefined") return;
listening = true;
window.addEventListener("keydown", () => (modality = "keyboard"), true);
window.addEventListener("pointerdown", () => (modality = "pointer"), true);
}
export function focusFromKeyboard() {
return modality === "keyboard";
}
"use client";
import { useIsPresent } from "motion/react";
import { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from "react";
import { type TooltipSide, useTooltipPosition } from "./use-position";
type PositionProps = Parameters<typeof useTooltipPosition>[0];
/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */
export function TooltipPositioner({
children,
...position
}: Omit<PositionProps, "open" | "onPosition"> & {
children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;
}) {
const present = useIsPresent();
const [ready, setReady] = useState(false);
const [side, setSide] = useState<TooltipSide>(position.side);
const onPosition = useCallback((placed: TooltipSide) => {
setReady(true);
setSide(placed);
}, []);
useTooltipPosition({ ...position, open: present, onPosition });
return (
<span
ref={position.floatingRef}
inert={!present}
aria-hidden={!present || undefined}
className="pointer-events-none fixed left-0 top-0 z-[9999] w-max"
style={{ visibility: "hidden", maxWidth: "calc(100vw - 16px)" }}
>
{children(ready, present, side)}
</span>
);
}
// Each arrow is a 12px box whose base sits on the surface's inner border edge,
// so its fill covers the border beneath it and only the two outer edges stroke.
const ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {
top: { path: "M0 6L6 12L12 6", style: { top: "calc(100% - 6px)" } },
bottom: { path: "M0 6L6 0L12 6", style: { bottom: "calc(100% - 6px)" } },
left: { path: "M6 0L12 6L6 12", style: { left: "calc(100% - 6px)" } },
right: { path: "M6 0L0 6L6 12", style: { right: "calc(100% - 6px)" } },
};
export function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {
const { path, style } = ARROW[side];
return (
<svg
ref={ref}
aria-hidden="true"
width="12"
height="12"
viewBox="0 0 12 12"
className="pointer-events-none absolute overflow-visible"
style={style}
>
<path d={`${path}Z`} style={{ fill: "var(--tooltip-arrow-fill, transparent)" }} />
<path
d={path}
fill="none"
strokeWidth="1"
style={{ stroke: "var(--tooltip-arrow-stroke, transparent)" }}
/>
</svg>
);
}
"use client";
import {
arrow as arrowMiddleware,
autoUpdate,
computePosition,
flip,
hide,
offset,
type Placement,
shift,
type VirtualElement,
} from "@floating-ui/dom";
import { type RefObject, useCallback, useLayoutEffect, useRef } from "react";
export type TooltipSide = "top" | "right" | "bottom" | "left";
export type TooltipAlign = "start" | "center" | "end";
export type TooltipPoint = { x: number; y: number };
export type TooltipAnchor = HTMLElement | SVGElement;
const ORIGIN: Record<TooltipSide, string> = {
top: "center bottom",
bottom: "center top",
left: "right center",
right: "left center",
};
/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */
export function useTooltipPosition({
open,
anchor,
floatingRef,
arrowRef,
anchorPoint,
followCursor,
side,
align,
sideOffset,
onDismiss,
onPosition,
pointer,
}: {
open: boolean;
anchor: TooltipAnchor | null;
floatingRef: RefObject<HTMLSpanElement | null>;
arrowRef?: RefObject<SVGSVGElement | null>;
anchorPoint?: TooltipPoint;
followCursor: boolean;
side: TooltipSide;
align: TooltipAlign;
sideOffset?: number;
onDismiss: () => void;
onPosition: (side: TooltipSide) => void;
pointer: ReturnType<typeof useTooltipPointer>;
}) {
const { cursor, onMove } = pointer;
const preferred: Placement = align === "center" ? side : `${side}-${align}`;
const cursorSide = useRef<Placement | null>(null);
useLayoutEffect(() => {
cursorSide.current = open ? preferred : null;
}, [open, preferred]);
const frame = useRef<number | null>(null);
const version = useRef(0);
const update = useRef<() => void>(() => {});
const schedule = useCallback(() => {
// Invalidate older async calculations as soon as new geometry is requested.
version.current++;
if (frame.current !== null) return;
frame.current = requestAnimationFrame(() => {
frame.current = null;
update.current();
});
}, []);
useLayoutEffect(() => {
onMove.current = schedule;
return () => {
onMove.current = null;
};
}, [onMove, schedule]);
const pointX = anchorPoint?.x;
const pointY = anchorPoint?.y;
// Latest committed inputs are read without recreating observers for every period/content update.
useLayoutEffect(() => {
update.current = () => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const revision = ++version.current;
const currentCursor = followCursor ? cursor.current : null;
const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;
const reference: Element | VirtualElement = virtual
? {
contextElement: anchor,
getBoundingClientRect: () => {
const rect = anchor.getBoundingClientRect();
const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);
const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);
return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };
},
}
: anchor;
const arrowElement = arrowRef?.current ?? null;
void computePosition(reference, floating, {
strategy: "fixed",
placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,
middleware: [
offset(sideOffset ?? (currentCursor ? 12 : 8)),
flip({ padding: 8 }),
shift({ padding: 8 }),
...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),
// A label left floating over whatever scrolled into its trigger's place
// describes nothing there. Points inside a chart move with the chart.
...(virtual ? [] : [hide({ strategy: "referenceHidden" })]),
],
}).then(({ x, y, placement, middlewareData }) => {
if (version.current !== revision || !floating.isConnected) return;
// Hold the chosen side for this hover session. Crossing a flip threshold
// repeatedly must not bounce the surface above and below the pointer.
if (currentCursor) cursorSide.current = placement;
else cursorSide.current = null;
const placedSide = placement.split("-")[0] as TooltipSide;
const dpr = window.devicePixelRatio || 1;
floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;
floating.style.setProperty("--tooltip-origin", ORIGIN[placedSide]);
// A box with no size has no clipped state to report, only a missing layout.
const box = anchor.getBoundingClientRect();
const clipped =
Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);
floating.style.visibility = clipped ? "hidden" : "visible";
floating.dataset.placement = placement;
const surface = arrowElement?.parentElement;
if (arrowElement && surface) {
// Measured against the positioner, drawn inside the surface's border.
const { x: ax, y: ay } = middlewareData.arrow ?? {};
if (ax != null) arrowElement.style.left = `${ax - surface.clientLeft}px`;
if (ay != null) arrowElement.style.top = `${ay - surface.clientTop}px`;
// Paint with whatever the surface resolved to, so a restyled tooltip
// keeps a matching arrow without a second set of classes.
const style = getComputedStyle(surface);
arrowElement.style.setProperty("--tooltip-arrow-fill", style.backgroundColor);
arrowElement.style.setProperty("--tooltip-arrow-stroke", style.borderTopColor);
}
onPosition(placedSide);
});
};
if (open) schedule();
}, [
open,
anchor,
floatingRef,
arrowRef,
followCursor,
pointX,
pointY,
preferred,
sideOffset,
schedule,
onPosition,
cursor,
]);
useLayoutEffect(() => {
const floating = floatingRef.current;
if (!open || !anchor || !floating) return;
const stop = autoUpdate(anchor, floating, schedule);
const onScroll = () => {
// A stationary pointer no longer describes the same chart point after scrolling.
if (followCursor && cursor.current) onDismiss();
};
window.addEventListener("scroll", onScroll, true);
return () => {
stop();
window.removeEventListener("scroll", onScroll, true);
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
frame.current = null;
};
}, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);
useLayoutEffect(
() => () => {
version.current++;
if (frame.current !== null) cancelAnimationFrame(frame.current);
},
[],
);
}
/** Pointer lifetime belongs to the anchor, including the opening delay. */
export function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {
const cursor = useRef<TooltipPoint | null>(null);
const onMove = useRef<(() => void) | null>(null);
const pointerFocus = useRef(false);
useLayoutEffect(() => {
if (!anchor || !followCursor) return;
const point = (event: PointerEvent) => {
if (event.type === "pointermove" && event.pointerType === "touch" && !event.buttons) return;
cursor.current = { x: event.clientX, y: event.clientY };
if (event.type === "pointerdown") pointerFocus.current = true;
onMove.current?.();
};
const keyboard = () => {
cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const focus = () => {
if (!pointerFocus.current) cursor.current = null;
pointerFocus.current = false;
onMove.current?.();
};
const leave = () => {
cursor.current = null;
};
anchor.addEventListener("pointerenter", point as EventListener, { passive: true });
anchor.addEventListener("pointermove", point as EventListener, { passive: true });
anchor.addEventListener("pointerdown", point as EventListener, { passive: true });
anchor.addEventListener("pointerleave", leave);
anchor.addEventListener("pointercancel", leave);
anchor.addEventListener("keydown", keyboard);
anchor.addEventListener("focusin", focus);
return () => {
cursor.current = null;
anchor.removeEventListener("pointerenter", point as EventListener);
anchor.removeEventListener("pointermove", point as EventListener);
anchor.removeEventListener("pointerdown", point as EventListener);
anchor.removeEventListener("pointerleave", leave);
anchor.removeEventListener("pointercancel", leave);
anchor.removeEventListener("keydown", keyboard);
anchor.removeEventListener("focusin", focus);
};
}, [anchor, followCursor]);
return { cursor, onMove };
}
"use client";
import { motion, useReducedMotion } from "motion/react";
import type { ComponentProps, ReactNode, Ref } from "react";
import { EASE_OUT } from "@/lib/ease";
import { cn } from "@/lib/utils";
/** Presentation only: the unanimated parent owns measurement and positioning. */
export function TooltipSurface({
children,
side: _side = "top",
className,
ref,
ready = true,
style,
...props
}: Omit<ComponentProps<typeof motion.span>, "children"> & {
children?: ReactNode;
/** Start the entrance only after the positioning layer has been measured. */
ready?: boolean;
side?: "top" | "right" | "bottom" | "left";
ref?: Ref<HTMLSpanElement>;
}) {
const reduce = useReducedMotion();
const closed = { opacity: 0, scale: reduce ? 1 : 0.94 };
return (
<motion.span
ref={ref}
role="tooltip"
initial={closed}
animate={{
...(ready ? { opacity: 1, scale: 1 } : closed),
transition: { duration: 0.18, ease: EASE_OUT },
}}
exit={{ ...closed, transition: { duration: 0.12, ease: EASE_OUT } }}
style={{ transformOrigin: "var(--tooltip-origin, center)", ...style }}
className={cn(
"block whitespace-nowrap rounded-lg border border-border bg-background px-2.5 py-1 text-xs font-medium text-foreground shadow-lg",
className,
)}
{...props}
>
{children}
</motion.span>
);
}
API Reference
value?FileUploadItem[]—defaultValue?FileUploadItem[]—onValueChange?((items: FileUploadItem[]) => void)—onFilesAdded?((items: FileUploadItem[], files: File[]) => void)—onRemove?((item: FileUploadItem) => void)—onRetry?((item: FileUploadItem) => void)—accept?string—multiple?booleantruemaxFiles?number—disabled?booleanfalsevariant?"default" | "centered"defaulttitle?stringDrop files heredescription?stringAdd files to the upload queuebrowseLabel?stringBrowseclassName?string—classNames?FileUploadClassNames—Related components
Feedback Widget
Corner trigger that morphs open into a feedback popup with message entry and animated sending, success and retry states.
OTP Input
One-time-code input with a gliding focus ring, digits that roll in per slot, error shake and a success check draw.
Availability Scheduler
Weekly availability editor where each day springs between available and unavailable, time ranges add and remove with blur-slide motion, times pick from a scrollable dropdown, and a copy menu clones hours to other days.
Keep in mind
Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.
Updated