# Integrate `FileExplorer` from Motion Garden

You are helping me add the **FileExplorer** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** FileExplorer
- **Category:** Power-User Systems
- **Summary:** A persistent three-pane file manager that stores real image, video, and blob uploads 100% client-side — OPFS when available, IndexedDB everywhere else — with nested folders, search, sort, drag-and-drop upload, move, and a live preview panel.
- **Reference:** https://motion-garden.netlify.app/components/file-explorer
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add lucide-react motion react-resizable-panels
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme {
  --font-display: "Space Mono", ui-monospace, "SFMono-Regular", monospace;
}

@theme inline {
  --color-surface: var(--sg-surface);
  --color-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
  --color-accent-hover: var(--sg-accent-hover);
  --color-danger: var(--sg-danger);
}

:root {
  --sg-surface: #f9f9fb;
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
  --sg-accent-hover: #6b21a8;
  --sg-danger: #dc2626;
  --sg-scroll: #c3c9cf;
}

.dark {
  --sg-surface: #0a0b0c;
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
  --sg-accent-hover: #b87df9;
  --sg-danger: #f87171;
  --sg-scroll: #464d56;
}

@utility scrollbar-thin {
  scrollbar-width: thin;
}

@utility scrollbar-none {
  scrollbar-width: none;
  &::-webkit-scrollbar {
    display: none;
  }
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

`font-display` expects Space Mono, and this CSS only names it. Load the font (with `next/font/google`, for example) or put my own display face first in the stack; until then it falls back to the system monospace.

## Files to create

24 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/file-explorer/file-explorer.tsx`

```tsx
"use client";

import {
	useCallback,
	useEffect,
	useMemo,
	useRef,
	useState,
	type CSSProperties,
	type DragEvent,
	type KeyboardEvent,
	type MouseEvent,
} from "react";
import { Group, Panel, Separator } from "react-resizable-panels";
import { AnimatePresence } from "motion/react";
import { Upload } from "lucide-react";
import {
	baseName,
	joinPath,
	parentPath,
	type FileNode,
	type StorePath,
} from "./store/types";
import { AutoScroll } from "./auto-scroll";
import { Breadcrumb } from "./breadcrumb";
import { ContextMenu } from "./context-menu";
import { DetailPanel } from "./detail-panel";
import { EmptyState } from "./empty-state";
import { FileGrid } from "./file-grid";
import { FileList } from "./file-list";
import { FolderTree } from "./folder-tree";
import { StorageMeter } from "./storage-meter";
import { Toolbar } from "./toolbar";
import { UndoSnackbar } from "./undo-snackbar";
import type { FileExplorerProps, ItemCallbacks, Row, SortKey } from "./types";
import {
	filterNodes,
	sortNodes,
	useFileExplorer,
} from "./use-file-explorer";
import {
	useDirectory,
	useFileStore,
	useStorageEstimate,
} from "./use-file-store";
import { cn, uniqueName } from "./util";

const MOVE_MIME = "application/x-fx-move";

interface PendingDelete {
	paths: string[];
	label: string;
}

export default function FileExplorer({
	store: storeSource,
	namespace = "sg-file-explorer",
	seed,
	defaultView = "grid",
	thumbnailSize = 112,
	density = "comfortable",
	sortBy = "name",
	sortDir = "asc",
	showFolderRail = true,
	showDetails = true,
	showHidden = false,
	allowUpload = true,
	allowDelete = true,
	undoWindowMs = 5000,
	accent = "#a855f7",
	reducedMotion = false,
	className,
}: FileExplorerProps) {
	const { store, ready, backend, error, revision, reload } = useFileStore(
		storeSource,
		namespace,
	);
	const [state, dispatch] = useFileExplorer({ defaultView, sortBy, sortDir });
	const { entries } = useDirectory(store, state.currentPath, revision);
	const estimate = useStorageEstimate(store, revision);

	const rootRef = useRef<HTMLDivElement>(null);
	const fileInputRef = useRef<HTMLInputElement>(null);
	const seededRef = useRef(false);
	const deleteTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
	const [pendingDelete, setPendingDelete] = useState<PendingDelete | null>(null);
	const [dragging, setDragging] = useState(false);

	useEffect(() => {
		dispatch({ type: "SYNC_PROPS", view: defaultView, sortBy, sortDir });
	}, [defaultView, sortBy, sortDir, dispatch]);

	useEffect(() => {
		if (!ready || !store || !seed?.length || seededRef.current) return;
		seededRef.current = true;
		(async () => {
			const root = await store.list("");
			if (root.length > 0) return;
			for (const entry of seed) {
				if (entry.blob) await store.write(entry.path, entry.blob);
				else await store.mkdir(entry.path);
			}
			reload();
		})();
	}, [ready, store, seed, reload]);

	const displayed = useMemo(() => {
		let list = entries;
		if (pendingDelete) {
			const hidden = new Set(pendingDelete.paths);
			list = list.filter((n) => !hidden.has(n.path));
		}
		return sortNodes(
			filterNodes(list, state.search, showHidden),
			state.sortBy,
			state.sortDir,
		);
	}, [entries, pendingDelete, state.search, state.sortBy, state.sortDir, showHidden]);

	const orderedPaths = useMemo(() => displayed.map((n) => n.path), [displayed]);

	const rows: Row[] = useMemo(
		() =>
			displayed.map((node) => ({
				node,
				selected: state.selection.includes(node.path),
				cut: state.clipboard.includes(node.path),
				renaming: state.renaming === node.path,
			})),
		[displayed, state.selection, state.clipboard, state.renaming],
	);

	const detailNode: FileNode | null = useMemo(() => {
		if (!showDetails || !state.detailPath) return null;
		const found = displayed.find((n) => n.path === state.detailPath);
		return found && found.kind === "file" ? found : null;
	}, [showDetails, state.detailPath, displayed]);

	const uploadFiles = useCallback(
		async (files: FileList | File[], dir: StorePath) => {
			if (!store || !allowUpload) return;
			const taken = new Set((await store.list(dir)).map((n) => n.name));
			for (const file of Array.from(files)) {
				const name = uniqueName(file.name, taken);
				taken.add(name);
				await store.write(joinPath(dir, name), file, file.type);
			}
			reload();
		},
		[store, allowUpload, reload],
	);

	const moveInto = useCallback(
		async (srcPath: StorePath, destDir: StorePath) => {
			if (!store || !allowDelete || !srcPath) return;
			if (destDir === srcPath || destDir.startsWith(`${srcPath}/`)) return;
			if (parentPath(srcPath) === destDir) return;
			const taken = new Set((await store.list(destDir)).map((n) => n.name));
			const name = uniqueName(baseName(srcPath), taken);
			try {
				await store.move(srcPath, joinPath(destDir, name));
				reload();
			} catch {
			}
		},
		[store, allowDelete, reload],
	);

	const handleDropPayload = useCallback(
		(e: DragEvent, destDir: StorePath) => {
			if (e.dataTransfer.files?.length) {
				void uploadFiles(e.dataTransfer.files, destDir);
				return;
			}
			const src = e.dataTransfer.getData(MOVE_MIME);
			if (src) void moveInto(src, destDir);
		},
		[uploadFiles, moveInto],
	);

	const newFolder = useCallback(async () => {
		if (!store || !allowUpload) return;
		const taken = new Set((await store.list(state.currentPath)).map((n) => n.name));
		const name = uniqueName("New folder", taken);
		const path = joinPath(state.currentPath, name);
		await store.mkdir(path);
		reload();
		dispatch({ type: "BEGIN_RENAME", path });
	}, [store, allowUpload, state.currentPath, reload, dispatch]);

	const commitRename = useCallback(
		async (node: FileNode, nextName: string) => {
			if (!store) return;
			const wasDetail = state.detailPath === node.path;
			dispatch({ type: "END_RENAME" });
			try {
				const moved = await store.rename(node.path, nextName);
				if (wasDetail) dispatch({ type: "OPEN_DETAIL", path: moved.path });
				else dispatch({ type: "SET_SELECTION", paths: [moved.path] });
				reload();
			} catch {
			}
		},
		[store, state.detailPath, dispatch, reload],
	);

	const saveText = useCallback(
		async (node: FileNode, text: string) => {
			if (!store) return;
			const mime = node.mime || "text/plain";
			await store.write(node.path, new Blob([text], { type: mime }), mime);
			reload();
		},
		[store, reload],
	);

	const commitDelete = useCallback(
		async (paths: string[]) => {
			if (!store) return;
			for (const path of paths) await store.remove(path);
			reload();
		},
		[store, reload],
	);

	const requestDelete = useCallback(
		(paths: string[]) => {
			if (!store || !allowDelete || paths.length === 0) return;
			if (undoWindowMs <= 0) {
				void commitDelete(paths);
				return;
			}
			const label =
				paths.length === 1
					? `Deleted ${baseName(paths[0])}`
					: `Deleted ${paths.length} items`;
			setPendingDelete({ paths, label });
			dispatch({ type: "CLEAR_SELECTION" });
			if (deleteTimer.current) clearTimeout(deleteTimer.current);
			deleteTimer.current = setTimeout(() => {
				void commitDelete(paths);
				setPendingDelete(null);
			}, undoWindowMs);
		},
		[store, allowDelete, undoWindowMs, commitDelete, dispatch],
	);

	const undoDelete = useCallback(() => {
		if (deleteTimer.current) clearTimeout(deleteTimer.current);
		setPendingDelete(null);
	}, []);

	const paste = useCallback(
		async (destDir: StorePath) => {
			if (!state.clipboard.length) return;
			for (const src of state.clipboard) await moveInto(src, destDir);
			dispatch({ type: "CLEAR_CLIPBOARD" });
		},
		[state.clipboard, moveInto, dispatch],
	);

	const download = useCallback(
		async (node: FileNode) => {
			if (!store || node.kind !== "file") return;
			const blob = await store.read(node.path);
			const url = URL.createObjectURL(blob);
			const a = document.createElement("a");
			a.href = url;
			a.download = node.name;
			a.click();
			setTimeout(() => URL.revokeObjectURL(url), 1000);
		},
		[store],
	);

	const openNode = useCallback(
		(node: FileNode) => {
			if (node.kind === "directory") {
				dispatch({ type: "NAVIGATE", path: node.path });
			} else {
				dispatch({ type: "OPEN_DETAIL", path: node.path });
			}
		},
		[dispatch],
	);

	const selectNode = useCallback(
		(node: FileNode, e: MouseEvent) => {
			let mode: "single" | "toggle" | "range";
			if (e.metaKey || e.ctrlKey) mode = "toggle";
			else if (e.shiftKey) mode = "range";
			else if (state.selection.length > 1 && state.selection.includes(node.path))
				mode = "toggle";
			else mode = "single";
			dispatch({ type: "SELECT", path: node.path, mode, ordered: orderedPaths });
		},
		[dispatch, orderedPaths, state.selection],
	);

	const openContextAt = useCallback(
		(clientX: number, clientY: number, targetPath: string | null) => {
			const rect = rootRef.current?.getBoundingClientRect();
			const x = rect ? Math.min(clientX - rect.left, rect.width - 200) : clientX;
			const y = rect ? Math.min(clientY - rect.top, rect.height - 260) : clientY;
			dispatch({
				type: "OPEN_CONTEXT",
				x: Math.max(4, x),
				y: Math.max(4, y),
				targetPath,
			});
		},
		[dispatch],
	);

	const itemCallbacks: ItemCallbacks = useMemo(
		() => ({
			onOpen: openNode,
			onSelect: selectNode,
			onContextMenu: (node, e) => {
				e.preventDefault();
				e.stopPropagation();
				openContextAt(e.clientX, e.clientY, node.path);
			},
			onRenameCommit: commitRename,
			onRenameCancel: () => dispatch({ type: "END_RENAME" }),
			onItemDragStart: (node, e) => {
				e.dataTransfer.setData(MOVE_MIME, node.path);
				e.dataTransfer.effectAllowed = "move";
			},
			onItemDrop: (node, e) => {
				e.preventDefault();
				e.stopPropagation();
				if (node.kind !== "directory") return;
				handleDropPayload(e, node.path);
			},
		}),
		[openNode, selectNode, openContextAt, commitRename, handleDropPayload, dispatch],
	);

	const onKeyDown = useCallback(
		(e: KeyboardEvent) => {
			const target = e.target as HTMLElement;
			if (
				state.renaming ||
				target.tagName === "INPUT" ||
				target.tagName === "TEXTAREA"
			) {
				return;
			}
			if (e.key === "Escape") {
				if (state.contextMenu) dispatch({ type: "CLOSE_CONTEXT" });
				else if (state.detailPath) dispatch({ type: "CLOSE_DETAIL" });
				else dispatch({ type: "CLEAR_SELECTION" });
			} else if ((e.key === "Delete" || e.key === "Del") && state.selection.length) {
				e.preventDefault();
				requestDelete(state.selection);
			} else if (e.key === "Backspace") {
				e.preventDefault();
				dispatch({ type: "NAVIGATE", path: parentPath(state.currentPath) });
			} else if (e.key === "Enter" && state.selection.length === 1) {
				const node = displayed.find((n) => n.path === state.selection[0]);
				if (node) openNode(node);
			} else if (e.key === "F2" && state.selection.length === 1 && allowDelete) {
				e.preventDefault();
				dispatch({ type: "BEGIN_RENAME", path: state.selection[0] });
			} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "a") {
				e.preventDefault();
				dispatch({ type: "SELECT_ALL", ordered: orderedPaths });
			} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "x" && state.selection.length && allowDelete) {
				dispatch({ type: "CUT", paths: state.selection });
			} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "v" && state.clipboard.length) {
				void paste(state.currentPath);
			}
		},
		[state, displayed, orderedPaths, dispatch, requestDelete, openNode, paste, allowDelete],
	);

	useEffect(() => {
		return () => {
			if (deleteTimer.current) clearTimeout(deleteTimer.current);
		};
	}, []);

	const rootStyle = {
		"--color-accent": accent,
		"--fx-accent": accent,
	} as CSSProperties;

	if (!ready) {
		return (
			<div
				className={cn(
					"flex h-full min-h-95 w-full items-center justify-center rounded-lg border border-hairline bg-surface",
					className,
				)}
			>
				<div className="h-6 w-6 animate-spin rounded-full border-2 border-hairline border-t-accent" />
			</div>
		);
	}

	if (error || !store) {
		return (
			<div
				className={cn(
					"flex h-full min-h-95 w-full items-center justify-center rounded-lg border border-hairline bg-surface",
					className,
				)}
				style={rootStyle}
			>
				<EmptyState variant="unsupported" />
			</div>
		);
	}

	const contentEmpty = displayed.length === 0;

	return (
		<div
			ref={rootRef}
			tabIndex={0}
			onKeyDown={onKeyDown}
			onDragEnter={(e) => {
				if (allowUpload && e.dataTransfer.types.includes("Files")) {
					setDragging(true);
				}
			}}
			onDragOver={(e) => {
				if (dragging || e.dataTransfer.types.includes("Files")) e.preventDefault();
			}}
			onDragLeave={(e) => {
				if (e.target === rootRef.current) setDragging(false);
			}}
			onDrop={(e) => {
				e.preventDefault();
				setDragging(false);
				handleDropPayload(e, state.currentPath);
			}}
			style={rootStyle}
			className={cn(
				"relative flex h-full min-h-95 w-full flex-col overflow-hidden rounded-lg border border-hairline bg-surface text-ink outline-none",
				className,
			)}
		>
			<Toolbar
				view={state.view}
				sortBy={state.sortBy}
				sortDir={state.sortDir}
				search={state.search}
				folderName={state.currentPath ? baseName(state.currentPath) : "Home"}
				selectionCount={state.selection.length}
				clipboardCount={state.clipboard.length}
				allowUpload={allowUpload}
				allowDelete={allowDelete}
				onViewChange={(view) => dispatch({ type: "SET_VIEW", view })}
				onSort={(key: SortKey) => dispatch({ type: "TOGGLE_SORT", sortBy: key })}
				onSearch={(search) => dispatch({ type: "SET_SEARCH", search })}
				onAdd={() => fileInputRef.current?.click()}
				onNewFolder={newFolder}
				onDeleteSelected={() => requestDelete(state.selection)}
				onClearSelection={() => dispatch({ type: "CLEAR_SELECTION" })}
				onPaste={() => paste(state.currentPath)}
			/>

			<div className="flex items-center justify-between gap-3 border-b border-hairline px-3 py-1.5">
				<Breadcrumb path={state.currentPath} onNavigate={(path) => dispatch({ type: "NAVIGATE", path })} />
				<span className="shrink-0 font-mono text-[11px] text-ink-mute">
					{displayed.length} item{displayed.length === 1 ? "" : "s"}
				</span>
			</div>

			<div className="min-h-0 flex-1">
				<Group orientation="horizontal" className="flex h-full">
					{showFolderRail ? (
						<>
							<Panel id="rail" defaultSize="22%" minSize="14%" maxSize="34%">
								<AutoScroll className="h-full border-r border-hairline bg-panel/40 px-1">
									<FolderTree
										store={store}
										revision={revision}
										currentPath={state.currentPath}
										density={density}
										onNavigate={(path) => dispatch({ type: "NAVIGATE", path })}
										onDropOnFolder={(dir, e) => {
											e.preventDefault();
											handleDropPayload(e, dir);
										}}
									/>
								</AutoScroll>
							</Panel>
							<Separator className="w-px shrink-0 bg-hairline transition-colors hover:bg-accent data-disabled:pointer-events-none" />
						</>
					) : null}

					<Panel id="content">
						<AutoScroll
							className="h-full"
							onClick={(e) => {
								if (e.target === e.currentTarget) dispatch({ type: "CLEAR_SELECTION" });
							}}
							onContextMenu={(e) => {
								if (e.target === e.currentTarget) {
									e.preventDefault();
									openContextAt(e.clientX, e.clientY, null);
								}
							}}
						>
							{contentEmpty ? (
								<EmptyState
									variant={state.search ? "no-results" : "empty"}
									onAdd={allowUpload ? () => fileInputRef.current?.click() : undefined}
								/>
							) : state.view === "grid" ? (
								<FileGrid
									rows={rows}
									store={store}
									thumbnailSize={thumbnailSize}
									callbacks={itemCallbacks}
								/>
							) : (
								<FileList
									rows={rows}
									store={store}
									density={density}
									sortBy={state.sortBy}
									sortDir={state.sortDir}
									onSort={(key) => dispatch({ type: "TOGGLE_SORT", sortBy: key })}
									callbacks={itemCallbacks}
								/>
							)}
						</AutoScroll>
					</Panel>

					{detailNode ? (
						<>
							<Separator className="w-px shrink-0 bg-hairline transition-colors hover:bg-accent data-disabled:pointer-events-none" />
							<Panel id="detail" defaultSize="28%" minSize="20%" maxSize="46%">
								<DetailPanel
									node={detailNode}
									store={store}
									allowDelete={allowDelete}
									onRename={(next) => commitRename(detailNode, next)}
									onSaveText={(text) => saveText(detailNode, text)}
									onDownload={() => download(detailNode)}
									onDelete={() => requestDelete([detailNode.path])}
									onClose={() => dispatch({ type: "CLOSE_DETAIL" })}
								/>
							</Panel>
						</>
					) : null}
				</Group>
			</div>

			<div className="flex items-center justify-between gap-3 border-t border-hairline px-3 py-1.5">
				<StorageMeter estimate={estimate} backend={backend} />
				{state.clipboard.length > 0 ? (
					<span className="font-mono text-[11px] text-ink-mute">
						{state.clipboard.length} cut · paste into a folder
					</span>
				) : null}
			</div>

			{state.contextMenu ? (
				<ContextMenu
					x={state.contextMenu.x}
					y={state.contextMenu.y}
					target={
						state.contextMenu.targetPath
							? (displayed.find((n) => n.path === state.contextMenu?.targetPath) ?? null)
							: null
					}
					hasClipboard={state.clipboard.length > 0}
					allowUpload={allowUpload}
					allowDelete={allowDelete}
					onOpen={() => {
						const node = displayed.find((n) => n.path === state.contextMenu?.targetPath);
						if (node) openNode(node);
					}}
					onDownload={() => {
						const node = displayed.find((n) => n.path === state.contextMenu?.targetPath);
						if (node) void download(node);
					}}
					onRename={() => {
						if (state.contextMenu?.targetPath) {
							dispatch({ type: "BEGIN_RENAME", path: state.contextMenu.targetPath });
						}
					}}
					onCut={() => dispatch({ type: "CUT", paths: state.selection })}
					onPaste={() =>
						paste(state.contextMenu?.targetPath ?? state.currentPath)
					}
					onDelete={() => requestDelete(state.selection)}
					onNewFolder={newFolder}
					onClose={() => dispatch({ type: "CLOSE_CONTEXT" })}
				/>
			) : null}

			<AnimatePresence>
				{pendingDelete ? (
					<UndoSnackbar
						label={pendingDelete.label}
						windowMs={undoWindowMs}
						onUndo={undoDelete}
						reducedMotion={reducedMotion}
					/>
				) : null}
			</AnimatePresence>

			{dragging ? (
				<div className="pointer-events-none absolute inset-0 z-30 flex items-center justify-center bg-accent/10 backdrop-blur-[1px]">
					<div className="flex items-center gap-2 rounded-lg border border-accent bg-panel px-4 py-3 text-sm text-accent shadow-lg">
						<Upload className="h-4 w-4" />
						Drop files to upload
					</div>
				</div>
			) : null}

			<input
				ref={fileInputRef}
				type="file"
				multiple
				hidden
				onChange={(e) => {
					if (e.target.files?.length) void uploadFiles(e.target.files, state.currentPath);
					e.target.value = "";
				}}
			/>
		</div>
	);
}
```

### 2. `components/registry/file-explorer/auto-scroll.tsx` — supporting file, required

```tsx
"use client";

