strata-react 1.0.41 → 1.0.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +3 -3
  2. package/UPGRADING.md +9 -1
  3. package/dist/components/book-viewer.d.ts +50 -0
  4. package/dist/components/box-overlay.d.ts +42 -0
  5. package/dist/components/button.d.ts +3 -1
  6. package/dist/components/conversation.d.ts +3 -1
  7. package/dist/components/folder-picker.d.ts +20 -3
  8. package/dist/components/lightbox.d.ts +28 -1
  9. package/dist/components/line-chart.d.ts +7 -1
  10. package/dist/components/region-editor.d.ts +14 -2
  11. package/dist/components/selectable-grid.d.ts +2 -4
  12. package/dist/components/tile-grid.d.ts +57 -0
  13. package/dist/components/tree.d.ts +3 -1
  14. package/dist/{errors-BunUBqpA.js → errors-ByjNcEDc.js} +25 -2
  15. package/dist/errors-ByjNcEDc.js.map +1 -0
  16. package/dist/index.d.ts +8 -3
  17. package/dist/index.js +1249 -241
  18. package/dist/index.js.map +1 -1
  19. package/dist/lib/book.d.ts +25 -0
  20. package/dist/lib/boxes.d.ts +32 -0
  21. package/dist/lib/dev.d.ts +2 -0
  22. package/dist/lib/region.d.ts +18 -0
  23. package/dist/panorama.js +1 -1
  24. package/dist/{query-B934ufsW.js → query-ib0ScvU2.js} +3 -2
  25. package/dist/query-ib0ScvU2.js.map +1 -0
  26. package/dist/{run-DEf1Vh0x.js → run-DE65qInG.js} +22 -2
  27. package/dist/run-DE65qInG.js.map +1 -0
  28. package/dist/testing.js +1 -1
  29. package/dist/{value-controls-FO4zQiHP.js → value-controls-DxbyeTQd.js} +2 -2
  30. package/dist/{value-controls-FO4zQiHP.js.map → value-controls-DxbyeTQd.js.map} +1 -1
  31. package/dist/visual/serve.d.ts +2 -0
  32. package/dist/visual-cli.js +1 -1
  33. package/dist/visual.js +1 -1
  34. package/package.json +1 -1
  35. package/dist/errors-BunUBqpA.js.map +0 -1
  36. package/dist/query-B934ufsW.js.map +0 -1
  37. package/dist/run-DEf1Vh0x.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import { a as Textarea, c as Tooltip, d as typeSteps, i as NativeSelect, l as KeyText, n as Field, o as useFieldControl, r as Input, s as controlHeight, t as ChoiceGroup, u as cn } from "./field-DeKNvGox.js";
2
2
  import { a as toDate, i as format, n as NBSP, r as createFormat, t as MISSING } from "./format-B32-PVi2.js";
3
- import { a as useAsyncAction, c as KeysLegend, d as useInView, i as AsyncButton, l as isTypingTarget, n as NumberField, o as Toolbar, r as Slider, s as ToolbarSeparator, t as ColorField, u as useHotkeys } from "./value-controls-FO4zQiHP.js";
4
- import { a as readErrorBody, c as RowAction, i as fieldErrorsOf, l as buttonVariants, n as describeActionError, o as Button, r as describeHttpError, s as IconButton, t as HttpError } from "./errors-BunUBqpA.js";
5
- import { a as toLoad, c as toast, i as staleOf, l as toastTimeout, n as createQueryClient, o as useLoad, r as fetchJson, s as StrataToastRegion, t as StrataQueryProvider, u as overlaySurface } from "./query-B934ufsW.js";
3
+ import { a as useAsyncAction, c as KeysLegend, d as useInView, i as AsyncButton, l as isTypingTarget, n as NumberField, o as Toolbar, r as Slider, s as ToolbarSeparator, t as ColorField, u as useHotkeys } from "./value-controls-DxbyeTQd.js";
4
+ import { a as readErrorBody, c as RowAction, i as fieldErrorsOf, l as buttonVariants, n as describeActionError, o as Button, r as describeHttpError, s as IconButton, t as HttpError, u as isDev } from "./errors-ByjNcEDc.js";
5
+ import { a as toLoad, c as toast, i as staleOf, l as toastTimeout, n as createQueryClient, o as useLoad, r as fetchJson, s as StrataToastRegion, t as StrataQueryProvider, u as overlaySurface } from "./query-ib0ScvU2.js";
6
6
  import { n as useSharedCursor, r as geo, t as CursorScope } from "./cursor-DDGBPiTJ.js";
7
7
  import { a as useColorScheme, i as colorSchemeScript, n as ColorSchemeChoice, o as useSystemColorScheme, r as ThemeProvider, s as Density, t as COLOR_SCHEME_STORAGE_KEY } from "./theme-DVaIxyNn.js";
8
8
  import * as React from "react";
9
- import { Autocomplete, Button as Button$1, Cell, Checkbox as Checkbox$1, Collection, Column, Dialog as Dialog$1, DialogTrigger, Disclosure as Disclosure$1, DisclosurePanel, DropIndicator, DropZone, FileTrigger, GridLayout, GridList, GridListItem, Header, Heading, Input as Input$1, Keyboard, ListLayout, ListStateContext, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, Popover as Popover$1, Row, SearchField, Separator, Slider as Slider$1, SliderThumb, SliderTrack, SubmenuTrigger, Switch as Switch$1, Tab, TabList, TabPanel, Table, TableBody, TableHeader, TableLayout, Tabs as Tabs$1, Text, ToggleButton, ToggleButtonGroup, Tree as Tree$1, TreeItem, TreeItemContent, Virtualizer, useDragAndDrop, useFilter } from "react-aria-components";
10
- import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, Ellipsis, Eye, EyeOff, FileQuestion, Flag, Folder, FolderOpen, GripVertical, History, ImageOff, Info, KeyRound, Loader, LoaderCircle, Lock, Maximize, Maximize2, Minimize, Minus, PanelBottomClose, PanelBottomOpen, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen, PanelTopClose, PanelTopOpen, Pause, Pencil, Play, Redo2, RotateCcw, Scan, Search, Send, SkipBack, SkipForward, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
9
+ import { Autocomplete, Button as Button$1, Cell, Checkbox as Checkbox$1, Collection, Column, Dialog as Dialog$1, DialogTrigger, Disclosure as Disclosure$1, DisclosurePanel, DropIndicator, DropZone, FileTrigger, GridLayout, GridList, GridListItem, Header, Heading, Input as Input$1, Keyboard, ListBox, ListBoxItem, ListLayout, ListStateContext, Menu as Menu$1, MenuItem, MenuSection, MenuTrigger, Modal, ModalOverlay, Popover as Popover$1, RouterProvider, Row, SearchField, Separator, Slider as Slider$1, SliderThumb, SliderTrack, SubmenuTrigger, Switch as Switch$1, Tab, TabList, TabPanel, Table, TableBody, TableHeader, TableLayout, Tabs as Tabs$1, Text, ToggleButton, ToggleButtonGroup, Tree as Tree$1, TreeItem, TreeItemContent, Virtualizer, useDragAndDrop, useFilter } from "react-aria-components";
10
+ import { ArrowDown, ArrowUp, ArrowUpDown, ArrowUpRight, Ban, Check, ChevronLeft, ChevronRight, CircleAlert, CircleCheck, Columns2, Ellipsis, Eye, EyeOff, FileQuestion, Flag, Folder, FolderOpen, GripVertical, History, ImageOff, Info, KeyRound, Loader, LoaderCircle, Lock, Maximize, Maximize2, Minimize, Minus, PanelBottomClose, PanelBottomOpen, PanelLeftClose, PanelLeftOpen, PanelRightClose, PanelRightOpen, PanelTopClose, PanelTopOpen, Pause, Pencil, Play, Redo2, RotateCcw, RotateCw, Scan, Search, Send, SkipBack, SkipForward, Square, StepBack, StepForward, Trash2, TriangleAlert, Undo2, Upload, Volume2, VolumeX, X, ZoomIn, ZoomOut } from "lucide-react";
11
11
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
- import { Link, NavLink, useSearchParams } from "react-router";
12
+ import { Link, NavLink, useHref, useNavigate, useSearchParams } from "react-router";
13
13
  import { createSortedRowModel, flexRender, rowSortingFeature, tableFeatures, useTable } from "@tanstack/react-table";
14
14
  import { VisuallyHidden, mergeProps, useDrop, useFocusRing, useMove, useSlider, useSliderThumb } from "react-aria";
15
15
  import { Size, useSliderState } from "react-stately";
@@ -177,6 +177,19 @@ function useCommands(commands, { enabled = true, platform } = {}) {
177
177
  window.addEventListener("keydown", onKeyDown);
178
178
  return () => window.removeEventListener("keydown", onKeyDown);
179
179
  }, [enabled, where]);
180
+ if (isDev()) warnOnClashes(commands, where);
181
+ }
182
+ function warnOnClashes(commands, platform) {
183
+ const seen = /* @__PURE__ */ new Map();
184
+ for (const c of commands) {
185
+ for (const k of c.keys ?? []) {
186
+ const shown = formatChord(k, platform);
187
+ const other = seen.get(shown);
188
+ if (other && other !== c.id) console.warn(`strata-react: "${shown}" is bound to both "${other}" and "${c.id}"; the first wins.`);
189
+ else seen.set(shown, c.id);
190
+ }
191
+ if (c.keys?.some((k) => isReservedChord(k, platform)) && !c.claim) console.warn(`strata-react: "${c.id}" uses a chord the browser keeps for itself; add \`claim: true\` to take it over.`);
192
+ }
180
193
  }
181
194
  /** The shortcut a command shows in menus and legends ("⌘Z", "Ctrl+Z"), or undefined. */
