# File library

> A team’s file library: drag a file row onto a folder tile, its ghost following the pointer, and the folder opens to take it.

A workspace window with a folder tree, a row of folder tiles and a table of loose files. Drag a row onto a folder and a tilted chip follows the pointer; the folder lights up, its frosted front tips forward and the papers inside rise. Drop it and the chip shrinks into the folder, a new paper drops in as its cover, the row folds away and a toast says what moved, with Undo. Tick several rows to drag them as a stack, or use Move to in the bar that rises at the bottom. Files dragged in from the desktop upload into a folder with a progress bar on its front.

A React component by Bruno Delorence: https://brunodelorence.com/components/file-library. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: Dashboards.

## Anatomy

1. **Window**: The workspace window: a 48 px top bar over a 52 px icon rail, the 218 px sidebar and the main column.
2. **Sidebar**: The library’s tree: General with its sub-folders and their counts. Its folders take drops too. Under 720 px it becomes a drawer.
3. **Folder tile**: One sub-folder: its picture, its name and how many files it holds. A drag over it lights it with a blue ring.
4. **Folder picture**: The folder’s back with its tab, its last three files as papers peeking out, the newest in front.
5. **Front panel**: Frosted glass over the papers’ lower half, carrying the members or a Private chip. It tips forward when a file comes over.
6. **File row**: A file loose in General: a tick box, its type’s icon, name, who added it and its size. Drag it by any part but the box.
7. **Selection bar**: Rises at the foot of the column while rows are ticked: the count, Move to, Share and a button that clears the ticks.

## Properties

### Colour scheme (`colorScheme`)

1. **Dark**: Near-black window, graphite folders and frosted glass: a media-heavy library.
2. **Light**: Paper whites with grey folder backs: an office library next to documents.

Leave it out and the library follows the page’s color-scheme. Set it only when the library sits on a surface of the other scheme.

## When to use

- A shared folder where people sort files into sub-folders: a team library, a client’s documents, a project’s assets.
- Moves that happen often and in bulk, where dragging rows onto a folder is faster than opening a dialog for each file.
- A view that has both levels at once: the folders as tiles to drop onto, the loose files as a table to pick from.
- Folders whose contents people recognise at a glance: the cover shows the last files that went in.

## When not to use

- Deep trees where files move several levels away. Use a Move dialog with a folder picker and a search field.
- Hundreds of folders. A row of tiles holds a handful; past that, drop onto the tree in the sidebar or use the Move to menu alone.
- A read-only archive or a download page. Without moves, a plain table with links is lighter.
- Phones as the main place it is used. Dragging works with a held finger, but the Move to menu is the better path there.

### Three ways to move

- **Drag a row onto a tile** or onto the folder in the sidebar’s tree. A mouse drag starts after 4 px of travel; a finger holds for 320 ms first, so a swipe still scrolls.
- **Tick rows, then drag any of them**: the ticked rows go together, as a stack with their count.
- **Tick rows, then Move to** in the bar: a menu of the folders, for the keyboard, for a screen reader and for small screens.
- **Escape** during a drag sends the ghost back to its row; dropping anywhere but a folder does the same.

### Feedback after a move

- **The row folds away** in 240 ms and the rows under it slide up; the Files count drops.
- **The folder changes**: a new paper drops in as its cover, its count goes up and turns blue for a moment, and its row in the tree flashes.
- **A toast with Undo**, which puts the files back where they were in the table and takes the paper out of the folder.

### Files from the desktop

- **Over a tile**, an “Upload to …” pill shows under it; dropped, a bar fills the folder’s front and the count reads the percentage.
- **When it’s done**, a green check shows on the front, the cover takes the new file and the toast says it was added.
- **Upload** in the header picks files from the device; they land in General, at the top of the table.

## Do’s and don’ts

- **Do**: Confirm every move with a toast that names the file and the folder, and offer Undo: a drop is easy to make by mistake, and Undo is cheaper than asking first.
- **Do**: Keep the Move to menu next to drag and drop. Dragging is one way in; the menu works with keys, a screen reader, a switch and a thumb.
- **Caution**: Keep the tiles to a handful. Past what fits, they scroll sideways and the folder a file is going to may be out of view; the tree in the sidebar takes drops for the rest.

## Content

The words are folder and file names, the counts, the toast and the bar.

- **Counts in words** under each tile: `12 files`, `1 file`, `No files`; while uploading, `Uploading 42%`.
- **The toast names both ends**: `Moved Pitch-Deck-v4.pdf to Contracts`, or `Moved 3 files to Contracts` for several. The file’s name is in the stronger colour.
- **Verbs on buttons**: `Move to`, `Share`, `Upload`, `Undo`. No “OK”.
- **File names as they are**, extension included, cut with an ellipsis when the column is narrow; the full name stays in the tick box’s label.

## Installation

Install it with the shadcn CLI, into components/file-library of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/file-library.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

```json
{
  "registries": {
    "@brunodelorence": "https://brunodelorence.com/r/{name}.json"
  }
}
```

```sh
npx shadcn@latest add @brunodelorence/file-library
```

Or copy all the source files below into one folder of your project. Either way it needs React 19.2 and a bundler with CSS Modules (Next.js, Vite).

It has a dark colour scheme. Its colours are CSS light-dark() pairs, kept inside @supports so that builds which rewrite light-dark() for older browsers leave them alone: it follows your page’s color-scheme (light unless the page sets one) or its colorScheme prop, with nothing to configure. Browsers without light-dark() show it light.

## Usage

```tsx
import { FileLibrary } from './file-library';

export function TeamFiles() {
  return (
    <FileLibrary
      autoplay={false}
      onMove={(files, folder) => console.log(`${files.length} → ${folder}`)}
    />
  );
}
```

## States

- **At rest**: Four folders over nine loose files. The tick boxes show on hover, on focus, or once any row is ticked.
- **Rows ticked**: Three rows tinted blue; the bar rises with “3 selected”, Move to and Share.
- **Dragging over a folder**: The ghost chip hangs from the pointer, tilted 3°; its row fades to a third. Contracts is lit, its front tipped forward.
- **Moved**: The row has folded away, Contracts holds 1 file with a new cover, and the toast says what moved, with Undo.
- **Uploading**: A picture dropped from the desktop onto Brand Assets: the bar fills the front and the count reads Uploading 42%.
- **Light**: With `colorScheme="light"`: the same window on paper whites, the folder backs a cool grey and the glass milkier.
- **Narrow**: At 390 px: no rail, the sidebar behind its button as a drawer, the tiles scrolling sideways, owners as faces only.

## How it works

- The drag is pointer events, not native drag and drop, so the ghost can be drawn: a 40 px chip with the file’s icon, name and size, tilted 3°, moved by a transform written straight to its style on each pointer move, with no React render. A mouse drag starts after 4 px; a finger holds 320 ms first, so a swipe still scrolls, and a non-passive touchmove keeps the page still once it has started.
- The folder under the pointer is found with elementFromPoint and the nearest [data-drop], so the tiles and the folders in the sidebar’s tree take drops the same way. Lit, a tile gets a blue ring and glow in 160 ms, its front panel tips forward 24° on its bottom edge (perspective 420 px, a slight overshoot over 280 ms) and its papers rise 6 px.
- Each folder picture is a 134 × 104 SVG back with a tab, its last three files as papers fanned at set offsets, and a frosted front (backdrop-filter blur 9 px) over their lower half. A document is a white page with its type’s coloured square, a picture a gradient card, so the cover changes as files go in.
- On a drop the ghost flies into the folder and shrinks to 35% in 200 ms (Web Animations API); then the new paper drops in from 34 px above on an overshooting curve (460 ms), the row folds from 1fr to 0fr in 240 ms while the rows under it slide up, and the count turns blue for a moment.
- Several ticked rows drag as a stack: two chips fanned behind the first and a blue count badge. Escape, or a drop outside any folder, flies the ghost back to its row in 220 ms.
- The toast comes down 6 px in 220 ms and stays 5 s, held while the pointer or the focus is on it; Undo puts each file back at its old place in the table (the row unfolds) and takes its paper out of the folder.
- Files from the desktop use native drag events: over a tile an “Upload to” pill shows under it, and dropped, a bar fills the front over 1.1 s (fast, then slowing) before the papers go in and a green check pops.
- The selection bar is sticky at the foot of the scrolling column (of the screen on a narrow library) and rises 14 px in 180 ms. Under 720 px of library the rail goes, the sidebar becomes a drawer and the tiles scroll sideways.
- While on screen and untouched, a demo pointer plays the story: one file into Contracts, three ticked and dragged together, then a picture from outside into Brand Assets; then it all resets. Any input stops it.
- Every colour is a token with light-dark(): the dark scheme is near-black with graphite folders, the light one paper whites with cool grey folder backs and milkier glass.

## API reference

- **onMove** (`(files: string[], folder: string, undone: boolean) => void`): Called after files move, with their names and the folder’s; called again with General and undone true when the move is undone.
- **defaultView** (`'rest' | 'selected' | 'dragging' | 'moved' | 'uploading'`, default `'rest'`): Starts at a moment of the story, as a still for docs and screenshots: rows ticked, a file mid-drag over a folder, a file just moved with its toast, or an upload under way. Anything but rest turns the demo off.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer drags files into folders; any input from the reader stops it.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): A class for the outer stage.

## Accessibility

### Keyboard

- Tab reaches each row’s tick box; Space ticks it. Once a row is ticked, the bar’s Move to button is the next stop after the table.
- Move to opens a menu with the focus on the first folder: the arrows, Home and End move, Enter moves the ticked files there, Escape closes it and returns to the button.
- After a move the focus waits on the table’s Select all box, since the bar goes away with the selection. Undo in the toast is a button too.
- Escape cancels a drag in progress, and closes the sidebar’s drawer on a narrow library.

### Screen readers

- The files are a `table` with column headers; each tick box is named “Select Pitch-Deck-v4.pdf”. Each tile is a list item named with its folder, its count and whether it is private.
- A polite live region says each drag, move, undo and upload: “Moved 3 files to Contracts.” The selection bar’s count is live too.
- The folder pictures, the ghost, the icons and the demo pointer are hidden from screen readers; the closed drawer and the hidden bar are inert.

### Pointer and touch

A drag needs a press and a move, so the Move to menu is the single-pointer alternative WCAG 2.5.7 asks for. On touch, a 320 ms hold starts the drag and a moving finger scrolls instead; a tap ticks the row.

### Motion

With reduced motion, rows go and come back at once, the papers appear without dropping in, the front doesn’t tip, the ghost doesn’t fly and the demo doesn’t play. The ring and the toast still say what happened.

### In this build

- Dragging has a keyboard and single-pointer alternative (WCAG 2.5.7): tick rows with Space, then Move to in the selection bar opens a menu of the folders; arrows, Home and End move, Enter moves the files, Escape closes.
- The files are a table with column headers; each tick box is named after its file. Each folder tile is a list item named with its count and whether it is private.
- A polite live region says each drag, move, undo and upload (“Moved 3 files to Contracts.”); the bar’s count is live too.
- Escape cancels a drag and closes the sidebar’s drawer. After a move from the menu the focus waits on Select all, since the bar goes away.
- The toast holds open while the pointer or the focus is on it, so Undo can be reached in time.
- Every control shows a focus ring. The folder pictures, the ghost, the icons and the demo pointer are hidden from screen readers; the closed drawer and the hidden bar are inert.
- With reduced motion, rows go and come at once, nothing flies, tips or drops in, and the demo does not play.

## Source

### file-library/file-library.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useEffectEvent,
  useId,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import {
  DEMO_UPLOAD,
  FILES,
  FOLDERS,
  GENERAL_COUNT,
  OTHER_FOLDERS,
  PEOPLE,
  SHARED_FOLDERS,
  formatSize,
  huesOf,
  kindOf,
  type FileItem,
  type Folder,
  type Kind,
  type Paper,
} from './data';
import { DemoPointer, runDemo, type Flight, type Point } from './demo-pointer';
import { Avatar, FolderArt } from './folder-art';
import { Icon } from './icons';
import { useAutoplay } from './use-autoplay';
import styles from './file-library.module.css';

/*
 * File library: a workspace's General folder, its sub-folders as tiles over a table of the files
 * loose in it. Drag a file row onto a tile (or onto the folder in the sidebar's tree) to move it
 * there; tick several rows and drag any of them to move them all.
 *
 * - The drag is pointer events, not native drag and drop, so the ghost can be drawn: a chip with
 *   the file's icon, name and size, tilted 3°, that follows the pointer; several files make a
 *   stack of chips with their count. The row it came from fades to a third while it flies.
 * - A tile under the ghost lifts: a blue ring and glow, its front panel tips forward on its
 *   bottom edge and the papers inside rise, so the folder looks opened for the file.
 * - Dropped, the ghost shrinks into the folder (200 ms), a new paper drops in as the folder's
 *   cover, the row folds away (240 ms) and the rows under it slide up. The count changes, the
 *   folder's row in the tree flashes, and a toast says what moved, with Undo for 5 s.
 * - Files dragged in from the desktop go onto a tile the same way; an "Upload to" pill shows
 *   under it, and dropped, a progress bar fills the front before the new cover goes in.
 * - The keyboard way: tick rows with Space, then Move to in the bar that rises at the bottom
 *   opens a menu of the folders. A polite live region says every move, undo and upload.
 * - While on screen and untouched, a demo pointer plays the reference's story: one file into
 *   Contracts, three ticked and dragged together, then a picture from outside into Brand Assets.
 */

type Drag =
  | { kind: 'files'; ids: string[]; name: string; size: string; fileKind: Kind }
  | { kind: 'upload'; name: string; size: string; hues: [number, number] };

type Move = {
  folder: string;
  items: { file: FileItem; index: number }[];
  papers: string[];
};

type Toast = {
  id: number;
  lead: string;
  rest: string;
  undo?: Move;
};

type Upload = { progress: number; label: string };

/** How long things take, in ms, measured from the reference at 10 frames a second. */
const ROW_OUT = 240;
const ROW_IN = 300;
const INTO_FOLDER = 200;
const BACK_TO_ROW = 220;
const UPLOAD_TIME = 1100;
const TOAST_TIME = 5000;
const FLASH_TIME = 1100;
/** A mouse drag starts after this many px; a finger holds this long first. */
const SLOP = 4;
const HOLD = 320;
/** Where the ghost hangs from the pointer: the chip by its middle-left, a picture by a corner. */
const GRAB = { files: { x: 96, y: 20 }, upload: { x: 18, y: 16 } };