import { useEffect, useRef, useState, type ComponentPropsWithoutRef } from "react";
import { cn } from "./util";

export const autoScrollClasses =
	"scrollbar-thin max-md:scrollbar-none [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:transition-colors [scrollbar-color:transparent_transparent] [&::-webkit-scrollbar-thumb]:bg-transparent md:hover:[scrollbar-color:var(--sg-scroll)_transparent] md:hover:[&::-webkit-scrollbar-thumb]:bg-(--sg-scroll)";

const revealClasses =
	"md:[scrollbar-color:var(--sg-scroll)_transparent] md:[&::-webkit-scrollbar-thumb]:bg-(--sg-scroll)";

export function AutoScroll({
	className,
	children,
	onScroll,
	...rest
}: ComponentPropsWithoutRef<"div">) {
	const [scrolling, setScrolling] = useState(false);
	const timer = useRef<ReturnType<typeof setTimeout> | null>(null);

	useEffect(
		() => () => {
			if (timer.current) clearTimeout(timer.current);
		},
		[],
	);

	return (
		<div
			{...rest}
			onScroll={(e) => {
				onScroll?.(e);
				setScrolling(true);
				if (timer.current) clearTimeout(timer.current);
				timer.current = setTimeout(() => setScrolling(false), 1000);
			}}
			className={cn(
				"overflow-y-auto",
				autoScrollClasses,
				scrolling && revealClasses,
				className,
			)}
		>
			{children}
		</div>
	);
}
```

### 3. `components/registry/file-explorer/breadcrumb.tsx` — supporting file, required

```tsx
"use client";

import { Fragment } from "react";
import { ChevronRight, House } from "lucide-react";
import { segments, type StorePath } from "./store/types";
import { cn } from "./util";

export function Breadcrumb({
	path,
	onNavigate,
	className,
}: {
	path: StorePath;
	onNavigate: (path: StorePath) => void;
	className?: string;
}) {
	const segs = segments(path);
	const crumbs = segs.map((name, i) => ({
		name,
		path: segs.slice(0, i + 1).join("/"),
	}));

	return (
		<nav
			aria-label="Breadcrumb"
			className={cn(
				"flex min-w-0 items-center gap-0.5 overflow-x-auto text-xs scrollbar-none",
				className,
			)}
		>
			<button
				type="button"
				onClick={() => onNavigate("")}
				aria-label="Home"
				className={cn(
					"flex shrink-0 items-center gap-1 rounded-sm px-1.5 py-1 text-ink-dim transition-colors hover:text-accent",
					path === "" && "text-ink",
				)}
			>
				<House className="h-3.5 w-3.5" />
			</button>
			{crumbs.map((crumb, i) => (
				<Fragment key={crumb.path}>
					<ChevronRight className="h-3.5 w-3.5 shrink-0 text-ink-mute" />
					<button
						type="button"
						onClick={() => onNavigate(crumb.path)}
						className={cn(
							"max-w-[12ch] shrink-0 truncate rounded-sm px-1.5 py-1 font-mono transition-colors hover:text-accent",
							i === crumbs.length - 1 ? "text-ink" : "text-ink-dim",
						)}
						aria-current={i === crumbs.length - 1 ? "page" : undefined}
					>
						{crumb.name}
					</button>
				</Fragment>
			))}
		</nav>
	);
}
```

### 4. `components/registry/file-explorer/context-menu.tsx` — supporting file, required

```tsx
"use client";

import {
	Download,
	FolderInput,
	FolderPlus,
	Pencil,
	Scissors,
	SquareArrowOutUpRight,
	Trash2,
} from "lucide-react";
import type { FileNode } from "./store/types";
import { cn } from "./util";

export interface ContextMenuProps {
	x: number;
	y: number;
	target: FileNode | null;
	hasClipboard: boolean;
	allowUpload: boolean;
	allowDelete: boolean;
	onOpen: () => void;
	onDownload: () => void;
	onRename: () => void;
	onCut: () => void;
	onPaste: () => void;
	onDelete: () => void;
	onNewFolder: () => void;
	onClose: () => void;
}

