strata-react 1.2.0 → 1.3.0

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
@@ -2667,6 +2667,45 @@ var SPAN_TONE = {
2667
2667
  danger: "bg-danger",
2668
2668
  neutral: "bg-neutral-8"
2669
2669
  };
2670
+ var COLOUR_NAME = /^--[\w-]+$/;
2671
+ /** One stretch drawn as a range of a bar of `duration` seconds, named with its times. Shared by the seek bar and the strip under the browser's own controls. */
2672
+ function SpanRange({ span, duration, thin, ...time }) {
2673
+ const name = `${span.label}, ${timecode(span.start, time)} to ${timecode(span.end, time)}`;
2674
+ const colour = span.colour && COLOUR_NAME.test(span.colour) ? span.colour : null;
2675
+ return /* @__PURE__ */ jsx("span", {
2676
+ role: "img",
2677
+ "aria-label": name,
2678
+ title: name,
2679
+ "data-span": "",
2680
+ "data-kind": span.kind,
2681
+ className: cn("absolute min-w-1 rounded-pill opacity-70", thin ? "h-1" : "h-1.5", !colour && SPAN_TONE[span.tone ?? "info"]),
2682
+ style: {
2683
+ left: `${span.start / duration * 100}%`,
2684
+ width: `${(span.end - span.start) / duration * 100}%`,
2685
+ ...colour ? { backgroundColor: `var(${colour})` } : void 0
2686
+ }
2687
+ });
2688
+ }
2689
+ /**
2690
+ * The marked stretches as a thin strip, for under a picture played with the browser's own controls, whose seek bar cannot draw them
2691
+ * (strata-react issue #270): the same ranges, names and colours as `SeekBar spans`, not a control. Draws nothing until `duration` is known.
2692
+ */
2693
+ function SpanStrip({ spans, duration, label = "Marked parts", precision = "seconds", fps = 30, className }) {
2694
+ const drawn = duration ? drawableSpans(spans, duration) : [];
2695
+ if (!duration || !drawn.length) return null;
2696
+ return /* @__PURE__ */ jsx("div", {
2697
+ role: "group",
2698
+ "aria-label": label,
2699
+ className: cn("relative h-1 w-full rounded-pill bg-muted", className),
2700
+ children: drawn.map((s) => /* @__PURE__ */ jsx(SpanRange, {
2701
+ span: s,
2702
+ duration,
2703
+ precision,
2704
+ fps,
2705
+ thin: true
2706
+ }, `${s.start}-${s.end}-${s.label}`))
2707
+ });
2708
+ }
2670
2709
  /** The spans a bar of `duration` seconds can draw: in order, cut to the bar, and none that are empty or backwards. */