const isImage = (kind: Kind) => kind === 'image';

/** The folder a drop target stands for: a tile's is its id, a tree row's is `tree:` and the id. */
const folderOf = (drop: string | null) => drop?.replace(/^tree:/, '') ?? null;

function plural(count: number, word: string) {
  return `${count} ${word}${count === 1 ? '' : 's'}`;
}

function filesLabel(folder: Folder, uploading: Upload | undefined) {
  if (uploading) return `Uploading ${Math.round(uploading.progress)}%`;
  return folder.count === 0 ? 'No files' : plural(folder.count, 'file');
}

/** A moment to start in, as a still for docs and screenshots. */
export type LibraryView = 'rest' | 'selected' | 'dragging' | 'moved' | 'uploading';

/** The library as a still view starts: which files, folders, ticks, toast and drag. */
function startOf(view: LibraryView) {
  const moved = view === 'moved';
  return {
    files: moved ? FILES.filter((file) => file.id !== 'f1') : FILES,
    folders: FOLDERS.map((folder) =>
      moved && folder.id === 'contracts'
        ? { ...folder, count: 1, papers: [{ id: 'still-paper', kind: 'pdf' as Kind }] }
        : folder,
    ),
    selected: new Set(view === 'selected' ? ['f2', 'f3', 'f4'] : []),
    toast: moved
      ? { id: 0, lead: 'Moved Pitch-Deck-v4.pdf', rest: ' to Contracts' }
      : (null as Toast | null),
    drag:
      view === 'dragging'
        ? ({
            kind: 'files',
            ids: ['f1'],
            name: FILES[0].name,
            size: FILES[0].size,
            fileKind: 'pdf',
          } as Drag)
        : null,
    over: view === 'dragging' ? 'contracts' : null,
    uploads:
      view === 'uploading'
        ? ({ brand: { progress: 42, label: DEMO_UPLOAD.name } } as Record<string, Upload>)
        : {},
  };
}