export function ContextMenu(props: ContextMenuProps) {
	const { target } = props;
	const isDir = target?.kind === "directory";
	const isFile = target?.kind === "file";

	return (
		<>
			<button
				type="button"
				aria-hidden
				tabIndex={-1}
				onClick={props.onClose}
				onContextMenu={(e) => {
					e.preventDefault();
					props.onClose();
				}}
				className="fixed inset-0 z-40 cursor-default"
			/>
			<div
				role="menu"
				style={{ left: props.x, top: props.y }}
				className="absolute z-50 min-w-48 overflow-hidden rounded-md border border-hairline bg-panel py-1 shadow-xl"
			>
				{target ? (
					<Item
						icon={SquareArrowOutUpRight}
						label={isDir ? "Open" : "Preview"}
						onClick={run(props.onOpen, props.onClose)}
					/>
				) : null}

				{props.hasClipboard && (isDir || !target) ? (
					<Item
						icon={FolderInput}
						label={target ? "Paste into folder" : "Paste"}
						onClick={run(props.onPaste, props.onClose)}
					/>
				) : null}

				{!target && props.allowUpload ? (
					<Item
						icon={FolderPlus}
						label="New folder"
						onClick={run(props.onNewFolder, props.onClose)}
					/>
				) : null}

				{isFile ? (
					<Item
						icon={Download}
						label="Download"
						onClick={run(props.onDownload, props.onClose)}
					/>
				) : null}

				{target && props.allowDelete ? (
					<Item
						icon={Pencil}
						label="Rename"
						onClick={run(props.onRename, props.onClose)}
					/>
				) : null}

				{target && props.allowDelete ? (
					<Item
						icon={Scissors}
						label="Cut"
						onClick={run(props.onCut, props.onClose)}
					/>
				) : null}

				{target && props.allowDelete ? (
					<>
						<div className="my-1 h-px bg-hairline/60" />
						<Item
							icon={Trash2}
							label="Delete"
							danger
							onClick={run(props.onDelete, props.onClose)}
						/>
					</>
				) : null}
			</div>
		</>
	);
}

function run(action: () => void, close: () => void) {
	return () => {
		action();
		close();
	};
}

function Item({
	icon: Icon,
	label,
	onClick,
	danger,
}: {
	icon: typeof Download;
	label: string;
	onClick: () => void;
	danger?: boolean;
}) {
	return (
		<button
			type="button"
			role="menuitem"
			onClick={onClick}
			className={cn(
				"flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-xs transition-colors",
				danger
					? "text-ink-dim hover:bg-danger/10 hover:text-danger"
					: "text-ink-dim hover:bg-raised hover:text-ink",
			)}
		>
			<Icon className="h-3.5 w-3.5 shrink-0" />
			{label}
		</button>
	);
}
```

### 5. `components/registry/file-explorer/detail-panel.tsx` — supporting file, required

```tsx
"use client";

import { useEffect, useState } from "react";
import { Download, Pencil, Trash2, X } from "lucide-react";
import type { FileNode, FileStore } from "./store/types";
import { parentPath } from "./store/types";
import { AutoScroll, autoScrollClasses } from "./auto-scroll";
import { InlineRename } from "./inline-rename";
import { Thumbnail } from "./thumbnail";
import { cn, fileExtension, formatBytes, kindForNode } from "./util";

export function DetailPanel({
	node,
	store,
	allowDelete,
	onRename,
	onSaveText,
	onDownload,
	onDelete,
	onClose,
}: {
	node: FileNode;
	store: FileStore | null;
	allowDelete: boolean;
	onRename: (nextName: string) => void;
	onSaveText: (text: string) => void;
	onDownload: () => void;
	onDelete: () => void;
	onClose: () => void;
}) {
	const [renaming, setRenaming] = useState(false);
	const kind = kindForNode(node);
	const location = parentPath(node.path);

	return (
		<aside className="flex h-full flex-col bg-panel">
			<header className="flex h-9 items-center justify-between gap-2 border-b border-hairline px-3">
				<span className="font-display text-[11px] uppercase tracking-[0.2em] text-ink-mute">
					Details
				</span>
				<button
					type="button"
					onClick={onClose}
					aria-label="Close details"
					className="text-ink-mute transition-colors hover:text-ink"
				>
					<X className="h-4 w-4" />
				</button>
			</header>

			<AutoScroll className="min-h-0 flex-1">
				<div className="flex items-center justify-center border-b border-hairline bg-surface/50 p-4">
					<div className="flex aspect-video w-full items-center justify-center overflow-hidden rounded-md bg-surface">
						<Preview
							key={node.path}
							node={node}
							store={store}
							canEdit={allowDelete}
							onSaveText={onSaveText}
						/>
					</div>
				</div>

				<div className="space-y-4 p-3">
					<div className="space-y-1">
						{renaming ? (
							<InlineRename
								initial={node.name}
								onCommit={(next) => {
									onRename(next);
									setRenaming(false);
								}}
								onCancel={() => setRenaming(false)}
								className="text-sm"
							/>
						) : (
							<button
								type="button"
								onDoubleClick={() => setRenaming(true)}
								title="Double-click to rename"
								className="block w-full wrap-break-word text-left text-sm font-medium text-ink"
							>
								{node.name}
							</button>
						)}
					</div>

					<dl className="space-y-2 text-xs">
						<Meta label="Kind" value={kind === "file" ? "File" : capitalize(kind)} />
						<Meta
							label="Type"
							value={node.mime || fileExtension(node.name) || "unknown"}
						/>
						<Meta label="Size" value={formatBytes(node.size)} />
						<Meta label="Modified" value={formatFull(node.mtime)} />
						<Meta label="Location" value={location ? `/${location}` : "Home"} />
					</dl>
				</div>
			</AutoScroll>

			<footer className="flex items-center gap-2 border-t border-hairline p-3">
				<button
					type="button"
					onClick={onDownload}
					className="inline-flex flex-1 items-center justify-center gap-1.5 rounded-md border border-hairline bg-surface px-3 py-1.5 text-xs text-ink-dim transition-colors hover:border-accent hover:text-accent"
				>
					<Download className="h-3.5 w-3.5" />
					Download
				</button>
				{allowDelete ? (
					<>
						<button
							type="button"
							onClick={() => setRenaming(true)}
							aria-label="Rename"
							className="flex h-8 w-8 items-center justify-center rounded-md border border-hairline text-ink-dim transition-colors hover:border-accent hover:text-accent"
						>
							<Pencil className="h-3.5 w-3.5" />
						</button>
						<button
							type="button"
							onClick={onDelete}
							aria-label="Delete"
							className="flex h-8 w-8 items-center justify-center rounded-md border border-hairline text-ink-dim transition-colors hover:border-danger hover:text-danger"
						>
							<Trash2 className="h-3.5 w-3.5" />
						</button>
					</>
				) : null}
			</footer>
		</aside>
	);
}

function Preview({
	node,
	store,
	canEdit,
	onSaveText,
}: {
	node: FileNode;
	store: FileStore | null;
	canEdit: boolean;
	onSaveText: (text: string) => void;
}) {
	const kind = kindForNode(node);
	const [text, setText] = useState<string | null>(null);
	const [mediaUrl, setMediaUrl] = useState<string | null>(null);
	const [editing, setEditing] = useState(false);
	const [draft, setDraft] = useState("");

	useEffect(() => {
		let cancelled = false;
		let created: string | null = null;
		const isMedia = kind === "image" || kind === "video" || kind === "audio";
		if (!store || !isMedia) return;
		store
			.read(node.path)
			.then((blob) => {
				if (cancelled) return;
				created = URL.createObjectURL(blob);
				setMediaUrl(created);
			})
			.catch(() => {});
		return () => {
			cancelled = true;
			if (created) URL.revokeObjectURL(created);
		};
	}, [store, node.path, node.mtime, kind]);

	useEffect(() => {
		let cancelled = false;
		if (!store || (kind !== "text" && kind !== "code")) return;
		store
			.read(node.path)
			.then((blob) => blob.slice(0, 64_000).text())
			.then((t) => {
				if (!cancelled) setText(t);
			})
			.catch(() => {});
		return () => {
			cancelled = true;
		};
	}, [store, node.path, node.mtime, kind]);

	if (kind === "image" && mediaUrl) {
		// eslint-disable-next-line @next/next/no-img-element -- object URL
		return <img src={mediaUrl} alt={node.name} className="h-full w-full object-contain" />;
	}
	if (kind === "video" && mediaUrl) {
		return <video src={mediaUrl} controls className="h-full w-full" />;
	}
	if (kind === "audio" && mediaUrl) {
		return (
			<div className="flex w-full items-center justify-center p-4">
				<audio src={mediaUrl} controls className="w-full" />
			</div>
		);
	}
	if ((kind === "text" || kind === "code") && text !== null) {
		if (editing) {
			const commit = () => {
				onSaveText(draft);
				setEditing(false);
			};
			return (
				<div className="flex h-full w-full flex-col bg-surface">
					<textarea
						value={draft}
						autoFocus
						spellCheck={false}
						onChange={(e) => setDraft(e.target.value)}
						onKeyDown={(e) => {
							if (e.key === "Escape") {
								e.preventDefault();
								setEditing(false);
							} else if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
								e.preventDefault();
								commit();
							}
							e.stopPropagation();
						}}
						className={cn(
							"min-h-0 flex-1 resize-none bg-transparent p-2 font-mono text-[11px] leading-relaxed text-ink outline-none",
							autoScrollClasses,
						)}
					/>
					<div className="flex items-center justify-end gap-1.5 border-t border-hairline p-1.5">
						<button
							type="button"
							onClick={() => setEditing(false)}
							className="rounded-sm px-2 py-1 text-[11px] text-ink-mute transition-colors hover:text-ink"
						>
							Cancel
						</button>
						<button
							type="button"
							onClick={commit}
							className="rounded-sm bg-accent px-2 py-1 text-[11px] font-medium text-on-accent transition-colors hover:bg-accent-hover"
						>
							Save
						</button>
					</div>
				</div>
			);
		}
		return (
			<pre
				onDoubleClick={
					canEdit
						? () => {
								setDraft(text);
								setEditing(true);
							}
						: undefined
				}
				title={canEdit ? "Double-click to edit" : undefined}
				className={cn(
					"h-full w-full overflow-auto p-3 text-left font-mono text-[11px] leading-relaxed text-ink-dim",
					canEdit && "cursor-text",
					autoScrollClasses,
				)}
			>
				{text}
			</pre>
		);
	}
	return (
		<div className="h-16 w-16">
			<Thumbnail node={node} store={store} />
		</div>
	);
}

function Meta({ label, value }: { label: string; value: string }) {
	return (
		<div className="flex items-baseline justify-between gap-3">
			<dt className="shrink-0 font-display text-[10px] uppercase tracking-[0.15em] text-ink-mute">
				{label}
			</dt>
			<dd className="min-w-0 truncate text-right font-mono text-ink-dim">{value}</dd>
		</div>
	);
}

function capitalize(s: string): string {
	return s.charAt(0).toUpperCase() + s.slice(1);
}

function formatFull(mtime: number): string {
	if (!mtime) return "—";
	return new Date(mtime).toLocaleString(undefined, {
		dateStyle: "medium",
		timeStyle: "short",
	});
}
```

### 6. `components/registry/file-explorer/empty-state.tsx` — supporting file, required

```tsx
"use client";

import { FolderOpen, SearchX, ServerCrash, Upload } from "lucide-react";
import { cn } from "./util";

export type EmptyVariant = "empty" | "no-results" | "unsupported";

const COPY: Record<
	EmptyVariant,
	{ Icon: typeof FolderOpen; title: string; body: string }
> = {
	empty: {
		Icon: FolderOpen,
		title: "This folder is empty",
		body: "Drag files in, or use the Add button to upload.",
	},
	"no-results": {
		Icon: SearchX,
		title: "No matches",
		body: "Nothing here matches your search.",
	},
	unsupported: {
		Icon: ServerCrash,
		title: "Storage unavailable",
		body: "This browser has no persistent file storage available.",
	},
};

export function EmptyState({
	variant,
	onAdd,
	className,
}: {
	variant: EmptyVariant;
	onAdd?: () => void;
	className?: string;
}) {
	const { Icon, title, body } = COPY[variant];
	return (
		<div
			className={cn(
				"flex h-full flex-col items-center justify-center gap-3 px-6 py-10 text-center",
				className,
			)}
		>
			<Icon className="h-10 w-10 text-ink-mute" strokeWidth={1.25} />
			<div className="space-y-1">
				<p className="font-display text-xs uppercase tracking-[0.2em] text-ink-dim">
					{title}
				</p>
				<p className="mx-auto max-w-[32ch] text-xs text-ink-mute">{body}</p>
			</div>
			{variant === "empty" && onAdd ? (
				<button
					type="button"
					onClick={onAdd}
					className="mt-1 inline-flex items-center gap-1.5 rounded-md border border-hairline bg-panel px-3 py-1.5 text-xs text-ink-dim transition-colors hover:border-accent hover:text-accent"
				>
					<Upload className="h-3.5 w-3.5" />
					Add files
				</button>
			) : null}
		</div>
	);
}
```

### 7. `components/registry/file-explorer/file-grid.tsx` — supporting file, required

```tsx
"use client";

import { useState } from "react";
import type { FileStore } from "./store/types";
import type { ItemCallbacks, Row } from "./types";
import { InlineRename } from "./inline-rename";
import { Thumbnail } from "./thumbnail";
import { cn, kindForNode } from "./util";

export function FileGrid({
	rows,
	store,
	thumbnailSize,
	callbacks,
}: {
	rows: Row[];
	store: FileStore | null;
	thumbnailSize: number;
	callbacks: ItemCallbacks;
}) {
	return (
		<div
			className="grid content-start justify-start gap-1 p-3"
			style={{
				gridTemplateColumns: `repeat(auto-fill, ${thumbnailSize}px)`,
			}}
		>
			{rows.map((row) => (
				<Tile
					key={row.node.path}
					row={row}
					store={store}
					callbacks={callbacks}
				/>
			))}
		</div>
	);
}