2671
2710
  function drawableSpans(spans, duration) {
2672
2711
  return spans.map((s) => ({
@@ -2782,26 +2821,12 @@ function SeekBar({ time, duration: known, onSeek, marks = [], spans = [], onMark
2782
2821
  className: "absolute left-0 h-1.5 rounded-pill bg-primary",
2783
2822
  style: { width: `${frac * 100}%` }
2784
2823
  }),
2785
- duration > 0 && drawableSpans(spans, duration).map((s) => {
2786
- const name = `${s.label}, ${timecode(s.start, {
2787
- precision,
2788
- fps
2789
- })} to ${timecode(s.end, {
2790
- precision,
2791
- fps
2792
- })}`;
2793
- return /* @__PURE__ */ jsx("span", {
2794
- role: "img",
2795
- "aria-label": name,
2796
- title: name,
2797
- "data-span": "",
2798
- className: cn("absolute h-1.5 min-w-1 rounded-pill opacity-70", SPAN_TONE[s.tone ?? "info"]),
2799
- style: {
2800
- left: `${s.start / duration * 100}%`,
2801
- width: `${(s.end - s.start) / duration * 100}%`
2802
- }
2803
- }, `${s.start}-${s.end}-${s.label}`);
2804
- }),
2824
+ duration > 0 && drawableSpans(spans, duration).map((s) => /* @__PURE__ */ jsx(SpanRange, {
2825
+ span: s,
2826
+ duration,
2827
+ precision,
2828
+ fps
2829
+ }, `${s.start}-${s.end}-${s.label}`)),
2805
2830
  otherTime !== null && otherTime >= 0 && otherTime <= duration && /* @__PURE__ */ jsx("span", {
2806
2831
  "aria-hidden": true,
2807
2832
  "data-cursor": "",
@@ -3147,7 +3172,7 @@ var WORDS$1 = {
3147
3172
  undo: "Undo"
3148
3173
  };
3149
3174
  /** How long "Skipped intro, Undo" stays. */
3150
- var NOTICE_MS = 6e3;
3175
+ var NOTICE_MS$1 = 6e3;
3151
3176
  /** Draws the spans' ranges and acts on them as playback reaches them. See the file comment for the rules. */
3152
3177
  function useMediaSpans({ spans, kinds = {}, words, onSpan, time, playing, duration, limit = Infinity, seek, volume, setVolume }) {
3153
3178
  const w = {
@@ -3181,7 +3206,9 @@ function useMediaSpans({ spans, kinds = {}, words, onSpan, time, playing, durati
3181
3206
  start: s.start,
3182
3207
  end: s.end,
3183
3208
  label: s.def.label,
3184
- tone: s.def.tone
3209
+ tone: s.def.tone,
3210
+ kind: s.kind,
3211
+ colour: s.def.colour
3185
3212
  })), [list]);
3186
3213
  const acted = React.useRef(/* @__PURE__ */ new Set());
3187
3214
  const undone = React.useRef(/* @__PURE__ */ new Set());
@@ -3215,7 +3242,7 @@ function useMediaSpans({ spans, kinds = {}, words, onSpan, time, playing, durati
3215
3242
  }, [content]);
3216
3243
  React.useEffect(() => {
3217
3244
  if (!notice) return;
3218
- const t = setTimeout(() => setNotice((n) => n?.key === notice.key ? null : n), NOTICE_MS);
3245
+ const t = setTimeout(() => setNotice((n) => n?.key === notice.key ? null : n), NOTICE_MS$1);
3219
3246
  return () => clearTimeout(t);
3220
3247
  }, [notice]);
3221
3248
  const current = list.find((s) => time >= s.start && time < s.end) ?? null;
@@ -3304,9 +3331,26 @@ function useMediaSpans({ spans, kinds = {}, words, onSpan, time, playing, durati
3304
3331
  } : null
3305
3332
  };
3306
3333
  }
3334
+ /** A short notice drawn over a picture (or under an audio player) with one way back: "Skipped intro, Undo", "Picked up at 2:05, Start over". The player's own notices use it, so an overlay of an app's own matches them without copying classes. */
3335
+ function PlayerNotice({ children, action, onAction }) {
3336
+ return /* @__PURE__ */ jsxs("div", {
3337
+ className: "flex items-center gap-2 rounded-overlay border border-border bg-background px-3 py-1 type-body-sm text-foreground shadow-overlay",
3338
+ children: [/* @__PURE__ */ jsx("span", { children }), /* @__PURE__ */ jsx(Button, {
3339
+ variant: "ghost",
3340
+ size: "sm",
3341
+ onClick: onAction,
3342
+ children: action
3343
+ })]
3344
+ });
3345
+ }
3307
3346
  /** The Skip button and the "Skipped intro, Undo" notice, for the player to draw over a picture or under the bar. The notice's live region is always present, so a screen reader hears what is put in it. */
3308
- function SpanActions({ state, className }) {
3347
+ function SpanActions({ state, other, className }) {
3309
3348
  const { offer, notice } = state;
3349
+ const shown = notice ? {
3350
+ text: notice.text,
3351
+ actionLabel: notice.undoLabel,
3352
+ run: notice.undo
3353
+ } : other ?? null;
3310
3354
  return /* @__PURE__ */ jsxs("div", {
3311
3355
  className,
3312
3356
  children: [offer && /* @__PURE__ */ jsxs(Button, {
@@ -3319,16 +3363,35 @@ function SpanActions({ state, className }) {
3319
3363
  })]
3320
3364
  }), /* @__PURE__ */ jsx("div", {
3321
3365
  role: "status",
3322
- className: notice ? "flex items-center gap-2 rounded-overlay border border-border bg-background px-3 py-1 type-body-sm text-foreground shadow-overlay" : void 0,
3323
- children: notice && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", { children: notice.text }), /* @__PURE__ */ jsx(Button, {
3324
- variant: "ghost",
3325
- size: "sm",
3326
- onClick: notice.undo,
3327
- children: notice.undoLabel
3328
- })] })
3366
+ children: shown && /* @__PURE__ */ jsx(PlayerNotice, {
3367
+ action: shown.actionLabel,
3368
+ onAction: shown.run,
3369
+ children: shown.text
3370
+ })
3329
3371
  })]
3330
3372
  });
