strata-react 1.0.42 → 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.
package/dist/index.js CHANGED
@@ -6,10 +6,10 @@ import { a as toLoad, c as toast, i as staleOf, l as toastTimeout, n as createQu
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";
@@ -6385,7 +6385,7 @@ function PropertyList({ items, label, className }) {
6385
6385
  })
6386
6386
  });
6387
6387
  }
6388
- // src/components/selectable-grid.tsx
6388
+ // src/components/tile-grid.tsx
6389
6389
  var minWidth = {
6390
6390
  sm: 96,
6391
6391
  md: 144,
@@ -6401,8 +6401,90 @@ var aspectRatio = {
6401
6401
  portrait: 4 / 3,
6402
6402
  landscape: 3 / 4
6403
6403
  };
6404
+ var thumbnailAspect = {
6405
+ square: 1,
6406
+ portrait: 3 / 4,
6407
+ landscape: 4 / 3
6408
+ };
6404
6409
  var GAP = 12;
6405
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
6406
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`. */
6407
6489
  function SelectableGrid({ label, rows, rowKey, renderImage, detail, selection, aspect = "square", tileSize = "md", virtualizeFrom = 100, maxHeight = 480, className }) {
6408
6490
  const select = useSelectRows(rows, rowKey, selection);
@@ -6427,10 +6509,7 @@ function SelectableGrid({ label, rows, rowKey, renderImage, detail, selection, a
6427
6509
  const picked = next === "all" ? rows.filter((r) => selection.isSelectable?.(r) ?? true).map(rowKey) : [...next].map(String).filter((k) => shownKeys.has(k));
6428
6510
  selection.onChange(/* @__PURE__ */ new Set([...outside, ...picked]));
6429
6511
  };
6430
- const layoutOptions = React.useMemo(() => ({
6431
- minItemSize: new Size(minWidth[tileSize], Math.round(minWidth[tileSize] * aspectRatio[aspect]) + TILE_CHROME),
6432
- minSpace: new Size(GAP, GAP)
6433
- }), [tileSize, aspect]);
6512
+ const layoutOptions = React.useMemo(() => tileLayoutOptions(tileSize, aspect), [tileSize, aspect]);
6434
6513
  const grid = /* @__PURE__ */ jsx(GridList, {
6435
6514
  "aria-label": label,
6436
6515
  layout: "grid",
@@ -6831,6 +6910,30 @@ function logScale(values, pin = {}) {
6831
6910
  log: true
6832
6911
  };
6833
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
+ }
6834
6937
  /** The value of a series at x, read between the two readings either side (flat beyond the ends). Series need not be sorted. */
6835
6938
  function valueAt(series, x) {
6836
6939
  const sorted = [...series].sort((p, q) => p.x - q.x);
@@ -6858,13 +6961,28 @@ function fitTicks(ticks, scale, widthOf, gap = 12) {
6858
6961
  return sorted.slice(0, 1);
6859
6962
  }
6860
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`. */
6861
- 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 }) {
6862
6965
  const [ref, width] = useWidth$1();
6863
6966
  const shared = useSharedCursor();
6864
6967
  const joined = Boolean(cursorProp) && shared !== null;
6865
6968
  const mapping = typeof cursorProp === "object" ? cursorProp : void 0;
6866
6969
  const gradientId = `heat-${React.useId().replace(/[^\w-]/g, "")}`;
6867
- 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
+ ];
6868
6986
  const xMin = xDomain ? xDomain[0] : Math.min(...all.map((p) => p.x));
6869
6987
  const xMax = xDomain ? xDomain[1] : Math.max(...all.map((p) => p.x));
6870
6988
  const log = yMode === "log";
@@ -6994,6 +7112,13 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
6994
7112
  strokeWidth: 1.5,
6995
7113
  strokeDasharray: "4 4"