function Tile({
	row,
	store,
	callbacks,
}: {
	row: Row;
	store: FileStore | null;
	callbacks: ItemCallbacks;
}) {
	const { node, selected, cut, renaming } = row;
	const isDir = node.kind === "directory";
	const [dropActive, setDropActive] = useState(false);

	return (
		<div
			role="option"
			aria-selected={selected}
			tabIndex={-1}
			draggable={!renaming}
			onDragStart={(e) => callbacks.onItemDragStart(node, e)}
			onDragOver={(e) => {
				if (!isDir) return;
				e.preventDefault();
				setDropActive(true);
			}}
			onDragLeave={() => setDropActive(false)}
			onDrop={(e) => {
				setDropActive(false);
				callbacks.onItemDrop(node, e);
			}}
			onClick={(e) => callbacks.onSelect(node, e)}
			onDoubleClick={() => callbacks.onOpen(node)}
			onContextMenu={(e) => callbacks.onContextMenu(node, e)}
			className={cn(
				"group flex cursor-default flex-col items-center gap-1.5 rounded-md border border-transparent p-2 transition-colors",
				selected
					? "border-accent/40 bg-accent/15"
					: "hover:bg-raised",
				cut && "opacity-50",
				dropActive && "ring-2 ring-accent",
			)}
		>
			<div
				className={cn(
					"flex aspect-square w-full items-center justify-center overflow-hidden rounded-md",
					kindForNode(node) === "image"
						? "bg-surface"
						: "bg-surface/60",
				)}
			>
				<Thumbnail node={node} store={store} />
			</div>
			{renaming ? (
				<InlineRename
					initial={node.name}
					onCommit={(next) => callbacks.onRenameCommit(node, next)}
					onCancel={callbacks.onRenameCancel}
					className="text-center text-xs"
				/>
			) : (
				<span
					title={node.name}
					className={cn(
						"line-clamp-2 w-full text-center text-xs leading-tight",
						selected ? "text-ink" : "text-ink-dim",
					)}
				>
					{node.name}
				</span>
			)}
		</div>
	);
}
```

### 8. `components/registry/file-explorer/file-list.tsx` — supporting file, required

```tsx
"use client";

import { useState } from "react";
import { ArrowDown, ArrowUp } from "lucide-react";
import type { FileStore } from "./store/types";
import type { Density, ItemCallbacks, Row, SortDir, SortKey } from "./types";
import { InlineRename } from "./inline-rename";
import { Thumbnail } from "./thumbnail";
import { cn, fileExtension, formatBytes, formatRelativeTime } from "./util";

const GRID = "grid grid-cols-[1fr_5rem_7rem] items-center gap-3";

export function FileList({
	rows,
	store,
	density,
	sortBy,
	sortDir,
	onSort,
	callbacks,
}: {
	rows: Row[];
	store: FileStore | null;
	density: Density;
	sortBy: SortKey;
	sortDir: SortDir;
	onSort: (key: SortKey) => void;
	callbacks: ItemCallbacks;
}) {
	return (
		<div className="min-w-0">
			<div
				className={cn(
					GRID,
					"sticky top-0 z-10 h-9 border-b border-hairline bg-panel px-3 font-display text-[10px] uppercase tracking-[0.15em] text-ink-mute",
				)}
			>
				<Header label="Name" col="name" {...{ sortBy, sortDir, onSort }} />
				<Header
					label="Size"
					col="size"
					className="justify-end"
					{...{ sortBy, sortDir, onSort }}
				/>
				<Header
					label="Modified"
					col="date"
					className="justify-end"
					{...{ sortBy, sortDir, onSort }}
				/>
			</div>
			<div className="divide-y divide-hairline/50">
				{rows.map((row) => (
					<ListRow
						key={row.node.path}
						row={row}
						store={store}
						density={density}
						callbacks={callbacks}
					/>
				))}
			</div>
		</div>
	);
}

function Header({
	label,
	col,
	sortBy,
	sortDir,
	onSort,
	className,
}: {
	label: string;
	col: SortKey;
	sortBy: SortKey;
	sortDir: SortDir;
	onSort: (key: SortKey) => void;
	className?: string;
}) {
	const active = sortBy === col;
	return (
		<button
			type="button"
			onClick={() => onSort(col)}
			className={cn(
				"flex items-center gap-1 transition-colors hover:text-ink",
				active && "text-accent",
				className,
			)}
		>
			<span>{label}</span>
			{active ? (
				sortDir === "asc" ? (
					<ArrowUp className="h-3 w-3" />
				) : (
					<ArrowDown className="h-3 w-3" />
				)
			) : null}
		</button>
	);
}

function ListRow({
	row,
	store,
	density,
	callbacks,
}: {
	row: Row;
	store: FileStore | null;
	density: Density;
	callbacks: ItemCallbacks;
}) {
	const { node, selected, cut, renaming } = row;
	const isDir = node.kind === "directory";
	const [dropActive, setDropActive] = useState(false);

	return (
		<div
			role="option"
			aria-selected={selected}
			tabIndex={-1}
			draggable={!renaming}
			onDragStart={(e) => callbacks.onItemDragStart(node, e)}
			onDragOver={(e) => {
				if (!isDir) return;
				e.preventDefault();
				setDropActive(true);
			}}
			onDragLeave={() => setDropActive(false)}
			onDrop={(e) => {
				setDropActive(false);
				callbacks.onItemDrop(node, e);
			}}
			onClick={(e) => callbacks.onSelect(node, e)}
			onDoubleClick={() => callbacks.onOpen(node)}
			onContextMenu={(e) => callbacks.onContextMenu(node, e)}
			className={cn(
				GRID,
				"cursor-default px-3 transition-colors",
				density === "compact" ? "py-1" : "py-1.5",
				selected ? "bg-accent/15" : "hover:bg-raised",
				cut && "opacity-50",
				dropActive && "ring-1 ring-inset ring-accent",
			)}
		>
			<div className="flex min-w-0 items-center gap-2.5">
				<span className="h-6 w-6 shrink-0">
					<Thumbnail node={node} store={store} />
				</span>
				{renaming ? (
					<InlineRename
						initial={node.name}
						onCommit={(next) => callbacks.onRenameCommit(node, next)}
						onCancel={callbacks.onRenameCancel}
						className="text-xs"
					/>
				) : (
					<span
						title={node.name}
						className={cn(
							"truncate text-xs",
							selected ? "text-ink" : "text-ink-dim",
						)}
					>
						{node.name}
					</span>
				)}
			</div>
			<span className="text-right font-mono text-[11px] tabular-nums text-ink-mute">
				{isDir ? "—" : formatBytes(node.size)}
			</span>
			<span className="truncate text-right font-mono text-[11px] text-ink-mute">
				{isDir
					? fileExtension(node.name) || "folder"
					: formatRelativeTime(node.mtime)}
			</span>
		</div>
	);
}
```

### 9. `components/registry/file-explorer/folder-tree.tsx` — supporting file, required

```tsx
"use client";

import { useEffect, useState } from "react";
import { ChevronRight, Folder, House } from "lucide-react";
import type { FileNode, FileStore, StorePath } from "./store/types";
import type { Density } from "./types";
import { cn } from "./util";

interface TreeCallbacks {
	onNavigate: (path: StorePath) => void;
	onDropOnFolder: (dir: StorePath, e: React.DragEvent) => void;
}

export function FolderTree({
	store,
	revision,
	currentPath,
	density,
	className,
	...callbacks
}: TreeCallbacks & {
	store: FileStore | null;
	revision: number;
	currentPath: StorePath;
	density: Density;
	className?: string;
}) {
	return (
		<div className={cn("min-w-0 py-1 text-sm", className)}>
			<TreeRow
				store={store}
				revision={revision}
				path=""
				name="Home"
				depth={0}
				currentPath={currentPath}
				density={density}
				{...callbacks}
			/>
		</div>
	);
}

function TreeRow({
	store,
	revision,
	path,
	name,
	depth,
	currentPath,
	density,
	onNavigate,
	onDropOnFolder,
}: TreeCallbacks & {
	store: FileStore | null;
	revision: number;
	path: StorePath;
	name: string;
	depth: number;
	currentPath: StorePath;
	density: Density;
}) {
	const inPath =
		path === "" || currentPath === path || currentPath.startsWith(`${path}/`);
	const [manualExpanded, setManualExpanded] = useState<boolean | null>(null);
	const expanded = manualExpanded ?? inPath;
	const [children, setChildren] = useState<FileNode[] | null>(null);
	const [dragOver, setDragOver] = useState(false);

	useEffect(() => {
		if (!expanded || !store) return;
		let cancelled = false;
		store
			.list(path)
			.then((list) => {
				if (!cancelled) {
					setChildren(list.filter((n) => n.kind === "directory"));
				}
			})
			.catch(() => {
				if (!cancelled) setChildren([]);
			});
		return () => {
			cancelled = true;
		};
	}, [expanded, store, path, revision]);

	const active = currentPath === path;
	const isRoot = path === "";
	const pad = density === "compact" ? "py-1" : "py-1.5";

	return (
		<div className="min-w-0">
			<div
				onDragOver={(e) => {
					e.preventDefault();
					setDragOver(true);
				}}
				onDragLeave={() => setDragOver(false)}
				onDrop={(e) => {
					setDragOver(false);
					onDropOnFolder(path, e);
				}}
				className={cn(
					"group flex min-w-0 items-center gap-1 rounded-sm pr-1.5 transition-colors",
					pad,
					active ? "bg-accent/15 text-ink" : "text-ink-dim hover:bg-raised",
					dragOver && "ring-1 ring-accent",
				)}
				style={{ paddingLeft: depth * 12 + 4 }}
			>
				<button
					type="button"
					aria-label={expanded ? "Collapse" : "Expand"}
					onClick={() => setManualExpanded(!expanded)}
					className="flex h-4 w-4 shrink-0 items-center justify-center text-ink-mute hover:text-ink"
				>
					<ChevronRight
						className={cn(
							"h-3.5 w-3.5 transition-transform",
							expanded && "rotate-90",
						)}
					/>
				</button>
				<button
					type="button"
					onClick={() => onNavigate(path)}
					className="flex min-w-0 flex-1 items-center gap-1.5"
				>
					{isRoot ? (
						<House className="h-4 w-4 shrink-0 text-accent" />
					) : (
						<Folder
							className={cn(
								"h-4 w-4 shrink-0",
								active ? "text-accent" : "text-ink-mute",
							)}
							strokeWidth={1.5}
						/>
					)}
					<span className="truncate">{name}</span>
				</button>
			</div>

			{expanded &&
				children?.map((child) => (
					<TreeRow
						key={child.path}
						store={store}
						revision={revision}
						path={child.path}
						name={child.name}
						depth={depth + 1}
						currentPath={currentPath}
						density={density}
						onNavigate={onNavigate}
						onDropOnFolder={onDropOnFolder}
					/>
				))}
		</div>
	);
}
```

### 10. `components/registry/file-explorer/inline-rename.tsx` — supporting file, required

```tsx
"use client";

import { useEffect, useRef, useState } from "react";
import { cn } from "./util";

export function InlineRename({
	initial,
	onCommit,
	onCancel,
	className,
}: {
	initial: string;
	onCommit: (nextName: string) => void;
	onCancel: () => void;
	className?: string;
}) {
	const [value, setValue] = useState(initial);
	const ref = useRef<HTMLInputElement>(null);

	useEffect(() => {
		const input = ref.current;
		if (!input) return;
		input.focus();
		const dot = initial.lastIndexOf(".");
		input.setSelectionRange(0, dot > 0 ? dot : initial.length);
	}, [initial]);

	function commit() {
		const next = value.trim();
		if (next && next !== initial) onCommit(next);
		else onCancel();
	}

	return (
		<input
			ref={ref}
			value={value}
			spellCheck={false}
			onChange={(e) => setValue(e.target.value)}
			onKeyDown={(e) => {
				if (e.key === "Enter") {
					e.preventDefault();
					commit();
				} else if (e.key === "Escape") {
					e.preventDefault();
					onCancel();
				}
				e.stopPropagation();
			}}
			onBlur={commit}
			onClick={(e) => e.stopPropagation()}
			onDoubleClick={(e) => e.stopPropagation()}
			className={cn(
				"w-full rounded-sm border border-accent bg-surface px-1 py-0.5 text-ink outline-none",
				className,
			)}
		/>
	);
}
```

### 11. `components/registry/file-explorer/storage-meter.tsx` — supporting file, required

```tsx
"use client";

import { HardDrive } from "lucide-react";
import type { FileStoreBackend, StorageEstimate } from "./store/types";
import { cn, formatBytes } from "./util";

const BACKEND_LABEL: Record<string, string> = {
	opfs: "OPFS",
	indexeddb: "IndexedDB",
	memory: "Memory",
};

export function StorageMeter({
	estimate,
	backend,
	className,
}: {
	estimate: StorageEstimate | null;
	backend: FileStoreBackend | null;
	className?: string;
}) {
	const usage = estimate?.usage ?? 0;
	const quota = estimate?.quota ?? 0;
	const pct = quota > 0 ? Math.min(100, (usage / quota) * 100) : null;
	const label = backend ? (BACKEND_LABEL[backend] ?? backend) : "—";

	return (
		<div
			className={cn(
				"flex items-center gap-2 text-[11px] text-ink-mute",
				className,
			)}
			title={
				quota > 0
					? `${formatBytes(usage)} of ${formatBytes(quota)} used · ${label}`
					: `${formatBytes(usage)} used · ${label}`
			}
		>
			<HardDrive className="h-3.5 w-3.5 shrink-0" />
			<span className="font-display uppercase tracking-[0.15em]">{label}</span>
			{pct !== null ? (
				<span
					className="h-1 w-16 shrink-0 overflow-hidden rounded-full bg-raised"
					role="presentation"
				>
					<span
						className="block h-full rounded-full bg-accent"
						style={{ width: `${Math.max(2, pct)}%` }}
					/>
				</span>
			) : null}
			<span className="font-mono tabular-nums">{formatBytes(usage)}</span>
		</div>
	);
}
```

### 12. `components/registry/file-explorer/thumbnail.tsx` — supporting file, required

```tsx
"use client";