3331
3373
  }
3374
+ // src/components/media-progress.ts
3375
+ function createWatchedRanges() {
3376
+ let ranges = [];
3377
+ return {
3378
+ add(start, end) {
3379
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return;
3380
+ const merged = [];
3381
+ let from = start;
3382
+ let to = end;
3383
+ for (const [a, b] of ranges) if (b < from || a > to) merged.push([a, b]);
3384
+ else {
3385
+ from = Math.min(from, a);
3386
+ to = Math.max(to, b);
3387
+ }
3388
+ merged.push([from, to]);
3389
+ ranges = merged.sort((x, y) => x[0] - y[0]);
3390
+ },
3391
+ total: () => Math.round(ranges.reduce((sum, [a, b]) => sum + (b - a), 0) * 10) / 10,
3392
+ clear: () => void (ranges = [])
3393
+ };
3394
+ }
3332
3395
  // src/components/media-player.tsx
3333
3396
  /** How far one notch of the wheel over a focused video moves the volume, in percent. */
3334
3397
  var WHEEL_VOLUME_STEP = 5;
@@ -3496,6 +3559,95 @@ function useMediaElement(ref, options = {}) {
3496
3559
  for (const type of EVENTS) el.removeEventListener(type, on);
3497
3560
  };
3498
3561
  });
3562
+ const seen = React.useRef({
3563
+ ranges: createWatchedRanges(),
3564
+ last: null,
3565
+ since: 0,
3566
+ position: 0,
3567
+ duration: null,
3568
+ reported: "",
3569
+ key: null,
3570
+ call: void 0
3571
+ });
3572
+ const report = React.useCallback(() => {
3573
+ const w = seen.current;
3574
+ const total = w.ranges.total();
3575
+ const signature = `${w.position}:${total}`;
3576
+ if (!w.call || signature === w.reported || total === 0 && w.position === 0) return;
3577
+ w.reported = signature;
3578
+ w.since = 0;
3579
+ w.call({
3580
+ position: w.position,
3581
+ watched: total,
3582
+ duration: w.duration
3583
+ });
3584
+ }, []);
3585
+ useElementListeners(ref, (el) => {
3586
+ const w = seen.current;
3587
+ const count = (to) => {
3588
+ if (w.last !== null && to > w.last && to - w.last <= 2 * Math.max(1, el.playbackRate) + .5) {
3589
+ w.ranges.add(w.last, to);
3590
+ w.since += to - w.last;
3591
+ }
3592
+ w.last = to;
3593
+ };
3594
+ const on = (e) => {
3595
+ const now = Number.isFinite(el.currentTime) ? el.currentTime : 0;
3596
+ w.position = now;
3597
+ w.duration = Number.isFinite(el.duration) && el.duration > 0 ? el.duration : null;
3598
+ if (e.type === "play" || e.type === "playing") w.last ??= now;
3599
+ else if (e.type === "seeking") w.last = null;
3600
+ else if (e.type === "seeked") w.last = el.paused ? null : now;
3601
+ else if (e.type === "timeupdate") {
3602
+ if (!el.paused && !el.ended) count(now);
3603
+ if (w.since >= (opts.current.progressEvery ?? 15)) report();
3604
+ } else if (e.type === "pause" || e.type === "ended") {
3605
+ if (e.type === "ended" && w.duration !== null) count(w.duration);
3606
+ else count(now);
3607
+ w.last = null;
3608
+ report();
3609
+ }
3610
+ };
3611
+ const types = [
3612
+ "play",
3613
+ "playing",
3614
+ "seeking",
3615
+ "seeked",
3616
+ "timeupdate",
3617
+ "pause",
3618
+ "ended"
3619
+ ];
3620
+ for (const t of types) el.addEventListener(t, on);
3621
+ return () => {
3622
+ for (const t of types) el.removeEventListener(t, on);
3623
+ };
3624
+ });
3625
+ React.useEffect(() => {
3626
+ const w = seen.current;
3627
+ const key = opts.current.progressKey ?? ref.current?.getAttribute("src") ?? "";
3628
+ if (w.key !== null && w.key !== key) {
3629
+ report();
3630
+ w.ranges.clear();
3631
+ w.last = null;
3632
+ w.since = 0;
3633
+ w.position = 0;
3634
+ w.reported = "";
3635
+ }
3636
+ w.key = key;
3637
+ w.call = opts.current.onProgress;
3638
+ });
3639
+ React.useEffect(() => {
3640
+ if (typeof document === "undefined") return;
3641
+ const hidden = () => document.visibilityState === "hidden" && report();
3642
+ const leave = () => report();
3643
+ document.addEventListener("visibilitychange", hidden);
3644
+ window.addEventListener("pagehide", leave);
3645
+ return () => {
3646
+ document.removeEventListener("visibilitychange", hidden);
3647
+ window.removeEventListener("pagehide", leave);
3648
+ report();
3649
+ };
3650
+ }, [report]);
3499
3651
  const joined = React.useRef(null);