182
195
  function commandShortcut(c, platform = detectPlatform()) {
@@ -3450,7 +3463,7 @@ var keyPlayers = (() => {
3450
3463
  get: () => snapshot,
3451
3464
  add(id) {
3452
3465
  ids.add(id);
3453
- if (ids.size === 2 && !warned && typeof process !== "undefined" && process.env.NODE_ENV !== "production") {
3466
+ if (ids.size === 2 && !warned && isDev()) {
3454
3467
  warned = true;
3455
3468
  console.warn("strata-react: several MediaPlayers are on this page, so Space, K, J, L and M go to the one last played or focused. Pass shortcuts={false} to one you bind your own keys for.");
3456
3469
  }
@@ -6372,7 +6385,7 @@ function PropertyList({ items, label, className }) {
6372
6385
  })
6373
6386
  });
6374
6387
  }
6375
- // src/components/selectable-grid.tsx
6388
+ // src/components/tile-grid.tsx
6376
6389
  var minWidth = {
6377
6390
  sm: 96,
6378
6391
  md: 144,
@@ -6388,8 +6401,90 @@ var aspectRatio = {
6388
6401
  portrait: 4 / 3,
6389
6402
  landscape: 3 / 4
6390
6403
  };
6404
+ var thumbnailAspect = {
6405
+ square: 1,
6406
+ portrait: 3 / 4,
6407
+ landscape: 4 / 3
6408
+ };
6391
6409
  var GAP = 12;
6392
6410
  var TILE_CHROME = 40;
6411
+ /** `GridLayout` options for tiles of this size and aspect: they grow from the minimum width to fill the row, and each row is as tall as its tallest tile as measured. */
6412
+ function tileLayoutOptions(tileSize, aspect) {
6413
+ return {
6414
+ minItemSize: new Size(minWidth[tileSize], Math.round(minWidth[tileSize] * aspectRatio[aspect]) + TILE_CHROME),
6415
+ minSpace: new Size(GAP, GAP)
6416
+ };
6417
+ }
6418
+ /** A grid of picture tiles that open something: a labelled list of links (or actions), two-dimensional arrow keys, a caption, a detail line and a corner badge on each, virtualised from `virtualizeFrom` tiles. No selection: use `SelectableGrid` for that. */
6419
+ function TileGrid({ label, items, itemKey, itemLabel, renderImage, caption, detail, badge, href, onAction, aspect = "square", tileSize = "md", virtualizeFrom = 100, maxHeight = 480, className }) {
6420
+ const navigate = useNavigate();
6421
+ const virtual = items.length >= virtualizeFrom;
6422
+ const layoutOptions = React.useMemo(() => tileLayoutOptions(tileSize, aspect), [tileSize, aspect]);
6423
+ const byKey = React.useMemo(() => new Map(items.map((item) => [itemKey(item), item])), [items, itemKey]);
6424
+ const grid = /* @__PURE__ */ jsx(GridList, {
6425
+ "aria-label": label,
6426
+ layout: "grid",
6427
+ "data-strata-scroll": "",
6428
+ onAction: onAction ? (key) => void (byKey.has(String(key)) && onAction(byKey.get(String(key)))) : void 0,
6429
+ className: cn("min-w-0 outline-none", virtual ? "overflow-y-auto" : "grid gap-3"),
6430
+ style: virtual ? { height: maxHeight } : { gridTemplateColumns: `repeat(auto-fill, minmax(min(${minWidth[tileSize]}px, 100%), 1fr))` },
6431
+ children: items.map((item, index) => {
6432
+ const key = itemKey(item);
6433
+ const corner = badge?.(item);
6434
+ return /* @__PURE__ */ jsxs(GridListItem, {
6435
+ id: key,
6436
+ textValue: itemLabel(item),
6437
+ "aria-label": itemLabel(item),
6438
+ href: href?.(item),
6439
+ "data-index": index,
6440
+ className: "group relative grid min-w-0 cursor-pointer gap-1.5 rounded-surface border border-transparent p-1.5 select-none outline-offset-2 transition-state hover:bg-surface-sunken",
6441
+ children: [
6442
+ /* @__PURE__ */ jsx("span", {
6443
+ className: cn("block overflow-hidden rounded-control bg-muted *:size-full *:object-cover", aspectClass[aspect]),
6444
+ children: renderImage(item)
6445
+ }),
6446
+ corner != null && /* @__PURE__ */ jsx("span", {
6447
+ className: "absolute top-3 right-3",
6448
+ children: corner
6449
+ }),
6450
+ caption?.(item) != null && /* @__PURE__ */ jsx("span", {
6451
+ className: "truncate type-label",
6452
+ children: caption(item)
6453
+ }),
6454
+ detail?.(item) != null && /* @__PURE__ */ jsx("span", {
6455
+ className: "truncate type-body-sm text-muted-foreground",
6456
+ children: detail(item)
6457
+ })
6458
+ ]
6459
+ }, key);
6460
+ })
6461
+ });
6462
+ return /* @__PURE__ */ jsx(RouterProvider, {
6463
+ navigate: (to) => void navigate(to),
6464
+ useHref,
6465
+ children: /* @__PURE__ */ jsx("div", {
6466
+ className: cn("min-w-0", className),
6467
+ children: virtual ? /* @__PURE__ */ jsx(Virtualizer, {
6468
+ layout: GridLayout,
6469
+ layoutOptions,
6470
+ children: grid
6471
+ }) : grid
6472
+ })
6473
+ });
6474
+ }
6475
+ /** The loading shape of a `TileGrid`: `count` picture boxes in the same grid at the same sizes, for a `DataView` skeleton, so nothing moves when the tiles arrive. */
6476
+ function TileGridSkeleton({ count = 12, aspect = "square", tileSize = "md", className }) {
6477
+ return /* @__PURE__ */ jsx("div", {
6478
+ "aria-hidden": true,
6479
+ className: cn("grid min-w-0 gap-3", className),
6480
+ style: { gridTemplateColumns: `repeat(auto-fill, minmax(min(${minWidth[tileSize]}px, 100%), 1fr))` },
6481
+ children: Array.from({ length: count }, (_, i) => /* @__PURE__ */ jsxs("div", {
6482
+ className: "grid gap-1.5 p-1.5",
6483
+ children: [/* @__PURE__ */ jsx(ThumbnailSkeleton, { aspect: thumbnailAspect[aspect] }), /* @__PURE__ */ jsx("span", { className: "h-4 w-2/3 rounded-control bg-muted" })]
6484
+ }, i))
6485
+ });
6486
+ }
6487
+ // src/components/selectable-grid.tsx
6393
6488
  /** A grid of pictures to choose from: each tile one labelled target, "Select all shown", Shift-click ranges, virtualised from `virtualizeFrom` tiles. Pair with `useSelection` and a `BulkBar`. */
6394
6489
  function SelectableGrid({ label, rows, rowKey, renderImage, detail, selection, aspect = "square", tileSize = "md", virtualizeFrom = 100, maxHeight = 480, className }) {
6395
6490
  const select = useSelectRows(rows, rowKey, selection);
@@ -6414,10 +6509,7 @@ function SelectableGrid({ label, rows, rowKey, renderImage, detail, selection, a
6414
6509
  const picked = next === "all" ? rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey) : [...next].map(String).filter((k) => shownKeys.has(k));
6415
6510
  selection.onChange(/* @__PURE__ */ new Set([...outside, ...picked]));
6416
6511
  };
6417
- const layoutOptions = React.useMemo(() => ({
6418
- minItemSize: new Size(minWidth[tileSize], Math.round(minWidth[tileSize] * aspectRatio[aspect]) + TILE_CHROME),
6419
- minSpace: new Size(GAP, GAP)
6420
- }), [tileSize, aspect]);
6512
+ const layoutOptions = React.useMemo(() => tileLayoutOptions(tileSize, aspect), [tileSize, aspect]);
6421
6513
  const grid = /* @__PURE__ */ jsx(GridList, {
6422
6514
  "aria-label": label,
6423
6515
  layout: "grid",
@@ -6818,6 +6910,30 @@ function logScale(values, pin = {}) {
6818
6910
  log: true
6819
6911
  };
6820
6912
  }
6913
+ /** The range of each reading, sorted by x; a reading without two finite numbers has none, and arrays of different lengths use the shorter. */
6914
+ function rangeLimits(series, range, log) {
6915
+ if (!range) return [];
6916
+ const out = [];
6917
+ for (let i = 0; i < Math.min(series.length, range.low.length, range.high.length); i++) {
6918
+ const a = range.low[i];
6919
+ const b = range.high[i];
6920
+ if (Number.isFinite(a) && Number.isFinite(b) && (!log || a > 0 && b > 0)) out.push({
6921
+ x: series[i].x,
6922
+ low: Math.min(a, b),
6923
+ high: Math.max(a, b)
6924
+ });
6925
+ }
6926
+ return out.sort((p, q) => p.x - q.x);
6927
+ }
6928
+ function rangePath(limits, sx, sy) {
6929
+ const top = limits.map((l, i) => `${i ? "L" : "M"}${sx(l.x).toFixed(1)},${sy(l.high).toFixed(1)}`);
6930
+ const bottom = [...limits].reverse().map((l) => `L${sx(l.x).toFixed(1)},${sy(l.low).toFixed(1)}`);
6931
+ return `${top.join("")}${bottom.join("")}Z`;
6932
+ }
6933
+ function rangeText(limits, x, formatY, joiner = "–") {
6934
+ const l = limits.find((r) => r.x === x);
6935
+ return l ? `${formatY(l.low)}${joiner}${formatY(l.high)}` : "";
6936
+ }
6821
6937
  /** The value of a series at x, read between the two readings either side (flat beyond the ends). Series need not be sorted. */
6822
6938
  function valueAt(series, x) {
6823
6939
  const sorted = [...series].sort((p, q) => p.x - q.x);
@@ -6845,13 +6961,28 @@ function fitTicks(ticks, scale, widthOf, gap = 12) {
6845
6961
  return sorted.slice(0, 1);
6846
6962
  }
6847
6963
  /** One measured series, drawn in real pixels, with the peak and current readings labelled on the chart and every reading in a screen-reader table. Optional plan, threshold band and `colourScale`. */
6848
- function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, formatX, xLabel = "Time", formatY, xTicks, xDomain, xAxis = "labels", yScale: yMode = "linear", yInvert = false, spans, marks, onMarkSelect, renderMarkCard, cursor: cursorProp, yMin, yMax, colour = "var(--chart-1)", colourScale, colourScaleLabel, current, end, formatCurrent, readout, onPick, area, height = 280, className }) {
6964
+ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, formatX, xLabel = "Time", formatY, xTicks, xDomain, xAxis = "labels", yScale: yMode = "linear", yInvert = false, spans, marks, onMarkSelect, renderMarkCard, cursor: cursorProp, yMin, yMax, colour = "var(--chart-1)", colourScale, colourScaleLabel, current, end, formatCurrent, readout, onPick, area, range, height = 280, className }) {
6849
6965
  const [ref, width] = useWidth$1();
6850
6966
  const shared = useSharedCursor();
6851
6967
  const joined = Boolean(cursorProp) && shared !== null;
6852
6968
  const mapping = typeof cursorProp === "object" ? cursorProp : void 0;
6853
6969
  const gradientId = `heat-${React.useId().replace(/[^\w-]/g, "")}`;
6854
- const all = [...series, ...planned ?? []];
6970
+ const limits = React.useMemo(() => rangeLimits(series, range, yMode === "log"), [
6971
+ series,
6972
+ range,
6973
+ yMode
6974
+ ]);
6975
+ const all = [
6976
+ ...series,
6977
+ ...planned ?? [],
6978
+ ...limits.flatMap((l) => [{
6979
+ x: l.x,
6980
+ y: l.low
6981
+ }, {
6982
+ x: l.x,
6983
+ y: l.high
6984
+ }])
6985
+ ];
6855
6986
  const xMin = xDomain ? xDomain[0] : Math.min(...all.map((p) => p.x));
6856
6987
  const xMax = xDomain ? xDomain[1] : Math.max(...all.map((p) => p.x));
6857
6988
  const log = yMode === "log";
@@ -6981,6 +7112,13 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
6981
7112
  strokeWidth: 1.5,
6982
7113
  strokeDasharray: "4 4"
6983
7114
  }),
7115
+ limits.length > 1 && /* @__PURE__ */ jsx("path", {
7116
+ d: rangePath(limits, sx, sy),
7117
+ fill: colour,
7118
+ fillOpacity: .18,
7119
+ stroke: "none",
7120
+ "data-chart-range": ""
7121
+ }),
6984
7122
  area && series.length > 1 && /* @__PURE__ */ jsx("path", {
6985
7123
  d: `${path(series)}L${sx(series[series.length - 1].x).toFixed(1)},${sy(y.min).toFixed(1)}L${sx(series[0].x).toFixed(1)},${sy(y.min).toFixed(1)}Z`,
6986
7124
  fill: colour,
@@ -7033,6 +7171,7 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
7033
7171
  width,
7034
7172
  height,
7035
7173
  series,
7174
+ limits,
7036
7175
  planned,
7037
7176
  band,
7038
7177
  tickList,
@@ -7056,14 +7195,25 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
7056
7195
  children: [
7057
7196
  /* @__PURE__ */ jsxs("table", { children: [
7058
7197
  /* @__PURE__ */ jsx("caption", { children: label }),
7059
- /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
7060
- scope: "col",
7061
- children: xLabel
7062
- }), /* @__PURE__ */ jsx("th", {
7063
- scope: "col",
7064
- children: seriesLabel
7065
- })] }) }),
7066
- /* @__PURE__ */ jsx("tbody", { children: series.map((p) => /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("td", { children: formatX(p.x) }), /* @__PURE__ */ jsx("td", { children: formatY(p.y) })] }, p.x)) })
7198
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
7199
+ /* @__PURE__ */ jsx("th", {
7200
+ scope: "col",
7201
+ children: xLabel
7202
+ }),
7203
+ /* @__PURE__ */ jsx("th", {
7204
+ scope: "col",
7205
+ children: seriesLabel
7206
+ }),
7207
+ range && /* @__PURE__ */ jsx("th", {
7208
+ scope: "col",
7209
+ children: range.label
7210
+ })
7211
+ ] }) }),
7212
+ /* @__PURE__ */ jsx("tbody", { children: series.map((p) => /* @__PURE__ */ jsxs("tr", { children: [
7213
+ /* @__PURE__ */ jsx("td", { children: formatX(p.x) }),
7214
+ /* @__PURE__ */ jsx("td", { children: formatY(p.y) }),
7215
+ range && /* @__PURE__ */ jsx("td", { children: rangeText(limits, p.x, formatY) })
7216
+ ] }, p.x)) })
7067
7217
  ] }),
7068
7218
  spans && spans.length > 0 && /* @__PURE__ */ jsx("ul", {
7069
7219
  "aria-label": "Shaded stretches",
@@ -7082,14 +7232,16 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
7082
7232
  formatY,
7083
7233
  xLabel,
7084
7234
  spans,
7085
- marks
7235
+ marks,
7236
+ range,
7237
+ limits
7086
7238
  ]);
7087
7239
  const sorted = React.useMemo(() => [...series].sort((p, q) => p.x - q.x), [series]);
7088
7240
  const interactive = Boolean(readout || onPick || joined);
7089
7241
  const [hover, setHover] = React.useState(null);
7090
7242
  const [kbd, setKbd] = React.useState(null);
7091
7243
  const [focused, setFocused] = React.useState(false);
7092
- const readoutText = (pt) => typeof readout === "function" ? readout(pt) : `${formatX(pt.x)}: ${formatY(pt.y)}`;
7244
+ const readoutText = (pt) => typeof readout === "function" ? readout(pt) : `${formatX(pt.x)}: ${formatY(pt.y)}${range ? ` (${rangeText(limits, pt.x, formatY, " to ")})` : ""}`;
7093
7245
  const nearest = (px) => {
7094
7246
  const target = xMin + (px - pad.left) / (w || 1) * (xMax - xMin || 1);
7095
7247
  let best = 0;
@@ -7344,6 +7496,21 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
7344
7496
  ] })
7345
7497
  ]
7346
7498
  }),