export function FileLibrary({
  autoplay = true,
  defaultView = 'rest',
  onMove,
  colorScheme,
  className = '',
}: {
  /** While on screen and untouched, a demo pointer drags files into folders. */
  autoplay?: boolean;
  /**
   * Starts at a moment of the story, as a still for docs and screenshots: rows ticked with the
   * bar up, a file mid-drag over a folder, a file just moved with its toast, or an upload under
   * way. Anything but 'rest' turns the autoplay demo off; the library works from there as usual.
   */
  defaultView?: LibraryView;
  /** Called after files move, with their names and the folder's (and again, reversed, on Undo). */
  onMove?: (files: string[], folder: string, undone: boolean) => void;
  /** Light or dark colours, or the reader's ('system'); without it, the page's color-scheme. */
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const { ref: root, playing, take } = useAutoplay<HTMLDivElement>();
  const [start] = useState(() => startOf(defaultView));
  const [files, setFiles] = useState<FileItem[]>(start.files);
  const [folders, setFolders] = useState<Folder[]>(start.folders);
  const [leaving, setLeaving] = useState<ReadonlySet<string>>(new Set());
  const [entering, setEntering] = useState<ReadonlySet<string>>(new Set());
  const [fresh, setFresh] = useState<ReadonlySet<string>>(new Set());
  const [selected, setSelected] = useState<ReadonlySet<string>>(start.selected);
  const [barCount, setBarCount] = useState(start.selected.size);
  const [drag, setDrag] = useState<Drag | null>(start.drag);
  const [over, setOver] = useState<string | null>(start.over);
  /** Files from the desktop are over the library: the tiles take uploads. */
  const [native, setNative] = useState(false);
  const [toast, setToast] = useState<Toast | null>(start.toast);
  const [uploads, setUploads] = useState<Record<string, Upload>>(start.uploads);
  const [done, setDone] = useState<string | null>(null);
  const [flash, setFlash] = useState<string | null>(null);
  const [menu, setMenu] = useState(false);
  const [query, setQuery] = useState('');
  const [tab, setTab] = useState<'folders' | 'shared'>('folders');
  const [generalOpen, setGeneralOpen] = useState(true);
  /** The sidebar: hidden by its button on a wide library, a drawer on a narrow one. */
  const [collapsed, setCollapsed] = useState(false);
  const [drawer, setDrawer] = useState(false);
  const [narrow, setNarrow] = useState(false);
  const [message, setMessage] = useState('');

  const ids = useId();
  const pointer = useRef<HTMLSpanElement>(null);
  const ghost = useRef<HTMLDivElement>(null);
  const strip = useRef<HTMLUListElement>(null);
  const moveButton = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const fileInput = useRef<HTMLInputElement>(null);
  const rowsGroup = useRef<HTMLDivElement>(null);
  const toastSlot = useRef<HTMLDivElement>(null);
  const rows = useRef(new Map<string, HTMLDivElement>());
  const tiles = useRef(new Map<string, HTMLLIElement>());
  /** Where the ghost's top-left is, in the stage's px. */
  const ghostAt = useRef<Point>({ x: 0, y: 0 });
  const overRef = useRef<string | null>(start.over);
  const dragRef = useRef<Drag | null>(start.drag);
  /** Rows on their way out: Undo takes them back before they go. */
  const removing = useRef(new Set<string>());
  const timers = useRef(new Set<number>());
  const toastTimer = useRef(0);
  const toastId = useRef(0);
  const paperId = useRef(0);
  const press = useRef<{
    id: string;
    pointerId: number;
    x: number;
    y: number;
    touch: boolean;
    hold: number;
    started: boolean;
  } | null>(null);
  const reduced = useRef(false);

  /** Repeats are made to differ, so screen readers announce them again. */
  const announce = (text: string) => setMessage((now) => (now === text ? `${text} ` : text));

  const later = (fn: () => void, ms: number) => {
    const timer = window.setTimeout(() => {
      timers.current.delete(timer);
      fn();
    }, ms);
    timers.current.add(timer);
  };

  useEffect(() => {
    const all = timers.current;
    return () => {
      all.forEach((timer) => window.clearTimeout(timer));
      window.clearTimeout(toastTimer.current);
    };
  }, []);

  useEffect(() => {
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const read = () => (reduced.current = motion.matches);
    read();
    motion.addEventListener('change', read);
    return () => motion.removeEventListener('change', read);
  }, []);

  // Narrow or wide, from the library's own width: the sidebar is a drawer under 720 px.
  useLayoutEffect(() => {
    const element = root.current;
    if (!element) return;
    const observer = new ResizeObserver(([entry]) => {
      const isNarrow = entry.contentRect.width < 720;
      setNarrow(isNarrow);
      if (!isNarrow) setDrawer(false);
    });
    observer.observe(element);
    return () => observer.disconnect();
  }, [root]);

  // --- The toast ----------------------------------------------------------------------------

  const armToast = () => {
    window.clearTimeout(toastTimer.current);
    toastTimer.current = window.setTimeout(() => setToast(null), TOAST_TIME);
  };
  const showToast = (next: Omit<Toast, 'id'>) => {
    toastId.current += 1;
    setToast({ ...next, id: toastId.current });
    armToast();
  };

  // --- Moving files -------------------------------------------------------------------------

  const flashFolder = (id: string) => {
    setFlash(id);
    later(() => setFlash((now) => (now === id ? null : now)), FLASH_TIME);
  };

  const addPapers = (folderId: string, papers: Paper[], count: number) => {
    setFolders((all) =>
      all.map((folder) =>
        folder.id === folderId
          ? { ...folder, count: folder.count + count, papers: [...folder.papers, ...papers] }
          : folder,
      ),
    );
    const added = papers.map((paper) => paper.id);
    setFresh((now) => new Set([...now, ...added]));
    later(() => setFresh((now) => new Set([...now].filter((id) => !added.includes(id)))), 700);
    flashFolder(folderId);
  };

  const paperFor = (kind: Kind, name: string, hues?: readonly [number, number]): Paper => {
    paperId.current += 1;
    return {
      id: `paper-${paperId.current}`,
      kind,
      hues: isImage(kind) ? [...(hues ?? huesOf(name))] : undefined,
    };
  };

  /** Moves the files `wanted` (in table order) into a folder. */
  const moveFiles = (wanted: string[], folderId: string) => {
    const folder = folders.find((each) => each.id === folderId);
    const moving = files
      .map((file, index) => ({ file, index }))
      .filter(({ file }) => wanted.includes(file.id) && !removing.current.has(file.id));
    if (!folder || moving.length === 0) return;
    const papers = moving.map(({ file }) => paperFor(file.kind, file.name));
    addPapers(folderId, papers, moving.length);
    const gone = moving.map(({ file }) => file.id);
    gone.forEach((id) => removing.current.add(id));
    setLeaving((now) => new Set([...now, ...gone]));
    setSelected((now) => new Set([...now].filter((id) => !gone.includes(id))));
    later(
      () => {
        const still = gone.filter((id) => removing.current.has(id));
        still.forEach((id) => removing.current.delete(id));
        setFiles((all) => all.filter((file) => !still.includes(file.id)));
        setLeaving((now) => new Set([...now].filter((id) => !gone.includes(id))));
      },
      reduced.current ? 0 : ROW_OUT,
    );
    const lead = moving.length === 1 ? moving[0].file.name : plural(moving.length, 'file');
    showToast({
      lead: `Moved ${lead}`,
      rest: ` to ${folder.name}`,
      undo: { folder: folderId, items: moving, papers: papers.map((paper) => paper.id) },
    });
    announce(`Moved ${lead} to ${folder.name}.`);
    onMove?.(
      moving.map(({ file }) => file.name),
      folder.name,
      false,
    );
  };

  const undo = (move: Move) => {
    const folder = folders.find((each) => each.id === move.folder);
    setFolders((all) =>
      all.map((each) =>
        each.id === move.folder
          ? {
              ...each,
              count: each.count - move.items.length,
              papers: each.papers.filter((paper) => !move.papers.includes(paper.id)),
            }
          : each,
      ),
    );
    const back = move.items.map(({ file }) => file.id);
    back.forEach((id) => removing.current.delete(id));
    setLeaving((now) => new Set([...now].filter((id) => !back.includes(id))));
    setFiles((all) => {
      const next = [...all];
      for (const { file, index } of [...move.items].sort((a, b) => a.index - b.index)) {
        if (!next.some((each) => each.id === file.id))
          next.splice(Math.min(index, next.length), 0, file);
      }
      return next;
    });
    setEntering((now) => new Set([...now, ...back]));
    later(() => setEntering((now) => new Set([...now].filter((id) => !back.includes(id)))), ROW_IN);
    window.clearTimeout(toastTimer.current);
    setToast(null);
    const lead = move.items.length === 1 ? move.items[0].file.name : plural(back.length, 'files');
    announce(`${lead} back in General${folder ? `, out of ${folder.name}` : ''}.`);
    onMove?.(
      move.items.map(({ file }) => file.name),
      'General',
      true,
    );
  };

  // --- Uploads ------------------------------------------------------------------------------

  /** Plays an upload into a folder: the bar fills, then the new papers drop in. */
  const uploadInto = (
    folderId: string,
    items: { name: string; kind: Kind; hues?: readonly [number, number] }[],
  ) => {
    const folder = folders.find((each) => each.id === folderId);
    if (!folder || items.length === 0 || uploads[folderId]) return;
    const label = items.length === 1 ? items[0].name : plural(items.length, 'file');
    const started = performance.now();
    const time = reduced.current ? 300 : UPLOAD_TIME;
    announce(`Uploading ${label} to ${folder.name}.`);
    setUploads((all) => ({ ...all, [folderId]: { progress: 0, label } }));
    const tick = () => {
      const t = Math.min(1, (performance.now() - started) / time);
      // Fast at first, slowing near the end, as uploads look.
      const progress = 100 * (1 - (1 - t) ** 2);
      if (t < 1) {
        setUploads((all) => ({ ...all, [folderId]: { progress, label } }));
        later(tick, 50);
        return;
      }
      setUploads((all) => {
        const next = { ...all };
        delete next[folderId];
        return next;
      });
      addPapers(
        folderId,
        items.map((item) => paperFor(item.kind, item.name, item.hues)),
        items.length,
      );
      setDone(folderId);
      later(() => setDone((now) => (now === folderId ? null : now)), 1600);
      showToast({ lead: label, rest: ` added to ${folder.name}` });
      announce(`${label} added to ${folder.name}.`);
    };
    later(tick, 50);
  };

  /** Files picked with Upload land in General, at the top of the table. */
  const uploadHere = (picked: File[]) => {
    if (picked.length === 0) return;
    const added: FileItem[] = picked.map((file, index) => ({
      id: `up-${Date.now()}-${index}`,
      name: file.name,
      kind: kindOf(file.name),
      owner: 'you',
      size: formatSize(file.size),
    }));
    setFiles((all) => [...added, ...all]);
    const fresh = added.map((file) => file.id);
    setEntering((now) => new Set([...now, ...fresh]));
    later(
      () => setEntering((now) => new Set([...now].filter((id) => !fresh.includes(id)))),
      ROW_IN,
    );
    const label = added.length === 1 ? added[0].name : plural(added.length, 'file');
    showToast({ lead: label, rest: ' added to General' });
    announce(`${label} added to General.`);
  };

  // --- The drag -----------------------------------------------------------------------------

  /** A point on the page, in the stage's own px (the docs may draw it scaled). */
  const local = (clientX: number, clientY: number): Point => {
    const stage = root.current;
    if (!stage) return { x: clientX, y: clientY };
    const rect = stage.getBoundingClientRect();
    const scale = rect.width / stage.offsetWidth || 1;
    return { x: (clientX - rect.left) / scale, y: (clientY - rect.top) / scale };
  };
  const centreOf = (element: Element, dx = 0.5, dy = 0.5): Point => {
    const rect = element.getBoundingClientRect();
    return local(rect.left + rect.width * dx, rect.top + rect.height * dy);
  };

  const placeGhost = (at: Point, kind: Drag['kind']) => {
    const grab = GRAB[kind];
    ghostAt.current = { x: at.x - grab.x, y: at.y - grab.y };
    if (ghost.current)
      ghost.current.style.transform = `translate(${ghostAt.current.x}px, ${ghostAt.current.y}px)`;
  };

  const beginDrag = (next: Drag, at: Point) => {
    dragRef.current = next;
    setDrag(next);
    setMenu(false);
    placeGhost(at, next.kind);
    if (next.kind === 'files')
      announce(
        `Dragging ${next.ids.length === 1 ? next.name : plural(next.ids.length, 'file')}. Drop it on a folder, or press Escape.`,
      );
  };

  const setOverFolder = (id: string | null) => {
    if (overRef.current === id) return;
    overRef.current = id;
    setOver(id);
  };

  // The ghost mounts with the drag: put it where the drag starts before it paints. A still that
  // starts mid-drag hangs it over its folder.
  useLayoutEffect(() => {
    const tile = tiles.current.get(overRef.current ?? '');
    if (drag && tile && ghostAt.current.x === 0 && ghostAt.current.y === 0)
      placeGhost(centreOf(tile, 0.55, 0.42), drag.kind);
    if (drag && ghost.current)
      ghost.current.style.transform = `translate(${ghostAt.current.x}px, ${ghostAt.current.y}px)`;
    // centreOf and placeGhost only read refs and the page.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [drag]);

  const endDrag = () => {
    dragRef.current = null;
    overRef.current = null;
    setDrag(null);
    setOver(null);
  };

  /** The ghost flies to `to` and fades, then `then` runs. */
  const flyGhost = (to: Point, scale: number, ms: number, then: () => void) => {
    const element = ghost.current;
    if (!element || reduced.current) {
      then();
      return;
    }
    const from = ghostAt.current;
    const box = { w: element.offsetWidth, h: element.offsetHeight };
    const end = { x: to.x - box.w / 2, y: to.y - box.h / 2 };
    const animation = element.animate(
      [
        { transform: `translate(${from.x}px, ${from.y}px) scale(1)`, opacity: 1 },
        { transform: `translate(${end.x}px, ${end.y}px) scale(${scale})`, opacity: 0 },
      ],
      { duration: ms, easing: 'cubic-bezier(0.4, 0, 0.7, 1)', fill: 'forwards' },
    );
    animation.finished.then(
      () => {
        then();
        animation.cancel();
      },
      () => then(),
    );
  };

  const drop = () => {
    const current = dragRef.current;
    const target = folderOf(overRef.current);
    if (!current) return;
    if (!target) {
      cancelDrag();
      return;
    }
    // Onto a tile, the ghost flies into its picture; onto the tree, it fades where it is.
    const tile = overRef.current === target ? tiles.current.get(target) : null;
    const art = tile?.querySelector('[data-part="folder-art"]');
    const finish = () => {
      if (current.kind === 'files') moveFiles(current.ids, target);
      else uploadInto(target, [{ name: current.name, kind: 'image', hues: current.hues }]);
      endDrag();
    };
    if (art) flyGhost(centreOf(art, 0.5, 0.35), 0.35, INTO_FOLDER, finish);
    else {
      const from = ghostAt.current;
      const box = ghost.current;
      flyGhost(
        { x: from.x + (box?.offsetWidth ?? 0) / 2, y: from.y + (box?.offsetHeight ?? 0) / 2 },
        0.6,
        INTO_FOLDER,
        finish,
      );
    }
  };

  const cancelDrag = () => {
    const current = dragRef.current;
    if (!current) return;
    const row = current.kind === 'files' ? rows.current.get(current.ids[0]) : null;
    const name = row?.querySelector('[data-part="file-name"]');
    announce('Move cancelled.');
    if (name) {
      const rect = name.getBoundingClientRect();
      const box = ghost.current;
      const start = local(rect.left, rect.top + rect.height / 2);
      flyGhost(
        {
          x: start.x - 36 + (box?.offsetWidth ?? 0) / 2,
          y: start.y,
        },
        1,
        BACK_TO_ROW,
        endDrag,
      );
    } else endDrag();
  };

  const hitTest = (clientX: number, clientY: number) => {
    const element = document.elementFromPoint(clientX, clientY);
    const target = element?.closest<HTMLElement>('[data-drop]');
    return target && root.current?.contains(target) ? (target.dataset.drop ?? null) : null;
  };

  const release = () => {
    if (press.current) window.clearTimeout(press.current.hold);
    press.current = null;
  };

  // The reader's drag: pointer down on a row, then a few px of travel (or a held finger).
  const onWindowMove = useEffectEvent((event: PointerEvent) => {
    const pressed = press.current;
    if (!pressed || event.pointerId !== pressed.pointerId) return;
    if (!pressed.started) {
      const far = Math.hypot(event.clientX - pressed.x, event.clientY - pressed.y);
      if (pressed.touch) {
        // A finger that moves before the hold is scrolling, not dragging.
        if (far > 8) release();
        return;
      }
      if (far < SLOP) return;
      startReaderDrag(event.clientX, event.clientY);
    }
    placeGhost(local(event.clientX, event.clientY), 'files');
    setOverFolder(hitTest(event.clientX, event.clientY));
  });
  const onWindowUp = useEffectEvent((event: PointerEvent) => {
    const pressed = press.current;
    if (!pressed || event.pointerId !== pressed.pointerId) return;
    const started = pressed.started;
    release();
    if (started) {
      if (event.type === 'pointercancel') cancelDrag();
      else drop();
    } else if (event.type === 'pointerup') toggle(pressed.id);
  });
  const onWindowKey = useEffectEvent((event: KeyboardEvent) => {
    if (event.key === 'Escape' && dragRef.current) {
      event.preventDefault();
      release();
      cancelDrag();
    } else if (event.key === 'Escape' && narrow && drawer) {
      // Escape closes the drawer, wherever the focus is.
      setDrawer(false);
    }
  });
  // While dragging with a finger, the page must not scroll under it.
  const onTouchMove = useEffectEvent((event: TouchEvent) => {
    if (press.current?.started) event.preventDefault();
  });

  useEffect(() => {
    const move = (event: PointerEvent) => onWindowMove(event);
    const up = (event: PointerEvent) => onWindowUp(event);
    const key = (event: KeyboardEvent) => onWindowKey(event);
    const touch = (event: TouchEvent) => onTouchMove(event);
    window.addEventListener('pointermove', move);
    window.addEventListener('pointerup', up);
    window.addEventListener('pointercancel', up);
    window.addEventListener('keydown', key);
    window.addEventListener('touchmove', touch, { passive: false });
    return () => {
      window.removeEventListener('pointermove', move);
      window.removeEventListener('pointerup', up);
      window.removeEventListener('pointercancel', up);
      window.removeEventListener('keydown', key);
      window.removeEventListener('touchmove', touch);
    };
  }, []);

  const startReaderDrag = (clientX: number, clientY: number) => {
    const pressed = press.current;
    if (!pressed) return;
    const file = files.find((each) => each.id === pressed.id);
    if (!file) return;
    pressed.started = true;
    // A ticked row takes the other ticked rows with it.
    const group = selected.has(file.id)
      ? files.filter((each) => selected.has(each.id)).map((each) => each.id)
      : [file.id];
    beginDrag(
      { kind: 'files', ids: group, name: file.name, size: file.size, fileKind: file.kind },
      local(clientX, clientY),
    );
  };

  const onRowDown = useEffectEvent((event: PointerEvent) => {
    const row = (event.target as HTMLElement).closest<HTMLElement>('[data-file]');
    const id = row?.dataset.file;
    if (!id || event.button !== 0 || dragRef.current || removing.current.has(id)) return;
    if ((event.target as HTMLElement).closest('input, button')) return;
    const touch = event.pointerType === 'touch';
    release();
    press.current = {
      id,
      pointerId: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      touch,
      hold: 0,
      started: false,
    };
    if (touch) {
      const { clientX, clientY } = event;
      press.current.hold = window.setTimeout(() => {
        startReaderDrag(clientX, clientY);
        if (press.current?.started) {
          placeGhost(local(clientX, clientY), 'files');
          navigator.vibrate?.(8);
        }
      }, HOLD);
    } else event.preventDefault();
  });

  // Files from the desktop: the tiles and the tree's folders take them as uploads.
  const onNativeOver = useEffectEvent((event: DragEvent) => {
    if (!event.dataTransfer?.types.includes('Files')) return;
    const target = (event.target as HTMLElement).closest<HTMLElement>('[data-drop]');
    setNative(true);
    if (target) {
      event.preventDefault();
      event.dataTransfer.dropEffect = 'copy';
    } else event.dataTransfer.dropEffect = 'none';
    setOverFolder(target?.dataset.drop ?? null);
  });
  const onNativeLeave = useEffectEvent((event: DragEvent) => {
    if (!root.current?.contains(event.relatedTarget as Node | null)) {
      setNative(false);
      setOverFolder(null);
    }
  });
  const onNativeDrop = useEffectEvent((event: DragEvent) => {
    const target = folderOf(overRef.current);
    setNative(false);
    setOverFolder(null);
    if (!target || !event.dataTransfer?.files.length) return;
    event.preventDefault();
    take();
    uploadInto(
      target,
      [...event.dataTransfer.files].map((file) => ({ name: file.name, kind: kindOf(file.name) })),
    );
  });

  // Listened to natively: the rows' presses, files from the desktop, and the toast's hover and
  // focus (which hold it open).
  const onToastHold = useEffectEvent((hold: boolean) => {
    if (hold) window.clearTimeout(toastTimer.current);
    else if (toast) armToast();
  });
  useEffect(() => {
    const element = root.current;
    const list = rowsGroup.current;
    const slot = toastSlot.current;
    if (!element || !list || !slot) return;
    const down = (event: PointerEvent) => onRowDown(event);
    const over = (event: DragEvent) => onNativeOver(event);
    const leave = (event: DragEvent) => onNativeLeave(event);
    const dropped = (event: DragEvent) => onNativeDrop(event);
    const hold = () => onToastHold(true);
    const free = (event: Event) => {
      const next = (event as FocusEvent).relatedTarget as Node | null;
      if (event.type === 'focusout' && slot.contains(next)) return;
      onToastHold(false);
    };
    list.addEventListener('pointerdown', down);
    element.addEventListener('dragover', over);
    element.addEventListener('dragleave', leave);
    element.addEventListener('drop', dropped);
    slot.addEventListener('pointerenter', hold);
    slot.addEventListener('pointerleave', free);
    slot.addEventListener('focusin', hold);
    slot.addEventListener('focusout', free);
    return () => {
      list.removeEventListener('pointerdown', down);
      element.removeEventListener('dragover', over);
      element.removeEventListener('dragleave', leave);
      element.removeEventListener('drop', dropped);
      slot.removeEventListener('pointerenter', hold);
      slot.removeEventListener('pointerleave', free);
      slot.removeEventListener('focusin', hold);
      slot.removeEventListener('focusout', free);
    };
  }, [root]);

  // --- Selection and the bar ------------------------------------------------------------------

  /** Sets the ticks; the bar keeps the last count it showed while it slides away. */
  const choose = (next: ReadonlySet<string>) => {
    setSelected(next);
    if (next.size > 0) setBarCount(next.size);
  };
  const toggle = (id: string) => {
    if (removing.current.has(id)) return;
    const next = new Set(selected);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    choose(next);
  };
  const clearSelection = () => {
    setSelected(new Set());
    setMenu(false);
  };

  const shown = files.filter((file) =>
    file.name.toLowerCase().includes(query.trim().toLowerCase()),
  );
  const selectedCount = files.filter((file) => selected.has(file.id)).length;
  const allShownSelected = shown.length > 0 && shown.every((file) => selected.has(file.id));

  const menuOpen = menu && selectedCount > 0;

  // The menu closes on a press elsewhere, and takes the focus to its first folder as it opens.
  useEffect(() => {
    if (!menuOpen) return;
    menuRef.current?.querySelector<HTMLElement>('[role="menuitem"]')?.focus();
    const onDown = (event: PointerEvent) => {
      const target = event.target as Node;
      if (!menuRef.current?.contains(target) && !moveButton.current?.contains(target))
        setMenu(false);
    };
    document.addEventListener('pointerdown', onDown);
    return () => document.removeEventListener('pointerdown', onDown);
  }, [menuOpen]);

  const onMenuKey = (event: ReactKeyboardEvent) => {
    const items = [...(menuRef.current?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [])];
    const index = items.indexOf(document.activeElement as HTMLElement);
    const go = (next: number) => {
      event.preventDefault();
      items[(next + items.length) % items.length]?.focus();
    };
    if (event.key === 'ArrowDown') go(index + 1);
    else if (event.key === 'ArrowUp') go(index - 1);
    else if (event.key === 'Home') go(0);
    else if (event.key === 'End') go(items.length - 1);
    else if (event.key === 'Escape' || event.key === 'Tab') {
      if (event.key === 'Escape') event.preventDefault();
      setMenu(false);
      moveButton.current?.focus();
    }
  };

  const moveSelectedTo = (folderId: string) => {
    setMenu(false);
    const group = files.filter((file) => selected.has(file.id)).map((file) => file.id);
    moveFiles(group, folderId);
    // The bar goes with the selection: the focus waits on the table's select-all box.
    later(() => document.getElementById(`${ids}-all`)?.focus(), 0);
  };

  const copyLink = (what: string) => {
    navigator.clipboard?.writeText(window.location.href).catch(() => {});
    showToast({ lead: `Link to ${what}`, rest: ' copied' });
    announce(`Link to ${what} copied.`);
  };

  // --- The demo -----------------------------------------------------------------------------

  const reset = () => {
    timers.current.forEach((timer) => window.clearTimeout(timer));
    timers.current.clear();
    removing.current.clear();
    window.clearTimeout(toastTimer.current);
    endDrag();
    setFiles(FILES);
    setFolders(FOLDERS);
    setLeaving(new Set());
    setFresh(new Set());
    setSelected(new Set());
    setUploads({});
    setDone(null);
    setFlash(null);
    setToast(null);
    setMenu(false);
    setEntering(new Set(FILES.map((file) => file.id)));
    later(() => setEntering(new Set()), ROW_IN);
  };

  const demoAct = useEffectEvent(
    (
      act:
        | { grab: string[]; at: Point }
        | { grabUpload: Point }
        | { flight: Flight; kind: Drag['kind'] }
        | { over: string | null }
        | { drop: true }
        | { toggle: string }
        | { reveal: string }
        | { reset: true }
        | { stop: true },
    ) => {
      if ('grab' in act) {
        const first = files.find((file) => file.id === act.grab[0]);
        if (!first) return;
        beginDrag(
          {
            kind: 'files',
            ids: act.grab,
            name: first.name,
            size: first.size,
            fileKind: first.kind,
          },
          act.at,
        );
      } else if ('grabUpload' in act) {
        beginDrag(
          {
            kind: 'upload',
            name: DEMO_UPLOAD.name,
            size: DEMO_UPLOAD.size,
            hues: [...DEMO_UPLOAD.hues],
          },
          act.grabUpload,
        );
      } else if ('flight' in act) {
        const element = ghost.current;
        const grab = GRAB[act.kind];
        const end = act.flight.points.at(-1);
        if (!element || !end) return;
        const at = (point: Point) => `translate(${point.x - grab.x}px, ${point.y - grab.y}px)`;
        placeGhost(end, act.kind);
        element.animate(
          act.flight.points.map((point) => ({ transform: at(point) })),
          act.flight.timing,
        );
      } else if ('over' in act) setOverFolder(act.over);
      else if ('drop' in act) drop();
      else if ('toggle' in act) toggle(act.toggle);
      else if ('reveal' in act) {
        // On a narrow library the tiles scroll sideways: bring the target into view.
        const tile = tiles.current.get(act.reveal);
        const list = strip.current;
        if (tile && list) {
          const left = tile.offsetLeft - list.offsetLeft;
          if (
            left < list.scrollLeft ||
            left + tile.offsetWidth > list.scrollLeft + list.clientWidth
          )
            list.scrollTo({ left: left - 16, behavior: 'smooth' });
        }
      } else if ('reset' in act) reset();
      else if (dragRef.current) endDrag();
    },
  );

  const demo = autoplay && defaultView === 'rest' && playing;
  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    const find = (selector: string) => stage.querySelector(selector);
    const local2 = (element: Element | null, dx = 0.5, dy = 0.5): Point => {
      if (!element) return { x: stage.offsetWidth / 2, y: stage.offsetHeight / 2 };
      const frame = stage.getBoundingClientRect();
      const scale = frame.width / stage.offsetWidth || 1;
      const rect = element.getBoundingClientRect();
      return {
        x: (rect.left + rect.width * dx - frame.left) / scale,
        y: (rect.top + rect.height * dy - frame.top) / scale,
      };
    };
    const nameOf = (id: string) => local2(find(`[data-file="${id}"] [data-part="file-name"]`), 0.6);
    const checkOf = (id: string) => local2(find(`[data-file="${id}"] [data-part="check"]`));
    const tileOf = (id: string) => local2(find(`[data-drop="${id}"] [data-part="folder-art"]`));
    const stop = runDemo(stage, arrow, async ({ wait, glide }) => {
      const carry = (to: Point, ms: number, kind: Drag['kind']) =>
        glide(to, ms, (flight) => demoAct({ flight, kind }));
      for (;;) {
        // One file into Contracts.
        await wait(700);
        await glide(nameOf('f1'), 900);
        await wait(300);
        demoAct({ grab: ['f1'], at: nameOf('f1') });
        await wait(200);
        demoAct({ reveal: 'contracts' });
        await wait(150);
        await carry(tileOf('contracts'), 1000, 'files');
        demoAct({ over: 'contracts' });
        await wait(650);
        demoAct({ drop: true });
        await wait(1500);
        // Three ticked, then dragged together.
        for (const id of ['f2', 'f3', 'f4']) {
          await glide(checkOf(id), id === 'f2' ? 700 : 320);
          await wait(140);
          demoAct({ toggle: id });
          await wait(260);
        }
        await wait(500);
        await glide(nameOf('f4'), 420);
        await wait(250);
        demoAct({ grab: ['f2', 'f3', 'f4'], at: nameOf('f4') });
        await wait(200);
        await carry(tileOf('contracts'), 1000, 'files');
        demoAct({ over: 'contracts' });
        await wait(600);
        demoAct({ drop: true });
        await wait(1500);
        // A picture from outside, into Brand Assets.
        demoAct({ reveal: 'brand' });
        const edge = { x: stage.offsetWidth + 30, y: tileOf('brand').y + 30 };
        await glide(edge, 700);
        demoAct({ grabUpload: edge });
        await carry(tileOf('brand'), 1100, 'upload');
        demoAct({ over: 'brand' });
        await wait(800);
        demoAct({ drop: true });
        await wait(3400);
        await glide({ x: stage.offsetWidth * 0.82, y: stage.offsetHeight * 0.85 }, 800);
        demoAct({ reset: true });
        await wait(1200);
      }
    });
    return () => {
      stop();
      demoAct({ stop: true });
    };
  }, [demo, root]);

  // --- Drawing ------------------------------------------------------------------------------

  const sidebarHidden = narrow ? !drawer : collapsed;
  const overDrop = drag?.kind === 'upload' || native ? 'upload' : 'move';
  const draggingIds = drag?.kind === 'files' ? drag.ids : [];

  const tree = (
    <ul className={styles.tree}>
      <li>
        <button
          type="button"
          className={styles.treeRow}
          data-current="true"
          aria-expanded={generalOpen}
          aria-controls={`${ids}-general`}
          onClick={() => setGeneralOpen((open) => !open)}
        >
          <Icon name={generalOpen ? 'folderOpen' : 'folder'} />
          <span className={styles.treeName}>General</span>
          <span className={styles.badge}>{GENERAL_COUNT}</span>
        </button>
        <ul id={`${ids}-general`} className={styles.subtree} hidden={!generalOpen}>
          {folders.map((folder) => (
            <li
              key={folder.id}
              className={styles.treeRow}
              data-sub="true"
              data-drop={`tree:${folder.id}`}
              data-over={over === `tree:${folder.id}` || undefined}
              data-flash={flash === folder.id || undefined}
            >
              <Icon name="folder" />
              <span className={styles.treeName}>{folder.name}</span>
              <span className={styles.badge}>{folder.count}</span>
            </li>
          ))}
        </ul>
      </li>
      {OTHER_FOLDERS.map((name) => (
        <li key={name} className={styles.treeRow}>
          <Icon name="folder" />
          <span className={styles.treeName}>{name}</span>
        </li>
      ))}
    </ul>
  );

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-color-scheme={colorScheme}
      data-dragging={drag ? drag.kind : undefined}
      data-selecting={selectedCount > 0 || undefined}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onWheelCapture={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') take();
      }}
    >
      <div className={styles.window} data-part="window">
        <header className={styles.topbar}>
          <span className={styles.logo} aria-hidden="true">
            <Icon name="mark" />
          </span>
          <span className={styles.workspace}>
            <i className={styles.workspaceSquare} aria-hidden="true" />
            Halden Studio
            <Icon name="updown" width="12" height="12" />
          </span>
        </header>

        <div className={styles.body}>
          <nav className={styles.rail} aria-label="Sections">
            {(['home', 'folder', 'clock', 'people', 'trash'] as const).map((name) => (
              <span
                key={name}
                className={styles.railIcon}
                data-current={name === 'folder' || undefined}
                aria-hidden="true"
              >
                <Icon name={name} />
              </span>
            ))}
          </nav>

          {narrow && drawer && (
            <button
              type="button"
              className={styles.scrim}
              aria-label="Close sidebar"
              onClick={() => setDrawer(false)}
            />
          )}
          <aside
            id={`${ids}-side`}
            className={styles.sidebar}
            data-part="sidebar"
            data-hidden={sidebarHidden || undefined}
            data-drawer={(narrow && drawer) || undefined}
            inert={sidebarHidden}
            aria-label="Library"
          >
            <div className={styles.sideHead}>
              <h2 className={styles.sideTitle}>Library</h2>
              <span className={styles.sideTools}>
                <span className={styles.ghostButton} aria-hidden="true">
                  <Icon name="plus" />
                </span>
                <button
                  type="button"
                  className={styles.ghostButton}
                  aria-label="Hide sidebar"
                  aria-controls={`${ids}-side`}
                  aria-expanded="true"
                  onClick={() => (narrow ? setDrawer(false) : setCollapsed(true))}
                >
                  <Icon name="panel" />
                </button>
              </span>
            </div>
            <label className={styles.search}>
              <Icon name="search" width="14" height="14" />
              <input
                type="search"
                placeholder="Search"
                aria-label="Search files"
                value={query}
                onChange={(event) => setQuery(event.target.value)}
              />
              <kbd aria-hidden="true">⌘K</kbd>
            </label>
            <div className={styles.segmented} role="tablist" aria-label="Show">
              {(['folders', 'shared'] as const).map((value) => (
                <button
                  key={value}
                  type="button"
                  role="tab"
                  aria-selected={tab === value}
                  className={styles.segment}
                  onClick={() => setTab(value)}
                >
                  {value === 'folders' ? 'Folders' : 'Shared'}
                </button>
              ))}
            </div>
            {tab === 'folders' ? (
              tree
            ) : (
              <ul className={styles.tree}>
                {SHARED_FOLDERS.map((folder) => (
                  <li key={folder.name} className={styles.treeRow}>
                    <Icon name="people" />
                    <span className={styles.treeName}>{folder.name}</span>
                    <span className={styles.badge}>{folder.count}</span>
                  </li>
                ))}
              </ul>
            )}
          </aside>

          <main className={styles.main} data-part="main">
            <div className={styles.mainHead}>
              {sidebarHidden && (
                <button
                  type="button"
                  className={styles.ghostButton}
                  aria-label="Show sidebar"
                  aria-controls={`${ids}-side`}
                  aria-expanded="false"
                  onClick={() => (narrow ? setDrawer(true) : setCollapsed(false))}
                >
                  <Icon name="panel" />
                </button>
              )}
              <nav className={styles.crumbs} aria-label="Breadcrumb">
                <span className={styles.crumbRoot}>Library</span>
                <span className={styles.crumbSlash} aria-hidden="true">
                  /
                </span>
                <span aria-current="page" className={styles.crumbHere}>
                  General
                  <Icon name="chevron" width="12" height="12" />
                </span>
              </nav>
              <span className={styles.headTools}>
                <span className={styles.people} aria-label="3 members" role="img">
                  {(['mc', 'aw', 'kd'] as const).map((id) => (
                    <Avatar key={id} id={id} className={styles.headAvatar} />
                  ))}
                </span>
                <button type="button" className={styles.button} onClick={() => copyLink('General')}>
                  <Icon name="link" width="14" height="14" />
                  <span className={styles.buttonText}>Share</span>
                </button>
                <button
                  type="button"
                  className={styles.primary}
                  data-part="upload"
                  onClick={() => fileInput.current?.click()}
                >
                  <Icon name="upload" width="14" height="14" />
                  Upload
                </button>
                <input
                  ref={fileInput}
                  type="file"
                  multiple
                  hidden
                  onChange={(event) => {
                    uploadHere([...(event.target.files ?? [])]);
                    event.target.value = '';
                  }}
                />
              </span>
            </div>

            <div
              ref={toastSlot}
              className={styles.toastSlot}
              aria-hidden={toast ? undefined : true}
            >
              {toast && (
                <div key={toast.id} className={styles.toast} data-part="toast">
                  <span className={styles.toastCheck} aria-hidden="true">
                    <Icon name="check" width="10" height="10" strokeWidth="2.2" />
                  </span>
                  <span className={styles.toastText}>
                    <b>{toast.lead}</b>
                    {toast.rest}
                  </span>
                  {toast.undo && (
                    <button
                      type="button"
                      className={styles.toastUndo}
                      onClick={() => toast.undo && undo(toast.undo)}
                    >
                      Undo
                    </button>
                  )}
                </div>
              )}
            </div>

            <div className={styles.scroll}>
              <section className={styles.section} aria-labelledby={`${ids}-folders`}>
                <h3 id={`${ids}-folders`} className={styles.heading}>
                  Folders <span className={styles.headingCount}>{folders.length}</span>
                </h3>
                <ul ref={strip} className={styles.tiles} data-part="folders">
                  {folders.map((folder) => {
                    const uploading = uploads[folder.id];
                    return (
                      <li
                        key={folder.id}
                        ref={(element) => {
                          if (element) tiles.current.set(folder.id, element);
                          else tiles.current.delete(folder.id);
                        }}
                        className={styles.tile}
                        data-part="folder"
                        data-drop={folder.id}
                        data-over={over === folder.id ? overDrop : undefined}
                        data-flash={flash === folder.id || undefined}
                        aria-label={`${folder.name}, ${filesLabel(folder, uploading)}${folder.private ? ', private' : ''}`}
                      >
                        <FolderArt
                          folder={folder}
                          fresh={fresh}
                          progress={uploading ? uploading.progress : null}
                          done={done === folder.id}
                        />
                        <span className={styles.tileName} aria-hidden="true">
                          {folder.name}
                        </span>
                        <span className={styles.tileCount} aria-hidden="true">
                          {filesLabel(folder, uploading)}
                        </span>
                        <span className={styles.uploadPill} aria-hidden="true">
                          <Icon name="upload" width="12" height="12" />
                          Upload to {folder.name}
                        </span>
                      </li>
                    );
                  })}
                </ul>
              </section>

              <section className={styles.section} aria-labelledby={`${ids}-files`}>
                <h3 id={`${ids}-files`} className={styles.heading}>
                  Files <span className={styles.headingCount}>{files.length - leaving.size}</span>
                </h3>
                <div className={styles.table} role="table" aria-labelledby={`${ids}-files`}>
                  <div className={styles.tableHead} role="rowgroup">
                    <div className={styles.row} role="row">
                      <span className={styles.cellCheck} role="columnheader">
                        <input
                          id={`${ids}-all`}
                          type="checkbox"
                          className={styles.check}
                          aria-label="Select all files"
                          checked={allShownSelected}
                          disabled={shown.length === 0}
                          onChange={() =>
                            choose(
                              allShownSelected ? new Set() : new Set(shown.map((file) => file.id)),
                            )
                          }
                        />
                      </span>
                      <span className={styles.cellName} role="columnheader">
                        Name
                      </span>
                      <span className={styles.cellOwner} role="columnheader">
                        Added by
                      </span>
                      <span className={styles.cellSize} role="columnheader">
                        Size
                      </span>
                    </div>
                  </div>
                  <div ref={rowsGroup} role="rowgroup" data-part="files">
                    {shown.map((file) => (
                      <div
                        key={file.id}
                        ref={(element) => {
                          if (element) rows.current.set(file.id, element);
                          else rows.current.delete(file.id);
                        }}
                        className={styles.rowWrap}
                        data-file={file.id}
                        data-leaving={leaving.has(file.id) || undefined}
                        data-entering={entering.has(file.id) || undefined}
                      >
                        <div
                          className={styles.row}
                          role="row"
                          data-part="file-row"
                          data-selected={selected.has(file.id) || undefined}
                          data-dragged={draggingIds.includes(file.id) || undefined}
                        >
                          <span className={styles.cellCheck} role="cell">
                            <input
                              type="checkbox"
                              className={styles.check}
                              data-part="check"
                              aria-label={`Select ${file.name}`}
                              checked={selected.has(file.id)}
                              onChange={() => toggle(file.id)}
                            />
                          </span>
                          <span className={styles.cellName} role="cell">
                            <span
                              className={styles.fileIcon}
                              data-kind={file.kind}
                              aria-hidden="true"
                            >
                              <Icon name="file" width="13" height="13" />
                              <i />
                            </span>
                            <span className={styles.fileName} data-part="file-name">
                              {file.name}
                            </span>
                          </span>
                          <span className={styles.cellOwner} role="cell">
                            <Avatar id={file.owner} className={styles.ownerAvatar} />
                            <span className={styles.ownerName}>{PEOPLE[file.owner].name}</span>
                          </span>
                          <span className={styles.cellSize} role="cell">
                            {file.size}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
                {shown.length === 0 && (
                  <p className={styles.empty}>
                    {query
                      ? `No files match “${query.trim()}”.`
                      : 'Every file here is in a folder.'}
                  </p>
                )}
              </section>

              <div className={styles.barSlot}>
                <div
                  className={styles.bar}
                  data-part="selection-bar"
                  data-shown={selectedCount > 0 || undefined}
                  inert={selectedCount === 0}
                  role="toolbar"
                  aria-label="Selected files"
                >
                  <span className={styles.barCount} aria-live="polite">
                    {barCount} selected
                  </span>
                  <span className={styles.barMenuWrap}>
                    <button
                      ref={moveButton}
                      type="button"
                      className={styles.primary}
                      aria-haspopup="menu"
                      aria-expanded={menuOpen}
                      aria-controls={`${ids}-menu`}
                      onClick={() => setMenu((open) => !open)}
                    >
                      <Icon name="move" width="14" height="14" />
                      Move to
                    </button>
                    {menuOpen && (
                      <div
                        ref={menuRef}
                        id={`${ids}-menu`}
                        className={styles.menu}
                        role="menu"
                        tabIndex={-1}
                        aria-label="Move to folder"
                        onKeyDown={onMenuKey}
                      >
                        {folders.map((folder) => (
                          <button
                            key={folder.id}
                            type="button"
                            role="menuitem"
                            tabIndex={-1}
                            className={styles.menuItem}
                            onClick={() => moveSelectedTo(folder.id)}
                          >
                            <Icon name="folder" width="14" height="14" />
                            <span>{folder.name}</span>
                            <span className={styles.menuCount}>{folder.count}</span>
                          </button>
                        ))}
                      </div>
                    )}
                  </span>
                  <button
                    type="button"
                    className={styles.barButton}
                    onClick={() => copyLink(plural(selectedCount, 'file'))}
                  >
                    <Icon name="link" width="14" height="14" />
                    Share
                  </button>
                  <i className={styles.barDivider} aria-hidden="true" />
                  <button
                    type="button"
                    className={styles.barClose}
                    aria-label="Clear selection"
                    onClick={clearSelection}
                  >
                    <Icon name="close" width="14" height="14" />
                  </button>
                </div>
              </div>
            </div>
          </main>
        </div>
      </div>

      <div className={styles.ghostLayer} aria-hidden="true">
        {drag && (
          <div ref={ghost} className={styles.ghost} data-kind={drag.kind} data-part="ghost">
            {drag.kind === 'files' ? (
              <span
                className={styles.ghostTilt}
                data-stack={Math.min(drag.ids.length, 3)}
                style={{ '--count': drag.ids.length } as CSSProperties}
              >
                {drag.ids.length > 1 && <i className={styles.ghostBehind} />}
                {drag.ids.length > 2 && <i className={styles.ghostBehind} />}
                <span className={styles.ghostChip}>
                  <span className={styles.fileIcon} data-kind={drag.fileKind}>
                    <Icon name="file" width="13" height="13" />
                    <i />
                  </span>
                  <span className={styles.ghostName}>{drag.name}</span>
                  <span className={styles.ghostSize}>{drag.size}</span>
                </span>
                {drag.ids.length > 1 && (
                  <span className={styles.ghostCount}>{drag.ids.length}</span>
                )}
              </span>
            ) : (
              <span className={styles.ghostTilt}>
                <span
                  className={styles.ghostPicture}
                  style={{ '--h1': drag.hues[0], '--h2': drag.hues[1] } as CSSProperties}
                >
                  <span className={styles.ghostPlus}>
                    <Icon name="plus" width="10" height="10" strokeWidth="2.2" />
                  </span>
                  <i />
                  <span className={styles.ghostCaption}>
                    <span>{drag.name}</span>
                    <span>{drag.size}</span>
                  </span>
                </span>
              </span>
            )}
          </div>
        )}
      </div>

      <p className={styles.hidden} aria-live="polite">
        {message}
      </p>
      <div className={styles.pointerLayer} aria-hidden="true">
        <DemoPointer
          ref={pointer}
          className={styles.pointer}
          arrowClass={styles.arrow}
          handClass={styles.hand}
        />
      </div>
    </div>
  );
}
```

### file-library/file-library.module.css

```css
/* File library (file-library.tsx): a workspace window, icon rail and folder tree on the left,
   General's folders as tiles over a table of its loose files. Rows drag onto tiles.

   Sizes are px, measured from the reference at 1440 × 900: a 48 px top bar, a 52 px rail, a
   218 px sidebar, a 47 px header over the main column; tiles 163 × 172 with a 134 × 104 folder
   picture, 12 apart; table rows 44 px. Under 720 px of library the rail goes, the sidebar becomes
   a drawer, and the tiles scroll sideways.

   Motion, from the reference's frames (10 a second): the ghost lifts in 160 ms, a tile lights in
   160 ms and its front tips forward on a slight overshoot (280 ms); dropped, the ghost shrinks
   into the folder in 200 ms, a paper drops in (460 ms, overshooting), the row folds in 240 ms and
   the toast comes down in 220 ms. The selection bar rises in 180 ms.

   Colours are the tokens below, light-dark(light, dark) where the two differ: the reference is
   the dark one; the light one is the same window on paper whites. */

.root {
  --canvas: #e9ebf0;
  --glow: rgb(80 120 255 / 0.12);
  --app: #ffffff;
  --side: #fbfbfc;
  --table: #ffffff;
  --line: #e7e7eb;
  --line-soft: #efeff2;
  --field: #f4f4f6;
  --seg: #f0f0f3;
  --seg-on: #ffffff;
  --seg-shadow: rgb(0 0 0 / 0.08);
  --hover: #f6f6f8;
  --row-current: #f0f0f3;
  --ink: #17171a;
  --ink-2: #3c3c43;
  --muted: #6e6e76;
  --faint: #a4a4ad;
  --badge: #efeff2;
  --button: #ffffff;
  --tile: #fafafb;
  --tile-edge: #e9e9ed;
  --back: #cfd1d8;
  --glass-top: rgb(255 255 255 / 0.5);
  --glass-bottom: rgb(236 238 243 / 0.78);
  --glass-edge: rgb(255 255 255 / 0.95);
  --glass-shade: rgb(30 35 50 / 0.1);
  --chip: rgb(255 255 255 / 0.75);
  --paper: #ffffff;
  --paper-line: #e3e4e9;
  --paper-shadow: rgb(20 25 40 / 0.16);
  --icon-tile: #f4f4f6;
  --accent: #2f6fe8;
  --accent-top: #4a86f5;
  --accent-ink: #ffffff;
  --accent-glow: rgb(47 111 232 / 0.32);
  --accent-soft: rgb(47 111 232 / 0.08);
  --accent-text: #2362d6;
  --ring: #2f6fe8;
  --green: #21a35e;
  --pop: #ffffff;
  --shadow: rgb(20 25 40 / 0.14);
  --shadow-deep: rgb(20 25 40 / 0.22);
  --scrim: rgb(20 22 30 / 0.32);
  --avatar-ring: #ffffff;
  /* The same on both schemes: each file type, and the people's pastels. */
  --pdf: #e5484d;
  --doc: #3e7bfa;
  --sheet: #26a269;
  --slides: #ef8a2a;
  --image: #9b5cf0;
  --avatar-ink: #1b1b1f;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: -apple-system, BlinkMacSystemFont, 'SF Pro Text', Inter, 'Segoe UI', Roboto, sans-serif;
  position: relative;
  container: fl / inline-size;
  width: 100%;
  min-width: 0;
  padding: clamp(8px, 2.6cqi, 28px);
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: radial-gradient(60% 40% at 55% 0%, var(--glow), transparent 70%), var(--canvas);
  color: var(--ink);
  font-family: var(--sans);
  font-size: 13px;
  line-height: 1.35;
  text-align: left;
  -webkit-font-smoothing: antialiased;
  -webkit-tap-highlight-color: transparent;
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --canvas: light-dark(#e9ebf0, #09090b);
    --glow: light-dark(rgb(80 120 255 / 0.12), rgb(60 80 230 / 0.2));
    --app: light-dark(#ffffff, #0c0b0e);
    --side: light-dark(#fbfbfc, #0f0f11);
    --table: light-dark(#ffffff, #101012);
    --line: light-dark(#e7e7eb, #1d1d20);
    --line-soft: light-dark(#efeff2, #18181b);
    --field: light-dark(#f4f4f6, #19191c);
    --seg: light-dark(#f0f0f3, #141416);
    --seg-on: light-dark(#ffffff, #242328);
    --seg-shadow: light-dark(rgb(0 0 0 / 0.08), rgb(0 0 0 / 0.3));
    --hover: light-dark(#f6f6f8, #151518);
    --row-current: light-dark(#f0f0f3, #1a1a1d);
    --ink: light-dark(#17171a, #ededf0);
    --ink-2: light-dark(#3c3c43, #c7c7cd);
    --muted: light-dark(#6e6e76, #8c8c93);
    --faint: light-dark(#a4a4ad, #55555c);
    --badge: light-dark(#efeff2, #222225);
    --button: light-dark(#ffffff, #1c1c1f);
    --tile: light-dark(#fafafb, #0f0f11);
    --tile-edge: light-dark(#e9e9ed, #1f1f22);
    --back: light-dark(#cfd1d8, #2b2a30);
    --glass-top: light-dark(rgb(255 255 255 / 0.5), rgb(84 83 92 / 0.55));
    --glass-bottom: light-dark(rgb(236 238 243 / 0.78), rgb(30 30 35 / 0.86));
    --glass-edge: light-dark(rgb(255 255 255 / 0.95), rgb(255 255 255 / 0.14));
    --glass-shade: light-dark(rgb(30 35 50 / 0.1), rgb(0 0 0 / 0.35));
    --chip: light-dark(rgb(255 255 255 / 0.75), rgb(0 0 0 / 0.32));
    --paper: light-dark(#ffffff, #f4f4f5);
    --paper-line: light-dark(#e3e4e9, #dcdce1);
    --paper-shadow: light-dark(rgb(20 25 40 / 0.16), rgb(0 0 0 / 0.4));
    --icon-tile: light-dark(#f4f4f6, #1b1a1e);
    --accent: light-dark(#2f6fe8, #3f7cf0);
    --accent-top: light-dark(#4a86f5, #6a9bf7);
    --accent-glow: light-dark(rgb(47 111 232 / 0.32), rgb(63 124 240 / 0.5));
    --accent-soft: light-dark(rgb(47 111 232 / 0.08), rgb(63 124 240 / 0.13));
    --accent-text: light-dark(#2362d6, #7ea7f8);
    --ring: light-dark(#2f6fe8, #4f88f2);
    --green: light-dark(#21a35e, #34c27a);
    --pop: light-dark(#ffffff, #19191c);
    --shadow: light-dark(rgb(20 25 40 / 0.14), rgb(0 0 0 / 0.5));
    --shadow-deep: light-dark(rgb(20 25 40 / 0.22), rgb(0 0 0 / 0.7));
    --scrim: light-dark(rgb(20 22 30 / 0.32), rgb(0 0 0 / 0.55));
    --avatar-ring: light-dark(#ffffff, #0c0b0e);
  }
}
.root[data-color-scheme='light'] {
  color-scheme: light;
}
.root[data-color-scheme='dark'] {
  color-scheme: dark;
}
.root[data-color-scheme='system'] {
  color-scheme: light dark;
}

:where(.root) :where(button, input) {
  font: inherit;
  color: inherit;
  letter-spacing: inherit;
}
:where(.root) :where(button) {
  margin: 0;
  padding: 0;
  border: 0;
  background: none;
  cursor: pointer;
}
:where(.root) :where(ul, p, h2, h3) {
  margin: 0;
  padding: 0;
}
:where(.root) :where(ul) {
  list-style: none;
}
:where(.root) :focus-visible {
  outline: 2px solid var(--ring);
  outline-offset: 2px;
}
.root[data-dragging],
.root[data-dragging] * {
  cursor: grabbing !important;
}

/* The window. */
.window {
  display: grid;
  grid-template-rows: 48px minmax(0, 1fr);
  height: 868px;
  overflow: hidden;
  overflow: clip;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--app);
  box-shadow: 0 24px 60px -24px var(--shadow-deep);
}
.topbar {
  display: flex;
  align-items: center;
  gap: 14px;
  padding-left: 13px;
  border-bottom: 1px solid var(--line);
}
.logo {
  display: grid;
  place-items: center;
  width: 24px;
  height: 24px;
  border-radius: 7px;
  background: var(--ink);
  color: var(--app);
  box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.1);
}
.logo svg {
  width: 14px;
  height: 14px;
}
.workspace {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  font-size: 12.5px;
}
.workspace svg {
  color: var(--muted);
}
.workspaceSquare {
  width: 16px;
  height: 16px;
  border-radius: 4.5px;
  background: linear-gradient(135deg, #ff9c76, #ff6e8a);
}

.body {
  position: relative;
  display: grid;
  grid-template-columns: 52px 218px minmax(0, 1fr);
  min-height: 0;
}

/* The icon rail: decoration, the section this view is in marked. */
.rail {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  padding-top: 13px;
  border-right: 1px solid var(--line);
}
.railIcon {
  display: grid;
  place-items: center;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  color: var(--muted);
}
.railIcon[data-current] {
  background: var(--row-current);
  box-shadow: inset 0 0 0 1px var(--line);
  color: var(--ink);
}

/* The sidebar: the library's tree. */
.sidebar {
  display: flex;
  flex-direction: column;
  min-width: 0;
  padding: 0 11px;
  border-right: 1px solid var(--line);
  background: var(--side);
}
.sideHead {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 4px 0 7px;
}
.sideTitle {
  font-size: 13px;
  font-weight: 600;
}
.sideTools {
  display: flex;
  gap: 2px;
  margin-left: auto;
  color: var(--muted);
}
.ghostButton {
  display: grid;
  place-items: center;
  width: 26px;
  height: 26px;
  border-radius: 7px;
  color: var(--muted);
}
button.ghostButton:hover {
  background: var(--hover);
  color: var(--ink);
}
.search {
  display: flex;
  align-items: center;
  gap: 7px;
  height: 28px;
  padding: 0 4px 0 9px;
  border: 1px solid var(--line-soft);
  border-radius: 8px;
  background: var(--field);
  color: var(--muted);
}
.search:focus-within {
  border-color: var(--ring);
}
.search input {
  flex: 1;
  min-width: 0;
  height: 100%;
  padding: 0;
  border: 0;
  outline: 0;
  background: none;
  color: var(--ink);
  font-size: 12.5px;
}
.search input::placeholder {
  color: var(--muted);
}
.search input::-webkit-search-cancel-button {
  display: none;
}
.search kbd {
  padding: 1px 5px;
  border: 1px solid var(--line);
  border-radius: 5px;
  color: var(--muted);
  font: 500 10px/1.4 var(--sans);
}
.segmented {
  display: flex;
  gap: 2px;
  height: 26px;
  margin-top: 13px;
  padding: 2px;
  border-radius: 8px;
  background: var(--seg);
}
.segment {
  flex: 1;
  border-radius: 6px;
  color: var(--muted);
  font-size: 12px;
  transition:
    background-color 0.16s,
    color 0.16s;
}
.segment[aria-selected='true'] {
  background: var(--seg-on);
  box-shadow: 0 1px 2px var(--seg-shadow);
  color: var(--ink);
}

.tree {
  margin-top: 14px;
}
.treeRow {
  position: relative;
  display: flex;
  align-items: center;
  gap: 9px;
  width: 100%;
  height: 28px;
  padding: 0 7px 0 8px;
  border-radius: 7px;
  color: var(--ink-2);
  font-size: 12.5px;
  text-align: left;
  transition:
    background-color 0.25s,
    box-shadow 0.16s;
}
.treeRow svg {
  flex: none;
  color: var(--muted);
}
.treeRow[data-current] {
  background: var(--row-current);
  color: var(--ink);
}
.treeRow[data-current] svg {
  color: var(--ink-2);
}
.treeName {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.badge {
  min-width: 20px;
  padding: 1px 5px;
  border-radius: 5px;
  background: var(--badge);
  color: var(--muted);
  font-size: 10.5px;
  font-variant-numeric: tabular-nums;
  text-align: center;
}
.subtree {
  position: relative;
  margin: 0 0 0 17px;
}
/* The guide down the sub-folders, with an elbow into each. */
.subtree::before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 14px;
  left: -4px;
  width: 1px;
  background: var(--line);
}
.subtree .treeRow::before {
  content: '';
  position: absolute;
  left: -4px;
  top: 13px;
  width: 6px;
  height: 1px;
  background: var(--line);
}
.treeRow[data-over],
.treeRow[data-flash] {
  background: var(--accent-soft);
}
.treeRow[data-over] {
  box-shadow: inset 0 0 0 1px var(--ring);
}
.treeRow[data-flash] .badge {
  color: var(--accent-text);
}

/* The main column: its header, the toast, the scrolling content and the bar at its foot. */
.main {
  position: relative;
  display: flex;
  flex-direction: column;
  min-width: 0;
  min-height: 0;
}
.mainHead {
  display: flex;
  flex: none;
  align-items: center;
  gap: 10px;
  height: 47px;
  padding: 0 14px 0 20px;
  border-bottom: 1px solid var(--line);
}
.mainHead > .ghostButton {
  margin-left: -8px;
}
.crumbs {
  display: flex;
  align-items: center;
  gap: 7px;
  min-width: 0;
  font-size: 12.5px;
}
.crumbRoot {
  color: var(--muted);
}
.crumbSlash {
  color: var(--faint);
}
.crumbHere {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}
.crumbHere svg {
  color: var(--muted);
}
.headTools {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
}
.people {
  display: flex;
  margin-right: 4px;
}
.people .headAvatar {
  width: 20px;
  height: 20px;
  font-size: 7.5px;
  box-shadow: 0 0 0 2px var(--avatar-ring);
}
.people .headAvatar + .headAvatar {
  margin-left: -4px;
}
.button,
.primary {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 28px;
  padding: 0 10px;
  border-radius: 8px;
  font-size: 12.5px;
  font-weight: 500;
  white-space: nowrap;
}
.button {
  border: 1px solid var(--line);
  background: var(--button);
  color: var(--ink);
}
.button:hover {
  background: var(--hover);
}
.button svg {
  color: var(--muted);
}
.primary {
  background: linear-gradient(var(--accent-top), var(--accent));
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 0.22),
    0 0 0 1px var(--accent),
    0 6px 16px -6px var(--accent-glow);
  color: var(--accent-ink);
}
.primary:hover {
  filter: brightness(1.06);
}

/* The toast: under the header, at the right. */
.toastSlot {
  position: absolute;
  top: 59px;
  right: 20px;
  z-index: 5;
  pointer-events: none;
}
.toast {
  display: flex;
  align-items: center;
  gap: 8px;
  max-width: 100%;
  height: 32px;
  padding: 0 4px 0 8px;
  border: 1px solid var(--line);
  border-radius: 10px;
  background: var(--pop);
  box-shadow: 0 10px 26px -10px var(--shadow-deep);
  font-size: 12px;
  pointer-events: auto;
  animation: toastIn 0.22s cubic-bezier(0.2, 0.8, 0.3, 1);
}
.toast:not(:has(button)) {
  padding-right: 10px;
}
.toastCheck {
  display: grid;
  flex: none;
  place-items: center;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: var(--green);
  color: #fff;
}
.toastText {
  overflow: hidden;
  color: var(--muted);
  text-overflow: ellipsis;
  white-space: nowrap;
}
.toastText b {
  color: var(--ink);
  font-weight: 500;
}
.toastUndo {
  flex: none;
  height: 24px;
  padding: 0 9px;
  border-radius: 7px;
  background: var(--badge);
  color: var(--ink);
  font-size: 11.5px;
  font-weight: 500;
}
.toastUndo:hover {
  background: var(--line);
}
@keyframes toastIn {
  from {
    opacity: 0;
    transform: translateY(-6px) scale(0.98);
  }
}

.scroll {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
  padding: 18px 20px 20px;
  overflow: auto;
  overscroll-behavior: contain;
  scrollbar-width: thin;
}
.section {
  flex: none;
}
.section + .section {
  margin-top: 28px;
}
.heading {
  display: flex;
  align-items: baseline;
  gap: 7px;
  margin-bottom: 14px;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: -0.01em;
}
.headingCount {
  color: var(--muted);
  font-size: 11px;
  font-weight: 500;
  font-variant-numeric: tabular-nums;
  letter-spacing: 0;
}

/* The tiles. The strip scrolls sideways when they don't fit; its padding leaves room for the
   ring's glow and the upload pill under a tile, and the negative margin takes that room back. */
.tiles {
  display: grid;
  grid-auto-columns: 163px;
  grid-auto-flow: column;
  justify-content: start;
  gap: 12px;
  margin: -10px -10px -46px;
  padding: 10px 10px 46px;
  overflow-x: auto;
  overflow-y: hidden;
  scroll-padding-inline: 10px;
  scroll-snap-type: x proximity;
  scrollbar-width: none;
}
.tiles::-webkit-scrollbar {
  display: none;
}
.tile {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 172px;
  padding-top: 17px;
  border: 1px solid var(--tile-edge);
  border-radius: 14px;
  background: var(--tile);
  scroll-snap-align: start;
  transition:
    border-color 0.16s,
    box-shadow 0.16s;
}
.tile[data-over] {
  border-color: var(--ring);
  box-shadow:
    0 0 0 1px var(--ring),
    0 0 24px -2px var(--accent-glow);
}
.tileName {
  margin-top: 13px;
  font-size: 12.5px;
  font-weight: 500;
}
.tileCount {
  margin-top: 2px;
  color: var(--muted);
  font-size: 11px;
  font-variant-numeric: tabular-nums;
  transition: color 0.4s;
}
.tile[data-flash] .tileCount {
  color: var(--accent-text);
  transition-duration: 0.1s;
}
.uploadPill {
  position: absolute;
  top: calc(100% + 10px);
  left: 50%;
  z-index: 2;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 26px;
  padding: 0 10px;
  border-radius: 8px;
  background: linear-gradient(var(--accent-top), var(--accent));
  box-shadow: 0 6px 18px -6px var(--accent-glow);
  color: var(--accent-ink);
  font-size: 11.5px;
  font-weight: 500;
  white-space: nowrap;
  opacity: 0;
  transform: translate(-50%, -4px) scale(0.96);
  transition:
    opacity 0.16s,
    transform 0.16s;
  pointer-events: none;
}
.tile[data-over='upload'] .uploadPill {
  opacity: 1;
  transform: translate(-50%, 0);
}

/* The folder's picture (folder-art.tsx). */
.art {
  position: relative;
  display: block;
  flex: none;
  width: 134px;
  height: 104px;
  perspective: 420px;
}
.back {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  fill: var(--back);
}
.papers {
  position: absolute;
  top: 9px;
  left: 18px;
  width: 98px;
  height: 64px;
  transition: transform 0.28s cubic-bezier(0.3, 1.3, 0.5, 1);
}
.tile[data-over] .papers {
  transform: translateY(-6px);
}
.paper {
  position: absolute;
  inset: 0;
  overflow: hidden;
  border-radius: 6px;
  background: var(--paper);
  box-shadow:
    0 1px 2px var(--paper-shadow),
    0 0 0 0.5px rgb(0 0 0 / 0.06);
  transform: translate(var(--x), var(--y)) rotate(var(--r));
}
.paper[data-kind='image'] {
  background:
    radial-gradient(80% 70% at 75% 20%, rgb(255 255 255 / 0.35), transparent 60%),
    linear-gradient(140deg, hsl(var(--h1) 90% 62%), hsl(var(--h2) 92% 55%));
}
.paper[data-fresh] {
  animation: paperIn 0.46s cubic-bezier(0.22, 1.25, 0.36, 1) both;
}
@keyframes paperIn {
  from {
    opacity: 0;
    transform: translate(var(--x), calc(var(--y) - 34px)) rotate(calc(var(--r) - 6deg)) scale(0.82);
  }
  40% {
    opacity: 1;
  }
}
.paperSquare {
  position: absolute;
  top: 9px;
  left: 10px;
  width: 11px;
  height: 11px;
  border-radius: 3px;
  background: var(--doc);
}
.paper[data-kind='pdf'] .paperSquare {
  background: var(--pdf);
}
.paper[data-kind='sheet'] .paperSquare {
  background: var(--sheet);
}
.paper[data-kind='slides'] .paperSquare {
  background: var(--slides);
}
.paperLine {
  position: absolute;
  top: 27px;
  left: 10px;
  width: 58%;
  height: 3px;
  border-radius: 2px;
  background: var(--paper-line);
}
.paperLine + .paperLine {
  top: 34px;
  width: 40%;
}
.front {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  height: 70px;
  border-radius: 10px;
  background: linear-gradient(var(--glass-top), var(--glass-bottom));
  box-shadow:
    inset 0 1px 0 var(--glass-edge),
    inset 0 0 0 0.5px var(--glass-edge),
    0 -2px 8px -4px var(--glass-shade);
  -webkit-backdrop-filter: blur(9px) saturate(1.5);
  backdrop-filter: blur(9px) saturate(1.5);
  transform-origin: 50% 100%;
  transition: transform 0.28s cubic-bezier(0.3, 1.35, 0.5, 1);
}
.tile[data-over] .front {
  transform: rotateX(-30deg);
}
.members {
  position: absolute;
  bottom: 10px;
  left: 10px;
  display: flex;
}
.members .memberAvatar {
  width: 17px;
  height: 17px;
  font-size: 0;
  box-shadow: 0 0 0 1px var(--glass-shade);
}
.members .memberAvatar + .memberAvatar {
  margin-left: -5px;
}
.privateChip {
  position: absolute;
  bottom: 9px;
  left: 9px;
  display: inline-flex;
  align-items: center;
  gap: 3px;
  height: 17px;
  padding: 0 6px 0 5px;
  border-radius: 5px;
  background: var(--chip);
  color: var(--ink-2);
  font-size: 9.5px;
  font-weight: 500;
}
.progress {
  position: absolute;
  right: 34px;
  bottom: 13px;
  left: 10px;
  height: 3px;
  overflow: hidden;
  border-radius: 2px;
  background: var(--chip);
}
.progress span {
  display: block;
  height: 100%;
  border-radius: inherit;
  background: var(--accent-top);
  transform-origin: 0 50%;
}
.doneBadge {
  position: absolute;
  right: 8px;
  bottom: 8px;
  display: grid;
  place-items: center;
  width: 17px;
  height: 17px;
  border-radius: 50%;
  background: var(--green);
  color: #fff;
  opacity: 0;
  transform: scale(0.4);
  transition:
    opacity 0.3s,
    transform 0.3s;
}
.doneBadge[data-shown] {
  opacity: 1;
  transform: none;
  transition-timing-function: cubic-bezier(0.3, 1.6, 0.5, 1);
}

/* Faces: initials on a pastel, the same on both schemes. */
.avatar {
  display: inline-grid;
  flex: none;
  place-items: center;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #f7b6cb;
  color: var(--avatar-ink);
  font-size: 7px;
  font-weight: 600;
  letter-spacing: 0.02em;
}
.avatar[data-person='aw'] {
  background: #a6dcb9;
}
.avatar[data-person='kd'] {
  background: #b9c8fb;
}
.avatar[data-person='sl'] {
  background: #f6d47e;
}
.avatar[data-person='you'] {
  background: #d6c3f7;
}

/* The table. Each row sits in a one-track grid so it can fold to 0fr and back. */
.table {
  border: 1px solid var(--line);
  border-radius: 12px;
  background: var(--table);
  overflow: hidden;
  overflow: clip;
}
.row {
  display: grid;
  grid-template-columns: 40px minmax(0, 1fr) 200px 110px;
  align-items: center;
}
.tableHead .row {
  height: 34px;
  border-bottom: 1px solid var(--line);
  color: var(--muted);
  font-size: 11px;
  font-weight: 500;
}
.rowWrap {
  position: relative;
  display: grid;
  grid-template-rows: 1fr;
  transition:
    grid-template-rows 0.24s cubic-bezier(0.3, 0, 0.2, 1),
    opacity 0.18s;
}
.rowWrap + .rowWrap::before {
  content: '';
  position: absolute;
  top: 0;
  right: 14px;
  left: 14px;
  height: 1px;
  background: var(--line-soft);
}
.rowWrap[data-leaving] {
  grid-template-rows: 0fr;
  opacity: 0;
  pointer-events: none;
}
.rowWrap[data-entering] {
  animation: rowIn 0.3s cubic-bezier(0.3, 0, 0.2, 1);
}
@keyframes rowIn {
  from {
    grid-template-rows: 0fr;
    opacity: 0;
  }
}
.rowWrap > .row {
  min-height: 0;
  overflow: hidden;
  cursor: grab;
  touch-action: pan-y;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
  transition:
    background-color 0.14s,
    opacity 0.16s;
}
.rowWrap > .row:hover {
  background: var(--hover);
}
.rowWrap > .row[data-selected] {
  background: var(--accent-soft);
}
.rowWrap > .row[data-dragged] {
  opacity: 0.35;
}
.rowWrap > .row > span {
  height: 44px;
}
.cellCheck,
.cellName,
.cellOwner,
.cellSize {
  display: flex;
  align-items: center;
  min-width: 0;
}
.cellCheck {
  justify-content: flex-end;
  padding-right: 8px;
}
.cellOwner {
  gap: 8px;
}
.cellSize {
  padding-right: 16px;
  color: var(--muted);
  font-size: 12px;
  font-variant-numeric: tabular-nums;
}
.check {
  appearance: none;
  display: block;
  flex: none;
  width: 14px;
  height: 14px;
  margin: 0;
  border: 1.5px solid var(--faint);
  border-radius: 4px;
  background: transparent;
  cursor: pointer;
  opacity: 0;
  transition:
    opacity 0.14s,
    background-color 0.14s,
    border-color 0.14s;
}
.check:checked {
  border-color: var(--accent);
  background: var(--accent)
    url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 14 14'%3E%3Cpath d='m3.6 7.2 2.3 2.3 4.6-4.8' fill='none' stroke='white' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")
    center / 12px no-repeat;
}
.check:disabled {
  cursor: default;
}
.row:hover .check,
.row:focus-within .check,
.check:checked,
.check:focus-visible,
.root[data-selecting] .check,
.table:hover .tableHead .check {
  opacity: 1;
}
.fileIcon {
  position: relative;
  display: grid;
  flex: none;
  place-items: center;
  width: 26px;
  height: 26px;
  border: 1px solid var(--line);
  border-radius: 7px;
  background: var(--icon-tile);
  color: var(--doc);
}
.fileIcon i {
  position: absolute;
  top: 12px;
  left: 11px;
  width: 4px;
  height: 4px;
  border-radius: 1px;
  background: currentColor;
}
.fileIcon[data-kind='pdf'] {
  color: var(--pdf);
}
.fileIcon[data-kind='sheet'] {
  color: var(--sheet);
}
.fileIcon[data-kind='slides'] {
  color: var(--slides);
}
.fileIcon[data-kind='image'] {
  color: var(--image);
}
.fileName {
  margin-left: 10px;
  overflow: hidden;
  font-size: 12.5px;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.ownerName {
  overflow: hidden;
  color: var(--ink-2);
  font-size: 12.5px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.empty {
  padding: 22px 0 6px;
  color: var(--muted);
  font-size: 12.5px;
  text-align: center;
}

/* The selection bar: it sticks to the foot of the scrolling column (or of the screen, when the
   library is narrow and the page scrolls). */
.barSlot {
  position: sticky;
  bottom: 4px;
  z-index: 4;
  flex: none;
  height: 0;
  margin-top: auto;
  pointer-events: none;
}
.bar {
  position: absolute;
  bottom: 0;
  left: 50%;
  display: flex;
  align-items: center;
  gap: 4px;
  height: 44px;
  padding: 0 6px;
  border: 1px solid var(--line);
  border-radius: 12px;
  background: var(--pop);
  box-shadow: 0 16px 36px -14px var(--shadow-deep);
  white-space: nowrap;
  opacity: 0;
  transform: translate(-50%, 14px) scale(0.97);
  transition:
    opacity 0.18s,
    transform 0.18s cubic-bezier(0.2, 0.8, 0.3, 1);
}
.bar[data-shown] {
  opacity: 1;
  transform: translate(-50%, 0);
  pointer-events: auto;
}
.barCount {
  padding: 0 10px 0 8px;
  color: var(--ink-2);
  font-size: 12.5px;
  font-variant-numeric: tabular-nums;
}
.bar .primary {
  height: 32px;
  padding: 0 12px;
}
.barMenuWrap {
  position: relative;
}
.barButton {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  height: 32px;
  padding: 0 10px;
  border-radius: 8px;
  color: var(--ink-2);
  font-size: 12.5px;
}
.barButton:hover,
.barClose:hover {
  background: var(--hover);
}
.barButton svg,
.barClose {
  color: var(--muted);
}
.barDivider {
  width: 1px;
  height: 18px;
  margin: 0 2px;
  background: var(--line);
}
.barClose {
  display: grid;
  place-items: center;
  width: 30px;
  height: 30px;
  border-radius: 8px;
}
.menu {
  position: absolute;
  bottom: calc(100% + 10px);
  left: 0;
  min-width: 196px;
  padding: 4px;
  border: 1px solid var(--line);
  border-radius: 10px;
  background: var(--pop);
  box-shadow: 0 16px 36px -12px var(--shadow-deep);
  animation: toastIn 0.16s ease-out;
}
.menuItem {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  height: 30px;
  padding: 0 8px;
  border-radius: 6px;
  color: var(--ink);
  font-size: 12.5px;
  text-align: left;
}
.menuItem svg {
  color: var(--muted);
}
.menuItem:hover {
  background: var(--badge);
}
.menuItem:focus-visible {
  outline: 0;
  background: var(--accent-soft);
  box-shadow: inset 0 0 0 1px var(--ring);
}
.menuCount {
  margin-left: auto;
  color: var(--muted);
  font-size: 11px;
  font-variant-numeric: tabular-nums;
}

/* The ghost: over everything, following the pointer. */
.ghostLayer {
  position: absolute;
  inset: 0;
  z-index: 6;
  pointer-events: none;
}
.ghost {
  position: absolute;
  top: 0;
  left: 0;
  transform-origin: 50% 50%;
  will-change: transform;
}
.ghostTilt {
  position: relative;
  display: block;
  isolation: isolate;
  transform: rotate(3deg);
  animation: ghostLift 0.16s ease-out;
}
.ghost[data-kind='upload'] .ghostTilt {
  transform: rotate(-3deg);
}
@keyframes ghostLift {
  from {
    opacity: 0.4;
    transform: rotate(0deg) scale(0.97);
  }
}
.ghostChip,
.ghostBehind {
  border: 1px solid var(--line);
  border-radius: 10px;
  background: var(--pop);
}
.ghostChip {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 200px;
  height: 40px;
  padding: 0 12px 0 7px;
  box-shadow:
    0 14px 30px -10px var(--shadow-deep),
    0 2px 6px -2px var(--shadow);
}
.ghostBehind {
  position: absolute;
  inset: 0;
  z-index: -1;
  box-shadow: 0 6px 16px -8px var(--shadow-deep);
  transform: translate(-7px, 7px) rotate(-4deg);
}
.ghostBehind + .ghostBehind {
  z-index: -2;
  transform: translate(-13px, 13px) rotate(-8deg);
}
.ghostName {
  font-size: 12.5px;
  font-weight: 500;
  white-space: nowrap;
}
.ghostSize {
  margin-left: auto;
  padding-left: 16px;
  color: var(--muted);
  font-size: 11px;
  white-space: nowrap;
}
.ghostCount {
  position: absolute;
  top: -9px;
  right: -9px;
  display: grid;
  place-items: center;
  min-width: 20px;
  height: 20px;
  padding: 0 5px;
  border-radius: 10px;
  background: var(--accent);
  box-shadow: 0 0 0 2px var(--app);
  color: var(--accent-ink);
  font-size: 11px;
  font-weight: 600;
}
.ghostPicture {
  position: relative;
  display: block;
  width: 152px;
  padding: 6px 6px 0;
  border: 1px solid var(--line);
  border-radius: 12px;
  background: var(--pop);
  box-shadow: 0 18px 36px -12px var(--shadow-deep);
}
.ghostPicture > i {
  display: block;
  height: 104px;
  border-radius: 8px;
  background:
    radial-gradient(70% 60% at 78% 18%, rgb(255 255 255 / 0.4), transparent 60%),
    linear-gradient(140deg, hsl(var(--h1) 88% 56%), hsl(var(--h2) 90% 60%));
}
.ghostCaption {
  display: flex;
  justify-content: space-between;
  gap: 8px;
  padding: 7px 3px 8px;
  font-size: 10.5px;
  font-weight: 500;
  white-space: nowrap;
}
.ghostCaption span + span {
  color: var(--muted);
  font-weight: 400;
}
.ghostPlus {
  position: absolute;
  top: -8px;
  left: -8px;
  display: grid;
  place-items: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: var(--green);
  box-shadow: 0 0 0 2px var(--app);
  color: #fff;
}

/* The demo pointer, over everything; one of its glyphs shows at a time. */
.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 9;
  pointer-events: none;
}
.pointer {
  width: 22px;
  height: 22px;
}
.hand {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .hand {
  visibility: visible;
}

.hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

/* The sidebar's button hides it on a wide library. */
@container fl (min-width: 720px) {
  .sidebar[data-hidden] {
    display: none;
  }
  .body:has(> .sidebar[data-hidden]) {
    grid-template-columns: 52px minmax(0, 1fr);
  }
}
@container fl (max-width: 1000px) {
  .row {
    grid-template-columns: 40px minmax(0, 1fr) 150px 84px;
  }
}

/* Narrow: no rail, the sidebar a drawer over the main column, the window as tall as it needs. */
@container fl (max-width: 719.98px) {
  .window {
    height: auto;
  }
  .body {
    grid-template-columns: minmax(0, 1fr);
  }
  .rail {
    display: none;
  }
  .sidebar {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    z-index: 8;
    width: min(270px, 84%);
    padding-bottom: 12px;
    box-shadow: 12px 0 32px -12px var(--shadow-deep);
    visibility: hidden;
    transform: translateX(-104%);
    transition:
      transform 0.24s cubic-bezier(0.3, 0, 0.2, 1),
      visibility 0s 0.24s;
  }
  .sidebar[data-drawer] {
    visibility: visible;
    transform: none;
    transition: transform 0.24s cubic-bezier(0.2, 0.8, 0.3, 1);
  }
  .scrim {
    position: absolute;
    inset: 0;
    z-index: 7;
    background: var(--scrim);
  }
  .mainHead {
    padding: 0 10px 0 16px;
  }
  .people {
    display: none;
  }
  .buttonText {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip-path: inset(50%);
  }
  .button {
    width: 28px;
    justify-content: center;
    padding: 0;
  }
  .toastSlot {
    right: 12px;
    left: 12px;
    display: flex;
    justify-content: center;
  }
  .scroll {
    padding: 16px 14px 18px;
    overflow: visible;
  }
  .barSlot {
    bottom: 12px;
  }
  .row {
    grid-template-columns: 34px minmax(0, 1fr) 30px 62px;
  }
  .cellCheck {
    padding-right: 6px;
  }
  .cellSize {
    justify-content: flex-end;
    padding-right: 12px;
  }
  .ownerName,
  .tableHead .cellOwner {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip-path: inset(50%);
  }
  /* No hover on a phone: the boxes show, so a tap has somewhere to go. */
  .check {
    opacity: 1;
  }
}

@media (prefers-reduced-motion: reduce) {
  .rowWrap,
  .rowWrap > .row,
  .tile,
  .papers,
  .front,
  .bar,
  .sidebar,
  .sidebar[data-drawer],
  .doneBadge,
  .uploadPill {
    transition-duration: 0s;
  }
  .rowWrap[data-entering],
  .paper[data-fresh],
  .toast,
  .menu,
  .ghostTilt {
    animation: none;
  }
  .tile[data-over] .front,
  .tile[data-over] .papers {
    transform: none;
  }
}
```

### file-library/folder-art.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

import type { CSSProperties } from 'react';
import { PEOPLE, type Folder, type PersonId } from './data';
import { Icon } from './icons';
import styles from './file-library.module.css';

/*
 * A folder tile's picture, 134 × 104 px: the folder's back with its tab, up to three papers
 * peeking out of it, and a frosted front panel over their lower half. The papers are the
 * folder's last three files, the newest in front, so the cover changes as files go in: a white
 * page with its type's coloured square for a document, a gradient card for a picture. The front
 * carries the members, a Private chip, or an upload's progress and its check.
 *
 * Everything that moves is CSS on the tile's data attributes (file-library.module.css): over a
 * drag, the front tips forward on its bottom edge and the papers rise; a new paper drops in.
 */

/** The small round face used across the library: initials on a pastel. */
export function Avatar({ id, className }: { id: PersonId; className?: string }) {
  return (
    <span className={`${styles.avatar} ${className ?? ''}`} data-person={id} aria-hidden="true">
      {PEOPLE[id].initials}
    </span>
  );
}

/** How the papers fan out, by depth (0 is the cover): x and y in px, then the turn in degrees. */
const FAN: [number, number, number][] = [
  [5, 3, 0.5],
  [-7, 0, -5],
  [12, -2, 4.5],
];

export function FolderArt({
  folder,
  fresh,
  progress,
  done,
}: {
  folder: Folder;
  /** Papers that just went in: they drop into place. */
  fresh: ReadonlySet<string>;
  /** An upload into this folder, 0 to 100, or null. */
  progress: number | null;
  /** An upload just finished here: the check shows. */
  done: boolean;
}) {
  const shown = folder.papers.slice(-3);
  return (
    <span className={styles.art} data-part="folder-art" aria-hidden="true">
      <svg className={styles.back} viewBox="0 0 134 104" preserveAspectRatio="none">
        {/* The back, with its tab on the left: one path so the tab's shoulder curves into it. */}
        <path d="M0 10a10 10 0 0 1 10-10h26c3.4 0 5.6 1.2 7.6 3.4L47 7.2c1.6 1.8 3.4 2.6 5.8 2.6H124a10 10 0 0 1 10 10V94a10 10 0 0 1-10 10H10A10 10 0 0 1 0 94Z" />
      </svg>
      <span className={styles.papers}>
        {shown.map((paper, index) => (
          <span
            key={paper.id}
            className={styles.paper}
            data-kind={paper.kind}
            data-fresh={fresh.has(paper.id) || undefined}
            style={
              {
                '--x': `${FAN[shown.length - 1 - index][0]}px`,
                '--y': `${FAN[shown.length - 1 - index][1]}px`,
                '--r': `${FAN[shown.length - 1 - index][2]}deg`,
                '--h1': paper.hues?.[0],
                '--h2': paper.hues?.[1],
              } as CSSProperties
            }
          >
            {paper.kind !== 'image' && (
              <>
                <i className={styles.paperSquare} />
                <i className={styles.paperLine} />
                <i className={styles.paperLine} />
              </>
            )}
          </span>
        ))}
      </span>
      <span className={styles.front} data-part="folder-front">
        {progress !== null ? (
          <span className={styles.progress}>
            <span style={{ transform: `scaleX(${progress / 100})` }} />
          </span>
        ) : folder.private ? (
          <span className={styles.privateChip}>
            <Icon name="lock" width="10" height="10" />
            Private
          </span>
        ) : (
          <span className={styles.members}>
            {folder.members.map((id) => (
              <Avatar key={id} id={id} className={styles.memberAvatar} />
            ))}
          </span>
        )}
        <span className={styles.doneBadge} data-shown={done || undefined}>
          <Icon name="check" width="10" height="10" strokeWidth="2" />
        </span>
      </span>
    </span>
  );
}
```

### file-library/data.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The library's starting contents: the people, the folders under General with the papers that
 * peek out of each, and the nine files loose in General. Counts add up: General's 34 is its four
 * folders (12 + 8 + 0 + 5) and its nine files, so a move between them leaves it unchanged.
 */

export type PersonId = 'mc' | 'aw' | 'kd' | 'sl' | 'you';
export type Person = { id: PersonId; name: string; initials: string };

export const PEOPLE: Record<PersonId, Person> = {
  mc: { id: 'mc', name: 'Maya Chen', initials: 'MC' },
  aw: { id: 'aw', name: 'Arno Weiss', initials: 'AW' },
  kd: { id: 'kd', name: 'Kai Doyle', initials: 'KD' },
  sl: { id: 'sl', name: 'Sara Lind', initials: 'SL' },
  you: { id: 'you', name: 'You', initials: 'YO' },
};

/** A file's type: its badge colour in the table and the square on its paper in a folder. */
export type Kind = 'pdf' | 'doc' | 'sheet' | 'slides' | 'image';

export type FileItem = {
  id: string;
  name: string;
  kind: Kind;
  owner: PersonId;
  size: string;
};

/**
 * A sheet that peeks out of a folder: a white page with a coloured square for a document, a
 * gradient card for a picture (its two hues).
 */
export type Paper = { id: string; kind: Kind; hues?: [number, number] };

export type Folder = {
  id: string;
  name: string;
  count: number;
  members: PersonId[];
  private?: boolean;
  /** Back to front: the last one is the cover, in front of the others. */
  papers: Paper[];
};

export const FOLDERS: Folder[] = [
  {
    id: 'onboarding',
    name: 'Onboarding',
    count: 12,
    members: ['mc', 'aw', 'kd'],
    papers: [
      { id: 'on-1', kind: 'doc' },
      { id: 'on-2', kind: 'pdf' },
      { id: 'on-3', kind: 'doc' },
    ],
  },
  {
    id: 'brand',
    name: 'Brand Assets',
    count: 8,
    members: ['sl', 'mc'],
    papers: [
      { id: 'br-1', kind: 'image', hues: [221, 232] },
      { id: 'br-2', kind: 'image', hues: [18, 34] },
    ],
  },
  { id: 'contracts', name: 'Contracts', count: 0, members: [], private: true, papers: [] },
  {
    id: 'research',
    name: 'Research',
    count: 5,
    members: ['kd', 'sl'],
    papers: [
      { id: 're-1', kind: 'sheet' },
      { id: 're-2', kind: 'doc' },
    ],
  },
];

/** The folders that sit beside General in the tree, outside this view. */
export const OTHER_FOLDERS = ['Design Reviews', 'Team Interviews'];
/** What the Shared tab lists: folders other teams shared with this one. */
export const SHARED_FOLDERS = [
  { name: 'Client Handoff', count: 6 },
  { name: 'Press Kit', count: 14 },
];

export const GENERAL_COUNT = 34;

export const FILES: FileItem[] = [
  { id: 'f1', name: 'Pitch-Deck-v4.pdf', kind: 'pdf', owner: 'mc', size: '4.2 MB' },
  { id: 'f2', name: 'NDA-Halden.pdf', kind: 'pdf', owner: 'aw', size: '380 KB' },
  { id: 'f3', name: 'Vendor-Agreement.docx', kind: 'doc', owner: 'kd', size: '96 KB' },
  { id: 'f4', name: 'SOW-Q4-Final.pdf', kind: 'pdf', owner: 'mc', size: '1.1 MB' },
  { id: 'f5', name: 'Hiring-Plan-2027.xlsx', kind: 'sheet', owner: 'sl', size: '220 KB' },
  { id: 'f6', name: 'Offsite-Agenda.pptx', kind: 'slides', owner: 'aw', size: '12 MB' },
  { id: 'f7', name: 'Logo-Usage.pdf', kind: 'pdf', owner: 'kd', size: '2.8 MB' },
  { id: 'f8', name: 'Roadmap-H1.pdf', kind: 'pdf', owner: 'sl', size: '640 KB' },
  { id: 'f9', name: 'Interview-Notes.docx', kind: 'doc', owner: 'mc', size: '54 KB' },
];

/** The picture the demo drops in from outside, onto Brand Assets. */
export const DEMO_UPLOAD = { name: 'moodboard-07.png', size: '2.4 MB', hues: [268, 322] } as const;

/** A file's type from its name, for files the reader drops or picks. */
export function kindOf(name: string): Kind {
  const ext = name.split('.').pop()?.toLowerCase() ?? '';
  if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'heic', 'svg'].includes(ext)) return 'image';
  if (['xls', 'xlsx', 'csv', 'numbers'].includes(ext)) return 'sheet';
  if (['ppt', 'pptx', 'key'].includes(ext)) return 'slides';
  if (ext === 'pdf') return 'pdf';
  return 'doc';
}

/** Two hues for a picture's card, from its name, so the same file always looks the same. */
export function huesOf(name: string): [number, number] {
  let hash = 0;
  for (const char of name) hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
  const first = hash % 360;
  return [first, (first + 40 + (hash % 50)) % 360];
}

/** Bytes in the units the table uses. */
export function formatSize(bytes: number) {
  if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(1)} MB`;
  return `${Math.max(1, Math.round(bytes / 1e3))} KB`;
}
```

### file-library/icons.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

import type { ReactNode, SVGProps } from 'react';

/*
 * The library's icons, drawn for it on a 16-unit grid with a 1.4 stroke in currentColor. All of
 * them are decorative: the control around each one carries its name.
 */

export type IconName =
  | 'mark'
  | 'home'
  | 'folder'
  | 'folderOpen'
  | 'clock'
  | 'people'
  | 'trash'
  | 'plus'
  | 'panel'
  | 'search'
  | 'chevron'
  | 'updown'
  | 'link'
  | 'upload'
  | 'check'
  | 'close'
  | 'move'
  | 'lock'
  | 'file';

const PATHS: Record<IconName, ReactNode> = {
  // The workspace's mark: a ring with a bite out of it.
  mark: (
    <path
      d="M11.6 4.6A5 5 0 1 0 11.6 11.4 3.6 3.6 0 1 1 11.6 4.6Z"
      fill="currentColor"
      stroke="none"
    />
  ),
  home: <path d="M2.8 7.2 8 3l5.2 4.2V13a.8.8 0 0 1-.8.8H9.6V10H6.4v3.8H3.6a.8.8 0 0 1-.8-.8Z" />,
  folder: (
    <path d="M2.2 4.6c0-.6.5-1.1 1.1-1.1h2.9l1.4 1.5h5.1c.6 0 1.1.5 1.1 1.1v5.8c0 .6-.5 1.1-1.1 1.1H3.3c-.6 0-1.1-.5-1.1-1.1Z" />
  ),
  folderOpen: (
    <>
      <path d="M2.2 11.4V4.6c0-.6.5-1.1 1.1-1.1h2.9l1.4 1.5h4.5c.6 0 1.1.5 1.1 1.1v1.1" />
      <path d="M2.2 11.4 3.9 7.8c.2-.4.6-.6 1-.6h8.5c.5 0 .8.5.6.9l-1.6 3.6c-.2.4-.6.7-1 .7H3.3c-.6 0-1.1-.5-1.1-1Z" />
    </>
  ),
  clock: (
    <>
      <circle cx="8" cy="8" r="5.6" />
      <path d="M8 5v3.2l2.1 1.3" />
    </>
  ),
  people: (
    <>
      <circle cx="6.2" cy="5.6" r="2.3" />
      <path d="M2.2 13c.4-2.2 2-3.4 4-3.4s3.6 1.2 4 3.4" />
      <path d="M10.4 3.6a2.2 2.2 0 0 1 0 4.1M11.8 9.9c1 .5 1.7 1.6 2 3.1" />
    </>
  ),
  trash: (
    <>
      <path d="M2.8 4.4h10.4M6.4 4.4V3c0-.3.3-.6.6-.6h2c.3 0 .6.3.6.6v1.4" />
      <path d="M4 4.4l.6 8.4c0 .5.5.9 1 .9h4.8c.5 0 1-.4 1-.9l.6-8.4M6.8 7v4.2M9.2 7v4.2" />
    </>
  ),
  plus: <path d="M8 3.2v9.6M3.2 8h9.6" />,
  panel: (
    <>
      <rect x="2.4" y="2.8" width="11.2" height="10.4" rx="1.8" />
      <path d="M6.2 2.8v10.4" />
    </>
  ),
  search: (
    <>
      <circle cx="7.2" cy="7.2" r="4.2" />
      <path d="m10.4 10.4 3 3" />
    </>
  ),
  chevron: <path d="m4.8 6.4 3.2 3.2 3.2-3.2" />,
  updown: <path d="m5.4 6 2.6-2.6L10.6 6M5.4 10 8 12.6l2.6-2.6" />,
  link: (
    <>
      <path d="M6.9 9.1a2.6 2.6 0 0 0 3.7 0l2-2a2.6 2.6 0 0 0-3.7-3.7l-.7.7" />
      <path d="M9.1 6.9a2.6 2.6 0 0 0-3.7 0l-2 2a2.6 2.6 0 0 0 3.7 3.7l.7-.7" />
    </>
  ),
  upload: (
    <>
      <path d="M8 10.4V3M5 5.8 8 2.8l3 3" />
      <path d="M2.8 10.2v1.9c0 .6.5 1.1 1.1 1.1h8.2c.6 0 1.1-.5 1.1-1.1v-1.9" />
    </>
  ),
  check: <path d="m3.8 8.3 2.7 2.7 5.7-6" />,
  close: <path d="m4.4 4.4 7.2 7.2M11.6 4.4l-7.2 7.2" />,
  // A folder with an arrow going in: Move to.
  move: (
    <>
      <path d="M2.2 7.4V4.6c0-.6.5-1.1 1.1-1.1h2.9l1.4 1.5h5.1c.6 0 1.1.5 1.1 1.1v5.8c0 .6-.5 1.1-1.1 1.1H8.6" />
      <path d="M2 10.4h4.6M5 8.6l1.8 1.8L5 12.2" />
    </>
  ),
  lock: (
    <>
      <rect x="3.6" y="7" width="8.8" height="6.4" rx="1.4" />
      <path d="M5.6 7V5.4a2.4 2.4 0 0 1 4.8 0V7" />
    </>
  ),
  file: (
    <>
      <path d="M4 2.6h5l3 3v7.2c0 .4-.3.6-.6.6H4.6c-.4 0-.6-.2-.6-.6Z" />
      <path d="M9 2.6v3h3" />
    </>
  ),
};

export function Icon({ name, ...rest }: { name: IconName } & SVGProps<SVGSVGElement>) {
  return (
    <svg
      viewBox="0 0 16 16"
      width="16"
      height="16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.4"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
      focusable="false"
      {...rest}
    >
      {PATHS[name]}
    </svg>
  );
}
```

### file-library/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it (nothing here uses
 * them yet). The arrow and the hand are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the hand a link shows. */
  glyph: (name: 'arrow' | 'hand') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (file-library.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, the hand white on a dark one, as the system draws them. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const HAND: CSSProperties = { fill: 'var(--pointer-edge)', stroke: 'var(--pointer)' };

/**
 * The pointer the demo moves around: an arrow, or a pointing hand over a control. It is
 * decorative: what it does shows on the control itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  handClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  handClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={handClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The tip of the finger sits where the arrow's tip is. */}
          <path
            d="M6.4 3.3c0-.8.6-1.4 1.3-1.4S9 2.5 9 3.3v5.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.7c.2-.4.6-.7 1.1-.7.7 0 1.2.5 1.2 1.2v3.5c0 2.8-1.9 4.9-4.6 4.9h-1.2c-1.8 0-3.1-.8-4.1-2.3l-2.6-3.9c-.4-.6-.2-1.3.4-1.7.6-.3 1.3-.2 1.7.4l.6.9z"
            style={HAND}
            strokeWidth="1.1"
            strokeLinejoin="round"
            transform="translate(-4.7 0.1)"
          />
        </svg>
      </span>
    </span>
  );
}
```

### file-library/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and never again once the reader has used it: `take()` hands it to the
 * reader for good (until the component mounts again), so it can't come back on its own.
 */
export function useAutoplay<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => setTaken(true), []);

  return { ref, take, playing: visible && !reduced && !taken };
}
```