import {
	Code,
	File as FileIcon,
	FileArchive,
	FileText,
	Film,
	Folder,
	Image as ImageIcon,
	Music,
} from "lucide-react";
import type { FileNode, FileStore } from "./store/types";
import { useStoredObjectUrl } from "./use-object-url";
import { cn, kindForNode, type FileKind } from "./util";

const ICON: Record<FileKind, typeof FileIcon> = {
	directory: Folder,
	image: ImageIcon,
	video: Film,
	audio: Music,
	pdf: FileText,
	text: FileText,
	code: Code,
	archive: FileArchive,
	file: FileIcon,
};

export function Thumbnail({
	node,
	store,
	enabled = true,
	iconClassName,
	className,
}: {
	node: FileNode;
	store: FileStore | null;
	enabled?: boolean;
	iconClassName?: string;
	className?: string;
}) {
	const kind = kindForNode(node);
	const wantsImage = enabled && kind === "image";
	const url = useStoredObjectUrl(store, wantsImage ? node : null, wantsImage);

	if (url && kind === "image") {
		return (
			// eslint-disable-next-line @next/next/no-img-element -- object URL, not a remote asset
			<img
				src={url}
				alt={node.name}
				loading="lazy"
				className={cn("h-full w-full object-cover", className)}
			/>
		);
	}

	const Icon = ICON[kind];
	return (
		<div
			className={cn(
				"flex h-full w-full items-center justify-center",
				className,
			)}
		>
			<Icon
				className={cn(
					"h-1/2 w-1/2",
					kind === "directory" ? "text-accent" : "text-ink-mute",
					iconClassName,
				)}
				strokeWidth={kind === "directory" ? 1.5 : 1.75}
			/>
		</div>
	);
}
```

### 13. `components/registry/file-explorer/toolbar.tsx` — supporting file, required

```tsx
"use client";

import { useState } from "react";
import {
	ArrowDownUp,
	Check,
	ClipboardPaste,
	FolderPlus,
	LayoutGrid,
	List as ListIcon,
	Search,
	Trash2,
	Upload,
	X,
} from "lucide-react";
import type { SortDir, SortKey, ViewMode } from "./types";
import { cn } from "./util";

const SORT_LABEL: Record<SortKey, string> = {
	name: "Name",
	date: "Date modified",
	size: "Size",
	type: "Type",
};

export interface ToolbarProps {
	view: ViewMode;
	sortBy: SortKey;
	sortDir: SortDir;
	search: string;
	folderName: string;
	selectionCount: number;
	clipboardCount: number;
	allowUpload: boolean;
	allowDelete: boolean;
	onViewChange: (view: ViewMode) => void;
	onSort: (sortBy: SortKey) => void;
	onSearch: (value: string) => void;
	onAdd: () => void;
	onNewFolder: () => void;
	onDeleteSelected: () => void;
	onClearSelection: () => void;
	onPaste: () => void;
}

export function Toolbar(props: ToolbarProps) {
	const bulk = props.selectionCount > 0;
	return (
		<div className="flex items-center gap-2 border-b border-hairline px-2 py-2">
			{bulk ? (
				<BulkBar {...props} />
			) : (
				<label className="flex min-w-0 flex-1 items-center gap-2 rounded-md border border-hairline bg-surface px-2.5 py-1.5 focus-within:border-accent">
					<Search className="h-3.5 w-3.5 shrink-0 text-ink-mute" />
					<input
						value={props.search}
						onChange={(e) => props.onSearch(e.target.value)}
						placeholder={`Search ${props.folderName}`}
						className="min-w-0 flex-1 bg-transparent text-xs text-ink outline-none placeholder:text-ink-mute"
					/>
					{props.search ? (
						<button
							type="button"
							onClick={() => props.onSearch("")}
							aria-label="Clear search"
							className="text-ink-mute hover:text-ink"
						>
							<X className="h-3.5 w-3.5" />
						</button>
					) : null}
				</label>
			)}

			<div className="flex shrink-0 items-center gap-1">
				{props.clipboardCount > 0 ? (
					<IconButton
						label={`Paste ${props.clipboardCount}`}
						onClick={props.onPaste}
					>
						<ClipboardPaste className="h-4 w-4" />
					</IconButton>
				) : null}

				<SortMenu sortBy={props.sortBy} sortDir={props.sortDir} onSort={props.onSort} />

				<div className="flex items-center rounded-md border border-hairline p-0.5">
					<ViewButton
						active={props.view === "grid"}
						label="Grid view"
						onClick={() => props.onViewChange("grid")}
					>
						<LayoutGrid className="h-4 w-4" />
					</ViewButton>
					<ViewButton
						active={props.view === "list"}
						label="List view"
						onClick={() => props.onViewChange("list")}
					>
						<ListIcon className="h-4 w-4" />
					</ViewButton>
				</div>

				{props.allowUpload ? (
					<>
						<IconButton label="New folder" onClick={props.onNewFolder}>
							<FolderPlus className="h-4 w-4" />
						</IconButton>
						<button
							type="button"
							onClick={props.onAdd}
							className="inline-flex items-center gap-1.5 rounded-md bg-accent px-2.5 py-1.5 text-xs font-medium text-on-accent transition-colors hover:bg-accent-hover"
						>
							<Upload className="h-3.5 w-3.5" />
							<span className="hidden sm:inline">Add</span>
						</button>
					</>
				) : null}
			</div>
		</div>
	);
}

function BulkBar(props: ToolbarProps) {
	return (
		<div className="flex min-w-0 flex-1 items-center gap-2">
			<span className="rounded-md bg-accent/15 px-2 py-1 font-display text-[11px] uppercase tracking-[0.15em] text-accent">
				{props.selectionCount} selected
			</span>
			{props.allowDelete ? (
				<button
					type="button"
					onClick={props.onDeleteSelected}
					className="inline-flex items-center gap-1.5 rounded-md border border-hairline px-2.5 py-1.5 text-xs text-ink-dim transition-colors hover:border-danger hover:text-danger"
				>
					<Trash2 className="h-3.5 w-3.5" />
					Delete
				</button>
			) : null}
			<button
				type="button"
				onClick={props.onClearSelection}
				className="inline-flex items-center gap-1.5 rounded-md px-2 py-1.5 text-xs text-ink-mute transition-colors hover:text-ink"
			>
				<X className="h-3.5 w-3.5" />
				Clear
			</button>
		</div>
	);
}

function SortMenu({
	sortBy,
	sortDir,
	onSort,
}: {
	sortBy: SortKey;
	sortDir: SortDir;
	onSort: (key: SortKey) => void;
}) {
	const [open, setOpen] = useState(false);
	return (
		<div className="relative">
			<IconButton
				label={`Sort by ${SORT_LABEL[sortBy]}, ${sortDir === "asc" ? "ascending" : "descending"}`}
				onClick={() => setOpen((v) => !v)}
				active={open}
			>
				<ArrowDownUp className="h-4 w-4" />
			</IconButton>
			{open ? (
				<>
					<button
						type="button"
						aria-hidden
						tabIndex={-1}
						onClick={() => setOpen(false)}
						className="fixed inset-0 z-40 cursor-default"
					/>
					<div
						role="menu"
						className="absolute right-0 top-full z-50 mt-1 min-w-44 overflow-hidden rounded-md border border-hairline bg-panel py-1 shadow-lg"
					>
						{(Object.keys(SORT_LABEL) as SortKey[]).map((key) => (
							<button
								key={key}
								type="button"
								role="menuitemradio"
								aria-checked={sortBy === key}
								onClick={() => {
									onSort(key);
									setOpen(false);
								}}
								className={cn(
									"flex w-full items-center justify-between px-3 py-1.5 text-left text-xs transition-colors hover:bg-raised",
									sortBy === key ? "text-accent" : "text-ink-dim",
								)}
							>
								<span>{SORT_LABEL[key]}</span>
								{sortBy === key ? (
									<span className="flex items-center gap-1 font-mono text-[10px] text-ink-mute">
										{sortDir === "asc" ? "A→Z" : "Z→A"}
										<Check className="h-3 w-3 text-accent" />
									</span>
								) : null}
							</button>
						))}
					</div>
				</>
			) : null}
		</div>
	);
}

function IconButton({
	children,
	label,
	onClick,
	active,
}: {
	children: React.ReactNode;
	label: string;
	onClick: () => void;
	active?: boolean;
}) {
	return (
		<button
			type="button"
			onClick={onClick}
			aria-label={label}
			title={label}
			className={cn(
				"flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-ink-dim transition-colors hover:bg-raised hover:text-ink",
				active && "border-hairline bg-raised text-ink",
			)}
		>
			{children}
		</button>
	);
}

function ViewButton({
	children,
	label,
	active,
	onClick,
}: {
	children: React.ReactNode;
	label: string;
	active: boolean;
	onClick: () => void;
}) {
	return (
		<button
			type="button"
			onClick={onClick}
			aria-label={label}
			aria-pressed={active}
			title={label}
			className={cn(
				"flex h-7 w-7 items-center justify-center rounded transition-colors",
				active
					? "bg-accent/15 text-accent"
					: "text-ink-mute hover:text-ink",
			)}
		>
			{children}
		</button>
	);
}
```

### 14. `components/registry/file-explorer/undo-snackbar.tsx` — supporting file, required

```tsx
"use client";

import { motion } from "motion/react";
import { RotateCcw, Trash2 } from "lucide-react";
import { cn } from "./util";

export function UndoSnackbar({
	label,
	windowMs,
	onUndo,
	reducedMotion = false,
	className,
}: {
	label: string;
	windowMs: number;
	onUndo: () => void;
	reducedMotion?: boolean;
	className?: string;
}) {
	return (
		<motion.div
			role="status"
			initial={reducedMotion ? { opacity: 0 } : { opacity: 0, y: 12 }}
			animate={reducedMotion ? { opacity: 1 } : { opacity: 1, y: 0 }}
			exit={reducedMotion ? { opacity: 0 } : { opacity: 0, y: 12 }}
			transition={{ duration: 0.18 }}
			className={cn(
				"pointer-events-auto absolute bottom-4 left-1/2 z-50 -translate-x-1/2",
				"flex items-center gap-3 overflow-hidden rounded-md border border-hairline bg-raised px-3 py-2 shadow-lg",
				className,
			)}
		>
			<Trash2 className="h-4 w-4 shrink-0 text-ink-mute" />
			<span className="max-w-[30ch] truncate text-xs text-ink-dim">{label}</span>
			<button
				type="button"
				onClick={onUndo}
				className="inline-flex items-center gap-1 rounded-sm px-1.5 py-0.5 text-xs font-medium text-accent transition-colors hover:bg-accent/15"
			>
				<RotateCcw className="h-3.5 w-3.5" />
				Undo
			</button>
			{!reducedMotion && windowMs > 0 ? (
				<motion.span
					aria-hidden
					initial={{ scaleX: 1 }}
					animate={{ scaleX: 0 }}
					transition={{ duration: windowMs / 1000, ease: "linear" }}
					style={{ originX: 0 }}
					className="absolute inset-x-0 bottom-0 h-0.5 bg-accent/60"
				/>
			) : null}
		</motion.div>
	);
}
```

### 15. `components/registry/file-explorer/types.ts` — supporting file, required

```tsx
import type { DragEvent, MouseEvent } from "react";
import type { FileNode, StorePath } from "./store/types";
import type { StoreSource } from "./use-file-store";

export type ViewMode = "grid" | "list";
export type SortKey = "name" | "date" | "size" | "type";
export type SortDir = "asc" | "desc";
export type Density = "comfortable" | "compact";

export interface SeedEntry {
	path: StorePath;
	blob?: Blob;
}

export interface FileExplorerProps {
	store?: StoreSource;
	namespace?: string;
	seed?: SeedEntry[];

	defaultView?: ViewMode;
	thumbnailSize?: number;
	density?: Density;
	sortBy?: SortKey;
	sortDir?: SortDir;
	showFolderRail?: boolean;
	showDetails?: boolean;
	showHidden?: boolean;
	allowUpload?: boolean;
	allowDelete?: boolean;
	undoWindowMs?: number;
	accent?: string;

	reducedMotion?: boolean;
	className?: string;
}

export interface ContextMenuState {
	x: number;
	y: number;
	targetPath: string | null;
}

export interface ExplorerState {
	currentPath: StorePath;
	view: ViewMode;
	sortBy: SortKey;
	sortDir: SortDir;
	search: string;
	selection: string[];
	lastSelected: string | null;
	detailPath: string | null;
	renaming: string | null;
	clipboard: string[];
	contextMenu: ContextMenuState | null;
}