3500
3652
  React.useEffect(() => {
3501
3653
  const el = ref.current;
@@ -3604,6 +3756,11 @@ function useMediaElement(ref, options = {}) {
3604
3756
  el.playbackRate = rate;
3605
3757
  el.preservesPitch = true;
3606
3758
  },
3759
+ markWatched: (start, end) => {
3760
+ const w = seen.current;
3761
+ const top = w.duration ?? end;
3762
+ w.ranges.add(Math.max(start, 0), Math.min(end, top));
3763
+ },
3607
3764
  retry: () => {
3608
3765
  const el = ref.current;
3609
3766
  if (!el) return;
@@ -3634,12 +3791,16 @@ function useMediaElement(ref, options = {}) {
3634
3791
  * Use it for a plain `<video>` the app owns, with `useMediaElement`; `MediaPlayer` does it for `attach`.
3635
3792
  * Returns `reload`, for the player's Try again (`useMediaElement`'s `onRetry`), and gives the engine's failures to `onProblem` (`reportProblem`).
3636
3793
  */
3637
- function useAttachedSource(ref, src, attach, onProblem, growing) {
3794
+ function useAttachedSource(ref, src, attach, onProblem, growing, start) {
3638
3795
  const hold = React.useRef(null);
3639
3796
  const problem = React.useRef(onProblem);
3640
3797
  problem.current = onProblem;
3641
3798
  const grows = React.useRef(growing);
3642
3799
  grows.current = growing;
3800
+ const first = React.useRef({
3801
+ src: void 0,
3802
+ start
3803
+ });
3643
3804
  React.useEffect(() => {
3644
3805
  const el = ref.current;
3645
3806
  const now = hold.current;
@@ -3647,12 +3808,14 @@ function useAttachedSource(ref, src, attach, onProblem, growing) {
3647
3808
  now?.attachment.detach();
3648
3809
  hold.current = null;
3649
3810
  if (!el || !attach || !src) return;
3811
+ first.current.src ??= src;
3812
+ const begin = src === first.current.src ? first.current.start : 0;
3650
3813
  hold.current = {
3651
3814
  el,
3652
3815
  src,
3653
3816
  attach,
3654
3817
  attachment: attach(el, src, {
3655
- startAt: 0,
3818
+ startAt: begin ?? 0,
3656
3819
  onProblem: (m) => problem.current?.(m),
3657
3820
  growing: grows.current
3658
3821
  })
@@ -3718,6 +3881,8 @@ var SPEECH_RATES = [
3718
3881
  3
3719
3882
  ];
3720
3883
  var JUMP = 10;
3884
+ /** How long a notice such as "Picked up at 2:05" stays once the player is playing. */
3885
+ var NOTICE_MS = 6e3;
3721
3886
  function useCoarsePointer() {
3722
3887
  const [coarse, setCoarse] = React.useState(false);
3723
3888
  React.useEffect(() => {
@@ -3735,7 +3900,7 @@ function useCoarsePointer() {
3735
3900
  * a touch device), with the failure to load shown and retried. For an editor or a replay, use the
3736
3901
  * parts and `useMediaElement` directly.
3737
3902
  */
3738
- function MediaPlayer({ label, kind = "audio", src, sources, index: controlledIndex, onIndexChange, autoAdvance = true, controls = "auto", autoPlay, poster, session, rates, shortcuts = true, attach, growing, window: bound, loop, showFull, group, onTimeUpdate, onWindowEnd, onEnded, onTimeChange, spans, spanKinds, onSpan, spanWords, mediaRef, overlay, status, warning, aspect, fullscreen = true, className }) {
3903
+ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledIndex, onIndexChange, autoAdvance = true, controls = "auto", autoPlay, poster, session, rates, shortcuts = true, attach, growing, window: bound, loop, showFull, group, onTimeUpdate, onWindowEnd, onEnded, onTimeChange, spans, spanKinds, onSpan, spanWords, start, resumeWords, onProgress, progressEvery, mediaRef, overlay, status, warning, aspect, fullscreen = true, className }) {
3739
3904
  const list = React.useMemo(() => sources ?? (src ? [{
3740
3905
  src,
3741
3906
  title: label
@@ -3749,6 +3914,11 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3749
3914
  const current = list[index];
3750
3915
  const ref = React.useRef(null);
3751
3916
  const stream = React.useRef({ reload: () => {} });
3917
+ const sourceIndex = React.useRef(index);
3918
+ const progress = React.useCallback((r) => onProgress?.({
3919
+ ...r,
3920
+ index: sourceIndex.current
3921
+ }), [onProgress]);
3752
3922
  const media = useMediaElement(ref, {
3753
3923
  window: bound,
3754
3924
  loop,
@@ -3756,9 +3926,13 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3756
3926
  onTimeUpdate,
3757
3927
  onWindowEnd,
3758
3928
  growing: growing !== void 0,
3759
- onRetry: attach ? (t) => stream.current.reload(t) : void 0
3929
+ onRetry: attach ? (t) => stream.current.reload(t) : void 0,
3930
+ onProgress: onProgress ? progress : void 0,
3931
+ progressEvery,
3932
+ progressKey: current?.src
3760
3933
  });
3761
- stream.current = useAttachedSource(ref, current?.src, attach, media.reportProblem, growing !== void 0);
3934
+ React.useEffect(() => void (sourceIndex.current = index), [index]);
3935
+ stream.current = useAttachedSource(ref, current?.src, attach, media.reportProblem, growing !== void 0, start);
3762
3936
  const coarse = useCoarsePointer();
3763
3937
  const native = controls === "native" || controls === "auto" && coarse;
3764
3938
  const go = React.useCallback((to) => {
@@ -3842,11 +4016,60 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
3842
4016
  resume.current = media.playing;
3843
4017
  go(to);
3844
4018
  };
4019
+ const carried = React.useRef(null);
4020
+ React.useEffect(() => {
4021
+ const c = carried.current;
4022
+ if (c && c.index === index) {
4023
+ carried.current = null;
4024
+ media.markWatched(0, c.end);
4025
+ }
4026
+ }, [index]);
4027
+ const toFile = (t) => cut ? t + cut.start : offsets ? t - offsets[index] : t;
4028
+ const spanSeen = (span, what) => {
4029
+ if (what === "skipped" && (span.action ?? "skip") === "skip") {
4030
+ media.markWatched(toFile(span.start), toFile(span.end));
4031
+ if (offsets && !cut) {
4032
+ let to = offsets.length - 1;
4033
+ while (to > 0 && offsets[to] > span.end) to--;
4034
+ if (to > index) carried.current = {
4035
+ index: to,
4036
+ end: span.end - offsets[to]
4037
+ };
4038
+ }
4039
+ }
4040
+ onSpan?.(span, what);
4041
+ };
4042
+ const [picked, setPicked] = React.useState(() => (start ?? 0) > 0);
4043
+ const pickedAt = React.useRef(start ?? 0);
4044
+ React.useEffect(() => {
4045
+ if (pickedAt.current > 0 && !attach) media.seek(pickedAt.current);
4046
+ }, []);
4047
+ React.useEffect(() => {
4048
+ if (!picked || !media.playing) return;
4049
+ const t = setTimeout(() => setPicked(false), NOTICE_MS);
4050
+ return () => clearTimeout(t);
4051
+ }, [picked, media.playing]);
4052
+ React.useEffect(() => {
4053
+ if (index > 0) setPicked(false);
4054
+ }, [index]);
4055
+ const say = {
4056
+ pickedUp: (t) => `Picked up at ${t}`,
4057
+ startOver: "Start over",
4058
+ ...resumeWords
4059
+ };
4060
+ const resumeNotice = picked ? {
4061
+ text: say.pickedUp(format.runningTime(pickedAt.current)),
4062
+ actionLabel: say.startOver,
4063
+ run: () => {
4064
+ setPicked(false);
4065
+ seek(0);
4066
+ }
4067
+ } : null;
3845
4068
  const spanState = useMediaSpans({
3846
4069
  spans,
3847
4070
  kinds: spanKinds,
3848
4071
  words: spanWords,
3849
- onSpan,
4072
+ onSpan: spanSeen,
3850
4073
  time,
3851
4074
  playing: media.playing,
3852
4075
  duration: growing ? null : duration,
@@ -4041,6 +4264,7 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
4041
4264
  "aria-label": `${label}, ${kind}`
4042
4265
  };
4043
4266
  const hasSpans = (spans?.length ?? 0) > 0;
4267
+ const showActions = hasSpans || picked;
4044
4268
  const element = kind === "video" ? /* @__PURE__ */ jsxs("div", {
4045
4269
  ref: stage,
4046
4270
  tabIndex: -1,
@@ -4053,10 +4277,11 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
4053
4277
  onClick: native ? void 0 : () => media.toggle(),
4054
4278
  onDoubleClick: canFull ? () => setFull((f) => !f) : void 0,
4055
4279
  className: "absolute inset-0 size-full object-contain"
4056
- }), (overlay || hasSpans) && /* @__PURE__ */ jsxs("div", {
4280
+ }), (overlay || showActions) && /* @__PURE__ */ jsxs("div", {
4057
4281
  className: "pointer-events-none absolute inset-0 [&>*]:pointer-events-auto",
4058
- children: [overlay?.(media), hasSpans && /* @__PURE__ */ jsx(SpanActions, {
4282
+ children: [overlay?.(media), showActions && /* @__PURE__ */ jsx(SpanActions, {
4059
4283
  state: spanState,
4284
+ other: resumeNotice,
4060
4285
  className: cn("absolute right-3 flex flex-col items-end gap-2", native ? "bottom-14" : "bottom-3")
4061
4286
  })]
4062
4287
  })]
@@ -4085,9 +4310,15 @@ function MediaPlayer({ label, kind = "audio", src, sources, index: controlledInd
4085
4310
  className: cn("relative grid w-full gap-2", full && "flex h-full min-h-0 flex-col"),
4086
4311
  children: [
4087
4312
  element,
4313
+ native && hasSpans && /* @__PURE__ */ jsx(SpanStrip, {
4314
+ spans: spanState.bars,
4315
+ duration,
4316
+ label: `Marked parts of ${label}`
4317
+ }),
4088
4318
  warningToast,
4089
- kind === "audio" && hasSpans && /* @__PURE__ */ jsx(SpanActions, {
4319
+ kind === "audio" && showActions && /* @__PURE__ */ jsx(SpanActions, {
4090
4320
  state: spanState,
4321
+ other: resumeNotice,
4091
4322
  className: "flex flex-wrap items-center gap-2"
4092
4323
  }),
4093
4324
  kind === "audio" && overlay?.(media),
@@ -9036,6 +9267,111 @@ function ChoiceGridSkeleton({ count = 4, size = "md", className }) {
9036
9267
  children: Array.from({ length: count }, (_, i) => /* @__PURE__ */ jsx("span", { className: "block aspect-square rounded-overlay bg-muted" }, i))
9037
9268
  });
9038
9269
  }
9270
+ // src/components/place-board.tsx
9271
+ var pieceSide = 96;
9272
+ var placedSide = 72;
9273
+ var placedPicture = { "--type-picture-size": "2.5rem" };
9274
+ var placeSide = 160;
9275
+ /** Pictures put into places with two taps (pick up, put down) for an answer that is an arrangement: give a number, order, match, sort. The app owns where each piece is and checks it; the board only moves what the learner asks. */
9276
+ function PlaceBoard({ label, pieces, pieceKey, pieceLabel, renderPiece, places, placeKey, placeLabel, renderPlace, placement, onMove, pileLabel, placeState = () => "open", marks, locked = false, className }) {
9277
+ const [heldKey, setHeld] = React.useState(null);
9278
+ const [follow, setFollow] = React.useState(null);
9279
+ const buttons = React.useRef(/* @__PURE__ */ new Map());
9280
+ const placeKeys = new Set(places.map(placeKey));
9281
+ const where = (p) => {
9282
+ const at = placement[pieceKey(p)];
9283
+ return at !== void 0 && placeKeys.has(at) ? at : null;
9284
+ };
9285
+ const held = locked ? void 0 : pieces.find((p) => pieceKey(p) === heldKey);
9286
+ const heldAt = held === void 0 ? null : where(held);
9287
+ React.useEffect(() => {
9288
+ if (follow === null) return;
9289
+ buttons.current.get(follow)?.focus();
9290
+ setFollow(null);
9291
+ }, [follow]);
9292
+ const move = (to) => {
9293
+ if (held === void 0) return;
9294
+ const key = pieceKey(held);
9295
+ setHeld(null);
9296
+ onMove(key, to);
9297
+ setFollow(key);
9298
+ };
9299
+ const piece = (p, placed) => {
9300
+ const key = pieceKey(p);
9301
+ const isHeld = held !== void 0 && pieceKey(held) === key;
9302
+ return /* @__PURE__ */ jsxs(ToggleButton, {
9303
+ ref: (el) => {
9304
+ if (el) buttons.current.set(key, el);
9305
+ else buttons.current.delete(key);
9306
+ },
9307
+ isSelected: isHeld,
9308
+ onChange: (on) => setHeld(on ? key : null),
9309
+ isDisabled: locked,
9310
+ "aria-label": isHeld ? `${pieceLabel(p)}, ${marks.held.toLowerCase()}` : pieceLabel(p),
9311
+ "data-held": isHeld || void 0,
9312
+ className: cn("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-1 text-card-foreground select-none outline-offset-2 transition-state press", "hover:border-primary disabled:cursor-default disabled:hover:border-border", "selected:border-4 selected:border-primary selected:bg-muted"),
9313
+ children: [/* @__PURE__ */ jsx("span", {
9314
+ "aria-hidden": true,
9315
+ className: "type-picture",
9316
+ style: placed ? placedPicture : void 0,
9317
+ children: renderPiece(p)
9318
+ }), isHeld && /* @__PURE__ */ jsx(Status, {
9319
+ tone: "info",
9320
+ className: "max-w-full truncate",
9321
+ children: marks.held
9322
+ })]
9323
+ }, key);
9324
+ };
9325
+ const grid = (inside, name, side) => inside.length > 0 && /* @__PURE__ */ jsx("div", {
9326
+ role: "group",
9327
+ "aria-label": name,
9328
+ className: "grid min-w-0 gap-2",
9329
+ style: { gridTemplateColumns: `repeat(auto-fill, minmax(min(${side}px, 100%), 1fr))` },
9330
+ children: inside.map((p) => piece(p, side === placedSide))
9331
+ });
9332
+ const pile = pieces.filter((p) => where(p) === null);
9333
+ return /* @__PURE__ */ jsxs("section", {
9334
+ "aria-label": label,
9335
+ className: cn("grid min-w-0 gap-6", className),
9336
+ children: [/* @__PURE__ */ jsxs("div", {
9337
+ className: "grid min-w-0 gap-2",
9338
+ children: [grid(pile, pileLabel, pieceSide), heldAt !== null && held !== void 0 && /* @__PURE__ */ jsx(Button$1, {
9339
+ onPress: () => move(null),
9340
+ className: "min-h-(--control-h) justify-self-start rounded-control border border-input bg-background px-3 type-label transition-state press hover:bg-muted",
9341
+ children: `Put ${pieceLabel(held)} back`
9342
+ })]
9343
+ }), /* @__PURE__ */ jsx("div", {
9344
+ className: "grid min-w-0 gap-4",
9345
+ style: { gridTemplateColumns: `repeat(auto-fill, minmax(min(${placeSide}px, 100%), 1fr))` },
9346
+ children: places.map((s) => {
9347
+ const key = placeKey(s);
9348
+ const state = placeState(s);
9349
+ const name = placeLabel(s);
9350
+ const inside = pieces.filter((p) => where(p) === key);
9351
+ const takes = held !== void 0 && heldAt !== key;
9352
+ return /* @__PURE__ */ jsxs("div", {
9353
+ "data-place": state,
9354
+ className: cn("grid min-w-0 content-start gap-2 rounded-overlay border-2 border-dashed border-input p-2 transition-state", takes && "border-solid border-primary", state === "right" && "border-4 border-solid border-success bg-success-subtle", state === "wrong" && "border-solid border-muted-foreground"),
9355
+ children: [/* @__PURE__ */ jsxs(Button$1, {
9356
+ isDisabled: !takes,
9357
+ onPress: () => move(key),
9358
+ "aria-label": (takes && held !== void 0 ? `Put ${pieceLabel(held)} in ${name}` : name) + (state === "open" ? "" : `, ${marks[state].toLowerCase()}`),
9359
+ className: "flex min-h-30 min-w-0 cursor-pointer flex-col items-center justify-center gap-1 rounded-surface outline-offset-2 transition-state press hover:bg-muted disabled:cursor-default disabled:hover:bg-transparent",
9360
+ children: [/* @__PURE__ */ jsx("span", {
9361
+ "aria-hidden": true,
9362
+ className: renderPlace ? "type-picture" : "type-heading",
9363
+ children: renderPlace ? renderPlace(s) : name
9364
+ }), state !== "open" && /* @__PURE__ */ jsx(Status, {
9365
+ tone: state === "right" ? "success" : "neutral",
9366
+ className: "max-w-full truncate",
9367
+ children: marks[state]
9368
+ })]
9369
+ }), grid(inside, `In ${name}`, placedSide)]
9370
+ }, key);
9371
+ })
9372
+ })]
9373
+ });
9374
+ }
9039
9375
  // src/components/infinite-list.tsx
9040
9376
  var PendingFocus = React.createContext(null);
9041
9377
  function MoreFailed({ message, retry }) {
@@ -16402,6 +16738,6 @@ function FolderPicker({ label, useFolders: useListing, value, onChange, onChoose
16402
16738
  ]
16403
16739
  });
16404
16740
  }
16405
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, 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, SelectableGridSkeleton, 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, ViewOptions, ViewportFrame, VirtualList, VolumeControl, Waveform, Workspace, actualPixelsScale, ancestorsOf, apiPage, boxViewport, buttonVariants, canFullscreen, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, errorPayload, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, isDoubtful, isReservedChord, isTaskRunning, isTypingTarget, jobProgressText, joinMediaGroup, joinRects, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, 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, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, usePlayerWarnings, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, wordAt, wordId, zoomAt, zoomToBox };
16741
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, BookViewer, BoxList, BoxOverlay, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGrid, ChoiceGridSkeleton, 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, PlaceBoard, PlayWindowButton, PlayerNotice, Popover, PropertyList, PropertyRow, RateChoice, RegionEditor, RichText, RowAction, SPEECH_RATES, SaveStatus, SecretField, SeekBar, SelectableGrid, SelectableGridSkeleton, SequenceTimeline, SideNav, Skeleton, Slider, SortableList, SpanActions, SpanStrip, 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, ViewOptions, ViewportFrame, VirtualList, VolumeControl, Waveform, Workspace, actualPixelsScale, ancestorsOf, apiPage, boxViewport, buttonVariants, canFullscreen, clampToRoom, clampViewport, cn, colorSchemeScript, commandShortcut, countMarks, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, describeRegion, detectPlatform, diffWords, differences, drawRect, ease, errorPayload, fetchJson, fieldErrorsOf, findPage, fitRect, format, formatChord, gainToVolume, geo, gridPoints, gutterOf, isDoubtful, isReservedChord, isTaskRunning, isTypingTarget, jobProgressText, joinMediaGroup, joinRects, labelOf, lerpRect, logScale, loudnessOf, matchEntities, matchGains, matchesAccept, matchesChord, measureLoudness, moveGutter, moveRect, noOverlap, normaliseAngle, pageName, parentOf, parseChord, parseInline, parseRichText, parseSort, peaksFromAudio, phraseAt, phraseDoubtful, phraseOfWordId, plainText, rangeBetween, readErrorBody, readPixels, readingOrder, regionShares, resample, resamplePeaks, resizeRect, safeHref, sayPosition, serialiseSort, settleCut, snapToGrid, sortRows, 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, useJobAction, useLeaveGuard, useLightboxUrl, useLoad, useMediaElement, useMediaSpans, usePlayerWarnings, useSelection, useSharedCursor, useSystemColorScheme, useTimelineZoom, useUndoable, useViewOptions, useViewport, useWorkspaceState, valueAt, viewOf, viewsOf, wordAt, wordId, zoomAt, zoomToBox };
16406
16742
 
16407
16743
  //# sourceMappingURL=index.js.map