strata-react 2.1.9 → 2.1.11

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
@@ -4,7 +4,7 @@ import { a as isDev, i as buttonVariants, n as IconButton, o as useInView, r as
4
4
  import { t as followAim } from "./follow-CXQsL86O.js";
5
5
  import { n as useViewPointers, r as useWheelZoom, t as useSettledStatus } from "./viewer-input-3Qa-o35k.js";
6
6
  import { A as StrataQueryProvider, C as toast, D as LoadError, E as EmptyState, F as useLoad, I as usePoll, L as overlaySurface, M as fetchJson, N as staleOf, O as Skeleton, P as toLoad, S as StrataToastRegion, T as DataView$1, _ as clampViewport, a as useMicrophone, b as viewportTransform, d as zoomToBox, f as FIT, g as boxViewport, h as actualPixelsScale, i as explainMicrophoneError, j as createQueryClient, k as StaleNotice, l as readingOrder, m as MIN_SCALE, n as MicrophoneError, o as Thumbnail, p as MAX_SCALE, r as browserMicrophone, s as ThumbnailSkeleton, t as MicrophoneContext, u as regionStyle, v as frameBoxToShares, w as toastTimeout, x as zoomAt, y as regionShares } from "./microphone-Db5o3SHZ.js";
7
- import { a as useAsyncAction, c as KeysLegend, d as useHotkeys, i as AsyncButton, l as isTypingTarget, n as NumberField, o as Toolbar, r as Slider, s as ToolbarSeparator, t as ColorField, u as keyName } from "./value-controls-D5zpPQuJ.js";
7
+ import { a as AsyncButton, c as ToolbarSeparator, d as keyName, f as useHotkeys, i as Slider, l as KeysLegend, n as NumberField, o as useAsyncAction, r as RangeSlider, s as Toolbar, t as ColorField, u as isTypingTarget } from "./value-controls-i1aGyO_3.js";
8
8
  import { n as useSharedCursor, r as geo, t as CursorScope } from "./cursor-Cwyvgwsw.js";
9
9
  import { a as fieldErrorsOf, i as errorPayload, n as describeActionError, o as readErrorBody, r as describeHttpError, t as HttpError } from "./errors-CmuwcWlb.js";
10
10
  import { a as PaletteChoice, c as paletteScript, d as usePalette, f as useSystemColorScheme, i as PALETTE_STORAGE_KEY, l as palettes, n as ColorSchemeChoice, o as ThemeProvider, p as Density, r as DEFAULT_PALETTE, s as colorSchemeScript, t as COLOR_SCHEME_STORAGE_KEY, u as useColorScheme } from "./theme-5Mb1ydlA.js";
@@ -22,13 +22,16 @@ import pixelmatch from "pixelmatch";
22
22
 
23
23
  // src/lib/countdown.ts
24
24
  /**
25
- * Counts down `seconds` whole seconds while `running`, then calls `onDone` once: the seconds left (never below 1), or
26
- * null when not counting (not running, or 0 seconds: the caller waits for a tap instead). Running false and true again
27
- * starts again from `seconds`, and so does a new `run` while it counts (a new look begun before the last one showed).
25
+ * Counts down `seconds` whole seconds while `running`, then calls `onDone` once (after `hold` is false, if given): the
26
+ * seconds left (never below 1), or null when not counting (not running, or 0 seconds: the caller waits for a tap
27
+ * instead). Running false and true again starts again from `seconds`, and so does a new `run` while it counts (a new
28
+ * look begun before the last one showed).
28
29
  */
29
- function useCountdown(running, seconds, onDone, run) {
30
+ function useCountdown(running, seconds, onDone, run, { hold = false, holdAtMost = 1e4 } = {}) {
30
31
  const counting = running && seconds > 0;
31
32
  const [left, setLeft] = React.useState(seconds);
33
+ const [overdue, setOverdue] = React.useState(false);
34
+ const [fired, setFired] = React.useState(false);
32
35
  const [was, setWas] = React.useState({
33
36
  counting: false,
34
37
  run
@@ -38,7 +41,11 @@ function useCountdown(running, seconds, onDone, run) {
38
41
  counting,
39
42
  run
40
43
  });
41
- if (counting) setLeft(seconds);
44
+ if (counting) {
45
+ setLeft(seconds);
46
+ setOverdue(false);
47
+ setFired(false);
48
+ }
42
49
  }
43
50
  const latest = React.useRef(onDone);
44
51
  React.useEffect(() => {
@@ -50,10 +57,7 @@ function useCountdown(running, seconds, onDone, run) {
50
57
  const t = setInterval(() => {
51
58
  n -= 1;
52
59
  setLeft(n);
53
- if (n <= 0) {
54
- clearInterval(t);
55
- latest.current();
56
- }
60
+ if (n <= 0) clearInterval(t);
57
61
  }, 1e3);
58
62
  return () => clearInterval(t);
59
63
  }, [
@@ -61,6 +65,22 @@ function useCountdown(running, seconds, onDone, run) {
61
65
  seconds,
62
66
  run
63
67
  ]);
68
+ const ranOut = counting && left <= 0;
69
+ React.useEffect(() => {
70
+ if (!ranOut || !hold) return;
71
+ const t = setTimeout(() => setOverdue(true), holdAtMost);
72
+ return () => clearTimeout(t);
73
+ }, [
74
+ ranOut,
75
+ hold,
76
+ holdAtMost
77
+ ]);
78
+ const due = ranOut && (!hold || overdue) && !fired;
79
+ React.useEffect(() => {
80
+ if (!due) return;
81
+ setFired(true);
82
+ latest.current();
83
+ }, [due]);
64
84
  return counting ? Math.max(left, 1) : null;
65
85
  }
66
86
 
@@ -3486,6 +3506,59 @@ function ScheduleTable({ caption, rows, now, className }) {
3486
3506
  });
3487
3507
  }
3488
3508
 
3509
+ // src/components/concealed.tsx
3510
+ /** Content covered until a person chooses to see it: the reason in words, a named Show / Hide button, and the picture itself supplied by the app (blurred by the server while covered), so nothing is hidden by CSS alone. */
3511
+ function Concealed({ concealed, reason, label, revealed, onRevealedChange, children, className }) {
3512
+ if (!concealed) return /* @__PURE__ */ jsx(Fragment, { children });
3513
+ const Icon = revealed ? EyeOff : Eye;
3514
+ return /* @__PURE__ */ jsxs("div", {
3515
+ className: cn("relative", className),
3516
+ "data-concealed": revealed ? "revealed" : "covered",
3517
+ children: [children, /* @__PURE__ */ jsxs("div", {
3518
+ className: "absolute inset-x-0 bottom-0 flex items-center justify-between gap-2 bg-background/85 px-2 py-1",
3519
+ children: [/* @__PURE__ */ jsx("span", {
3520
+ className: "min-w-0 truncate type-caption text-foreground",
3521
+ children: reason
3522
+ }), /* @__PURE__ */ jsx(IconButton, {
3523
+ icon: Icon,
3524
+ size: "sm",
3525
+ label: `${revealed ? "Hide" : "Show"} ${label}`,
3526
+ onPress: () => onRevealedChange(!revealed)
3527
+ })]
3528
+ })]
3529
+ });
3530
+ }
3531
+ /** Which covered items a person has chosen to see on this screen, and a show-all switch; for this visit only, never stored. */
3532
+ function useRevealed() {
3533
+ const [ids, setIds] = React.useState(/* @__PURE__ */ new Set());
3534
+ const [all, setAllState] = React.useState(false);
3535
+ const isRevealed = React.useCallback((id) => all || ids.has(id), [all, ids]);
3536
+ const set = React.useCallback((id, revealed) => {
3537
+ setIds((prev) => {
3538
+ const next = new Set(prev);
3539
+ if (revealed) next.add(id);
3540
+ else next.delete(id);
3541
+ return next;
3542
+ });
3543
+ if (!revealed) setAllState(false);
3544
+ }, []);
3545
+ const setAll = React.useCallback((on) => {
3546
+ setAllState(on);
3547
+ if (!on) setIds(/* @__PURE__ */ new Set());
3548
+ }, []);
3549
+ return React.useMemo(() => ({
3550
+ isRevealed,
3551
+ set,
3552
+ all,
3553
+ setAll
3554
+ }), [
3555
+ isRevealed,
3556
+ set,
3557
+ all,
3558
+ setAll
3559
+ ]);
3560
+ }
3561
+
3489
3562
  // src/components/film-strip.tsx
3490
3563
  const GAP$1 = 4;
3491
3564
  /** `n` of `items` spread evenly from the first to the last (all of them when there are no more than `n`). */
@@ -4308,17 +4381,17 @@ let snapshot = {
4308
4381
  count: 0,
4309
4382
  active: null
4310
4383
  };
4311
- const listeners = /* @__PURE__ */ new Set();
4384
+ const listeners$1 = /* @__PURE__ */ new Set();
4312
4385
  const emit = () => {
4313
4386
  snapshot = {
4314
4387
  count: members.size,
4315
4388
  active
4316
4389
  };
4317
- listeners.forEach((l) => l());
4390
+ listeners$1.forEach((l) => l());
4318
4391
  };
4319
4392
  const subscribe = (l) => {
4320
- listeners.add(l);
4321
- return () => void listeners.delete(l);
4393
+ listeners$1.add(l);
4394
+ return () => void listeners$1.delete(l);
4322
4395
  };
4323
4396
  const get = () => snapshot;
4324
4397
  /**
@@ -12828,7 +12901,7 @@ function nextBeckon(open, last) {
12828
12901
  const others = open.length > 1 ? open.filter((k) => k !== last) : open;
12829
12902
  return others[Math.floor(Math.random() * others.length)] ?? null;
12830
12903
  }
12831
- const SEP$1 = "\0";
12904
+ const SEP$2 = "\0";
12832
12905
  const REDUCE = "(prefers-reduced-motion: reduce)";
12833
12906
  const reduceQuery = () => typeof matchMedia === "function" ? matchMedia(REDUCE) : null;
12834
12907
  function subscribeReduce(change) {
@@ -12845,11 +12918,11 @@ function useReducedMotion() {
12845
12918
  * open tile, lit beat after beat, still pulses each time (Codex on #400). */
12846
12919
  function useBeckon(on, open, ms) {
12847
12920
  const [lit, setLit] = React.useState(null);
12848
- const openKey = open.join(SEP$1);
12921
+ const openKey = open.join(SEP$2);
12849
12922
  const still = useReducedMotion();
12850
12923
  React.useEffect(() => {
12851
12924
  if (!on || still || openKey === "") return;
12852
- const keys = openKey.split(SEP$1);
12925
+ const keys = openKey.split(SEP$2);
12853
12926
  let last = null;
12854
12927
  let beat = 0;
12855
12928
  const t = setInterval(() => {
@@ -12888,6 +12961,13 @@ function pictureInTile(content) {
12888
12961
  const n = [...letters.segment(content)].length;
12889
12962
  return n <= 2 ? { fontSize: TILE } : { fontSize: `min(var(--type-picture-size, 4.5rem), 75cqi, ${Math.round(WORD_SHARE / n * 10) / 10}cqi)` };
12890
12963
  }
12964
+ const CAPTION = "var(--type-body-size, 1rem)";
12965
+ const CAPTION_SHARE = 160;
12966
+ /** A caption's size in its tile: the body step, or smaller for a long caption so it fits across the tile on one line. */
12967
+ function captionInTile(content) {
12968
+ const n = typeof content === "string" ? [...letters.segment(content)].length : 0;
12969
+ return n <= 8 ? { fontSize: `min(${CAPTION}, 20cqi)` } : { fontSize: `min(${CAPTION}, ${Math.round(CAPTION_SHARE / n * 10) / 10}cqi)` };
12970
+ }
12891
12971
 
12892
12972
  // src/components/choice-grid.tsx
12893
12973
  const minSide = {
@@ -12897,11 +12977,11 @@ const minSide = {
12897
12977
  const closed = (s) => s === "right" || s === "answer" || s === "picked";
12898
12978
  const columns = (size, stretch = false) => ({ gridTemplateColumns: `repeat(${stretch ? "auto-fit" : "auto-fill"}, minmax(min(${minSide[size]}px, 100%), 1fr))` });
12899
12979
  /** A grid of large picture tiles for answering one question with a tap: each tile open, wrong, right, shown as the answer or (no answer key) picked, with its word; answered tiles cannot be pressed again, and the grid closes once the answer shows. */
12900
- function ChoiceGrid({ label, items, itemKey, itemLabel, renderPicture, state, marks, onChoose, size = "md", stretch = false, beckon = false, beckonMs = 1600, className }) {
12980
+ function ChoiceGrid({ label, items, itemKey, itemLabel, renderPicture, state, marks, onChoose, size = "md", stretch = false, beckon = false, beckonMs = 1600, renderCaption, onHover, reading = null, className }) {
12901
12981
  const byKey = new Map(items.map((item) => [itemKey(item), item]));
12902
12982
  const over = items.some((item) => closed(state(item)));
12903
12983
  const disabledKeys = items.filter((item) => over || state(item) !== "open").map(itemKey);
12904
- const lit = useBeckon(beckon && !over, items.filter((item) => state(item) === "open").map(itemKey), beckonMs);
12984
+ const lit = useBeckon(beckon && !over && reading === null, items.filter((item) => state(item) === "open").map(itemKey), beckonMs);
12905
12985
  return /* @__PURE__ */ jsx(GridList, {
12906
12986
  "aria-label": label,
12907
12987
  layout: "grid",
@@ -12923,20 +13003,35 @@ function ChoiceGrid({ label, items, itemKey, itemLabel, renderPicture, state, ma
12923
13003
  "aria-label": mark ? `${itemLabel(item)}, ${mark.toLowerCase()}` : itemLabel(item),
12924
13004
  "data-choice": s,
12925
13005
  "data-beckon": key === lit?.key || void 0,
12926
- className: cn("@container flex aspect-square min-w-0 cursor-pointer flex-col items-center justify-center gap-1 rounded-overlay border-2 border-border bg-card p-2 text-card-foreground select-none outline-offset-2 transition-state press", "hover:border-primary disabled:cursor-default disabled:hover:border-border", key === lit?.key && cn(lit.className, "border-primary"), (s === "right" || s === "answer") && "border-4 border-success bg-success-subtle disabled:hover:border-success", s === "picked" && "border-4 border-primary bg-surface-sunken disabled:hover:border-primary"),
12927
- children: [(() => {
12928
- const drawn = renderPicture(item);
12929
- return /* @__PURE__ */ jsx("span", {
12930
- "aria-hidden": true,
12931
- className: cn("type-picture transition-state", s === "wrong" && "opacity-40"),
12932
- style: pictureInTile(drawn),
12933
- children: drawn
12934
- });
12935
- })(), mark && /* @__PURE__ */ jsx(Status, {
12936
- tone: s === "wrong" || s === "picked" ? "neutral" : "success",
12937
- className: "max-w-full truncate",
12938
- children: mark
12939
- })]
13006
+ "data-reading": key === reading || void 0,
13007
+ onPointerEnter: onHover && ((e) => e.pointerType !== "touch" && onHover(item)),
13008
+ className: cn("@container flex aspect-square min-w-0 cursor-pointer flex-col items-center justify-center gap-1 rounded-overlay border-2 border-border bg-card p-2 text-card-foreground select-none outline-offset-2 transition-state press", "hover:border-primary disabled:cursor-default disabled:hover:border-border", key === lit?.key && cn(lit.className, "border-primary"), key === reading && "border-primary ring-4 ring-primary", (s === "right" || s === "answer") && "border-4 border-success bg-success-subtle disabled:hover:border-success", s === "picked" && "border-4 border-primary bg-surface-sunken disabled:hover:border-primary"),
13009
+ children: [
13010
+ (() => {
13011
+ const drawn = renderPicture(item);
13012
+ return /* @__PURE__ */ jsx("span", {
13013
+ "aria-hidden": true,
13014
+ className: cn("type-picture transition-state", s === "wrong" && "opacity-40"),
13015
+ style: pictureInTile(drawn),
13016
+ children: drawn
13017
+ });
13018
+ })(),
13019
+ renderCaption && (() => {
13020
+ const caption = renderCaption(item);
13021
+ return /* @__PURE__ */ jsx("span", {
13022
+ "aria-hidden": true,
13023
+ "data-caption": true,
13024
+ className: cn("type-body max-w-full truncate font-medium", s === "wrong" && "opacity-40"),
13025
+ style: captionInTile(caption),
13026
+ children: caption
13027
+ });
13028
+ })(),
13029
+ mark && /* @__PURE__ */ jsx(Status, {
13030
+ tone: s === "wrong" || s === "picked" ? "neutral" : "success",
13031
+ className: "max-w-full truncate",
13032
+ children: mark
13033
+ })
13034
+ ]
12940
13035
  }, key);
12941
13036
  })
12942
13037
  });
@@ -12957,7 +13052,7 @@ const placedSide = 72;
12957
13052
  const placedPicture = { "--type-picture-size": "2.5rem" };
12958
13053
  const placeSide = 160;
12959
13054
  /** Pictures put into places for an answer that is an arrangement (give a number, order, match, sort): two taps (pick up, put down), one tap when there is one place, or a drag. The app owns where each piece is and checks it; the board only moves what the learner asks, and keeps every piece's slot so nothing shifts. */
12960
- function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places, placeKey, placeLabel, renderPlace, placement, onMove, pileLabel, placeState = () => "open", marks, locked = false, stretch = false, beckon = false, beckonMs = 1600, check, limit, className }) {
13055
+ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places, placeKey, placeLabel, renderPlace, placement, onMove, pileLabel, placeState = () => "open", marks, locked = false, stretch = false, beckon = false, beckonMs = 1600, check, limit, renderCaption, onHover, onHoverPlace, reading = null, className }) {
12961
13056
  const fill = stretch ? "auto-fit" : "auto-fill";
12962
13057
  const [heldKey, setHeld] = React.useState(null);
12963
13058
  const [follow, setFollow] = React.useState(null);
@@ -12974,7 +13069,7 @@ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places,
12974
13069
  const only = places.length === 1 ? places[0] : void 0;
12975
13070
  const held = locked ? void 0 : pieces.find((p) => pieceKey(p) === heldKey);
12976
13071
  const heldAt = held === void 0 ? null : where(held);
12977
- const lit = useBeckon(beckon && !locked && held === void 0, pieces.filter((p) => where(p) === null).map(pieceKey), beckonMs);
13072
+ const lit = useBeckon(beckon && !locked && held === void 0 && reading === null, pieces.filter((p) => where(p) === null).map(pieceKey), beckonMs);
12978
13073
  React.useEffect(() => {
12979
13074
  if (follow === null) return;
12980
13075
  buttons.current.get(follow)?.focus();
@@ -13083,7 +13178,7 @@ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places,
13083
13178
  if (el) buttons.current.set(key, el);
13084
13179
  else buttons.current.delete(key);
13085
13180
  };
13086
- const pieceClass = (key) => cn("@container relative flex aspect-square w-full min-w-0 cursor-pointer flex-col items-center justify-center gap-1 rounded-overlay border-2 border-border bg-card p-1 text-card-foreground select-none outline-offset-2 transition-state press", "hover:border-primary disabled:cursor-default disabled:hover:border-border", "selected:border-info selected:bg-info-subtle selected:ring-4 selected:ring-info", key === lit?.key && cn(lit.className, "border-primary"));
13181
+ const pieceClass = (key) => cn("@container relative flex aspect-square w-full min-w-0 cursor-pointer flex-col items-center justify-center gap-1 rounded-overlay border-2 border-border bg-card p-1 text-card-foreground select-none outline-offset-2 transition-state press", "hover:border-primary disabled:cursor-default disabled:hover:border-border", "selected:border-info selected:bg-info-subtle selected:ring-4 selected:ring-info", key === lit?.key && cn(lit.className, "border-primary"), key === reading && "border-primary ring-4 ring-primary");
13087
13182
  const picture = (p, placed) => {
13088
13183
  const drawn = renderPiece(p);
13089
13184
  return /* @__PURE__ */ jsx("span", {
@@ -13096,6 +13191,20 @@ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places,
13096
13191
  children: drawn
13097
13192
  });
13098
13193
  };
13194
+ const caption = (p) => {
13195
+ if (!renderCaption) return null;
13196
+ const text = renderCaption(p);
13197
+ return /* @__PURE__ */ jsx("span", {
13198
+ "aria-hidden": true,
13199
+ "data-caption": true,
13200
+ className: "type-body max-w-full truncate font-medium",
13201
+ style: captionInTile(text),
13202
+ children: text
13203
+ });
13204
+ };
13205
+ const hover = (say) => (e) => {
13206
+ if (e.pointerType !== "touch") say();
13207
+ };
13099
13208
  const piece = (p, placed) => {
13100
13209
  const key = pieceKey(p);
13101
13210
  const isHeld = held !== void 0 && pieceKey(held) === key;
@@ -13109,15 +13218,19 @@ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places,
13109
13218
  "aria-label": placed ? `Take ${name} out of ${placeLabel(only)}` : `Put ${name} in ${placeLabel(only)}`,
13110
13219
  "data-beckon": key === lit?.key || void 0,
13111
13220
  className: cn(pieceClass(key), "group", isHeld && "border-info bg-info-subtle ring-4 ring-info"),
13112
- children: [picture(p, placed), placed && !locked && /* @__PURE__ */ jsx("span", {
13113
- "aria-hidden": true,
13114
- "data-remove": true,
13115
- className: "absolute inset-0 flex items-center justify-center rounded-overlay bg-background/70 text-foreground opacity-0 transition-state group-hover:opacity-100 group-focus-visible:opacity-100",
13116
- children: /* @__PURE__ */ jsx(X, {
13117
- className: "size-3/4",
13118
- strokeWidth: 3
13221
+ children: [
13222
+ picture(p, placed),
13223
+ caption(p),
13224
+ placed && !locked && /* @__PURE__ */ jsx("span", {
13225
+ "aria-hidden": true,
13226
+ "data-remove": true,
13227
+ className: "absolute inset-0 flex items-center justify-center rounded-overlay bg-background/70 text-foreground opacity-0 transition-state group-hover:opacity-100 group-focus-visible:opacity-100",
13228
+ children: /* @__PURE__ */ jsx(X, {
13229
+ className: "size-3/4",
13230
+ strokeWidth: 3
13231
+ })
13119
13232
  })
13120
- })]
13233
+ ]
13121
13234
  }) : /* @__PURE__ */ jsxs(ToggleButton, {
13122
13235
  ref: ref(key),
13123
13236
  isSelected: isHeld,
@@ -13129,15 +13242,21 @@ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places,
13129
13242
  "data-held": isHeld || void 0,
13130
13243
  "data-beckon": key === lit?.key || void 0,
13131
13244
  className: pieceClass(key),
13132
- children: [picture(p, placed), isHeld && /* @__PURE__ */ jsx(Status, {
13133
- tone: "info",
13134
- className: "absolute inset-x-1 bottom-1 justify-center truncate",
13135
- children: marks.held
13136
- })]
13245
+ children: [
13246
+ picture(p, placed),
13247
+ caption(p),
13248
+ isHeld && /* @__PURE__ */ jsx(Status, {
13249
+ tone: "info",
13250
+ className: "absolute inset-x-1 bottom-1 justify-center truncate",
13251
+ children: marks.held
13252
+ })
13253
+ ]
13137
13254
  });
13138
13255
  return /* @__PURE__ */ jsx("div", {
13139
13256
  "data-piece": key,
13140
13257
  onPointerDownCapture: press(key),
13258
+ onPointerEnter: onHover && hover(() => onHover(p)),
13259
+ "data-reading": key === reading || void 0,
13141
13260
  onDragStart: (e) => e.preventDefault(),
13142
13261
  className: cn("grid min-w-0 items-start", !locked && "touch-none", drag?.key === key && "opacity-30"),
13143
13262
  children: control
@@ -13185,6 +13304,7 @@ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places,
13185
13304
  return /* @__PURE__ */ jsxs("div", {
13186
13305
  ref: zone(key),
13187
13306
  "data-place": state,
13307
+ onPointerEnter: onHoverPlace && hover(() => onHoverPlace(s)),
13188
13308
  className: cn("grid min-w-0 content-start items-start gap-2 rounded-overlay border-2 border-dashed border-input p-2 transition-state", takes && "border-solid border-info ring-4 ring-info", takes && target(drag?.over === key), state === "right" && "border-solid border-success bg-success-subtle ring-2 ring-success", state === "wrong" && "border-solid border-muted-foreground"),
13189
13309
  children: [/* @__PURE__ */ jsxs(Button$1, {
13190
13310
  isDisabled: !takes || only !== void 0,
@@ -13238,17 +13358,17 @@ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places,
13238
13358
  }),
13239
13359
  drag !== null && createPortal((() => {
13240
13360
  const p = pieces.find((q) => pieceKey(q) === drag.key);
13241
- return p === void 0 ? null : /* @__PURE__ */ jsx("div", {
13361
+ return p === void 0 ? null : /* @__PURE__ */ jsxs("div", {
13242
13362
  "aria-hidden": true,
13243
13363
  "data-dragging": true,
13244
- className: "@container pointer-events-none fixed z-50 flex items-center justify-center rounded-overlay border-2 border-info bg-info-subtle p-1 text-card-foreground shadow-overlay ring-4 ring-info",
13364
+ className: "@container pointer-events-none fixed z-50 flex flex-col items-center justify-center gap-1 rounded-overlay border-2 border-info bg-info-subtle p-1 text-card-foreground shadow-overlay ring-4 ring-info",
13245
13365
  style: {
13246
13366
  left: drag.x - drag.w / 2,
13247
13367
  top: drag.y - drag.h / 2,
13248
13368
  width: drag.w,
13249
13369
  height: drag.h
13250
13370
  },
13251
- children: picture(p, where(p) !== null)
13371
+ children: [picture(p, where(p) !== null), caption(p)]
13252
13372
  });
13253
13373
  })(), document.body)
13254
13374
  ]
@@ -15371,6 +15491,38 @@ function pickVoice(voices, lang) {
15371
15491
  const base = wanted.split("-")[0];
15372
15492
  return voices.find((v) => v.lang.toLowerCase().replace("_", "-") === wanted) ?? voices.find((v) => v.lang.toLowerCase().replace("_", "-").split("-")[0] === base);
15373
15493
  }
15494
+ /** The turn now speaking (0 when nothing is), and who is told when that changes. */
15495
+ let turn = 0;
15496
+ let turns = 0;
15497
+ const listeners = /* @__PURE__ */ new Set();
15498
+ function setTurn(next) {
15499
+ if (turn === next) return;
15500
+ turn = next;
15501
+ for (const listener of listeners) listener();
15502
+ }
15503
+ /** A new turn: what `options.onEnd` is called with ends it, unless a later `speak` or a stop has taken over. */
15504
+ function begin(options) {
15505
+ const mine = ++turns;
15506
+ setTurn(mine);
15507
+ return {
15508
+ ...options,
15509
+ onEnd: () => {
15510
+ if (turn === mine) setTurn(0);
15511
+ options.onEnd?.();
15512
+ }
15513
+ };
15514
+ }
15515
+ /** Whether anything is being said or played now: a recording, or the browser's voice. */
15516
+ function isSpeaking() {
15517
+ return turn !== 0;
15518
+ }
15519
+ /** Re-renders when speech starts or ends anywhere on the page: true while something is being said or played. */
15520
+ function useSpeaking() {
15521
+ return React.useSyncExternalStore((listener) => {
15522
+ listeners.add(listener);
15523
+ return () => listeners.delete(listener);
15524
+ }, isSpeaking, () => false);
15525
+ }
15374
15526
  /** The recording playing now, so the next prompt or `stopSpeaking` can cut it off. */
15375
15527
  let playing;
15376
15528
  function speakText(text, { lang, rate = .9, onEnd }) {
@@ -15428,17 +15580,21 @@ function speak(saying, options = {}) {
15428
15580
  if (!parts.length) return false;
15429
15581
  if (allRecorded(parts) && canPlayClips()) {
15430
15582
  stopSpeaking();
15431
- playFrom(parts, 0, options);
15583
+ playFrom(parts, 0, begin(options));
15432
15584
  return true;
15433
15585
  }
15434
15586
  if (!canSpeak() || !textOf(parts)) return false;
15435
15587
  stopSpeaking();
15436
- return speakText(textOf(parts), options);
15588
+ const turned = begin(options);
15589
+ if (speakText(textOf(parts), turned)) return true;
15590
+ setTurn(0);
15591
+ return false;
15437
15592
  }
15438
15593
  /** Stops whatever is being said or played. */
15439
15594
  function stopSpeaking() {
15440
15595
  playing?.stop();
15441
15596
  if (canSpeak()) window.speechSynthesis.cancel();
15597
+ setTurn(0);
15442
15598
  }
15443
15599
  /**
15444
15600
  * Speech for a screen: `const { say, supported } = useSpeech({ lang })`. Waits for voices that load late (`voiceschanged`), cancels on unmount so a
@@ -15561,6 +15717,107 @@ function useSayOnShow(text, { muted = false } = {}) {
15561
15717
  ]);
15562
15718
  }
15563
15719
 
15720
+ // src/lib/read-aloud.ts
15721
+ const SEP$1 = "\0";
15722
+ /** Reads a grid's tiles aloud once, one at a time, and says which is being read so the grid can light it. */
15723
+ function useReadAloud({ keys, say, gapMs = 300 }) {
15724
+ const [reading, setReading] = React.useState(null);
15725
+ const setKey = keys.join(SEP$1);
15726
+ const run = React.useRef({
15727
+ token: 0,
15728
+ spent: false,
15729
+ timer: void 0
15730
+ });
15731
+ const latest = React.useRef({
15732
+ keys,
15733
+ say,
15734
+ gapMs
15735
+ });
15736
+ latest.current = {
15737
+ keys,
15738
+ say,
15739
+ gapMs
15740
+ };
15741
+ const stop = React.useCallback(() => {
15742
+ const r = run.current;
15743
+ r.token += 1;
15744
+ r.spent = true;
15745
+ clearTimeout(r.timer);
15746
+ setReading(null);
15747
+ }, []);
15748
+ React.useEffect(() => {
15749
+ const r = run.current;
15750
+ r.spent = false;
15751
+ return () => {
15752
+ r.token += 1;
15753
+ clearTimeout(r.timer);
15754
+ setReading(null);
15755
+ };
15756
+ }, [setKey]);
15757
+ return {
15758
+ reading,
15759
+ start: React.useCallback(() => {
15760
+ const r = run.current;
15761
+ if (r.spent) return;
15762
+ r.spent = true;
15763
+ const token = ++r.token;
15764
+ const from = (i) => {
15765
+ if (token !== r.token) return;
15766
+ const key = latest.current.keys[i];
15767
+ if (key === void 0) {
15768
+ setReading(null);
15769
+ return;
15770
+ }
15771
+ setReading(key);
15772
+ let said = false;
15773
+ const done = () => {
15774
+ if (said || token !== r.token) return;
15775
+ said = true;
15776
+ r.timer = setTimeout(() => from(i + 1), latest.current.gapMs);
15777
+ };
15778
+ if (!latest.current.say(key, done)) {
15779
+ r.token += 1;
15780
+ setReading(null);
15781
+ }
15782
+ };
15783
+ from(0);
15784
+ }, []),
15785
+ stop
15786
+ };
15787
+ }
15788
+
15789
+ // src/components/read-along.tsx
15790
+ /** A run of words or numbers read aloud a part at a time, each lit as it is said, with the part the question is about left lit and pulsing. */
15791
+ function ReadAlong({ parts, reading = null, target = null, onPress, label, className }) {
15792
+ const drawn = parts.map((p) => /* @__PURE__ */ jsx("span", {
15793
+ "data-part": p.key,
15794
+ "data-reading": p.key === reading || void 0,
15795
+ "data-target": p.key === target && reading === null || void 0,
15796
+ className: cn("inline-block rounded-control px-2 ring-primary transition-state", p.key === reading && "bg-accent text-accent-foreground ring-4", p.key === target && reading === null && "beckon-loop bg-accent text-accent-foreground ring-4"),
15797
+ children: p.text
15798
+ }, p.key));
15799
+ const row = "flex flex-wrap items-center justify-center gap-x-2 gap-y-1 text-center";
15800
+ return onPress ? /* @__PURE__ */ jsx(Button$1, {
15801
+ "aria-label": label,
15802
+ onPress,
15803
+ className: cn(row, "cursor-pointer rounded-surface transition-state press", className),
15804
+ children: /* @__PURE__ */ jsx("span", {
15805
+ "aria-hidden": true,
15806
+ className: "contents",
15807
+ children: drawn
15808
+ })
15809
+ }) : /* @__PURE__ */ jsx("div", {
15810
+ role: "group",
15811
+ "aria-label": label,
15812
+ className: cn(row, className),
15813
+ children: /* @__PURE__ */ jsx("span", {
15814
+ "aria-hidden": true,
15815
+ className: "contents",
15816
+ children: drawn
15817
+ })
15818
+ });
15819
+ }
15820
+
15564
15821
  // src/components/say-again.tsx
15565
15822
  /** An icon button that says one sentence aloud, from its recordings when given, else with the browser's voice; hidden where neither can be heard or it is muted. */
15566
15823
  function SayAgain({ text, parts, verb = "Say", className, ...options }) {
@@ -23283,5 +23540,5 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
23283
23540
  });
23284
23541
  }
23285
23542
 
23286
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BRUSHES, BookViewer, BoxList, BoxOverlay, BoxedPicture, Breadcrumb, BulkBar, Button, ButtonLink, ByteView, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, ChoiceGroup, ClipsProvider, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, Console, ContextMenu, Conversation, CursorScope, DEFAULT_PALETTE, DEFAULT_TOLERANCE, DataTable, DataView$1 as DataView, Density, Dialog, Disclosure, Done, DragSource, DrawingLayer, DrawingToolbar, EditListPlayer, EmptyState, FIT, Field, FileButton, FileDropOverlay, FileDropZone, FileOutcomes, FilmStrip, FolderPicker, FullscreenFrame, Glimpse, HttpError, INK_COLOURS, IconButton, InfiniteList, Input, InputLevel, Inspector, InspectorSection, JobStatus, JobsTable, KeysLegend, LEVEL_FLOOR_DB, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, ListeningLevel, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaContents, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MicrophoneContext, MicrophoneError, MissingFile, NBSP, NativeSelect, NumberField, OutboxStatus, PALETTE_STORAGE_KEY, PageHeader, PairJudge, PairVote, PaletteChoice, Pane, PauseButton, PixelImage, PlaceBoard, PlayWindowButton, PlayerNotice, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, STRATA_DRAG_TYPE, SaveStatus, SayAgain, SayPicture, ScheduleTable, SecretField, SeekBar, SelectableGrid, SelectableGridSkeleton, SequenceTimeline, ShortcutEditor, SideNav, Skeleton, Slider, SortableList, SpanActions, SpanStrip, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, SystemPanel, TableSkeleton, Tabs, TakeLevel, TextLink, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TileGrid, TileGridSkeleton, TimeReadout, Timeline, TimelinePlayer, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewOptions, ViewportFrame, VirtualList, VolumeControl, Waveform, WorkflowSteps, WorkflowSummary, Workspace, WorkspaceBar, actualPixelsScale, ancestorsOf, apiPage, appBase, applyOp, boxViewport, browserMicrophone, buttonVariants, canFullscreen, canPlayClips, canSay, canSpeak, checkKey, clampToRoom, clampViewport, clipsQueryKey, cn, colorSchemeScript, commandShortcut, continues, countMarks, createApi, createFormat, createOutbox, createQueryClient, createReserve, createSegmenter, createTypedApi, crossedThreshold, currentItem, currentOf, curvePoints, describeActionError, describeHttpError, describeRegion, describeWorkflowSummary, detectPlatform, diffWords, differences, diskThresholds, drawRect, drawingToSvg, ease, editTimeOf, editTimes, emptyDrawing, encodeWav, errorPayload, explainMicrophoneError, feedbackMarker, fetchJson, fieldErrorsOf, filterMarkup, findPage, fitPoints, fitRect, followAim, format, formatChord, frameAt, gainToVolume, geo, gridPoints, gutterOf, hitsStroke, inkMatch, inputLevelThresholds, invertOp, isDoubtful, isRefusal, isReservedChord, isTaskRunning, isTypingTarget, isWorkflowRunning, jobProgressText, joinMediaGroup, joinRects, joinSamples, keyName, labelOf, lerpRect, locateInEdit, logScale, loudnessOf, marksFor, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, mediaStatRows, moveGutter, movePoints, moveRect, newStrokeId, nextBreak, noOverlap, normaliseAngle, pageName, paletteScript, palettes, parentOf, parseChord, parseInline, parseRichText, parseSort, peakDb, peakGain, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickEvenly, pickVoice, pixelZoom, plainText, pointsBox, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, regionStyle, replay, resample, resamplePeaks, rescaleDrawing, resizeRect, rgbaToBlob, rmsDb, safeHref, sayPosition, serialiseSort, settleCut, simplifyPoints, skipAction, smoothPath, snapToGrid, sortRows, speak, speechLevel, splitRect, staleOf, stepId, stepOnGrid, stopSpeaking, strokeAt, strokeBox, strokeShape, summariseWorkflow, textOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, turnRect, turnedSize, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoRecorder, useAutoSave, useBookUrl, useBoxes, useChoices, useClientWork, useClips, useColorScheme, useCommands, useCountdown, useDifference, useDrawing, useEditList, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useInkMatch, useJob, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, useMediaStats, useMicrophone, useObjectUrl, useOutbox, useOutboxStarted, usePalette, usePlayerWarnings, usePoll, useRebindableShortcuts, useRecorder, useReserve, useSayOnShow, useSearchParam, useSelection, useSettledStatus, useSharedCursor, useSpeech, useSystemColorScheme, useSystemInfo, useTimeline, useTimelineZoom, useUndoable, useViewOptions, useViewPointers, useViewport, useWheelZoom, useWorkflowRun, useWorkspaceState, valueAt, viewOf, viewsOf, widthsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
23543
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BRUSHES, BookViewer, BoxList, BoxOverlay, BoxedPicture, Breadcrumb, BulkBar, Button, ButtonLink, ByteView, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, ChoiceGroup, ClipsProvider, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, Composer, CompositionBar, Concealed, Console, ContextMenu, Conversation, CursorScope, DEFAULT_PALETTE, DEFAULT_TOLERANCE, DataTable, DataView$1 as DataView, Density, Dialog, Disclosure, Done, DragSource, DrawingLayer, DrawingToolbar, EditListPlayer, EmptyState, FIT, Field, FileButton, FileDropOverlay, FileDropZone, FileOutcomes, FilmStrip, FolderPicker, FullscreenFrame, Glimpse, HttpError, INK_COLOURS, IconButton, InfiniteList, Input, InputLevel, Inspector, InspectorSection, JobStatus, JobsTable, KeysLegend, LEVEL_FLOOR_DB, Lightbox, LineChart, LineChartGroup, LinkCard, LinkCardList, ListeningLevel, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, Mark, MarkSummary, MarkableText, MediaContents, MediaGroup, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MicrophoneContext, MicrophoneError, MissingFile, NBSP, NativeSelect, NumberField, OutboxStatus, PALETTE_STORAGE_KEY, PageHeader, PairJudge, PairVote, PaletteChoice, Pane, PauseButton, PixelImage, PlaceBoard, PlayWindowButton, PlayerNotice, Popover, PropertyList, PropertyRow, RangeSlider, RateChoice, ReadAlong, RegionEditor, RichText, RowAction, SPEECH_RATES, STRATA_DRAG_TYPE, SaveStatus, SayAgain, SayPicture, ScheduleTable, SecretField, SeekBar, SelectableGrid, SelectableGridSkeleton, SequenceTimeline, ShortcutEditor, SideNav, Skeleton, Slider, SortableList, SpanActions, SpanStrip, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, SystemPanel, TableSkeleton, Tabs, TakeLevel, TextLink, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TileGrid, TileGridSkeleton, TimeReadout, Timeline, TimelinePlayer, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, TranscriptView, Transport, Tree, UndoBar, ViewOptions, ViewportFrame, VirtualList, VolumeControl, Waveform, WorkflowSteps, WorkflowSummary, Workspace, WorkspaceBar, actualPixelsScale, ancestorsOf, apiPage, appBase, applyOp, boxViewport, browserMicrophone, buttonVariants, canFullscreen, canPlayClips, canSay, canSpeak, checkKey, clampToRoom, clampViewport, clipsQueryKey, cn, colorSchemeScript, commandShortcut, continues, countMarks, createApi, createFormat, createOutbox, createQueryClient, createReserve, createSegmenter, createTypedApi, crossedThreshold, currentItem, currentOf, curvePoints, describeActionError, describeHttpError, describeRegion, describeWorkflowSummary, detectPlatform, diffWords, differences, diskThresholds, drawRect, drawingToSvg, ease, editTimeOf, editTimes, emptyDrawing, encodeWav, errorPayload, explainMicrophoneError, feedbackMarker, fetchJson, fieldErrorsOf, filterMarkup, findPage, fitPoints, fitRect, followAim, format, formatChord, frameAt, gainToVolume, geo, gridPoints, gutterOf, hitsStroke, inkMatch, inputLevelThresholds, invertOp, isDoubtful, isRefusal, isReservedChord, isSpeaking, isTaskRunning, isTypingTarget, isWorkflowRunning, jobProgressText, joinMediaGroup, joinRects, joinSamples, keyName, labelOf, lerpRect, locateInEdit, logScale, loudnessOf, marksFor, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, mediaStatRows, moveGutter, movePoints, moveRect, newStrokeId, nextBreak, noOverlap, normaliseAngle, pageName, paletteScript, palettes, parentOf, parseChord, parseInline, parseRichText, parseSort, peakDb, peakGain, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, pickEvenly, pickVoice, pixelZoom, plainText, pointsBox, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, regionStyle, replay, resample, resamplePeaks, rescaleDrawing, resizeRect, rgbaToBlob, rmsDb, safeHref, sayPosition, serialiseSort, settleCut, simplifyPoints, skipAction, smoothPath, snapToGrid, sortRows, speak, speechLevel, splitRect, staleOf, stepId, stepOnGrid, stopSpeaking, strokeAt, strokeBox, strokeShape, summariseWorkflow, textOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toPeakPair, toast, toastTimeout, transportShortcuts, turnRect, turnedSize, typeSteps, useActiveItem, useAsyncAction, useAttachedSource, useAutoRecorder, useAutoSave, useBookUrl, useBoxes, useChoices, useClientWork, useClips, useColorScheme, useCommands, useCountdown, useDifference, useDrawing, useEditList, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useInkMatch, useJob, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, useMediaStats, useMicrophone, useObjectUrl, useOutbox, useOutboxStarted, usePalette, usePlayerWarnings, usePoll, useReadAloud, useRebindableShortcuts, useRecorder, useReserve, useRevealed, useSayOnShow, useSearchParam, useSelection, useSettledStatus, useSharedCursor, useSpeaking, useSpeech, useSystemColorScheme, useSystemInfo, useTimeline, useTimelineZoom, useUndoable, useViewOptions, useViewPointers, useViewport, useWheelZoom, useWorkflowRun, useWorkspaceState, valueAt, viewOf, viewsOf, widthsOf, withBase, wordAt, wordId, zoomAt, zoomToBox };
23287
23544
  //# sourceMappingURL=index.js.map