6996
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
+ }),
6997
7122
  area && series.length > 1 && /* @__PURE__ */ jsx("path", {
6998
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`,
6999
7124
  fill: colour,
@@ -7046,6 +7171,7 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
7046
7171
  width,
7047
7172
  height,
7048
7173
  series,
7174
+ limits,
7049
7175
  planned,
7050
7176
  band,
7051
7177
  tickList,
@@ -7069,14 +7195,25 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
7069
7195
  children: [
7070
7196
  /* @__PURE__ */ jsxs("table", { children: [
7071
7197
  /* @__PURE__ */ jsx("caption", { children: label }),
7072
- /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
7073
- scope: "col",
7074
- children: xLabel
7075
- }), /* @__PURE__ */ jsx("th", {
7076
- scope: "col",
7077
- children: seriesLabel
7078
- })] }) }),
7079
- /* @__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)) })
7080
7217
  ] }),
7081
7218
  spans && spans.length > 0 && /* @__PURE__ */ jsx("ul", {
7082
7219
  "aria-label": "Shaded stretches",
@@ -7095,14 +7232,16 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
7095
7232
  formatY,
7096
7233
  xLabel,
7097
7234
  spans,
7098
- marks
7235
+ marks,
7236
+ range,
7237
+ limits
7099
7238
  ]);
7100
7239
  const sorted = React.useMemo(() => [...series].sort((p, q) => p.x - q.x), [series]);
7101
7240
  const interactive = Boolean(readout || onPick || joined);
7102
7241
  const [hover, setHover] = React.useState(null);
7103
7242
  const [kbd, setKbd] = React.useState(null);
7104
7243
  const [focused, setFocused] = React.useState(false);
7105
- 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 ")})` : ""}`;
7106
7245
  const nearest = (px) => {
7107
7246
  const target = xMin + (px - pad.left) / (w || 1) * (xMax - xMin || 1);
7108
7247
  let best = 0;
@@ -7357,6 +7496,21 @@ function LineChart({ label, series, seriesLabel, planned, plannedLabel, band, fo
7357
7496
  ] })
7358
7497
  ]
7359
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
+ }),
7360
7514
  spans?.map((sp) => /* @__PURE__ */ jsxs("span", {
7361
7515
  className: "inline-flex items-center gap-2",
7362
7516
  children: [/* @__PURE__ */ jsx("svg", {
@@ -12159,15 +12313,16 @@ function Conversation({ label, turns, answerName, personName = "You", entities,
12159
12313
  });
12160
12314
  }
12161
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. */
12162
- 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 }) {
12163
12317
  const [text, setText] = React.useState("");
12164
12318
  const reasonId = React.useId();
12165
12319
  const send = (value) => {
12166
12320
  const v = value.trim();
12167
- if (!v || answering) return;
12321
+ if (!v || answering || disabled) return;
12168
12322
  onSend(v);
12169
12323
  setText("");
12170
12324
  };
12325
+ const reason = answering ? answeringReason : disabled;
12171
12326
  return /* @__PURE__ */ jsxs("div", {
12172
12327
  className: cn("space-y-2", className),
12173
12328
  children: [
@@ -12177,6 +12332,7 @@ function Composer({ label, onSend, answering = false, onStop, answeringReason, s
12177
12332
  className: "flex flex-wrap gap-2",
12178
12333
  children: suggestions.map((s) => /* @__PURE__ */ jsx(Button, {
12179
12334
  size: "sm",
12335
+ disabled: !!disabled,
12180
12336
  onClick: () => send(s),
12181
12337
  children: s
12182
12338
  }, s))
@@ -12189,10 +12345,10 @@ function Composer({ label, onSend, answering = false, onStop, answeringReason, s
12189
12345
  },
12190
12346
  children: [/* @__PURE__ */ jsx(Textarea, {
12191
12347
  "aria-label": label,
12192
- "aria-describedby": answering ? reasonId : void 0,
12348
+ "aria-describedby": reason ? reasonId : void 0,
12193
12349
  rows: 2,
12194
12350
  value: text,
12195
- disabled: answering,
12351
+ disabled: answering || !!disabled,
12196
12352
  onChange: (e) => setText(e.target.value),
12197
12353
  onKeyDown: (e) => {
12198
12354
  if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
@@ -12207,7 +12363,7 @@ function Composer({ label, onSend, answering = false, onStop, answeringReason, s
12207
12363
  }) : /* @__PURE__ */ jsxs(Button, {
12208
12364
  type: "submit",
12209
12365
  variant: "default",
12210
- disabled: !text.trim(),
12366
+ disabled: !text.trim() || !!disabled,
12211
12367
  children: [
12212
12368
  /* @__PURE__ */ jsx(Send, {}),
12213
12369
  " ",
@@ -12215,15 +12371,35 @@ function Composer({ label, onSend, answering = false, onStop, answeringReason, s
12215
12371
  ]
12216
12372
  })]
12217
12373
  }),
12218
- answering && /* @__PURE__ */ jsx("p", {
12374
+ reason && /* @__PURE__ */ jsx("p", {
12219
12375
  id: reasonId,
12220
12376
  className: "type-caption text-muted-foreground",
12221
- children: answeringReason
12377
+ children: reason
12222
12378
  })
12223
12379
  ]
12224
12380
  });
12225
12381
  }
12226
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
+ }
12227
12403
  var NARROW = "(max-width: 719px)";
12228
12404
  function useNarrow() {
12229
12405
  const [narrow, setNarrow] = React.useState(() => typeof matchMedia === "function" && matchMedia(NARROW).matches);
@@ -12238,7 +12414,7 @@ function useNarrow() {
12238
12414
  return narrow;
12239
12415
  }
12240
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. */
12241
- 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 }) {
12242
12418
  const last = items.length - 1;
12243
12419
  const at = Math.min(Math.max(index, 0), Math.max(last, 0));
12244
12420
  const item = items[at];
@@ -12269,7 +12445,7 @@ function Lightbox({ title, items, index, onIndexChange, open, onOpenChange, miss
12269
12445
  const keys = React.useRef((_) => {});
12270
12446
  keys.current = (e) => {
12271
12447
  if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
12272
- 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;
12273
12449
  const to = e.key === "ArrowLeft" ? at - 1 : e.key === "ArrowRight" ? at + 1 : e.key === "Home" ? 0 : e.key === "End" ? last : null;
12274
12450
  if (to === null) return;
12275
12451
  e.preventDefault();
@@ -12290,90 +12466,140 @@ function Lightbox({ title, items, index, onIndexChange, open, onOpenChange, miss
12290
12466
  size: "full",
12291
12467
  children: item && /* @__PURE__ */ jsxs("div", {
12292
12468
  className: "flex h-full min-h-0 flex-col gap-3 outline-none",
12293
- children: [/* @__PURE__ */ jsxs("div", {
12294
- className: "flex flex-wrap items-center gap-2",
12295
- children: [
12296
- /* @__PURE__ */ jsx(IconButton, {
12297
- icon: ChevronLeft,
12298
- label: "Previous picture",
12299
- onPress: () => go(at - 1),
12300
- disabled: at === 0
12301
- }),
12302
- /* @__PURE__ */ jsx(IconButton, {
12303
- icon: ChevronRight,
12304
- label: "Next picture",
12305
- onPress: () => go(at + 1),
12306
- disabled: at === last
12307
- }),
12308
- /* @__PURE__ */ jsxs("span", {
12309
- className: "type-label tabular-nums",
12310
- "aria-live": "polite",
12311
- "aria-atomic": "true",
12312
- children: [
12313
- at + 1,
12314
- " of ",
12315
- items.length
12316
- ]
12317
- }),
12318
- /* @__PURE__ */ jsx(Toolbar, {
12319
- label: "Zoom",
12320
- className: "ml-2 flex items-center gap-1",
12321
- 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,
12322
12534
  viewport,
12323
- zoom,
12324
- 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)]
12325
12545
  })
12326
- }),
12327
- onCompare && ticked && /* @__PURE__ */ jsxs(Button, {
12328
- size: "sm",
12329
- className: "ml-auto",
12330
- disabled: !ready,
12331
- onPress: () => onCompare(ticked),
12332
- children: [
12333
- "Compare ticked (",
12334
- ticked.length,
12335
- ")"
12336
- ]
12337
- })
12338
- ]
12339
- }), /* @__PURE__ */ jsxs("div", {
12340
- className: cn("flex min-h-0 flex-1 gap-4", narrow ? "flex-col" : "flex-row"),
12341
- children: [/* @__PURE__ */ jsx("div", {
12342
- className: "min-h-0 min-w-0 flex-1",
12343
- children: failed.has(item.id) ? /* @__PURE__ */ jsx("p", {
12344
- role: "img",
12345
- "aria-label": item.label,
12346
- 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",
12347
- children: missing
12348
- }) : /* @__PURE__ */ jsx(ViewportFrame, {
12349
- ref: frame,
12350
- label: item.label,
12351
- aspect,
12352
- viewport,
12353
- setViewport,
12354
- maxHeight: narrow ? "50svh" : "calc(100svh - 12rem)",
12355
- children: /* @__PURE__ */ jsx("img", {
12356
- src: item.src,
12357
- alt: item.label,
12358
- draggable: false,
12359
- className: "size-full object-contain",
12360
- onLoad: (e) => setNatural([e.currentTarget.naturalWidth, e.currentTarget.naturalHeight]),
12361
- onError: () => setFailed((f) => new Set(f).add(item.id))
12362
- }, item.id)
12363
- })
12364
- }), body && (narrow ? /* @__PURE__ */ jsx(Disclosure, {
12365
- summary: detailsLabel,
12366
- className: "shrink-0",
12367
- children: body
12368
- }) : /* @__PURE__ */ jsx("aside", {
12369
- "aria-label": detailsLabel,
12370
- className: "min-h-0 w-72 shrink-0 overflow-y-auto",
12371
- children: body
12372
- }))]
12373
- })]
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
+ ]
12374
12562
  })
12375
12563
  });
12376
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
+ }
12377
12603
  // src/lib/region.ts
12378
12604
  var HANDLES = [
12379
12605
  "nw",
@@ -12519,6 +12745,86 @@ var sameRect = (a, b) => [
12519
12745
  "w",
12520
12746
  "h"
12521
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
+ }
12522
12828
  // src/components/region-editor.tsx
12523
12829
  var TONE$1 = {
12524
12830
  neutral: {
@@ -12566,8 +12872,12 @@ var round = (n) => format.integer(Math.round(n));
12566
12872
  /** A window said in words. */
12567
12873
  var describeRegion = (r) => `${r.label}: ${round(r.w)} wide by ${round(r.h)} high, ${round(r.x)} across and ${round(r.y)} down`;
12568
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. */
12569
- 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 }) {
12570
- 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;
12571
12881
  const limits = React.useMemo(() => ({
12572
12882
  bounds: bounds ?? {
12573
12883
  x: 0,
@@ -12601,7 +12911,7 @@ function RegionEditor({ label, children, size, regions, onChange, selectedId, on
12601
12911
  const [said, setSaid] = React.useState("");
12602
12912
  const hintId = React.useId();
12603
12913
  const rectOf = (r) => draft?.id === r.id ? draft.rect : r;
12604
- const shown = regions.map((r) => ({
12914
+ const shownBase = regions.map((r) => ({
12605
12915
  ...r,
12606
12916
  ...rectOf(r)
12607
12917
  }));
@@ -12732,6 +13042,70 @@ function RegionEditor({ label, children, size, regions, onChange, selectedId, on
12732
13042
  ...next
12733
13043
  });
12734
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);
12735
13109
  const chosen = shown.find((r) => r.id === selected);
12736
13110
  const setSide = (key, value) => {
12737
13111
  if (!chosen || value === null) return;
@@ -12797,111 +13171,234 @@ function RegionEditor({ label, children, size, regions, onChange, selectedId, on
12797
13171
  /* @__PURE__ */ jsxs("div", {
12798
13172
  className: "relative overflow-hidden rounded-surface border border-border bg-surface-sunken",
12799
13173
  style: { aspectRatio: `${w} / ${h}` },
12800
- children: [children, /* @__PURE__ */ jsxs("div", {
12801
- ref: overlay,
12802
- role: "group",
12803
- "aria-label": label,
12804
- "aria-describedby": hintId,
12805
- className: cn("absolute inset-0 touch-none select-none", onDraw && "cursor-crosshair"),
12806
- onPointerDown: beginDraw,
12807
- onPointerMove: onMove,
12808
- onPointerUp: onUp,
12809
- onPointerCancel: () => {
12810
- gesture.current = null;
12811
- setDraft(null);
12812
- setDrawing(null);
12813
- },
12814
- children: [
12815
- mode === "move" && from && to && /* @__PURE__ */ jsxs("svg", {
12816
- className: "pointer-events-none absolute inset-0 size-full",
12817
- viewBox: `0 0 ${w} ${h}`,
12818
- preserveAspectRatio: "none",
12819
- "aria-hidden": true,
12820
- children: [/* @__PURE__ */ jsx("defs", { children: /* @__PURE__ */ jsx("marker", {
12821
- id: `${hintId}-arrow`,
12822
- viewBox: "0 0 10 10",
12823
- refX: "8",
12824
- refY: "5",
12825
- markerWidth: "6",
12826
- markerHeight: "6",
12827
- orient: "auto-start-reverse",
12828
- children: /* @__PURE__ */ jsx("path", {
12829
- d: "M0 0 10 5 0 10z",
12830
- fill: "var(--foreground)"
12831
- })
12832
- }) }), /* @__PURE__ */ jsx("line", {
12833
- x1: from.x + from.w / 2,
12834
- y1: from.y + from.h / 2,
12835
- x2: to.x + to.w / 2,
12836
- y2: to.y + to.h / 2,
12837
- stroke: "var(--foreground)",
12838
- strokeWidth: 2,
12839
- vectorEffect: "non-scaling-stroke",
12840
- strokeDasharray: "6 4",
12841
- markerEnd: `url(#${hintId}-arrow)`
12842
- })]
12843
- }),
12844
- shown.map((r) => {
12845
- const tone = TONE$1[r.tone ?? "neutral"];
12846
- const active = r.id === selected;
12847
- return /* @__PURE__ */ jsxs("div", {
12848
- role: "group",
12849
- "aria-roledescription": "region",
12850
- "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),
12851
13296
  tabIndex: 0,
12852
- "data-region": r.id,
12853
- "data-selected": active || void 0,
12854
- onFocus: () => select(r.id),
12855
- onBlur: (e) => {
12856
- 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);
12857
13315
  },
12858
- onKeyDown: (e) => keys(e, r),
12859
- onPointerDown: (e) => beginMove(e, r),
12860
- className: cn("absolute cursor-move border-2 outline-offset-2 transition-state", active ? "z-10" : "opacity-90"),
13316
+ onPointerUp: (e) => {
13317
+ if (gutterDraft === null) return;
13318
+ e.stopPropagation();
13319
+ keepGutter(gutterDraft);
13320
+ },
13321
+ className: "absolute z-20 -ml-2 w-4 cursor-col-resize touch-none outline-offset-2",
12861
13322
  style: {
12862
- ...pct(r),
12863
- borderColor: tone.edge,
12864
- backgroundColor: `color-mix(in oklab, ${tone.fill} 35%, transparent)`,
12865
- 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}%`
12866
13326
  },
12867
13327
  children: [/* @__PURE__ */ jsx("span", {
12868
- className: "pointer-events-none absolute left-0 top-0 max-w-full -translate-y-full truncate rounded-t-control px-1.5 type-caption",
12869
- style: {
12870
- backgroundColor: tone.edge,
12871
- color: "var(--background)"
12872
- },
12873
- children: r.label
12874
- }), active && HANDLES.map((handle) => /* @__PURE__ */ jsx("span", {
12875
13328
  "aria-hidden": true,
12876
- "data-handle": handle,
12877
- onPointerDown: (e) => beginResize(e, r, handle),
12878
- className: cn("absolute size-3 rounded-pill border-2 bg-background", HANDLE_AT[handle]),
12879
- style: {
12880
- borderColor: tone.edge,
12881
- cursor: CURSOR[handle]
12882
- }
12883
- }, handle))]
12884
- }, r.id);
12885
- }),
12886
- drawing && /* @__PURE__ */ jsx("div", {
12887
- "aria-hidden": true,
12888
- className: "pointer-events-none absolute border-2 border-dashed border-foreground bg-foreground/10",
12889
- style: pct(drawing)
12890
- }),
12891
- watching && /* @__PURE__ */ jsx("div", {
12892
- "aria-hidden": true,
12893
- "data-preview": true,
12894
- className: "pointer-events-none absolute z-20 border-2 border-foreground bg-foreground/15",
12895
- style: pct(watching)
12896
- })
12897
- ]
12898
- })]
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
+ ]
12899
13350
  }),
12900
13351
  /* @__PURE__ */ jsxs("p", {
12901
13352
  id: hintId,
12902
13353
  className: "type-caption text-muted-foreground",
12903
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."]
12904
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
+ }) }),
12905
13402
  (mode === "move" || defaults && modified) && /* @__PURE__ */ jsxs("div", {
12906
13403
  className: "flex flex-wrap items-center gap-2",
12907
13404
  children: [mode === "move" && /* @__PURE__ */ jsxs(Button, {
@@ -12984,6 +13481,454 @@ function RegionEditor({ label, children, size, regions, onChange, selectedId, on
12984
13481
  ]
12985
13482
  });
12986
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
+ }
12987
13932
  // src/lib/sequence.ts
12988
13933
  var EPS = 1e-9;
12989
13934
  /** The grid point nearest to `time`, or `time` itself when there is no grid. */
@@ -14118,6 +15063,6 @@ function MarkableText({ label, ids, marks, kinds, onMark, clearKeys = [], onCare
14118
15063
  ]
14119
15064
  });
14120
15065
  }
14121
- 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 };
14122
15067
 
14123
15068
  //# sourceMappingURL=index.js.map