7499
+ range && limits.length > 0 && /* @__PURE__ */ jsxs("span", {
7500
+ className: "inline-flex items-center gap-2",
7501
+ children: [/* @__PURE__ */ jsx("svg", {
7502
+ width: "14",
7503
+ height: "10",
7504
+ "aria-hidden": true,
7505
+ children: /* @__PURE__ */ jsx("rect", {
7506
+ width: "14",
7507
+ height: "10",
7508
+ rx: "2",
7509
+ fill: colour,
7510
+ fillOpacity: .18
7511
+ })
7512
+ }), range.label]
7513
+ }),
7347
7514
  spans?.map((sp) => /* @__PURE__ */ jsxs("span", {
7348
7515
  className: "inline-flex items-center gap-2",
7349
7516
  children: [/* @__PURE__ */ jsx("svg", {
@@ -12146,15 +12313,16 @@ function Conversation({ label, turns, answerName, personName = "You", entities,
12146
12313
  });
12147
12314
  }
12148
12315
  /** The box a question is typed in: Enter sends, Shift+Enter is a new line, disabled with its reason while answering (and Stop), suggestions as buttons. */
12149
- function Composer({ label, onSend, answering = false, onStop, answeringReason, suggestions, sendLabel = "Send", className }) {
12316
+ function Composer({ label, onSend, answering = false, onStop, answeringReason, suggestions, sendLabel = "Send", disabled, className }) {
12150
12317
  const [text, setText] = React.useState("");
12151
12318
  const reasonId = React.useId();
12152
12319
  const send = (value) => {
12153
12320
  const v = value.trim();
12154
- if (!v || answering) return;
12321
+ if (!v || answering || disabled) return;
12155
12322
  onSend(v);
12156
12323
  setText("");
12157
12324
  };
12325
+ const reason = answering ? answeringReason : disabled;
12158
12326
  return /* @__PURE__ */ jsxs("div", {
12159
12327
  className: cn("space-y-2", className),
12160
12328
  children: [
@@ -12164,6 +12332,7 @@ function Composer({ label, onSend, answering = false, onStop, answeringReason, s
12164
12332
  className: "flex flex-wrap gap-2",
12165
12333
  children: suggestions.map((s) => /* @__PURE__ */ jsx(Button, {
12166
12334
  size: "sm",
12335
+ disabled: !!disabled,
12167
12336
  onClick: () => send(s),
12168
12337
  children: s
12169
12338
  }, s))
@@ -12176,10 +12345,10 @@ function Composer({ label, onSend, answering = false, onStop, answeringReason, s
12176
12345
  },
12177
12346
  children: [/* @__PURE__ */ jsx(Textarea, {
12178
12347
  "aria-label": label,
12179
- "aria-describedby": answering ? reasonId : void 0,
12348
+ "aria-describedby": reason ? reasonId : void 0,
12180
12349
  rows: 2,
12181
12350
  value: text,
12182
- disabled: answering,
12351
+ disabled: answering || !!disabled,
12183
12352
  onChange: (e) => setText(e.target.value),
12184
12353
  onKeyDown: (e) => {
12185
12354
  if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
@@ -12194,7 +12363,7 @@ function Composer({ label, onSend, answering = false, onStop, answeringReason, s
12194
12363
  }) : /* @__PURE__ */ jsxs(Button, {
12195
12364
  type: "submit",
12196
12365
  variant: "default",
12197
- disabled: !text.trim(),
12366
+ disabled: !text.trim() || !!disabled,
12198
12367
  children: [
12199
12368
  /* @__PURE__ */ jsx(Send, {}),
12200
12369
  " ",
@@ -12202,15 +12371,35 @@ function Composer({ label, onSend, answering = false, onStop, answeringReason, s
12202
12371
  ]
12203
12372
  })]
12204
12373
  }),
12205
- answering && /* @__PURE__ */ jsx("p", {
12374
+ reason && /* @__PURE__ */ jsx("p", {
12206
12375
  id: reasonId,
12207
12376
  className: "type-caption text-muted-foreground",
12208
- children: answeringReason
12377
+ children: reason
12209
12378
  })
12210
12379
  ]
12211
12380
  });
12212
12381
  }
12213
12382
  // src/components/lightbox.tsx
12383
+ /** Keeps the open picture in the URL (`?view=<id>`): a link or a reload opens it, Back closes it, and stepping between pictures replaces the entry. */
12384
+ function useLightboxUrl(items, { param = "view" } = {}) {
12385
+ const [params, setParams] = useSearchParams();
12386
+ const id = params.get(param);
12387
+ const found = id === null ? -1 : items.findIndex((i) => i.id === id);
12388
+ const set = React.useCallback((next, replace) => setParams((p) => {
12389
+ const out = new URLSearchParams(p);
12390
+ if (next === null) out.delete(param);
12391
+ else out.set(param, next);
12392
+ return out;
12393
+ }, { replace }), [param, setParams]);
12394
+ const index = Math.max(found, 0);
12395
+ return {
12396
+ open: found >= 0,
12397
+ index,
12398
+ onIndexChange: (i) => items[i] && set(items[i].id, true),
12399
+ onOpenChange: (open) => open ? items[index] && set(items[index].id, false) : set(null, true),
12400
+ show: (to) => set(to, false)
12401
+ };
12402
+ }
12214
12403
  var NARROW = "(max-width: 719px)";
12215
12404
  function useNarrow() {
12216
12405
  const [narrow, setNarrow] = React.useState(() => typeof matchMedia === "function" && matchMedia(NARROW).matches);
@@ -12225,7 +12414,7 @@ function useNarrow() {
12225
12414
  return narrow;
12226
12415
  }
12227
12416
  /** A picture from a set in a full-size dialog: previous/next and arrow keys, "3 of 40", zoom and pan, details beside it, neighbours preloaded, a `missing` sentence for one that fails, and a Compare ticked hand-off. Focus returns to the tile that opened it. */
12228
- function Lightbox({ title, items, index, onIndexChange, open, onOpenChange, missing, details, detailsLabel = "Details", ticked, onCompare, aspect = 3 / 2 }) {
12417
+ function Lightbox({ title, items, index, onIndexChange, open, onOpenChange, missing, details, detailsLabel = "Details", ticked, onCompare, aspect = 3 / 2, overlay, actions, strip }) {
12229
12418
  const last = items.length - 1;
12230
12419
  const at = Math.min(Math.max(index, 0), Math.max(last, 0));
12231
12420
  const item = items[at];
@@ -12256,7 +12445,7 @@ function Lightbox({ title, items, index, onIndexChange, open, onOpenChange, miss
12256
12445
  const keys = React.useRef((_) => {});
12257
12446
  keys.current = (e) => {
12258
12447
  if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
12259
- if (e.target.closest?.("[role=\"toolbar\"], input, textarea, select, [contenteditable=\"true\"]")) return;
12448
+ if (e.target.closest?.("[role=\"toolbar\"], [role=\"listbox\"], input, textarea, select, [contenteditable=\"true\"]")) return;
12260
12449
  const to = e.key === "ArrowLeft" ? at - 1 : e.key === "ArrowRight" ? at + 1 : e.key === "Home" ? 0 : e.key === "End" ? last : null;
12261
12450
  if (to === null) return;
12262
12451
  e.preventDefault();
@@ -12277,90 +12466,140 @@ function Lightbox({ title, items, index, onIndexChange, open, onOpenChange, miss
12277
12466
  size: "full",
12278
12467
  children: item && /* @__PURE__ */ jsxs("div", {
12279
12468
  className: "flex h-full min-h-0 flex-col gap-3 outline-none",
12280
- children: [/* @__PURE__ */ jsxs("div", {
12281
- className: "flex flex-wrap items-center gap-2",
12282
- children: [
12283
- /* @__PURE__ */ jsx(IconButton, {
12284
- icon: ChevronLeft,
12285
- label: "Previous picture",
12286
- onPress: () => go(at - 1),
12287
- disabled: at === 0
12288
- }),
12289
- /* @__PURE__ */ jsx(IconButton, {
12290
- icon: ChevronRight,
12291
- label: "Next picture",
12292
- onPress: () => go(at + 1),
12293
- disabled: at === last
12294
- }),
12295
- /* @__PURE__ */ jsxs("span", {
12296
- className: "type-label tabular-nums",
12297
- "aria-live": "polite",
12298
- "aria-atomic": "true",
12299
- children: [
12300
- at + 1,
12301
- " of ",
12302
- items.length
12303
- ]
12304
- }),
12305
- /* @__PURE__ */ jsx(Toolbar, {
12306
- label: "Zoom",
12307
- className: "ml-2 flex items-center gap-1",
12308
- children: /* @__PURE__ */ jsx(ZoomControls, {
12469
+ children: [
12470
+ /* @__PURE__ */ jsxs("div", {
12471
+ className: "flex flex-wrap items-center gap-2",
12472
+ children: [
12473
+ /* @__PURE__ */ jsx(IconButton, {
12474
+ icon: ChevronLeft,
12475
+ label: "Previous picture",
12476
+ onPress: () => go(at - 1),
12477
+ disabled: at === 0
12478
+ }),
12479
+ /* @__PURE__ */ jsx(IconButton, {
12480
+ icon: ChevronRight,
12481
+ label: "Next picture",
12482
+ onPress: () => go(at + 1),
12483
+ disabled: at === last
12484
+ }),
12485
+ /* @__PURE__ */ jsxs("span", {
12486
+ className: "type-label tabular-nums",
12487
+ "aria-live": "polite",
12488
+ "aria-atomic": "true",
12489
+ children: [
12490
+ item.position ?? at + 1,
12491
+ " of ",
12492
+ items.length
12493
+ ]
12494
+ }),
12495
+ /* @__PURE__ */ jsx(Toolbar, {
12496
+ label: "Zoom",
12497
+ className: "ml-2 flex items-center gap-1",
12498
+ children: /* @__PURE__ */ jsx(ZoomControls, {
12499
+ viewport,
12500
+ zoom,
12501
+ natural: natural ?? item.natural ?? null
12502
+ })
12503
+ }),
12504
+ actions && /* @__PURE__ */ jsx("div", {
12505
+ className: "ml-2 flex flex-wrap items-center gap-2",
12506
+ children: actions(item)
12507
+ }),
12508
+ onCompare && ticked && /* @__PURE__ */ jsxs(Button, {
12509
+ size: "sm",
12510
+ className: "ml-auto",
12511
+ disabled: !ready,
12512
+ onPress: () => onCompare(ticked),
12513
+ children: [
12514
+ "Compare ticked (",
12515
+ ticked.length,
12516
+ ")"
12517
+ ]
12518
+ })
12519
+ ]
12520
+ }),
12521
+ /* @__PURE__ */ jsxs("div", {
12522
+ className: cn("flex min-h-0 flex-1 gap-4", narrow ? "flex-col" : "flex-row"),
12523
+ children: [/* @__PURE__ */ jsx("div", {
12524
+ className: "min-h-0 min-w-0 flex-1",
12525
+ children: failed.has(item.id) ? /* @__PURE__ */ jsx("p", {
12526
+ role: "img",
12527
+ "aria-label": item.label,
12528
+ className: "grid h-full min-h-40 place-items-center rounded-surface border border-dashed border-border p-6 text-center type-body text-muted-foreground",
12529
+ children: missing
12530
+ }) : /* @__PURE__ */ jsxs(ViewportFrame, {
12531
+ ref: frame,
12532
+ label: item.label,
12533
+ aspect,
12309
12534
  viewport,
12310
- zoom,
12311
- natural: natural ?? item.natural ?? null
12535
+ setViewport,
12536
+ maxHeight: narrow ? "50svh" : "calc(100svh - 12rem)",
12537
+ children: [/* @__PURE__ */ jsx("img", {
12538
+ src: item.src,
12539
+ alt: item.label,
12540
+ draggable: false,
12541
+ className: "size-full object-contain",
12542
+ onLoad: (e) => setNatural([e.currentTarget.naturalWidth, e.currentTarget.naturalHeight]),
12543
+ onError: () => setFailed((f) => new Set(f).add(item.id))
12544
+ }, item.id), overlay?.(item, natural ?? item.natural ?? null)]
12312
12545
  })
12313
- }),
12314
- onCompare && ticked && /* @__PURE__ */ jsxs(Button, {
12315
- size: "sm",
12316
- className: "ml-auto",
12317
- disabled: !ready,
12318
- onPress: () => onCompare(ticked),
12319
- children: [
12320
- "Compare ticked (",
12321
- ticked.length,
12322
- ")"
12323
- ]
12324
- })
12325
- ]
12326
- }), /* @__PURE__ */ jsxs("div", {
12327
- className: cn("flex min-h-0 flex-1 gap-4", narrow ? "flex-col" : "flex-row"),
12328
- children: [/* @__PURE__ */ jsx("div", {
12329
- className: "min-h-0 min-w-0 flex-1",
12330
- children: failed.has(item.id) ? /* @__PURE__ */ jsx("p", {
12331
- role: "img",
12332
- "aria-label": item.label,
12333
- className: "grid h-full min-h-40 place-items-center rounded-surface border border-dashed border-border p-6 text-center type-body text-muted-foreground",
12334
- children: missing
12335
- }) : /* @__PURE__ */ jsx(ViewportFrame, {
12336
- ref: frame,
12337
- label: item.label,
12338
- aspect,
12339
- viewport,
12340
- setViewport,
12341
- maxHeight: narrow ? "50svh" : "calc(100svh - 12rem)",
12342
- children: /* @__PURE__ */ jsx("img", {
12343
- src: item.src,
12344
- alt: item.label,
12345
- draggable: false,
12346
- className: "size-full object-contain",
12347
- onLoad: (e) => setNatural([e.currentTarget.naturalWidth, e.currentTarget.naturalHeight]),
12348
- onError: () => setFailed((f) => new Set(f).add(item.id))
12349
- }, item.id)
12350
- })
12351
- }), body && (narrow ? /* @__PURE__ */ jsx(Disclosure, {
12352
- summary: detailsLabel,
12353
- className: "shrink-0",
12354
- children: body
12355
- }) : /* @__PURE__ */ jsx("aside", {
12356
- "aria-label": detailsLabel,
12357
- className: "min-h-0 w-72 shrink-0 overflow-y-auto",
12358
- children: body
12359
- }))]
12360
- })]
12546
+ }), body && (narrow ? /* @__PURE__ */ jsx(Disclosure, {
12547
+ summary: detailsLabel,
12548
+ className: "shrink-0",
12549
+ children: body
12550
+ }) : /* @__PURE__ */ jsx("aside", {
12551
+ "aria-label": detailsLabel,
12552
+ className: "min-h-0 w-72 shrink-0 overflow-y-auto",
12553
+ children: body
12554
+ }))]
12555
+ }),
12556
+ strip && items.length > 1 && /* @__PURE__ */ jsx(ThumbnailStrip, {
12557
+ items,
12558
+ at,
12559
+ onPick: go
12560
+ })
12561
+ ]
12361
12562
  })
12362
12563
  });
12363
12564
  }
12565
+ function ThumbnailStrip({ items, at, onPick, badge, label = "Pictures in this set" }) {
12566
+ const ref = React.useRef(null);
12567
+ const current = items[at]?.id;
12568
+ React.useEffect(() => {
12569
+ ref.current?.querySelector(`[data-key="${CSS.escape(current ?? "")}"]`)?.scrollIntoView?.({
12570
+ inline: "center",
12571
+ block: "nearest"
12572
+ });
12573
+ }, [current]);
12574
+ return /* @__PURE__ */ jsx(ListBox, {
12575
+ ref,
12576
+ "aria-label": label,
12577
+ orientation: "horizontal",
12578
+ layout: "stack",
12579
+ selectionMode: "single",
12580
+ disallowEmptySelection: true,
12581
+ selectedKeys: current ? [current] : [],
12582
+ onSelectionChange: (keys) => {
12583
+ const i = items.findIndex((it) => it.id === [...keys][0]);
12584
+ if (i >= 0) onPick(i);
12585
+ },
12586
+ className: "flex shrink-0 gap-2 overflow-x-auto p-1",
12587
+ children: items.map((it, i) => /* @__PURE__ */ jsx(ListBoxItem, {
12588
+ id: it.id,
12589
+ textValue: it.position ? `${it.position}, ${it.label}` : it.label,
12590
+ "aria-label": it.position ? `${it.position}, ${it.label}` : it.label,
12591
+ className: "w-16 shrink-0 cursor-pointer rounded-control border-2 border-transparent outline-offset-2 transition-state selected:border-primary",
12592
+ children: /* @__PURE__ */ jsx(Thumbnail, {
12593
+ src: it.thumb ?? it.src,
12594
+ alt: "",
12595
+ aspect: 1,
12596
+ fallback: /* @__PURE__ */ jsx("span", { "aria-hidden": true }),
12597
+ eager: Math.abs(i - at) < 6,
12598
+ children: badge?.(it)
12599
+ })
12600
+ }, it.id))
12601
+ });
12602
+ }
12364
12603
  // src/lib/region.ts
12365
12604
  var HANDLES = [
12366
12605
  "nw",
@@ -12506,6 +12745,86 @@ var sameRect = (a, b) => [
12506
12745
  "w",
12507
12746
  "h"
12508
12747
  ].every((k) => Math.abs(a[k] - b[k]) < .001);
12748
+ /** The canvas a picture of `size` needs once turned by `angle` degrees: the bounding box of the turned picture. Zero degrees is the picture's own size. */
12749
+ function turnedSize(size, angle) {
12750
+ const a = angle * Math.PI / 180;
12751
+ const c = Math.abs(Math.cos(a));
12752
+ const s = Math.abs(Math.sin(a));
12753
+ const clean = (n) => Math.round(n * 1e6) / 1e6;
12754
+ return [clean(size[0] * c + size[1] * s), clean(size[0] * s + size[1] * c)];
12755
+ }
12756
+ /**
12757
+ * Where a window goes when the picture under it is turned from `from` to `to` degrees. The window's
12758
+ * centre turns with the picture about the canvas centre, its size stays, and it is held inside the
12759
+ * new canvas (shrunk if it no longer fits). `size` is the picture's own, unturned size.
12760
+ */
12761
+ function turnRect(rect, size, from, to) {
12762
+ const [w0, h0] = turnedSize(size, from);
12763
+ const [w1, h1] = turnedSize(size, to);
12764
+ const d = (to - from) * Math.PI / 180;
12765
+ const vx = rect.x + rect.w / 2 - w0 / 2;
12766
+ const vy = rect.y + rect.h / 2 - h0 / 2;
12767
+ const cx = w1 / 2 + vx * Math.cos(d) - vy * Math.sin(d);
12768
+ const cy = h1 / 2 + vx * Math.sin(d) + vy * Math.cos(d);
12769
+ const w = Math.min(rect.w, w1);
12770
+ const h = Math.min(rect.h, h1);
12771
+ return moveRect({
12772
+ x: cx - w / 2,
12773
+ y: cy - h / 2,
12774
+ w,
12775
+ h
12776
+ }, 0, 0, {
12777
+ x: 0,
12778
+ y: 0,
12779
+ w: w1,
12780
+ h: h1
12781
+ });
12782
+ }
12783
+ /** An angle in degrees brought into -180 to 180 and rounded to a tenth, the step the turn control works in. */
12784
+ function normaliseAngle(angle) {
12785
+ const a = ((angle + 180) % 360 + 360) % 360 - 180;
12786
+ return Math.round(a * 10) / 10 || 0;
12787
+ }
12788
+ /** One window cut into a left and a right half at `at` (0 to 1 across it, default the middle). */
12789
+ function splitRect(r, at = .5) {
12790
+ const cut = r.w * Math.min(Math.max(at, 0), 1);
12791
+ return [{
12792
+ ...r,
12793
+ w: cut
12794
+ }, {
12795
+ ...r,
12796
+ x: r.x + cut,
12797
+ w: r.w - cut
12798
+ }];
12799
+ }
12800
+ /** The one window that holds both (their union): a spread made one page again. */
12801
+ function joinRects(a, b) {
12802
+ const x = Math.min(a.x, b.x);
12803
+ const y = Math.min(a.y, b.y);
12804
+ return {
12805
+ x,
12806
+ y,
12807
+ w: Math.max(a.x + a.w, b.x + b.w) - x,
12808
+ h: Math.max(a.y + a.h, b.y + b.h) - y
12809
+ };
12810
+ }
12811
+ /** The x of the gutter between two windows: halfway between the left one's right edge and the right one's left edge. */
12812
+ var gutterOf = (left, right) => (left.x + left.w + right.x) / 2;
12813
+ /** Moves the gutter by `dx`: the left window's right edge and the right window's left edge both move, so they resize together and the gap between them is kept. Neither shrinks below `min` wide, and neither leaves the bounds. */
12814
+ function moveGutter(left, right, dx, { bounds, min }) {
12815
+ const mw = min?.w ?? 0;
12816
+ const lo = Math.max(mw - left.w, bounds.x - right.x);
12817
+ const hi = right.w - mw;
12818
+ const d = Math.min(Math.max(dx, lo), Math.max(lo, hi));
12819
+ return [{
12820
+ ...left,
12821
+ w: left.w + d
12822
+ }, {
12823
+ ...right,
12824
+ x: right.x + d,
12825
+ w: right.w - d
12826
+ }];
12827
+ }
12509
12828
  // src/components/region-editor.tsx
12510
12829
  var TONE$1 = {
12511
12830
  neutral: {
@@ -12553,8 +12872,12 @@ var round = (n) => format.integer(Math.round(n));
12553
12872
  /** A window said in words. */
12554
12873
  var describeRegion = (r) => `${r.label}: ${round(r.w)} wide by ${round(r.h)} high, ${round(r.x)} across and ${round(r.y)} down`;
12555
12874
  /** Draw and move one or two named windows on a picture, with pointer, keyboard and numbers kept in step; aspect and bounds hold through all three; two windows make a from/to move with a Watch preview. */
12556
- function RegionEditor({ label, children, size, regions, onChange, selectedId, onSelectedChange, aspect, min, bounds, step, onDraw, mode = "single", onPreview, duration = 1500, easing = "ease-in-out", fields = true, unit = "px", defaults, className }) {
12557
- const [w, h] = size;
12875
+ function RegionEditor({ label, children, size, regions, onChange, selectedId, onSelectedChange, aspect, min, bounds, step, onDraw, mode = "single", onPreview, duration = 1500, easing = "ease-in-out", fields = true, unit = "px", defaults, angle = 0, onAngleChange, guide, spreadLabels = {
12876
+ one: "Page",
12877
+ left: "Left page",
12878
+ right: "Right page"
12879
+ }, className }) {
12880
+ const [w, h] = angle ? turnedSize(size, angle) : size;
12558
12881
  const limits = React.useMemo(() => ({
12559
12882
  bounds: bounds ?? {
12560
12883
  x: 0,
@@ -12588,7 +12911,7 @@ function RegionEditor({ label, children, size, regions, onChange, selectedId, on
12588
12911
  const [said, setSaid] = React.useState("");
12589
12912
  const hintId = React.useId();
12590
12913
  const rectOf = (r) => draft?.id === r.id ? draft.rect : r;
12591
- const shown = regions.map((r) => ({
12914
+ const shownBase = regions.map((r) => ({
12592
12915
  ...r,
12593
12916
  ...rectOf(r)
12594
12917
  }));
@@ -12719,6 +13042,70 @@ function RegionEditor({ label, children, size, regions, onChange, selectedId, on
12719
13042
  ...next
12720
13043
  });
12721
13044
  };
13045
+ const turnTo = (next) => {
13046
+ const to = normaliseAngle(next);
13047
+ if (to === angle) return;
13048
+ setDraft(null);
13049
+ onAngleChange?.(to);
13050
+ onChange(regions.map((r) => ({
13051
+ ...r,
13052
+ ...turnRect(r, size, angle, to)
13053
+ })));
13054
+ setSaid(`Turned to ${to}°`);
13055
+ };
13056
+ const quarter = Math.round(angle / 90) * 90;
13057
+ const fine = Math.round((angle - quarter) * 10) / 10;
13058
+ const spread = mode === "spread";
13059
+ const [gutterDraft, setGutterDraft] = React.useState(null);
13060
+ const pair = spread && regions.length === 2 ? [rectOf(regions[0]), rectOf(regions[1])] : null;
13061
+ const gutter = pair ? gutterDraft === null ? gutterOf(pair[0], pair[1]) : gutterDraft : 0;
13062
+ const gutterRects = (at) => pair ? moveGutter(pair[0], pair[1], at - gutterOf(pair[0], pair[1]), limits) : null;
13063
+ const keepGutter = (at) => {
13064
+ const moved = gutterRects(at);
13065
+ setGutterDraft(null);
13066
+ if (moved && regions.length === 2) {
13067
+ onChange([{
13068
+ ...regions[0],
13069
+ ...moved[0]
13070
+ }, {
13071
+ ...regions[1],
13072
+ ...moved[1]
13073
+ }]);
13074
+ setSaid(`Gutter at ${round(gutterOf(moved[0], moved[1]))}: ${spreadLabels.left} ${round(moved[0].w)} wide, ${spreadLabels.right} ${round(moved[1].w)} wide`);
13075
+ }
13076
+ };
13077
+ const split = () => {
13078
+ const only = regions[0];
13079
+ if (!only) return;
13080
+ const [l, r] = splitRect(rectOf(only));
13081
+ onChange([{
13082
+ ...only,
13083
+ ...l,
13084
+ label: spreadLabels.left
13085
+ }, {
13086
+ ...only,
13087
+ ...r,
13088
+ id: `${only.id}-right`,
13089
+ label: spreadLabels.right,
13090
+ tone: "info"
13091
+ }]);
13092
+ setSaid(`Split into ${spreadLabels.left} and ${spreadLabels.right}`);
13093
+ };
13094
+ const join = () => {
13095
+ if (regions.length !== 2) return;
13096
+ onChange([{
13097
+ ...regions[0],
13098
+ ...joinRects(rectOf(regions[0]), rectOf(regions[1])),
13099
+ label: spreadLabels.one
13100
+ }]);
13101
+ select(regions[0].id);
13102
+ setSaid(`Made one ${spreadLabels.one}`);
13103
+ };
13104
+ const moving = gutterDraft !== null ? gutterRects(gutterDraft) : null;
13105
+ const shown = shownBase.map((r, i) => moving && i < 2 ? {
13106
+ ...r,
13107
+ ...moving[i]
13108
+ } : r);
12722
13109
  const chosen = shown.find((r) => r.id === selected);
12723
13110
  const setSide = (key, value) => {
12724
13111
  if (!chosen || value === null) return;
@@ -12784,111 +13171,234 @@ function RegionEditor({ label, children, size, regions, onChange, selectedId, on
12784
13171
  /* @__PURE__ */ jsxs("div", {
12785
13172
  className: "relative overflow-hidden rounded-surface border border-border bg-surface-sunken",
12786
13173
  style: { aspectRatio: `${w} / ${h}` },
12787
- children: [children, /* @__PURE__ */ jsxs("div", {
12788
- ref: overlay,
12789
- role: "group",
12790
- "aria-label": label,
12791
- "aria-describedby": hintId,
12792
- className: cn("absolute inset-0 touch-none select-none", onDraw && "cursor-crosshair"),
12793
- onPointerDown: beginDraw,
12794
- onPointerMove: onMove,
12795
- onPointerUp: onUp,
12796
- onPointerCancel: () => {
12797
- gesture.current = null;
12798
- setDraft(null);
12799
- setDrawing(null);
12800
- },
12801
- children: [
12802
- mode === "move" && from && to && /* @__PURE__ */ jsxs("svg", {
12803
- className: "pointer-events-none absolute inset-0 size-full",
12804
- viewBox: `0 0 ${w} ${h}`,
12805
- preserveAspectRatio: "none",
12806
- "aria-hidden": true,
12807
- children: [/* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("marker", {
12808
- id: `${hintId}-arrow`,
12809
- viewBox: "0 0 10 10",
12810
- refX: "8",
12811
- refY: "5",
12812
- markerWidth: "6",
12813
- markerHeight: "6",
12814
- orient: "auto-start-reverse",
12815
- children: /* @__PURE__ */ jsx("path", {
12816
- d: "M0 0 10 5 0 10z",
12817
- fill: "var(--foreground)"
12818
- })
12819
- }) }), /* @__PURE__ */ jsx("line", {
12820
- x1: from.x + from.w / 2,
12821
- y1: from.y + from.h / 2,
12822
- x2: to.x + to.w / 2,
12823
- y2: to.y + to.h / 2,
12824
- stroke: "var(--foreground)",
12825
- strokeWidth: 2,
12826
- vectorEffect: "non-scaling-stroke",
12827
- strokeDasharray: "6 4",
12828
- markerEnd: `url(#${hintId}-arrow)`
12829
- })]
12830
- }),
12831
- shown.map((r) => {
12832
- const tone = TONE$1[r.tone ?? "neutral"];
12833
- const active = r.id === selected;
12834
- return /* @__PURE__ */ jsxs("div", {
12835
- role: "group",
12836
- "aria-roledescription": "region",
12837
- "aria-label": describeRegion(r),
13174
+ children: [
13175
+ angle ? /* @__PURE__ */ jsx("div", {
13176
+ className: "absolute",
13177
+ style: {
13178
+ left: "50%",
13179
+ top: "50%",
13180
+ width: `${size[0] / w * 100}%`,
13181
+ height: `${size[1] / h * 100}%`,
13182
+ transform: `translate(-50%, -50%) rotate(${angle}deg)`
13183
+ },
13184
+ children
13185
+ }) : children,
13186
+ guide && /* @__PURE__ */ jsx("svg", {
13187
+ "aria-hidden": true,
13188
+ "data-guide": true,
13189
+ className: "pointer-events-none absolute inset-0 size-full",
13190
+ viewBox: "0 0 8 8",
13191
+ preserveAspectRatio: "none",
13192
+ children: Array.from({ length: 7 }, (_, i) => /* @__PURE__ */ jsx("line", {
13193
+ x1: "0",
13194
+ x2: "8",
13195
+ y1: i + 1,
13196
+ y2: i + 1,
13197
+ stroke: "var(--foreground)",
13198
+ strokeOpacity: .35,
13199
+ strokeWidth: 1,
13200
+ vectorEffect: "non-scaling-stroke"
13201
+ }, i))
13202
+ }),
13203
+ /* @__PURE__ */ jsxs("div", {
13204
+ ref: overlay,
13205
+ role: "group",
13206
+ "aria-label": label,
13207
+ "aria-describedby": hintId,
13208
+ className: cn("absolute inset-0 touch-none select-none", onDraw && "cursor-crosshair"),
13209
+ onPointerDown: beginDraw,
13210
+ onPointerMove: onMove,
13211
+ onPointerUp: onUp,
13212
+ onPointerCancel: () => {
13213
+ gesture.current = null;
13214
+ setDraft(null);
13215
+ setDrawing(null);
13216
+ },
13217
+ children: [
13218
+ mode === "move" && from && to && /* @__PURE__ */ jsxs("svg", {
13219
+ className: "pointer-events-none absolute inset-0 size-full",
13220
+ viewBox: `0 0 ${w} ${h}`,
13221
+ preserveAspectRatio: "none",
13222
+ "aria-hidden": true,
13223
+ children: [/* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("marker", {
13224
+ id: `${hintId}-arrow`,
13225
+ viewBox: "0 0 10 10",
13226
+ refX: "8",
13227
+ refY: "5",
13228
+ markerWidth: "6",
13229
+ markerHeight: "6",
13230
+ orient: "auto-start-reverse",
13231
+ children: /* @__PURE__ */ jsx("path", {
13232
+ d: "M0 0 10 5 0 10z",
13233
+ fill: "var(--foreground)"
13234
+ })
13235
+ }) }), /* @__PURE__ */ jsx("line", {
13236
+ x1: from.x + from.w / 2,
13237
+ y1: from.y + from.h / 2,
13238
+ x2: to.x + to.w / 2,
13239
+ y2: to.y + to.h / 2,
13240
+ stroke: "var(--foreground)",
13241
+ strokeWidth: 2,
13242
+ vectorEffect: "non-scaling-stroke",
13243
+ strokeDasharray: "6 4",
13244
+ markerEnd: `url(#${hintId}-arrow)`
13245
+ })]
13246
+ }),
13247
+ shown.map((r) => {
13248
+ const tone = TONE$1[r.tone ?? "neutral"];
13249
+ const active = r.id === selected;
13250
+ return /* @__PURE__ */ jsxs("div", {
13251
+ role: "group",
13252
+ "aria-roledescription": "region",
13253
+ "aria-label": describeRegion(r),
13254
+ tabIndex: 0,
13255
+ "data-region": r.id,
13256
+ "data-selected": active || void 0,
13257
+ onFocus: () => select(r.id),
13258
+ onBlur: (e) => {
13259
+ if (draft?.id === r.id && !e.currentTarget.contains(e.relatedTarget)) keep(r.id, draft.rect);
13260
+ },
13261
+ onKeyDown: (e) => keys(e, r),
13262
+ onPointerDown: (e) => beginMove(e, r),
13263
+ className: cn("absolute cursor-move border-2 outline-offset-2 transition-state", active ? "z-10" : "opacity-90"),
13264
+ style: {
13265
+ ...pct(r),
13266
+ borderColor: tone.edge,
13267
+ backgroundColor: `color-mix(in oklab, ${tone.fill} 35%, transparent)`,
13268
+ borderStyle: active ? "solid" : "dashed"
13269
+ },
13270
+ children: [/* @__PURE__ */ jsx("span", {
13271
+ className: "pointer-events-none absolute left-0 top-0 max-w-full -translate-y-full truncate rounded-t-control px-1.5 type-caption",
13272
+ style: {
13273
+ backgroundColor: tone.edge,
13274
+ color: "var(--background)"
13275
+ },
13276
+ children: r.label
13277
+ }), active && HANDLES.map((handle) => /* @__PURE__ */ jsx("span", {
13278
+ "aria-hidden": true,
13279
+ "data-handle": handle,
13280
+ onPointerDown: (e) => beginResize(e, r, handle),
13281
+ className: cn("absolute size-3 rounded-pill border-2 bg-background", HANDLE_AT[handle]),
13282
+ style: {
13283
+ borderColor: tone.edge,
13284
+ cursor: CURSOR[handle]
13285
+ }
13286
+ }, handle))]
13287
+ }, r.id);
13288
+ }),
13289
+ pair && /* @__PURE__ */ jsxs("div", {
13290
+ role: "separator",
13291
+ "aria-orientation": "vertical",
13292
+ "aria-label": "Gutter between the two pages",
13293
+ "aria-valuenow": Math.round(gutter),
13294
+ "aria-valuemin": Math.round(limits.bounds.x + limits.min.w),
13295
+ "aria-valuemax": Math.round(limits.bounds.x + limits.bounds.w - limits.min.w),
12838
13296
  tabIndex: 0,
12839
- "data-region": r.id,
12840
- "data-selected": active || void 0,
12841
- onFocus: () => select(r.id),
12842
- onBlur: (e) => {
12843
- if (draft?.id === r.id && !e.currentTarget.contains(e.relatedTarget)) keep(r.id, draft.rect);
13297
+ "data-gutter": "",
13298
+ onKeyDown: (e) => {
13299
+ const dir = e.key === "ArrowLeft" ? -1 : e.key === "ArrowRight" ? 1 : 0;
13300
+ if (!dir) return;
13301
+ e.preventDefault();
13302
+ e.stopPropagation();
13303
+ keepGutter(gutter + dir * stride * (e.shiftKey ? 5 : 1));
13304
+ },
13305
+ onPointerDown: (e) => {
13306
+ if (e.button !== 0) return;
13307
+ e.stopPropagation();
13308
+ capture(e);
13309
+ setGutterDraft(gutter);
13310
+ },
13311
+ onPointerMove: (e) => {
13312
+ if (gutterDraft === null) return;
13313
+ e.stopPropagation();
13314
+ setGutterDraft(unitsAt(e).x);
13315
+ },
13316
+ onPointerUp: (e) => {
13317
+ if (gutterDraft === null) return;
13318
+ e.stopPropagation();
13319
+ keepGutter(gutterDraft);
12844
13320
  },
12845
- onKeyDown: (e) => keys(e, r),
12846
- onPointerDown: (e) => beginMove(e, r),
12847
- className: cn("absolute cursor-move border-2 outline-offset-2 transition-state", active ? "z-10" : "opacity-90"),
13321
+ className: "absolute z-20 -ml-2 w-4 cursor-col-resize touch-none outline-offset-2",
12848
13322
  style: {
12849
- ...pct(r),
12850
- borderColor: tone.edge,
12851
- backgroundColor: `color-mix(in oklab, ${tone.fill} 35%, transparent)`,
12852
- borderStyle: active ? "solid" : "dashed"
13323
+ left: `${gutter / w * 100}%`,
13324
+ top: `${Math.min(shown[0].y, shown[1].y) / h * 100}%`,
13325
+ height: `${(Math.max(shown[0].y + shown[0].h, shown[1].y + shown[1].h) - Math.min(shown[0].y, shown[1].y)) / h * 100}%`
12853
13326
  },
12854
13327
  children: [/* @__PURE__ */ jsx("span", {
12855
- className: "pointer-events-none absolute left-0 top-0 max-w-full -translate-y-full truncate rounded-t-control px-1.5 type-caption",
12856
- style: {
12857
- backgroundColor: tone.edge,
12858
- color: "var(--background)"
12859
- },
12860
- children: r.label
12861
- }), active && HANDLES.map((handle) => /* @__PURE__ */ jsx("span", {
12862
13328
  "aria-hidden": true,
12863
- "data-handle": handle,
12864
- onPointerDown: (e) => beginResize(e, r, handle),
12865
- className: cn("absolute size-3 rounded-pill border-2 bg-background", HANDLE_AT[handle]),
12866
- style: {
12867
- borderColor: tone.edge,
12868
- cursor: CURSOR[handle]
12869
- }
12870
- }, handle))]
12871
- }, r.id);
12872
- }),
12873
- drawing && /* @__PURE__ */ jsx("div", {
12874
- "aria-hidden": true,
12875
- className: "pointer-events-none absolute border-2 border-dashed border-foreground bg-foreground/10",
12876
- style: pct(drawing)
12877
- }),
12878
- watching && /* @__PURE__ */ jsx("div", {
12879
- "aria-hidden": true,
12880
- "data-preview": true,
12881
- className: "pointer-events-none absolute z-20 border-2 border-foreground bg-foreground/15",
12882
- style: pct(watching)
12883
- })
12884
- ]
12885
- })]
13329
+ className: "absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-foreground"
13330
+ }), /* @__PURE__ */ jsx("span", {
13331
+ "aria-hidden": true,
13332
+ className: "absolute top-1/2 left-1/2 grid size-5 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-pill border-2 border-foreground bg-background",
13333
+ children: /* @__PURE__ */ jsx(Columns2, { className: "size-3" })
13334
+ })]
13335
+ }),
13336
+ drawing && /* @__PURE__ */ jsx("div", {
13337
+ "aria-hidden": true,
13338
+ className: "pointer-events-none absolute border-2 border-dashed border-foreground bg-foreground/10",
13339
+ style: pct(drawing)
13340
+ }),
13341
+ watching && /* @__PURE__ */ jsx("div", {
13342
+ "aria-hidden": true,
13343
+ "data-preview": true,
13344
+ className: "pointer-events-none absolute z-20 border-2 border-foreground bg-foreground/15",
13345
+ style: pct(watching)
13346
+ })
13347
+ ]
13348
+ })
13349
+ ]
12886
13350
  }),
12887
13351
  /* @__PURE__ */ jsxs("p", {
12888
13352
  id: hintId,
12889
13353
  className: "type-caption text-muted-foreground",
12890
13354
  children: [onDraw ? "Drag on the picture to draw a window. " : "", "Drag a window to move it, or its handles to resize. Keys: arrows move, Shift and arrows resize, Enter keeps, Escape undoes."]
12891
13355
  }),
13356
+ onAngleChange && /* @__PURE__ */ jsxs("div", {
13357
+ role: "group",
13358
+ "aria-label": "Turn the picture",
13359
+ className: "flex flex-wrap items-center gap-2",
13360
+ children: [
13361
+ /* @__PURE__ */ jsxs(Button, {
13362
+ size: "sm",
13363
+ variant: "outline",
13364
+ onPress: () => turnTo(angle - 90),
13365
+ children: [/* @__PURE__ */ jsx(RotateCcw, {}), " Turn left 90°"]
13366
+ }),
13367
+ /* @__PURE__ */ jsxs(Button, {
13368
+ size: "sm",
13369
+ variant: "outline",
13370
+ onPress: () => turnTo(angle + 90),
13371
+ children: [/* @__PURE__ */ jsx(RotateCw, {}), " Turn right 90°"]
13372
+ }),
13373
+ /* @__PURE__ */ jsx(Slider, {
13374
+ "aria-label": "Fine turn",
13375
+ className: "min-w-48 flex-1",
13376
+ value: fine,
13377
+ onChange: (v) => turnTo(quarter + v),
13378
+ min: -45,
13379
+ max: 45,
13380
+ step: .1,
13381
+ unit: "°",
13382
+ editable: true
13383
+ }),
13384
+ fine !== 0 && /* @__PURE__ */ jsx(Button, {
13385
+ size: "sm",
13386
+ variant: "ghost",
13387
+ onPress: () => turnTo(quarter),
13388
+ children: "Level"
13389
+ })
13390
+ ]
13391
+ }),
13392
+ spread && (regions.length === 1 || regions.length === 2) && /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsxs(Button, {
13393
+ size: "sm",
13394
+ variant: "outline",
13395
+ onPress: regions.length === 1 ? split : join,
13396
+ children: [
13397
+ /* @__PURE__ */ jsx(Columns2, {}),
13398
+ " ",
13399
+ regions.length === 1 ? "Split into two" : "Make one"
13400
+ ]
13401
+ }) }),
12892
13402
  (mode === "move" || defaults && modified) && /* @__PURE__ */ jsxs("div", {
12893
13403
  className: "flex flex-wrap items-center gap-2",
12894
13404
  children: [mode === "move" && /* @__PURE__ */ jsxs(Button, {
@@ -12971,6 +13481,454 @@ function RegionEditor({ label, children, size, regions, onChange, selectedId, on
12971
13481
  ]
12972
13482
  });
12973
13483
  }
13484
+ // src/lib/book.ts
13485
+ /**
13486
+ * The pages shown together, as indexes into the set. In a spread the first page stands alone on
13487
+ * the right (a book opens on its first recto, so the left side is empty), then pages pair 2 and 3,
13488
+ * 4 and 5, and an odd one out at the end stands alone on the left. In a single layout every page
13489
+ * is its own view.
13490
+ */
13491
+ function viewsOf(count, spread) {
13492
+ if (!spread) return Array.from({ length: count }, (_, i) => [i]);
13493
+ const views = count > 0 ? [[0]] : [];
13494
+ for (let i = 1; i < count; i += 2) views.push(i + 1 < count ? [i, i + 1] : [i]);
13495
+ return views;
13496
+ }
13497
+ /** The index of the view that holds page `index`. */
13498
+ function viewOf(index, spread) {
13499
+ return spread ? index <= 0 ? 0 : Math.floor((index + 1) / 2) : Math.max(index, 0);
13500
+ }
13501
+ var norm = (s) => s.trim().toLowerCase();
13502
+ /**
13503
+ * Finds the page a person typed. A printed label wins ("iv", "12") because that is what is printed
13504
+ * on the page they are looking at; otherwise it is the scan's own position ("22" is the 22nd
13505
+ * image). Roman numerals and any other label match as text, case aside. Returns the index, or
13506
+ * `null` when no page has that name.
13507
+ */
13508
+ function findPage(pages, query) {
13509
+ const q = norm(query.replace(/^(page|p\.?)\s+/i, ""));
13510
+ if (!q) return null;
13511
+ const printed = pages.findIndex((p) => p.printed !== void 0 && norm(p.printed) === q);
13512
+ if (printed >= 0) return printed;
13513
+ const scan = pages.findIndex((p) => norm(p.scan) === q);
13514
+ return scan >= 0 ? scan : null;
13515
+ }
13516
+ /** A page said in words: "Page 22 (12)" or "Page 22" with no printed label. */
13517
+ var pageName = (p, word = "Page") => `${word} ${p.scan}${p.printed ? ` (${p.printed})` : ""}`;
13518
+ /** Where the viewer is, in words: "Page 22 (12) of 44", or "Pages 22 and 23 of 44" for a spread. */
13519
+ function sayPosition(shown, total, word = "Page", plural = "Pages") {
13520
+ if (shown.length === 0) return "";
13521
+ if (shown.length === 1) return `${pageName(shown[0], word)} of ${total}`;
13522
+ const label = (p) => `${p.scan}${p.printed ? ` (${p.printed})` : ""}`;
13523
+ return `${plural} ${label(shown[0])} and ${label(shown[1])} of ${total}`;
13524
+ }
13525
+ // src/components/book-viewer.tsx
13526
+ /** Keeps the page being read in the URL (`?page=22`, the 1-based position in the scan): a link or a reload opens it, and turning pages replaces the entry so Back leaves the book. */
13527
+ function useBookUrl(count, { param = "page" } = {}) {
13528
+ const [params, setParams] = useSearchParams();
13529
+ const n = Number(params.get(param));
13530
+ return {
13531
+ index: Number.isInteger(n) && n >= 1 && n <= count ? n - 1 : 0,
13532
+ onIndexChange: React.useCallback((i) => setParams((p) => {
13533
+ const out = new URLSearchParams(p);
13534
+ out.set(param, String(Math.min(Math.max(i, 0), Math.max(count - 1, 0)) + 1));
13535
+ return out;
13536
+ }, { replace: true }), [
13537
+ count,
13538
+ param,
13539
+ setParams
13540
+ ])
13541
+ };
13542
+ }
13543
+ /** A scanned book read as a book: facing pages (the first alone on the right) or one page, printed and scan names with a go-to that takes either, arrows, Page Up/Down, Home/End and a click on a page's outer half, the position in the URL and in words, a thumbnail strip with badges, an optional text pane. */
13544
+ function BookViewer({ label, pages, index, onIndexChange, missing, layout = "spread", side, sideLabel = "Text", badge, overlay, strip = true, aspect = 2 / 3, word = "Page", className }) {
13545
+ const narrow = useNarrow();
13546
+ const spread = layout === "spread" && !narrow;
13547
+ const views = React.useMemo(() => viewsOf(pages.length, spread), [pages.length, spread]);
13548
+ const at = Math.min(Math.max(index, 0), Math.max(pages.length - 1, 0));
13549
+ const view = viewOf(at, spread);
13550
+ const shown = (views[view] ?? []).map((i) => pages[i]);
13551
+ const lastView = views.length - 1;
13552
+ const goView = (k) => {
13553
+ const to = views[Math.min(Math.max(k, 0), lastView)];
13554
+ if (to) onIndexChange(to[0]);
13555
+ };
13556
+ const slots = spread ? view === 0 ? [null, shown[0] ?? null] : [shown[0] ?? null, shown[1] ?? null] : [shown[0] ?? null];
13557
+ const { viewport, setViewport } = useViewport(FIT);
13558
+ const frame = React.useRef(null);
13559
+ const [failed, setFailed] = React.useState(/* @__PURE__ */ new Set());
13560
+ const [naturals, setNaturals] = React.useState(/* @__PURE__ */ new Map());
13561
+ const naturalOf = (p) => naturals.get(p.id) ?? p.natural ?? null;
13562
+ const zoom = useZoom({
13563
+ viewport,
13564
+ setViewport,
13565
+ frame,
13566
+ natural: shown[0] ? naturalOf(shown[0]) : null
13567
+ });
13568
+ const viewKey = shown.map((p) => p.id).join("+");
13569
+ React.useEffect(() => setViewport(FIT), [viewKey, setViewport]);
13570
+ React.useEffect(() => {
13571
+ if (typeof Image === "undefined") return;
13572
+ for (const k of [view - 1, view + 1]) for (const i of views[k] ?? []) new Image().src = pages[i].src;
13573
+ }, [
13574
+ view,
13575
+ views,
13576
+ pages
13577
+ ]);
13578
+ const root = React.useRef(null);
13579
+ const keys = (e) => {
13580
+ if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
13581
+ if (e.target.closest?.("[role=\"toolbar\"], [role=\"listbox\"], input, textarea, select, [contenteditable=\"true\"]")) return;
13582
+ const to = e.key === "ArrowRight" || e.key === "PageDown" ? view + 1 : e.key === "ArrowLeft" || e.key === "PageUp" ? view - 1 : e.key === "Home" ? 0 : e.key === "End" ? lastView : null;
13583
+ if (to === null) return;
13584
+ e.preventDefault();
13585
+ goView(to);
13586
+ requestAnimationFrame(() => {
13587
+ if (root.current && !root.current.contains(document.activeElement)) root.current.focus({ preventScroll: true });
13588
+ });
13589
+ };
13590
+ const [query, setQuery] = React.useState("");
13591
+ const [problem, setProblem] = React.useState();
13592
+ const goTo = (e) => {
13593
+ e.preventDefault();
13594
+ if (!query.trim()) return;
13595
+ const found = findPage(pages, query);
13596
+ if (found === null) {
13597
+ setProblem(`No ${word.toLowerCase()} is called “${query.trim()}”. Try its number in the scan, or what is printed on it, such as iv or 12.`);
13598
+ return;
13599
+ }
13600
+ setProblem(void 0);
13601
+ setQuery("");
13602
+ onIndexChange(found);
13603
+ };
13604
+ const items = React.useMemo(() => pages.map((p) => ({
13605
+ id: p.id,
13606
+ src: p.src,
13607
+ thumb: p.thumb,
13608
+ label: p.label,
13609
+ position: pageName(p, word),
13610
+ natural: p.natural
13611
+ })), [pages, word]);
13612
+ const position = sayPosition(shown, pages.length, word, `${word}s`);
13613
+ const prevWord = spread ? `Previous ${word.toLowerCase()}s` : `Previous ${word.toLowerCase()}`;
13614
+ const nextWord = spread ? `Next ${word.toLowerCase()}s` : `Next ${word.toLowerCase()}`;
13615
+ const body = side?.(shown);
13616
+ const zones = (slot) => {
13617
+ const back = slots.length === 1 || slot === 0;
13618
+ const forward = slots.length === 1 || slot === 1;
13619
+ return {
13620
+ describe: `Click the outer half of the page to turn it. Previous is on the left, next on the right.`,
13621
+ zoneAt: (x) => back && x < .5 && view > 0 ? {
13622
+ value: "prev",
13623
+ from: 0,
13624
+ to: .5,
13625
+ hint: prevWord
13626
+ } : forward && x >= .5 && view < lastView ? {
13627
+ value: "next",
13628
+ from: .5,
13629
+ to: 1,
13630
+ hint: nextWord
13631
+ } : null
13632
+ };
13633
+ };
13634
+ return /* @__PURE__ */ jsxs("div", {
13635
+ ref: root,
13636
+ role: "region",
13637
+ "aria-label": label,
13638
+ "aria-roledescription": "book",
13639
+ tabIndex: -1,
13640
+ onKeyDown: keys,
13641
+ className: cn("grid min-w-0 gap-3 outline-none", className),
13642
+ children: [
13643
+ /* @__PURE__ */ jsxs("div", {
13644
+ className: "flex flex-wrap items-end gap-2",
13645
+ children: [
13646
+ /* @__PURE__ */ jsx(IconButton, {
13647
+ icon: ChevronLeft,
13648
+ label: prevWord,
13649
+ onPress: () => goView(view - 1),
13650
+ disabled: view === 0
13651
+ }),
13652
+ /* @__PURE__ */ jsx(IconButton, {
13653
+ icon: ChevronRight,
13654
+ label: nextWord,
13655
+ onPress: () => goView(view + 1),
13656
+ disabled: view === lastView
13657
+ }),
13658
+ /* @__PURE__ */ jsx("span", {
13659
+ className: "type-label tabular-nums",
13660
+ "aria-hidden": true,
13661
+ children: position
13662
+ }),
13663
+ /* @__PURE__ */ jsx(Toolbar, {
13664
+ label: "Zoom",
13665
+ className: "ml-2 flex items-center gap-1",
13666
+ children: /* @__PURE__ */ jsx(ZoomControls, {
13667
+ viewport,
13668
+ zoom,
13669
+ natural: shown[0] ? naturalOf(shown[0]) : null
13670
+ })
13671
+ }),
13672
+ /* @__PURE__ */ jsx("form", {
13673
+ onSubmit: goTo,
13674
+ className: "ml-auto",
13675
+ children: /* @__PURE__ */ jsx(Field, {
13676
+ label: `Go to ${word.toLowerCase()}`,
13677
+ error: problem,
13678
+ action: /* @__PURE__ */ jsx(Button, {
13679
+ type: "submit",
13680
+ size: "sm",
13681
+ variant: "outline",
13682
+ children: "Go"
13683
+ }),
13684
+ children: /* @__PURE__ */ jsx(Input, {
13685
+ size: "sm",
13686
+ value: query,
13687
+ onChange: (e) => {
13688
+ setQuery(e.target.value);
13689
+ setProblem(void 0);
13690
+ },
13691
+ className: "w-32",
13692
+ autoComplete: "off"
13693
+ })
13694
+ })
13695
+ })
13696
+ ]
13697
+ }),
13698
+ /* @__PURE__ */ jsxs("div", {
13699
+ className: cn("grid min-w-0 gap-4", body && !narrow && "grid-cols-[minmax(0,1fr)_20rem]"),
13700
+ children: [/* @__PURE__ */ jsx("div", {
13701
+ className: cn("grid min-w-0 gap-0", slots.length === 2 ? "grid-cols-2" : "grid-cols-1"),
13702
+ children: slots.map((page, slot) => page === null ? /* @__PURE__ */ jsx("div", { "aria-hidden": true }, slot) : failed.has(page.id) ? /* @__PURE__ */ jsx("p", {
13703
+ role: "img",
13704
+ "aria-label": page.label,
13705
+ className: "grid min-h-40 place-items-center rounded-surface border border-dashed border-border p-6 text-center type-body text-muted-foreground",
13706
+ children: missing
13707
+ }, page.id) : /* @__PURE__ */ jsxs(ViewportFrame, {
13708
+ ref: slot === slots.findIndex((s) => s !== null) ? frame : void 0,
13709
+ label: page.label,
13710
+ aspect,
13711
+ viewport,
13712
+ setViewport,
13713
+ maxHeight: "calc(100svh - 14rem)",
13714
+ pick: {
13715
+ ...zones(slot),
13716
+ onPick: (zone) => goView(view + (zone.value === "prev" ? -1 : 1)),
13717
+ token: String(view)
13718
+ },
13719
+ children: [/* @__PURE__ */ jsx("img", {
13720
+ src: page.src,
13721
+ alt: page.label,
13722
+ draggable: false,
13723
+ className: "size-full object-contain",
13724
+ onLoad: (e) => {
13725
+ const img = e.currentTarget;
13726
+ setNaturals((m) => new Map(m).set(page.id, [img.naturalWidth, img.naturalHeight]));
13727
+ },
13728
+ onError: () => setFailed((f) => new Set(f).add(page.id))
13729
+ }), overlay?.(page, naturalOf(page))]
13730
+ }, `slot-${slot}`))
13731
+ }), body && /* @__PURE__ */ jsx("aside", {
13732
+ "aria-label": sideLabel,
13733
+ className: "min-h-0 min-w-0 overflow-y-auto",
13734
+ children: body
13735
+ })]
13736
+ }),
13737
+ strip && pages.length > 1 && /* @__PURE__ */ jsx(ThumbnailStrip, {
13738
+ items,
13739
+ at,
13740
+ onPick: onIndexChange,
13741
+ badge: badge ? (it) => badge(pages.find((p) => p.id === it.id)) : void 0,
13742
+ label: `${word}s in this book`
13743
+ }),
13744
+ /* @__PURE__ */ jsx("div", {
13745
+ role: "status",
13746
+ "aria-live": "polite",
13747
+ className: "sr-only",
13748
+ children: position
13749
+ })
13750
+ ]
13751
+ });
13752
+ }
13753
+ // src/lib/boxes.ts
13754
+ /**
13755
+ * The boxes in reading order: top to bottom in rows, left to right within a row. A box joins the
13756
+ * row above when its centre falls inside that row's first box vertically, so lines of text that
13757
+ * wobble a few pixels still read in order and two columns read row by row, not column by column.
13758
+ * Returns ids, so a caller keeps its own objects.
13759
+ */
13760
+ function readingOrder(boxes) {
13761
+ const byTop = [...boxes].sort((a, b) => a.y + a.h / 2 - (b.y + b.h / 2) || a.x - b.x);
13762
+ const rows = [];
13763
+ for (const box of byTop) {
13764
+ const row = rows[rows.length - 1];
13765
+ const centre = box.y + box.h / 2;
13766
+ if (row && centre >= row[0].y && centre <= row[0].y + row[0].h) row.push(box);
13767
+ else rows.push([box]);
13768
+ }
13769
+ return rows.flatMap((row) => row.sort((a, b) => a.x - b.x).map((b) => b.id));
13770
+ }
13771
+ /**
13772
+ * The viewport that fills a frame with one box of the picture. The picture sits in the frame the way
13773
+ * `object-fit: contain` puts it (a frame of another shape leaves bars), which is also how
13774
+ * `BoxOverlay` draws it, so the same numbers agree. `margin` is the share of the box added on every
13775
+ * side so the box is not touching the frame (default 0.25).
13776
+ */
13777
+ function zoomToBox(box, of, frame, margin = .25) {
13778
+ const s = Math.min(frame.width / of.w, frame.height / of.h);
13779
+ const ox = (frame.width - of.w * s) / 2;
13780
+ const oy = (frame.height - of.h * s) / 2;
13781
+ const mx = box.w * margin;
13782
+ const my = box.h * margin;
13783
+ return boxViewport([
13784
+ (ox + (box.x - mx) * s) / frame.width,
13785
+ (oy + (box.y - my) * s) / frame.height,
13786
+ (box.w + 2 * mx) * s / frame.width,
13787
+ (box.h + 2 * my) * s / frame.height
13788
+ ], frame);
13789
+ }
13790
+ // src/components/box-overlay.tsx
13791
+ /** Holds the active and pointed box for a `BoxOverlay` and the `BoxList` beside it. */
13792
+ function useBoxes(initial = null) {
13793
+ const [active, setActive] = React.useState(initial);
13794
+ const [source, setSource] = React.useState(null);
13795
+ const [pointed, point] = React.useState(null);
13796
+ const choose = React.useCallback((id, from = "list") => {
13797
+ setActive(id);
13798
+ setSource(from);
13799
+ }, []);
13800
+ return React.useMemo(() => ({
13801
+ active,
13802
+ pointed,
13803
+ source,
13804
+ choose,
13805
+ point
13806
+ }), [
13807
+ active,
13808
+ pointed,
13809
+ source,
13810
+ choose
13811
+ ]);
13812
+ }
13813
+ var STROKE = {
13814
+ neutral: "var(--foreground)",
13815
+ info: "var(--info)",
13816
+ success: "var(--success)",
13817
+ warning: "var(--warning)",
13818
+ danger: "var(--danger)"
13819
+ };
13820
+ var FILL = {
13821
+ neutral: "var(--muted)",
13822
+ info: "var(--info-subtle)",
13823
+ success: "var(--success-subtle)",
13824
+ warning: "var(--warning-subtle)",
13825
+ danger: "var(--danger-subtle)"
13826
+ };
13827
+ /** Read-only boxes drawn as one SVG layer over a picture, inside `ViewportFrame` so they zoom with it: outline by tone, hover and choice shared with a `BoxList`, one tab stop with arrows in reading order. */
13828
+ function BoxOverlay({ label, of, boxes, state, onChoose }) {
13829
+ const order = React.useMemo(() => readingOrder(boxes), [boxes]);
13830
+ const byId = React.useMemo(() => new Map(boxes.map((b) => [b.id, b])), [boxes]);
13831
+ const group = React.useRef(null);
13832
+ const stop = state.active && byId.has(state.active) ? state.active : order[0];
13833
+ const move = (id, e) => {
13834
+ const i = order.indexOf(id);
13835
+ const to = e.key === "ArrowRight" || e.key === "ArrowDown" ? i + 1 : e.key === "ArrowLeft" || e.key === "ArrowUp" ? i - 1 : e.key === "Home" ? 0 : e.key === "End" ? order.length - 1 : null;
13836
+ if (to !== null) {
13837
+ e.preventDefault();
13838
+ e.stopPropagation();
13839
+ const next = order[Math.min(Math.max(to, 0), order.length - 1)];
13840
+ group.current?.querySelector(`[data-box-id="${CSS.escape(next)}"]`)?.focus();
13841
+ } else if (e.key === "Enter" || e.key === " ") {
13842
+ e.preventDefault();
13843
+ e.stopPropagation();
13844
+ choose(id);
13845
+ }
13846
+ };
13847
+ const choose = (id) => {
13848
+ state.choose(id, "picture");
13849
+ const box = byId.get(id);
13850
+ if (box) onChoose?.(box);
13851
+ };
13852
+ const drawn = [...order, ...[state.pointed, state.active].filter((id) => id !== null && order.includes(id))];
13853
+ return /* @__PURE__ */ jsx("svg", {
13854
+ ref: group,
13855
+ role: "group",
13856
+ "aria-label": label,
13857
+ viewBox: `0 0 ${of.w} ${of.h}`,
13858
+ preserveAspectRatio: "xMidYMid meet",
13859
+ className: "absolute inset-0 size-full overflow-visible",
13860
+ children: drawn.map((id, n) => {
13861
+ const b = byId.get(id);
13862
+ const tone = b.tone ?? "neutral";
13863
+ const on = id === state.active;
13864
+ const lit = on || id === state.pointed;
13865
+ const repeat = n >= order.length;
13866
+ return /* @__PURE__ */ jsx("rect", {
13867
+ "data-box-id": id,
13868
+ role: "button",
13869
+ "aria-label": b.label,
13870
+ "aria-pressed": on,
13871
+ "aria-hidden": repeat || void 0,
13872
+ tabIndex: repeat ? void 0 : id === stop ? 0 : -1,
13873
+ x: b.x,
13874
+ y: b.y,
13875
+ width: b.w,
13876
+ height: b.h,
13877
+ fill: lit ? FILL[tone] : "none",
13878
+ fillOpacity: lit ? .25 : void 0,
13879
+ stroke: STROKE[tone],
13880
+ strokeWidth: on ? 3 : 1.5,
13881
+ strokeOpacity: lit || tone !== "neutral" ? 1 : .55,
13882
+ vectorEffect: "non-scaling-stroke",
13883
+ pointerEvents: repeat ? "none" : "all",
13884
+ className: cn("cursor-pointer", repeat && "pointer-events-none"),
13885
+ onPointerEnter: () => state.point(id),
13886
+ onPointerLeave: () => state.point(null),
13887
+ onFocus: () => state.point(id),
13888
+ onBlur: () => state.point(null),
13889
+ onPointerUp: (e) => e.stopPropagation(),
13890
+ onClick: () => choose(id),
13891
+ onKeyDown: (e) => move(id, e)
13892
+ }, repeat ? `${id}:raised` : id);
13893
+ })
13894
+ });
13895
+ }
13896
+ /** The list beside a `BoxOverlay`, in the same reading order: choosing a line marks its box, pointing at one lights it, and choosing a box in the picture scrolls the list to its line and focuses it. */
13897
+ function BoxList({ label, boxes, state, renderBox, className }) {
13898
+ const order = React.useMemo(() => readingOrder(boxes), [boxes]);
13899
+ const byId = React.useMemo(() => new Map(boxes.map((b) => [b.id, b])), [boxes]);
13900
+ const ref = React.useRef(null);
13901
+ React.useEffect(() => {
13902
+ if (state.source !== "picture" || !state.active) return;
13903
+ const el = ref.current?.querySelector(`[data-key="${CSS.escape(state.active)}"]`);
13904
+ el?.scrollIntoView?.({ block: "nearest" });
13905
+ el?.focus({ preventScroll: true });
13906
+ }, [state.active, state.source]);
13907
+ return /* @__PURE__ */ jsx(ListBox, {
13908
+ ref,
13909
+ "aria-label": label,
13910
+ selectionMode: "single",
13911
+ disallowEmptySelection: true,
13912
+ selectedKeys: state.active ? [state.active] : [],
13913
+ onSelectionChange: (keys) => {
13914
+ const id = [...keys][0];
13915
+ if (id !== void 0) state.choose(String(id), "list");
13916
+ },
13917
+ className: cn("min-w-0 overflow-y-auto rounded-surface border border-border", className),
13918
+ children: order.map((id) => {
13919
+ const b = byId.get(id);
13920
+ return /* @__PURE__ */ jsx(ListBoxItem, {
13921
+ id,
13922
+ textValue: b.label,
13923
+ onHoverStart: () => state.point(id),
13924
+ onHoverEnd: () => state.point(null),
13925
+ className: cn("flex cursor-pointer items-baseline gap-2 border-l-2 px-3 py-1.5 type-body-sm outline-offset-[-2px] transition-state", "selected:bg-surface-sunken selected:font-medium hover:bg-surface-sunken", state.pointed === id && "bg-surface-sunken"),
13926
+ style: { borderLeftColor: (b.tone ?? "neutral") === "neutral" ? "transparent" : STROKE[b.tone ?? "neutral"] },
13927
+ children: renderBox ? renderBox(b) : b.label
13928
+ }, id);
13929
+ })
13930
+ });
13931
+ }
12974
13932
  // src/lib/sequence.ts
12975
13933
  var EPS = 1e-9;
12976
13934
  /** The grid point nearest to `time`, or `time` itself when there is no grid. */
@@ -13412,7 +14370,7 @@ function Children({ node }) {
13412
14370
  return /* @__PURE__ */ jsx(Nodes, { nodes: load.data });
13413
14371
  }
13414
14372
  /** A hierarchy whose children load as each node opens (a `useChildren` hook per open node): a skeleton row, a Try again row and an "empty" row per node, type-ahead and arrow keys, single selection, open state optionally in the URL, always virtualised. */
13415
- function Tree({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderNode, selected, onSelect, choices, expanded, loadingRow, emptyRow, height = "24rem", className }) {
14373
+ function Tree({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderNode, selected, onSelect, choices, expanded, beforeOpen, loadingRow, emptyRow, height = "24rem", className }) {
13416
14374
  const nodes = React.useRef(/* @__PURE__ */ new Map()).current;
13417
14375
  const childKeys = React.useRef(/* @__PURE__ */ new Map()).current;
13418
14376
  const below = (key) => (childKeys.get(key) ?? []).flatMap((k) => [k, ...below(k)]);
@@ -13548,7 +14506,14 @@ function Tree({ label, roots, useChildren, nodeKey, nodeLabel, isBranch, renderN
13548
14506
  selectedKeys: choices ? displayKeys : selected === null ? [] : [selected],
13549
14507
  onSelectionChange: choices ? chooseMany : choose,
13550
14508
  expandedKeys: expanded.expanded,
13551
- onExpandedChange: (keys) => expanded.onChange(new Set([...keys].map(String).filter((k) => !isNote(k)))),
14509
+ onExpandedChange: (keys) => {
14510
+ const next = new Set([...keys].map(String).filter((k) => !isNote(k)));
14511
+ if (beforeOpen) for (const k of [...next]) {
14512
+ const node = nodes.get(k);
14513
+ if (!expanded.isOpen(k) && node !== void 0 && beforeOpen(node) === false) next.delete(k);
14514
+ }
14515
+ expanded.onChange(next);
14516
+ },
13552
14517
  renderEmptyState: () => /* @__PURE__ */ jsx("p", {
13553
14518
  className: "p-3 type-body-sm text-muted-foreground",
13554
14519
  children: emptyRow
@@ -13605,8 +14570,22 @@ var parentOf = (path) => {
13605
14570
  /** Every folder from the top down to `path`, which the tree must have open to show it. */
13606
14571
  var ancestorsOf = (path) => parts(path).slice(0, -1).map((_, i, a) => `${SEP}${a.slice(0, i + 1).join(SEP)}`);
13607
14572
  /** A server folder chooser: a lazy tree, a breadcrumb that is also editable text, Up, recents, a New folder field that shows the server's refusal, and Choose this folder as the one filled button. */
13608
- function FolderPicker({ label, useFolders, value, onChange, onChoose, expanded, recent, onCreate, topLabel = "Top", emptyRow = "No folders", height = "18rem", className }) {
14573
+ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose, expanded, recent, canChoose, chooseLabel = "Choose this folder", onOpen, onCreate, topLabel = "Top", emptyRow = "No folders", height = "18rem", className }) {
14574
+ const useFolders = (path) => {
14575
+ const l = useListing(path);
14576
+ return l.status === "ready" && !Array.isArray(l.data) ? {
14577
+ ...l,
14578
+ data: l.data.folders
14579
+ } : l;
14580
+ };
13609
14581
  const roots = useFolders(null);
14582
+ const siblings = useFolders(value ? parentOf(value) : null);
14583
+ const own = useListing(value);
14584
+ const folder = value && siblings.status === "ready" ? siblings.data.find((f) => f.path === value) : void 0;
14585
+ const footer = value && own.status === "ready" && !Array.isArray(own.data) ? own.data.footer : void 0;
14586
+ const verdict = value && canChoose ? canChoose(value, folder) : true;
14587
+ const reason = typeof verdict === "string" ? verdict : void 0;
14588
+ const reasonId = React.useId();
13610
14589
  const [editing, setEditing] = React.useState(false);
13611
14590
  const [text, setText] = React.useState("");
13612
14591
  const go = (path) => onChange(path);
@@ -13676,14 +14655,17 @@ function FolderPicker({ label, useFolders, value, onChange, onChoose, expanded,
13676
14655
  "aria-hidden": true,
13677
14656
  className: "text-muted-foreground",
13678
14657
  children: "/"
13679
- }), /* @__PURE__ */ jsx(Button, {
13680
- size: "sm",
13681
- variant: "ghost",
13682
- title: path,
13683
- onPress: () => go(path),
13684
- "aria-current": last ? "location" : void 0,
13685
- className: cn("max-w-48 truncate", last && "font-medium"),
13686
- children: c
14658
+ }), /* @__PURE__ */ jsx(Tooltip, {
14659
+ label: path,
14660
+ side: "bottom",
14661
+ children: /* @__PURE__ */ jsx(Button, {
14662
+ size: "sm",
14663
+ variant: "ghost",
14664
+ onPress: () => go(path),
14665
+ "aria-current": last ? "location" : void 0,
14666
+ className: cn("max-w-48 truncate", last && "font-medium"),
14667
+ children: c
14668
+ })
13687
14669
  })]
13688
14670
  }, path);
13689
14671
  })]
@@ -13704,16 +14686,30 @@ function FolderPicker({ label, useFolders, value, onChange, onChoose, expanded,
13704
14686
  roots,
13705
14687
  useChildren: (f) => useFolders(f.path),
13706
14688
  nodeKey: (f) => f.path,
13707
- nodeLabel: (f) => f.name,
14689
+ nodeLabel: (f) => f.badge ? `${f.name}, ${f.badge}` : f.name,
14690
+ beforeOpen: onOpen ? (f) => {
14691
+ if (onOpen(f) !== "choose") return true;
14692
+ go(f.path);
14693
+ onChoose(f.path);
14694
+ return false;
14695
+ } : void 0,
13708
14696
  renderNode: (f) => /* @__PURE__ */ jsxs("span", {
13709
14697
  className: "flex min-w-0 items-baseline gap-2",
13710
- children: [/* @__PURE__ */ jsx("span", {
13711
- className: "truncate",
13712
- children: f.name
13713
- }), f.count !== void 0 && /* @__PURE__ */ jsx("span", {
13714
- className: "type-caption tabular-nums text-muted-foreground",
13715
- children: format.integer(f.count)
13716
- })]
14698
+ children: [
14699
+ /* @__PURE__ */ jsx("span", {
14700
+ className: "truncate",
14701
+ children: f.name
14702
+ }),
14703
+ f.badge && /* @__PURE__ */ jsx(Status, {
14704
+ tone: f.tone ?? "neutral",
14705
+ className: "self-center",
14706
+ children: f.badge
14707
+ }),
14708
+ f.count !== void 0 && /* @__PURE__ */ jsx("span", {
14709
+ className: "type-caption tabular-nums text-muted-foreground",
14710
+ children: format.integer(f.count)
14711
+ })
14712
+ ]
13717
14713
  }),
13718
14714
  selected: value,
13719
14715
  onSelect: (key) => onChange(key),
@@ -13729,13 +14725,16 @@ function FolderPicker({ label, useFolders, value, onChange, onChoose, expanded,
13729
14725
  children: [/* @__PURE__ */ jsx("span", {
13730
14726
  className: "type-caption text-muted-foreground",
13731
14727
  children: "Recent"
13732
- }), recent.map((r) => /* @__PURE__ */ jsx(Button, {
13733
- size: "sm",
13734
- variant: "outline",
13735
- title: r,
13736
- onPress: () => go(r),
13737
- className: "max-w-64 truncate font-mono",
13738
- children: r
14728
+ }), recent.map((r) => /* @__PURE__ */ jsx(Tooltip, {
14729
+ label: r,
14730
+ side: "bottom",
14731
+ children: /* @__PURE__ */ jsx(Button, {
14732
+ size: "sm",
14733
+ variant: "outline",
14734
+ onPress: () => go(r),
14735
+ className: "max-w-64 truncate font-mono",
14736
+ children: r
14737
+ })
13739
14738
  }, r))]
13740
14739
  }),
13741
14740
  onCreate && /* @__PURE__ */ jsx("form", {
@@ -13768,14 +14767,23 @@ function FolderPicker({ label, useFolders, value, onChange, onChoose, expanded,
13768
14767
  })
13769
14768
  })
13770
14769
  }),
13771
- /* @__PURE__ */ jsx("div", {
13772
- className: "flex justify-end",
13773
- children: /* @__PURE__ */ jsx(Button, {
14770
+ footer && /* @__PURE__ */ jsx("p", {
14771
+ className: "type-body-sm text-muted-foreground",
14772
+ children: footer
14773
+ }),
14774
+ /* @__PURE__ */ jsxs("div", {
14775
+ className: "flex flex-wrap items-center justify-end gap-3",
14776
+ children: [reason && /* @__PURE__ */ jsx("p", {
14777
+ id: reasonId,
14778
+ className: "min-w-0 flex-1 type-body-sm text-muted-foreground",
14779
+ children: reason
14780
+ }), /* @__PURE__ */ jsx(Button, {
13774
14781
  variant: "default",
13775
- disabled: !value,
14782
+ disabled: !value || reason !== void 0,
14783
+ "aria-describedby": reason ? reasonId : void 0,
13776
14784
  onPress: () => value && onChoose(value),
13777
- children: "Choose this folder"
13778
- })
14785
+ children: chooseLabel
14786
+ })]
13779
14787
  })
13780
14788
  ]
13781
14789
  });
@@ -14055,6 +15063,6 @@ function MarkableText({ label, ids, marks, kinds, onMark, clearKeys = [], onCare
14055
15063
  ]
14056
15064
  });
14057
15065
  }
14058
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, ContextMenu, Conversation, CursorScope, DEFAULT_TOLERANCE, DataTable, DataView, Density, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, PairJudge, PairVote, Pane, PlayWindowButton, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, SaveStatus, SecretField, SeekBar, SelectableGrid, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewportFrame, VirtualList, VolumeControl, Waveform, Workspace, actualPixelsScale, ancestorsOf, boxViewport, buttonVariants, canFullscreen, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, fetchJson, fieldErrorsOf, fitRect, format, formatChord, gainToVolume, geo, gridPoints, isDoubtful, isReservedChord, isTypingTarget, joinMediaGroup, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveRect, noOverlap, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, phraseDoubtful, plainText, rangeBetween, readErrorBody, readPixels, regionShares, resample, resamplePeaks, resizeRect, safeHref, serialiseSort, settleCut, snapToGrid, staleOf, stepId, stepOnGrid, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoSave, useChoices, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useLeaveGuard, useLoad, useMediaElement, useMediaSpans, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, useWorkspaceState, valueAt, wordAt, zoomAt };
15066
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, ContextMenu, Conversation, CursorScope, DEFAULT_TOLERANCE, DataTable, DataView, Density, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FolderPicker, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, PairJudge, PairVote, Pane, PlayWindowButton, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, SaveStatus, SecretField, SeekBar, SelectableGrid, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TileGrid, TileGridSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewportFrame, VirtualList, VolumeControl, Waveform, Workspace, actualPixelsScale, ancestorsOf, boxViewport, buttonVariants, canFullscreen, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, isDoubtful, isReservedChord, isTypingTarget, joinMediaGroup, joinRects, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, phraseDoubtful, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, splitRect, staleOf, stepId, stepOnGrid, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, turnRect, turnedSize, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoSave, useBookUrl, useBoxes, useChoices, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, wordAt, zoomAt, zoomToBox };
14059
15067
 
14060
15068
  //# sourceMappingURL=index.js.map