export type ExplorerAction =
	| { type: "NAVIGATE"; path: StorePath }
	| { type: "SET_VIEW"; view: ViewMode }
	| { type: "SET_SORT"; sortBy: SortKey; sortDir: SortDir }
	| { type: "TOGGLE_SORT"; sortBy: SortKey }
	| { type: "SET_SEARCH"; search: string }
	| {
			type: "SELECT";
			path: string;
			mode: "single" | "toggle" | "range";
			ordered: string[];
	  }
	| { type: "SELECT_ALL"; ordered: string[] }
	| { type: "CLEAR_SELECTION" }
	| { type: "SET_SELECTION"; paths: string[] }
	| { type: "OPEN_DETAIL"; path: string }
	| { type: "CLOSE_DETAIL" }
	| { type: "BEGIN_RENAME"; path: string }
	| { type: "END_RENAME" }
	| { type: "CUT"; paths: string[] }
	| { type: "CLEAR_CLIPBOARD" }
	| { type: "OPEN_CONTEXT"; x: number; y: number; targetPath: string | null }
	| { type: "CLOSE_CONTEXT" }
	| { type: "SYNC_PROPS"; view?: ViewMode; sortBy?: SortKey; sortDir?: SortDir };

export interface Row {
	node: FileNode;
	selected: boolean;
	cut: boolean;
	renaming: boolean;
}

export interface ItemCallbacks {
	onOpen: (node: FileNode) => void;
	onSelect: (node: FileNode, e: MouseEvent) => void;
	onContextMenu: (node: FileNode, e: MouseEvent) => void;
	onRenameCommit: (node: FileNode, nextName: string) => void;
	onRenameCancel: () => void;
	onItemDragStart: (node: FileNode, e: DragEvent) => void;
	onItemDrop: (node: FileNode, e: DragEvent) => void;
}
```

### 16. `components/registry/file-explorer/use-file-explorer.ts` — supporting file, required

```tsx
"use client";

import { useReducer } from "react";
import type { FileNode } from "./store/types";
import type {
	ExplorerAction,
	ExplorerState,
	FileExplorerProps,
} from "./types";
import { fileExtension, kindForNode } from "./util";

export function initExplorerState(
	props: Pick<FileExplorerProps, "defaultView" | "sortBy" | "sortDir">,
): ExplorerState {
	return {
		currentPath: "",
		view: props.defaultView ?? "grid",
		sortBy: props.sortBy ?? "name",
		sortDir: props.sortDir ?? "asc",
		search: "",
		selection: [],
		lastSelected: null,
		detailPath: null,
		renaming: null,
		clipboard: [],
		contextMenu: null,
	};
}

export function explorerReducer(
	state: ExplorerState,
	action: ExplorerAction,
): ExplorerState {
	switch (action.type) {
		case "NAVIGATE":
			return {
				...state,
				currentPath: action.path,
				selection: [],
				lastSelected: null,
				detailPath: null,
				search: "",
				renaming: null,
				contextMenu: null,
			};

		case "SET_VIEW":
			return { ...state, view: action.view };

		case "SET_SORT":
			return { ...state, sortBy: action.sortBy, sortDir: action.sortDir };

		case "TOGGLE_SORT":
			return {
				...state,
				sortBy: action.sortBy,
				sortDir:
					state.sortBy === action.sortBy
						? state.sortDir === "asc"
							? "desc"
							: "asc"
						: "asc",
			};

		case "SET_SEARCH":
			return { ...state, search: action.search };

		case "SELECT": {
			const { path, mode, ordered } = action;
			if (mode === "single") {
				return { ...state, selection: [path], lastSelected: path, contextMenu: null };
			}
			if (mode === "toggle") {
				const has = state.selection.includes(path);
				return {
					...state,
					selection: has
						? state.selection.filter((p) => p !== path)
						: [...state.selection, path],
					lastSelected: path,
					contextMenu: null,
				};
			}
			const anchor = state.lastSelected ?? path;
			const a = ordered.indexOf(anchor);
			const b = ordered.indexOf(path);
			if (a === -1 || b === -1) {
				return { ...state, selection: [path], lastSelected: path };
			}
			const [lo, hi] = a <= b ? [a, b] : [b, a];
			return {
				...state,
				selection: ordered.slice(lo, hi + 1),
				lastSelected: anchor,
				contextMenu: null,
			};
		}

		case "SELECT_ALL":
			return {
				...state,
				selection: action.ordered,
				lastSelected: action.ordered.at(-1) ?? null,
			};

		case "CLEAR_SELECTION":
			return { ...state, selection: [], lastSelected: null };

		case "SET_SELECTION":
			return {
				...state,
				selection: action.paths,
				lastSelected: action.paths.at(-1) ?? null,
			};

		case "OPEN_DETAIL":
			return {
				...state,
				detailPath: action.path,
				selection: [action.path],
				lastSelected: action.path,
				contextMenu: null,
			};

		case "CLOSE_DETAIL":
			return { ...state, detailPath: null };

		case "BEGIN_RENAME":
			return { ...state, renaming: action.path, contextMenu: null };

		case "END_RENAME":
			return { ...state, renaming: null };

		case "CUT":
			return { ...state, clipboard: action.paths, contextMenu: null };

		case "CLEAR_CLIPBOARD":
			return { ...state, clipboard: [] };

		case "OPEN_CONTEXT": {
			const selection =
				action.targetPath && !state.selection.includes(action.targetPath)
					? [action.targetPath]
					: state.selection;
			return {
				...state,
				selection,
				lastSelected: action.targetPath ?? state.lastSelected,
				contextMenu: {
					x: action.x,
					y: action.y,
					targetPath: action.targetPath,
				},
			};
		}

		case "CLOSE_CONTEXT":
			return { ...state, contextMenu: null };

		case "SYNC_PROPS":
			return {
				...state,
				view: action.view ?? state.view,
				sortBy: action.sortBy ?? state.sortBy,
				sortDir: action.sortDir ?? state.sortDir,
			};

		default:
			return state;
	}
}

export function useFileExplorer(
	props: Pick<FileExplorerProps, "defaultView" | "sortBy" | "sortDir">,
) {
	return useReducer(explorerReducer, props, initExplorerState);
}

export function filterNodes(
	nodes: FileNode[],
	search: string,
	showHidden: boolean,
): FileNode[] {
	let out = showHidden ? nodes : nodes.filter((n) => !n.name.startsWith("."));
	const query = search.trim().toLowerCase();
	if (query) {
		const words = query.split(/\s+/);
		out = out.filter((n) => {
			const hay = n.name.toLowerCase();
			return words.every((w) => hay.includes(w));
		});
	}
	return out;
}

export function sortNodes(
	nodes: FileNode[],
	sortBy: ExplorerState["sortBy"],
	sortDir: ExplorerState["sortDir"],
): FileNode[] {
	const dir = sortDir === "asc" ? 1 : -1;
	return [...nodes].sort((a, b) => {
		if (a.kind !== b.kind) return a.kind === "directory" ? -1 : 1;

		let cmp = 0;
		switch (sortBy) {
			case "name":
				cmp = collate(a.name, b.name);
				break;
			case "date":
				cmp = a.mtime - b.mtime;
				break;
			case "size":
				cmp = a.size - b.size;
				break;
			case "type":
				cmp =
					kindForNode(a).localeCompare(kindForNode(b)) ||
					fileExtension(a.name).localeCompare(fileExtension(b.name));
				break;
		}
		if (cmp === 0) cmp = collate(a.name, b.name);
		return cmp * dir;
	});
}

function collate(a: string, b: string): number {
	return a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" });
}
```

### 17. `components/registry/file-explorer/use-file-store.ts` — supporting file, required

```tsx
"use client";
/* eslint-disable react-hooks/set-state-in-effect --
   These hooks fetch from the async FileStore and reflect loading/results in
   state — legitimate effect-driven synchronization with an external system. */

import { useCallback, useEffect, useRef, useState } from "react";
import { createFileStore } from "./store";
import type {
	FileNode,
	FileStore,
	FileStoreBackend,
	StorageEstimate,
	StorePath,
} from "./store/types";

export type StoreSource = FileStore | (() => Promise<FileStore>);

export interface UseFileStoreResult {
	store: FileStore | null;
	ready: boolean;
	backend: FileStoreBackend | null;
	error: Error | null;
	revision: number;
	reload: () => void;
}

export function useFileStore(
	source: StoreSource | undefined,
	namespace: string,
): UseFileStoreResult {
	const [store, setStore] = useState<FileStore | null>(null);
	const [ready, setReady] = useState(false);
	const [error, setError] = useState<Error | null>(null);
	const [revision, setRevision] = useState(0);

	const sourceRef = useRef(source);
	const namespaceRef = useRef(namespace);

	useEffect(() => {
		let cancelled = false;
		(async () => {
			try {
				const src = sourceRef.current;
				const resolved =
					typeof src === "function"
						? await src()
						: (src ?? (await createFileStore(namespaceRef.current)));
				await resolved.init();
				if (cancelled) return;
				setStore(resolved);
				setReady(true);
			} catch (e) {
				if (cancelled) return;
				setError(e instanceof Error ? e : new Error(String(e)));
				setReady(true);
			}
		})();
		return () => {
			cancelled = true;
		};
	}, []);

	const reload = useCallback(() => setRevision((r) => r + 1), []);

	return {
		store,
		ready,
		backend: store?.backend ?? null,
		error,
		revision,
		reload,
	};
}

export function useDirectory(
	store: FileStore | null,
	dir: StorePath,
	revision: number,
): { entries: FileNode[]; loading: boolean } {
	const [entries, setEntries] = useState<FileNode[]>([]);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		let cancelled = false;
		if (!store) {
			setEntries([]);
			setLoading(true);
			return;
		}
		setLoading(true);
		store
			.list(dir)
			.then((list) => {
				if (cancelled) return;
				setEntries(list);
				setLoading(false);
			})
			.catch(() => {
				if (cancelled) return;
				setEntries([]);
				setLoading(false);
			});
		return () => {
			cancelled = true;
		};
	}, [store, dir, revision]);

	return { entries, loading };
}

export function useStorageEstimate(
	store: FileStore | null,
	revision: number,
): StorageEstimate | null {
	const [estimate, setEstimate] = useState<StorageEstimate | null>(null);

	useEffect(() => {
		let cancelled = false;
		if (!store) {
			setEstimate(null);
			return;
		}
		store
			.estimate()
			.then((e) => {
				if (!cancelled) setEstimate(e);
			})
			.catch(() => {
			});
		return () => {
			cancelled = true;
		};
	}, [store, revision]);

	return estimate;
}
```

### 18. `components/registry/file-explorer/use-object-url.ts` — supporting file, required

```tsx
"use client";
/* eslint-disable react-hooks/set-state-in-effect --
   These effects synchronize an external resource (object URLs / fetched blobs)
   into React state — the canonical, React-docs-blessed use of setState inside
   an effect. The set-state-in-effect heuristic over-flags it here. */

import { useEffect, useState } from "react";
import type { FileNode, FileStore } from "./store/types";

export function useObjectUrl(blob: Blob | null | undefined): string | null {
	const [url, setUrl] = useState<string | null>(null);
	useEffect(() => {
		if (!blob) {
			setUrl(null);
			return;
		}
		const next = URL.createObjectURL(blob);
		setUrl(next);
		return () => URL.revokeObjectURL(next);
	}, [blob]);
	return url;
}

export function useStoredObjectUrl(
	store: FileStore | null,
	node: FileNode | null | undefined,
	enabled = true,
): string | null {
	const [blob, setBlob] = useState<Blob | null>(null);
	const path = node?.path;
	const mtime = node?.mtime;
	const isFile = node?.kind === "file";

	useEffect(() => {
		let cancelled = false;
		if (!store || !enabled || !isFile || path == null) {
			setBlob(null);
			return;
		}
		store
			.read(path)
			.then((b) => {
				if (!cancelled) setBlob(b);
			})
			.catch(() => {
				if (!cancelled) setBlob(null);
			});
		return () => {
			cancelled = true;
		};
	}, [store, path, mtime, isFile, enabled]);

	return useObjectUrl(blob);
}
```

### 19. `components/registry/file-explorer/util.ts` — supporting file, required

```tsx
import type { FileNode } from "./store/types";

export function cn(...parts: Array<string | false | null | undefined>): string {
	return parts.filter(Boolean).join(" ");
}

export function formatBytes(bytes: number): string {
	if (!bytes) return "0 B";
	const units = ["B", "KB", "MB", "GB", "TB"];
	const exp = Math.min(
		Math.floor(Math.log(bytes) / Math.log(1024)),
		units.length - 1,
	);
	const value = bytes / 1024 ** exp;
	return `${value >= 100 || exp === 0 ? Math.round(value) : value.toFixed(1)} ${units[exp]}`;
}

export function formatRelativeTime(mtime: number, now = Date.now()): string {
	if (!mtime) return "—";
	const secs = Math.round((now - mtime) / 1000);
	if (secs < 45) return "just now";
	const mins = Math.round(secs / 60);
	if (mins < 60) return `${mins}m ago`;
	const hrs = Math.round(mins / 60);
	if (hrs < 24) return `${hrs}h ago`;
	const days = Math.round(hrs / 24);
	if (days < 7) return `${days}d ago`;
	return new Date(mtime).toLocaleDateString(undefined, {
		year: "numeric",
		month: "short",
		day: "numeric",
	});
}

export function fileExtension(name: string): string {
	const dot = name.lastIndexOf(".");
	return dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
}

export type FileKind =
	| "directory"
	| "image"
	| "video"
	| "audio"
	| "pdf"
	| "text"
	| "code"
	| "archive"
	| "file";

export function kindForNode(node: FileNode): FileKind {
	if (node.kind === "directory") return "directory";
	const mime = node.mime ?? "";
	if (mime.startsWith("image/")) return "image";
	if (mime.startsWith("video/")) return "video";
	if (mime.startsWith("audio/")) return "audio";
	if (mime === "application/pdf") return "pdf";
	const ext = fileExtension(node.name);
	if (["zip", "tar", "gz", "rar", "7z"].includes(ext)) return "archive";
	if (
		["js", "ts", "tsx", "jsx", "json", "css", "html", "py", "rs", "go", "sh"].includes(
			ext,
		)
	) {
		return "code";
	}
	if (mime.startsWith("text/") || ["txt", "md", "csv", "log"].includes(ext)) {
		return "text";
	}
	return "file";
}

export function isPreviewable(kind: FileKind): boolean {
	return (
		kind === "image" ||
		kind === "video" ||
		kind === "audio" ||
		kind === "text" ||
		kind === "code"
	);
}

export function uniqueName(base: string, taken: Set<string>): string {
	if (!taken.has(base)) return base;
	const dot = base.lastIndexOf(".");
	const stem = dot > 0 ? base.slice(0, dot) : base;
	const ext = dot > 0 ? base.slice(dot) : "";
	let i = 2;
	let candidate = `${stem} (${i})${ext}`;
	while (taken.has(candidate)) {
		i += 1;
		candidate = `${stem} (${i})${ext}`;
	}
	return candidate;
}
```

### 20. `components/registry/file-explorer/store/index.ts` — supporting file, required

```tsx
import { IndexedDbFileStore } from "./idb-store";
import { MemoryFileStore } from "./memory-store";
import { OpfsFileStore } from "./opfs-store";
import type { FileStore } from "./types";

export * from "./types";
export { OpfsFileStore } from "./opfs-store";
export { IndexedDbFileStore } from "./idb-store";
export { MemoryFileStore } from "./memory-store";

export async function createFileStore(namespace: string): Promise<FileStore> {
	if (
		typeof navigator !== "undefined" &&
		navigator.storage &&
		typeof navigator.storage.getDirectory === "function"
	) {
		try {
			const store = new OpfsFileStore(namespace);
			await store.init();
			return store;
		} catch {
		}
	}

	if (typeof indexedDB !== "undefined") {
		try {
			const store = new IndexedDbFileStore(namespace);
			await store.init();
			return store;
		} catch {
		}
	}

	const store = new MemoryFileStore();
	await store.init();
	return store;
}
```

### 21. `components/registry/file-explorer/store/types.ts` — supporting file, required

```tsx
export type StorePath = string;

export type NodeKind = "file" | "directory";

export interface FileNode {
	name: string;
	path: StorePath;
	kind: NodeKind;
	size: number;
	mtime: number;
	mime?: string;
}

export interface StorageEstimate {
	usage: number;
	quota: number;
}

export type FileStoreBackend = "opfs" | "indexeddb" | "memory" | (string & {});

export interface FileStore {
	readonly backend: FileStoreBackend;

	init(): Promise<void>;

	list(dir?: StorePath): Promise<FileNode[]>;

	stat(path: StorePath): Promise<FileNode | null>;

	read(path: StorePath): Promise<Blob>;

	write(path: StorePath, data: Blob, mime?: string): Promise<FileNode>;

	mkdir(path: StorePath): Promise<FileNode>;

	remove(path: StorePath): Promise<void>;

	move(from: StorePath, to: StorePath): Promise<FileNode>;

	rename(path: StorePath, nextName: string): Promise<FileNode>;

	estimate(): Promise<StorageEstimate>;
}

export function segments(path: StorePath): string[] {
	return path.split("/").filter(Boolean);
}

export function joinPath(dir: StorePath, name: string): StorePath {
	return dir ? `${dir}/${name}` : name;
}

export function parentPath(path: StorePath): StorePath {
	const segs = segments(path);
	segs.pop();
	return segs.join("/");
}

export function baseName(path: StorePath): string {
	const segs = segments(path);
	return segs.length ? segs[segs.length - 1] : "";
}

export function guessMime(name: string): string {
	const ext = name.slice(name.lastIndexOf(".") + 1).toLowerCase();
	return MIME_BY_EXT[ext] ?? "";
}

const MIME_BY_EXT: Record<string, string> = {
	png: "image/png",
	jpg: "image/jpeg",
	jpeg: "image/jpeg",
	gif: "image/gif",
	webp: "image/webp",
	avif: "image/avif",
	svg: "image/svg+xml",
	bmp: "image/bmp",
	ico: "image/x-icon",
	mp4: "video/mp4",
	webm: "video/webm",
	mov: "video/quicktime",
	mkv: "video/x-matroska",
	mp3: "audio/mpeg",
	wav: "audio/wav",
	ogg: "audio/ogg",
	flac: "audio/flac",
	m4a: "audio/mp4",
	txt: "text/plain",
	md: "text/markdown",
	json: "application/json",
	csv: "text/csv",
	html: "text/html",
	css: "text/css",
	js: "text/javascript",
	ts: "text/typescript",
	pdf: "application/pdf",
	zip: "application/zip",
};
```

### 22. `components/registry/file-explorer/store/idb-store.ts` — supporting file, required

```tsx
import {
	baseName,
	guessMime,
	joinPath,
	parentPath,
	segments,
	type FileNode,
	type FileStore,
	type FileStoreBackend,
	type StorageEstimate,
	type StorePath,
} from "./types";

interface NodeRecord {
	path: string;
	name: string;
	parent: string;
	kind: "file" | "directory";
	size: number;
	mtime: number;
	mime?: string;
	blobId?: string;
}

interface ChangeSet {
	putNodes?: NodeRecord[];
	deleteNodePaths?: string[];
	putBlobs?: { id: string; blob: Blob }[];
	deleteBlobIds?: string[];
}

const NODES = "nodes";
const BLOBS = "blobs";

function uid(): string {
	if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
		return crypto.randomUUID();
	}
	return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
}

function toNode(rec: NodeRecord): FileNode {
	return {
		name: rec.name,
		path: rec.path,
		kind: rec.kind,
		size: rec.size,
		mtime: rec.mtime,
		mime: rec.mime,
	};
}

function req<T>(request: IDBRequest<T>): Promise<T> {
	return new Promise((resolve, reject) => {
		request.onsuccess = () => resolve(request.result);
		request.onerror = () => reject(request.error);
	});
}

function txDone(tx: IDBTransaction): Promise<void> {
	return new Promise((resolve, reject) => {
		tx.oncomplete = () => resolve();
		tx.onerror = () => reject(tx.error);
		tx.onabort = () => reject(tx.error);
	});
}

export class IndexedDbFileStore implements FileStore {
	readonly backend: FileStoreBackend = "indexeddb";
	private db: IDBDatabase | null = null;
	private opening: Promise<void> | null = null;

	constructor(private readonly namespace: string) {}

	init(): Promise<void> {
		if (this.db) return Promise.resolve();
		if (this.opening) return this.opening;
		this.opening = new Promise<void>((resolve, reject) => {
			const open = indexedDB.open(this.namespace, 1);
			open.onupgradeneeded = () => {
				const db = open.result;
				if (!db.objectStoreNames.contains(NODES)) {
					const nodes = db.createObjectStore(NODES, { keyPath: "path" });
					nodes.createIndex("by_parent", "parent", { unique: false });
				}
				if (!db.objectStoreNames.contains(BLOBS)) {
					db.createObjectStore(BLOBS, { keyPath: "id" });
				}
			};
			open.onsuccess = () => {
				this.db = open.result;
				resolve();
			};
			open.onerror = () => reject(open.error);
		});
		return this.opening;
	}

	private get database(): IDBDatabase {
		if (!this.db) throw new Error("IndexedDbFileStore: init() not awaited");
		return this.db;
	}

	private async allNodes(): Promise<NodeRecord[]> {
		const tx = this.database.transaction(NODES, "readonly");
		return req<NodeRecord[]>(tx.objectStore(NODES).getAll());
	}

	private async apply(change: ChangeSet): Promise<void> {
		const tx = this.database.transaction([NODES, BLOBS], "readwrite");
		const nodes = tx.objectStore(NODES);
		const blobs = tx.objectStore(BLOBS);
		change.deleteBlobIds?.forEach((id) => blobs.delete(id));
		change.putBlobs?.forEach((b) => blobs.put(b));
		change.deleteNodePaths?.forEach((p) => nodes.delete(p));
		change.putNodes?.forEach((n) => nodes.put(n));
		await txDone(tx);
	}

	private missingDirs(
		existing: Set<string>,
		path: StorePath,
		now: number,
		includeSelf: boolean,
	): NodeRecord[] {
		const segs = segments(path);
		const upto = includeSelf ? segs.length : segs.length - 1;
		const out: NodeRecord[] = [];
		let cursor = "";
		for (let i = 0; i < upto; i++) {
			cursor = joinPath(cursor, segs[i]);
			if (!existing.has(cursor)) {
				existing.add(cursor);
				out.push({
					path: cursor,
					name: segs[i],
					parent: parentPath(cursor),
					kind: "directory",
					size: 0,
					mtime: now,
				});
			}
		}
		return out;
	}

	async list(dir: StorePath = ""): Promise<FileNode[]> {
		const tx = this.database.transaction(NODES, "readonly");
		const index = tx.objectStore(NODES).index("by_parent");
		const rows = await req<NodeRecord[]>(index.getAll(IDBKeyRange.only(dir)));
		return rows.map(toNode);
	}

	async stat(path: StorePath): Promise<FileNode | null> {
		if (path === "") {
			return { name: "", path: "", kind: "directory", size: 0, mtime: 0 };
		}
		const tx = this.database.transaction(NODES, "readonly");
		const rec = await req<NodeRecord | undefined>(
			tx.objectStore(NODES).get(path),
		);
		return rec ? toNode(rec) : null;
	}

	async read(path: StorePath): Promise<Blob> {
		const tx = this.database.transaction([NODES, BLOBS], "readonly");
		const rec = await req<NodeRecord | undefined>(
			tx.objectStore(NODES).get(path),
		);
		if (!rec || rec.kind !== "file" || !rec.blobId) {
			throw new Error(`Not a readable file: ${path}`);
		}
		const row = await req<{ id: string; blob: Blob } | undefined>(
			tx.objectStore(BLOBS).get(rec.blobId),
		);
		if (!row) throw new Error(`Missing blob for: ${path}`);
		return row.blob;
	}

	async write(path: StorePath, data: Blob, mime?: string): Promise<FileNode> {
		const now = Date.now();
		const all = await this.allNodes();
		const existing = new Set(all.map((n) => n.path));
		const prior = all.find((n) => n.path === path);
		const blobId = uid();
		const record: NodeRecord = {
			path,
			name: baseName(path),
			parent: parentPath(path),
			kind: "file",
			size: data.size,
			mtime: now,
			mime: mime || data.type || guessMime(baseName(path)),
			blobId,
		};
		await this.apply({
			putBlobs: [{ id: blobId, blob: data }],
			deleteBlobIds: prior?.blobId ? [prior.blobId] : undefined,
			putNodes: [...this.missingDirs(existing, path, now, false), record],
		});
		return toNode(record);
	}

	async mkdir(path: StorePath): Promise<FileNode> {
		const now = Date.now();
		const all = await this.allNodes();
		const existing = new Set(all.map((n) => n.path));
		const dirs = this.missingDirs(existing, path, now, true);
		if (dirs.length) await this.apply({ putNodes: dirs });
		const self =
			all.find((n) => n.path === path) ??
			dirs.find((n) => n.path === path);
		return self
			? toNode(self)
			: { name: baseName(path), path, kind: "directory", size: 0, mtime: now };
	}

	async remove(path: StorePath): Promise<void> {
		if (path === "") return;
		const all = await this.allNodes();
		const prefix = `${path}/`;
		const victims = all.filter(
			(n) => n.path === path || n.path.startsWith(prefix),
		);
		if (!victims.length) return;
		await this.apply({
			deleteNodePaths: victims.map((n) => n.path),
			deleteBlobIds: victims
				.map((n) => n.blobId)
				.filter((id): id is string => Boolean(id)),
		});
	}

	async move(from: StorePath, to: StorePath): Promise<FileNode> {
		if (from === "" || from === to) throw new Error("Invalid move");
		const all = await this.allNodes();
		if (all.some((n) => n.path === to)) {
			throw new Error(`Destination exists: ${to}`);
		}
		const src = all.find((n) => n.path === from);
		if (!src) throw new Error(`Not found: ${from}`);
		const now = Date.now();
		const existing = new Set(all.map((n) => n.path));
		const prefix = `${from}/`;
		const affected = all.filter(
			(n) => n.path === from || n.path.startsWith(prefix),
		);
		const rewritten: NodeRecord[] = affected.map((n) => {
			const nextPath = to + n.path.slice(from.length);
			return {
				...n,
				path: nextPath,
				name: baseName(nextPath),
				parent: parentPath(nextPath),
				mtime: n.path === from ? now : n.mtime,
			};
		});
		await this.apply({
			deleteNodePaths: affected.map((n) => n.path),
			putNodes: [...this.missingDirs(existing, to, now, false), ...rewritten],
		});
		return toNode(rewritten[0]);
	}

	rename(path: StorePath, nextName: string): Promise<FileNode> {
		return this.move(path, joinPath(parentPath(path), nextName));
	}

	async estimate(): Promise<StorageEstimate> {
		if (typeof navigator !== "undefined" && navigator.storage?.estimate) {
			const e = await navigator.storage.estimate();
			return { usage: e.usage ?? 0, quota: e.quota ?? 0 };
		}
		return { usage: 0, quota: 0 };
	}
}
```

### 23. `components/registry/file-explorer/store/memory-store.ts` — supporting file, required

```tsx
import {
	baseName,
	guessMime,
	joinPath,
	parentPath,
	segments,
	type FileNode,
	type FileStore,
	type FileStoreBackend,
	type StorageEstimate,
	type StorePath,
} from "./types";

interface Rec {
	path: string;
	name: string;
	parent: string;
	kind: "file" | "directory";
	size: number;
	mtime: number;
	mime?: string;
	blob?: Blob;
}

function toNode(r: Rec): FileNode {
	return {
		name: r.name,
		path: r.path,
		kind: r.kind,
		size: r.size,
		mtime: r.mtime,
		mime: r.mime,
	};
}

export class MemoryFileStore implements FileStore {
	readonly backend: FileStoreBackend = "memory";
	private nodes = new Map<string, Rec>();

	init(): Promise<void> {
		return Promise.resolve();
	}

	private ensureDirs(path: StorePath, now: number, includeSelf: boolean): void {
		const segs = segments(path);
		const upto = includeSelf ? segs.length : segs.length - 1;
		let cursor = "";
		for (let i = 0; i < upto; i++) {
			cursor = joinPath(cursor, segs[i]);
			if (!this.nodes.has(cursor)) {
				this.nodes.set(cursor, {
					path: cursor,
					name: segs[i],
					parent: parentPath(cursor),
					kind: "directory",
					size: 0,
					mtime: now,
				});
			}
		}
	}

	list(dir: StorePath = ""): Promise<FileNode[]> {
		const out: FileNode[] = [];
		for (const rec of this.nodes.values()) {
			if (rec.parent === dir) out.push(toNode(rec));
		}
		return Promise.resolve(out);
	}

	stat(path: StorePath): Promise<FileNode | null> {
		if (path === "") {
			return Promise.resolve({
				name: "",
				path: "",
				kind: "directory",
				size: 0,
				mtime: 0,
			});
		}
		const rec = this.nodes.get(path);
		return Promise.resolve(rec ? toNode(rec) : null);
	}

	read(path: StorePath): Promise<Blob> {
		const rec = this.nodes.get(path);
		if (!rec || rec.kind !== "file" || !rec.blob) {
			return Promise.reject(new Error(`Not a readable file: ${path}`));
		}
		return Promise.resolve(rec.blob);
	}

	write(path: StorePath, data: Blob, mime?: string): Promise<FileNode> {
		const now = Date.now();
		this.ensureDirs(path, now, false);
		const rec: Rec = {
			path,
			name: baseName(path),
			parent: parentPath(path),
			kind: "file",
			size: data.size,
			mtime: now,
			mime: mime || data.type || guessMime(baseName(path)),
			blob: data,
		};
		this.nodes.set(path, rec);
		return Promise.resolve(toNode(rec));
	}

	mkdir(path: StorePath): Promise<FileNode> {
		const now = Date.now();
		this.ensureDirs(path, now, true);
		return Promise.resolve(
			toNode(
				this.nodes.get(path) ?? {
					path,
					name: baseName(path),
					parent: parentPath(path),
					kind: "directory",
					size: 0,
					mtime: now,
				},
			),
		);
	}

	remove(path: StorePath): Promise<void> {
		if (path === "") return Promise.resolve();
		const prefix = `${path}/`;
		for (const key of [...this.nodes.keys()]) {
			if (key === path || key.startsWith(prefix)) this.nodes.delete(key);
		}
		return Promise.resolve();
	}

	move(from: StorePath, to: StorePath): Promise<FileNode> {
		if (from === "" || from === to) return Promise.reject(new Error("Invalid move"));
		if (this.nodes.has(to)) return Promise.reject(new Error(`Destination exists: ${to}`));
		const src = this.nodes.get(from);
		if (!src) return Promise.reject(new Error(`Not found: ${from}`));
		const now = Date.now();
		this.ensureDirs(to, now, false);
		const prefix = `${from}/`;
		const affected = [...this.nodes.values()].filter(
			(n) => n.path === from || n.path.startsWith(prefix),
		);
		for (const n of affected) this.nodes.delete(n.path);
		let moved: Rec | null = null;
		for (const n of affected) {
			const nextPath = to + n.path.slice(from.length);
			const rec: Rec = {
				...n,
				path: nextPath,
				name: baseName(nextPath),
				parent: parentPath(nextPath),
				mtime: n.path === from ? now : n.mtime,
			};
			this.nodes.set(nextPath, rec);
			if (n.path === from) moved = rec;
		}
		return Promise.resolve(toNode(moved!));
	}

	rename(path: StorePath, nextName: string): Promise<FileNode> {
		return this.move(path, joinPath(parentPath(path), nextName));
	}

	estimate(): Promise<StorageEstimate> {
		let usage = 0;
		for (const rec of this.nodes.values()) usage += rec.size;
		return Promise.resolve({ usage, quota: 0 });
	}
}
```

### 24. `components/registry/file-explorer/store/opfs-store.ts` — supporting file, required

```tsx
import {
	baseName,
	guessMime,
	parentPath,
	segments,
	type FileNode,
	type FileStore,
	type FileStoreBackend,
	type StorageEstimate,
	type StorePath,
} from "./types";

type DirHandle = FileSystemDirectoryHandle & {
	entries(): AsyncIterableIterator<[string, FileSystemHandle]>;
};
type MovableHandle = FileSystemHandle & {
	move?: (
		dest?: FileSystemDirectoryHandle | string,
		name?: string,
	) => Promise<void>;
};

function supportsNativeMove(handle: FileSystemHandle): handle is MovableHandle {
	return typeof (handle as MovableHandle).move === "function";
}

export class OpfsFileStore implements FileStore {
	readonly backend: FileStoreBackend = "opfs";
	private root: FileSystemDirectoryHandle | null = null;
	private opening: Promise<void> | null = null;

	constructor(private readonly namespace: string) {}

	init(): Promise<void> {
		if (this.root) return Promise.resolve();
		if (this.opening) return this.opening;
		this.opening = (async () => {
			const base = await navigator.storage.getDirectory();
			this.root = await base.getDirectoryHandle(this.namespace, {
				create: true,
			});
		})();
		return this.opening;
	}

	private get base(): FileSystemDirectoryHandle {
		if (!this.root) throw new Error("OpfsFileStore: init() not awaited");
		return this.root;
	}

	private async dirAt(
		path: StorePath,
		create: boolean,
	): Promise<FileSystemDirectoryHandle> {
		let handle = this.base;
		for (const seg of segments(path)) {
			handle = await handle.getDirectoryHandle(seg, { create });
		}
		return handle;
	}

	private async handleAt(
		path: StorePath,
	): Promise<{ kind: "file" | "directory"; handle: FileSystemHandle } | null> {
		if (path === "") return { kind: "directory", handle: this.base };
		let parent: FileSystemDirectoryHandle;
		try {
			parent = await this.dirAt(parentPath(path), false);
		} catch {
			return null;
		}
		const name = baseName(path);
		try {
			const file = await parent.getFileHandle(name);
			return { kind: "file", handle: file };
		} catch {
		}
		try {
			const dir = await parent.getDirectoryHandle(name);
			return { kind: "directory", handle: dir };
		} catch {
			return null;
		}
	}

	private async fileNode(
		handle: FileSystemFileHandle,
		path: StorePath,
	): Promise<FileNode> {
		const file = await handle.getFile();
		return {
			name: baseName(path),
			path,
			kind: "file",
			size: file.size,
			mtime: file.lastModified,
			mime: file.type || guessMime(baseName(path)),
		};
	}

	async list(dir: StorePath = ""): Promise<FileNode[]> {
		const handle = (await this.dirAt(dir, false)) as DirHandle;
		const out: FileNode[] = [];
		for await (const [name, child] of handle.entries()) {
			const path = dir ? `${dir}/${name}` : name;
			if (child.kind === "file") {
				out.push(await this.fileNode(child as FileSystemFileHandle, path));
			} else {
				out.push({ name, path, kind: "directory", size: 0, mtime: 0 });
			}
		}
		return out;
	}

	async stat(path: StorePath): Promise<FileNode | null> {
		const found = await this.handleAt(path);
		if (!found) return null;
		if (found.kind === "file") {
			return this.fileNode(found.handle as FileSystemFileHandle, path);
		}
		return { name: baseName(path), path, kind: "directory", size: 0, mtime: 0 };
	}

	async read(path: StorePath): Promise<Blob> {
		const parent = await this.dirAt(parentPath(path), false);
		const handle = await parent.getFileHandle(baseName(path));
		return handle.getFile();
	}

	async write(path: StorePath, data: Blob, mime?: string): Promise<FileNode> {
		const parent = await this.dirAt(parentPath(path), true);
		const handle = await parent.getFileHandle(baseName(path), { create: true });
		const writable = await handle.createWritable();
		await writable.write(data);
		await writable.close();
		return {
			name: baseName(path),
			path,
			kind: "file",
			size: data.size,
			mtime: Date.now(),
			mime: mime || data.type || guessMime(baseName(path)),
		};
	}

	async mkdir(path: StorePath): Promise<FileNode> {
		await this.dirAt(path, true);
		return { name: baseName(path), path, kind: "directory", size: 0, mtime: 0 };
	}

	async remove(path: StorePath): Promise<void> {
		if (path === "") return;
		const parent = await this.dirAt(parentPath(path), false);
		try {
			await parent.removeEntry(baseName(path), { recursive: true });
		} catch {
		}
	}

	async move(from: StorePath, to: StorePath): Promise<FileNode> {
		if (from === "" || from === to) throw new Error("Invalid move");
		if (await this.stat(to)) throw new Error(`Destination exists: ${to}`);
		const found = await this.handleAt(from);
		if (!found) throw new Error(`Not found: ${from}`);

		const destParent = await this.dirAt(parentPath(to), true);
		const destName = baseName(to);

		if (supportsNativeMove(found.handle)) {
			await found.handle.move!(destParent, destName);
		} else {
			await this.copyInto(found, destParent, destName);
			await this.remove(from);
		}
		const node = await this.stat(to);
		if (!node) throw new Error(`Move failed: ${to}`);
		return node;
	}

	private async copyInto(
		src: { kind: "file" | "directory"; handle: FileSystemHandle },
		destParent: FileSystemDirectoryHandle,
		destName: string,
	): Promise<void> {
		if (src.kind === "file") {
			const file = await (src.handle as FileSystemFileHandle).getFile();
			const target = await destParent.getFileHandle(destName, { create: true });
			const writable = await target.createWritable();
			await writable.write(file);
			await writable.close();
			return;
		}
		const targetDir = await destParent.getDirectoryHandle(destName, {
			create: true,
		});
		for await (const [name, child] of (src.handle as DirHandle).entries()) {
			await this.copyInto(
				{ kind: child.kind as "file" | "directory", handle: child },
				targetDir,
				name,
			);
		}
	}

	rename(path: StorePath, nextName: string): Promise<FileNode> {
		const parent = parentPath(path);
		return this.move(path, parent ? `${parent}/${nextName}` : nextName);
	}

	async estimate(): Promise<StorageEstimate> {
		if (navigator.storage?.estimate) {
			const e = await navigator.storage.estimate();
			return { usage: e.usage ?? 0, quota: e.quota ?? 0 };
		}
		return { usage: 0, quota: 0 };
	}
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultView` | `"grid" | "list"` | `"grid"` | Initial content layout. The toolbar toggle overrides it live. |
| `thumbnailSize` | `number` | `112` | Grid tile edge length. Larger tiles, fewer columns. Range 72–220 px. |
| `density` | `"comfortable" | "compact"` | `"comfortable"` | Row height and padding for the list view and folder rail. |
| `sortBy` | `"name" | "date" | "size" | "type"` | `"name"` | Initial sort field. The toolbar sort menu overrides it live. |
| `sortDir` | `"asc" | "desc"` | `"asc"` | Initial sort direction. |
| `showFolderRail` | `boolean` | `true` | Show the left folder-tree rail. |
| `showDetails` | `boolean` | `true` | Open the detail panel when a single file is selected. |
| `showHidden` | `boolean` | `false` | Reveal entries whose name starts with a dot. |
| `allowUpload` | `boolean` | `true` | Enable drag-and-drop and the Add button. Off makes the explorer read-only for new files. |
| `allowDelete` | `boolean` | `true` | Enable delete, rename, and move. Off locks the store's contents. |
| `undoWindowMs` | `number` | `5000` | Grace period to undo a delete. 0 deletes immediately. Range 0–15000 ms. Ignored while `allowDelete` is `false`. |
| `accent` | `string (hex)` | `"#a855f7"` | Selection highlight, active folder, and focus accent. |

## Usage

```tsx
import FileExplorer from "@/components/registry/file-explorer/file-explorer";

<FileExplorer
  defaultView="grid"
  thumbnailSize={112}
  density="comfortable"
  sortBy="name"
  sortDir="asc"
  showFolderRail={true}
  showDetails={true}
  showHidden={false}
  allowUpload={true}
  allowDelete={true}
  undoWindowMs={5000}
  accent="#a855f7"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- The supporting files are part of the component, not examples. Copy every file listed, preserving the directory layout — they import each other by relative path.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
