strata-react 1.0.26 → 1.0.28

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
@@ -6816,7 +6816,7 @@ function useViewport(initial = FIT) {
6816
6816
  }
6817
6817
  var PAN_STEP = 48;
6818
6818
  /** A clipped frame whose children zoom and pan together; the viewport is the caller's, so frames can share one. */
6819
- var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, viewport, setViewport, children, cover, overlay, className }, forwardedRef) {
6819
+ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, viewport, setViewport, children, cover, overlay, maxHeight, className }, forwardedRef) {
6820
6820
  const ref = React.useRef(null);
6821
6821
  React.useImperativeHandle(forwardedRef, () => ref.current);
6822
6822
  const latest = React.useRef(viewport);
@@ -6916,6 +6916,10 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
6916
6916
  },
6917
6917
  style: {
6918
6918
  aspectRatio: String(aspect),
6919
+ ...maxHeight ? {
6920
+ maxWidth: `calc(${maxHeight} * ${aspect})`,
6921
+ marginInline: "auto"
6922
+ } : {},
6919
6923
  touchAction: zoomed ? "none" : "pan-y"
6920
6924
  },
6921
6925
  className: cn("relative w-full overflow-hidden rounded-surface border border-border bg-muted select-none", zoomed ? "cursor-grab active:cursor-grabbing" : "cursor-zoom-in", "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring", className),
@@ -6958,6 +6962,7 @@ var MODE_LABEL = {
6958
6962
  blink: "Blink",
6959
6963
  difference: "Difference"
6960
6964
  };
6965
+ var VIEWPORT_HEIGHT = "max(16rem, calc(100svh - 14rem))";
6961
6966
  var ALL_MODES = [
6962
6967
  "side",
6963
6968
  "swipe",
@@ -6966,7 +6971,7 @@ var ALL_MODES = [
6966
6971
  "difference"
6967
6972
  ];
6968
6973
  /** Two pictures to judge, side by side or laid over each other, zoomed and panned together, and full screen. */
6969
- function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, keys = true, extraShortcuts = [], footer, cannotCompare = "Could not read these pictures to compare their pixels.", readPixels, defaultDifference = "brightness", className }) {
6974
+ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, keys = true, extraShortcuts = [], footer, maxHeight, cannotCompare = "Could not read these pictures to compare their pixels.", readPixels, defaultDifference = "brightness", className }) {
6970
6975
  const { viewport, setViewport } = useViewport();
6971
6976
  const [full, setFull] = React.useState(false);
6972
6977
  const pairKey = `${a.media.src}|${b.media.src}`;
@@ -7020,7 +7025,8 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7020
7025
  const frameProps = {
7021
7026
  viewport,
7022
7027
  setViewport,
7023
- aspect
7028
+ aspect,
7029
+ maxHeight: maxHeight === "viewport" ? VIEWPORT_HEIGHT : maxHeight
7024
7030
  };
7025
7031
  let body;
7026
7032
  if (mode === "side") body = /* @__PURE__ */ jsx("div", {
@@ -7288,8 +7294,30 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7288
7294
  });
7289
7295
  }
7290
7296
  // src/components/pair-vote.tsx
7291
- /** A blind pairwise judgment: two pictures in `Compare`, answer keys in its legend, and a vote bar that never leans on either side. */
7292
- function PairVote({ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words = {}, ...compare }) {
7297
+ /** A blind pairwise judgment of two pictures: `Compare`, answer keys in its legend, and a vote bar that never leans on either side. */
7298
+ function PairVote({ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words, ...compare }) {
7299
+ return /* @__PURE__ */ jsx(PairJudge, {
7300
+ pair,
7301
+ skeleton,
7302
+ empty,
7303
+ onAnswer,
7304
+ pending,
7305
+ progress,
7306
+ flagReasons,
7307
+ preload,
7308
+ last,
7309
+ words,
7310
+ view: (slot, p) => /* @__PURE__ */ jsx(Compare, {
7311
+ ...compare,
7312
+ label: p.label,
7313
+ a: p.a,
7314
+ b: p.b,
7315
+ ...slot
7316
+ })
7317
+ });
7318
+ }
7319
+ /** A blind pairwise judgment of anything: the answer keys, vote bar, pending, flag menu, progress, preload and Undo around a `view` that draws the pair (`CompareAudio`, `CompareText`, your own). */
7320
+ function PairJudge({ pair, skeleton, empty, onAnswer, pending, progress, flagReasons, preload, last, words = {}, view }) {
7293
7321
  React.useEffect(() => {
7294
7322
  for (const src of preload ?? []) new Image().src = src;
7295
7323
  }, [preload]);
@@ -7320,7 +7348,7 @@ function PairVote({ pair, skeleton, empty, onAnswer, pending, progress, flagReas
7320
7348
  flagReasons,
7321
7349
  words: w,
7322
7350
  last,
7323
- compare
7351
+ view
7324
7352
  })
7325
7353
  }),
7326
7354
  last && !(pair.status === "ready" && pair.data) && /* @__PURE__ */ jsx(LastAnswer, { last })
@@ -7343,7 +7371,7 @@ function LastAnswer({ last }) {
7343
7371
  ]
7344
7372
  });
7345
7373
  }
7346
- function Judged({ pair, onAnswer, pending, flagReasons, words, last, compare }) {
7374
+ function Judged({ pair, onAnswer, pending, flagReasons, words, last, view }) {
7347
7375
  const { a, b } = pair;
7348
7376
  const answer = (x) => !pending && onAnswer(x);
7349
7377
  const shortcuts = [
@@ -7428,13 +7456,553 @@ function Judged({ pair, onAnswer, pending, flagReasons, words, last, compare })
7428
7456
  last && /* @__PURE__ */ jsx(LastAnswer, { last })
7429
7457
  ]
7430
7458
  });
7431
- return /* @__PURE__ */ jsx(Compare, {
7432
- ...compare,
7433
- label: pair.label,
7434
- a,
7435
- b,
7459
+ return /* @__PURE__ */ jsx(Fragment, { children: view({
7436
7460
  extraShortcuts: shortcuts,
7437
7461
  footer
7462
+ }, pair) });
7463
+ }
7464
+ var db$1 = (x) => x > 0 ? 20 * Math.log10(x) : -Infinity;
7465
+ /** The RMS and peak of channel data (-1 to 1), over all channels together. */
7466
+ function loudnessOf(channels) {
7467
+ let sum = 0;
7468
+ let count = 0;
7469
+ let peak = 0;
7470
+ for (const c of channels) for (let i = 0; i < c.length; i++) {
7471
+ const v = c[i];
7472
+ sum += v * v;
7473
+ const a = Math.abs(v);
7474
+ if (a > peak) peak = a;
7475
+ }
7476
+ count = channels.reduce((n, c) => n + c.length, 0);
7477
+ return {
7478
+ rms: db$1(Math.sqrt(count ? sum / count : 0)),
7479
+ peak: db$1(peak)
7480
+ };
7481
+ }
7482
+ /** How much to turn each of two clips down (in dB, zero or less) so they play at the same RMS: the louder is lowered to the quieter. */
7483
+ function matchGains(a, b) {
7484
+ if (!Number.isFinite(a.rms) || !Number.isFinite(b.rms)) return {
7485
+ a: 0,
7486
+ b: 0
7487
+ };
7488
+ const diff = a.rms - b.rms;
7489
+ return diff > 0 ? {
7490
+ a: -diff,
7491
+ b: 0
7492
+ } : {
7493
+ a: 0,
7494
+ b: diff
7495
+ };
7496
+ }
7497
+ /** dB to a media element's volume (0 to 1). */
7498
+ var gainToVolume = (decibels) => Math.min(1, Math.max(0, 10 ** (decibels / 20)));
7499
+ /** Fetches and decodes a clip and measures it. Needs the Web Audio API; reads at most `MAX_SECONDS`. */
7500
+ async function measureLoudness(src) {
7501
+ const response = await fetch(src);
7502
+ if (!response.ok) throw new Error(`Could not read ${src}: ${response.status}`);
7503
+ const context = new (window.AudioContext ?? window.webkitAudioContext)();
7504
+ try {
7505
+ const buffer = await context.decodeAudioData(await response.arrayBuffer());
7506
+ const frames = Math.min(buffer.length, Math.floor(buffer.sampleRate * 120));
7507
+ return loudnessOf(Array.from({ length: buffer.numberOfChannels }, (_, c) => buffer.getChannelData(c).subarray(0, frames)));
7508
+ } finally {
7509
+ context.close();
7510
+ }
7511
+ }
7512
+ // src/components/compare-audio.tsx
7513
+ var db = (x) => `${Math.abs(x).toFixed(1)} dB`;
7514
+ /** Two clips to judge by ear: one transport, a switch that keeps the playhead, a loop, and matched levels. */
7515
+ function CompareAudio({ label, a, b, blind, missing, levelMatch = true, align = "auto", measure = measureLoudness, keys = true, extraShortcuts = [], footer, className }) {
7516
+ const refA = React.useRef(null);
7517
+ const refB = React.useRef(null);
7518
+ const sa = useMediaElement(refA);
7519
+ const sb = useMediaElement(refB);
7520
+ const [showing, setShowing] = React.useState("a");
7521
+ const [volume, setVolume] = React.useState(100);
7522
+ const [matching, setMatching] = React.useState(levelMatch);
7523
+ const [loop, setLoop] = React.useState({
7524
+ start: null,
7525
+ end: null
7526
+ });
7527
+ const [levels, setLevels] = React.useState(null);
7528
+ const active = showing === "a" ? sa : sb;
7529
+ const keyOf = `${a.media.src}|${b.media.src}`;
7530
+ React.useEffect(() => {
7531
+ if (!matching) return;
7532
+ let live = true;
7533
+ setLevels(null);
7534
+ Promise.all([measure(a.media.src), measure(b.media.src)]).then(([la, lb]) => live && setLevels({
7535
+ key: keyOf,
7536
+ a: la,
7537
+ b: lb
7538
+ }), () => live && setLevels("failed"));
7539
+ return () => {
7540
+ live = false;
7541
+ };
7542
+ }, [
7543
+ matching,
7544
+ keyOf,
7545
+ a.media.src,
7546
+ b.media.src,
7547
+ measure
7548
+ ]);
7549
+ const gains = matching && levels && levels !== "failed" && levels.key === keyOf ? matchGains(levels.a, levels.b) : {
7550
+ a: 0,
7551
+ b: 0
7552
+ };
7553
+ React.useEffect(() => {
7554
+ if (refA.current) refA.current.volume = volume / 100 * gainToVolume(gains.a);
7555
+ if (refB.current) refB.current.volume = volume / 100 * gainToVolume(gains.b);
7556
+ }, [
7557
+ volume,
7558
+ gains.a,
7559
+ gains.b
7560
+ ]);
7561
+ const carry = (time, from, to) => {
7562
+ if (!(from.duration && to.duration) || align === "time") return time;
7563
+ const differ = Math.abs(from.duration - to.duration) / Math.max(from.duration, to.duration) > .02;
7564
+ return align === "proportion" || differ ? time / from.duration * to.duration : time;
7565
+ };
7566
+ const hear = (side) => {
7567
+ if (side === showing) return;
7568
+ const from = showing === "a" ? sa : sb;
7569
+ const to = side === "a" ? sa : sb;
7570
+ const wasPlaying = from.playing;
7571
+ from.pause();
7572
+ to.seek(carry(from.time, from, to));
7573
+ if (from.duration && to.duration) {
7574
+ const move = (share) => share === null ? null : Math.min(1, carry(share * from.duration, from, to) / to.duration);
7575
+ setLoop((l) => ({
7576
+ start: move(l.start),
7577
+ end: move(l.end)
7578
+ }));
7579
+ }
7580
+ if (wasPlaying) to.play();
7581
+ setShowing(side);
7582
+ };
7583
+ const flip = () => hear(showing === "a" ? "b" : "a");
7584
+ const duration = active.duration ?? 0;
7585
+ const at = (share) => share === null || !duration ? null : share * duration;
7586
+ const setPoint = (point) => {
7587
+ if (!duration) return;
7588
+ const share = active.time / duration;
7589
+ setLoop((l) => {
7590
+ const next = {
7591
+ ...l,
7592
+ [point]: share
7593
+ };
7594
+ if (next.start !== null && next.end !== null && next.start >= next.end) return point === "start" ? {
7595
+ start: share,
7596
+ end: null
7597
+ } : {
7598
+ start: null,
7599
+ end: share
7600
+ };
7601
+ return next;
7602
+ });
7603
+ };
7604
+ const clearLoop = () => setLoop({
7605
+ start: null,
7606
+ end: null
7607
+ });
7608
+ const looping = loop.start !== null && loop.end !== null;
7609
+ const enforce = React.useCallback(() => {
7610
+ const e = (showing === "a" ? refA : refB).current;
7611
+ if (!e || !looping || !Number.isFinite(e.duration)) return;
7612
+ if (e.currentTime >= loop.end * e.duration || e.currentTime < loop.start * e.duration - .05) e.currentTime = loop.start * e.duration;
7613
+ }, [
7614
+ showing,
7615
+ looping,
7616
+ loop.start,
7617
+ loop.end
7618
+ ]);
7619
+ React.useEffect(() => {
7620
+ if (looping && active.playing && active.time >= loop.end * duration) enforce();
7621
+ }, [
7622
+ active.time,
7623
+ active.playing,
7624
+ looping,
7625
+ loop.end,
7626
+ duration,
7627
+ enforce
7628
+ ]);
7629
+ React.useEffect(() => {
7630
+ if (!looping || !active.playing) return;
7631
+ let frame = requestAnimationFrame(function tick() {
7632
+ enforce();
7633
+ frame = requestAnimationFrame(tick);
7634
+ });
7635
+ return () => cancelAnimationFrame(frame);
7636
+ }, [
7637
+ looping,
7638
+ active.playing,
7639
+ enforce
7640
+ ]);
7641
+ const shortcuts = [
7642
+ ...extraShortcuts,
7643
+ {
7644
+ keys: ["1"],
7645
+ label: `Hear ${a.label}`,
7646
+ run: () => hear("a")
7647
+ },
7648
+ {
7649
+ keys: ["2"],
7650
+ label: `Hear ${b.label}`,
7651
+ run: () => hear("b")
7652
+ },
7653
+ {
7654
+ keys: ["x"],
7655
+ label: `Flip ${a.label} and ${b.label}`,
7656
+ run: flip
7657
+ },
7658
+ {
7659
+ keys: [" ", "k"],
7660
+ label: "Play or pause",
7661
+ run: active.toggle
7662
+ },
7663
+ {
7664
+ keys: ["j"],
7665
+ label: "Back 1 s",
7666
+ run: () => active.seek(Math.max(0, active.time - 1)),
7667
+ repeat: true
7668
+ },
7669
+ {
7670
+ keys: ["l"],
7671
+ label: "Forward 1 s",
7672
+ run: () => active.seek(active.time + 1),
7673
+ repeat: true
7674
+ },
7675
+ {
7676
+ keys: ["i"],
7677
+ label: "Loop starts here",
7678
+ run: () => setPoint("start")
7679
+ },
7680
+ {
7681
+ keys: ["o"],
7682
+ label: "Loop ends here",
7683
+ run: () => setPoint("end")
7684
+ },
7685
+ {
7686
+ keys: ["c"],
7687
+ label: "Clear the loop",
7688
+ run: clearLoop,
7689
+ disabled: loop.start === null && loop.end === null
7690
+ }
7691
+ ];
7692
+ useHotkeys(shortcuts, { enabled: keys });
7693
+ const failed = sa.error || sb.error;
7694
+ const marks = [...loop.start !== null && at(loop.start) !== null ? [{
7695
+ time: at(loop.start),
7696
+ label: "Loop start"
7697
+ }] : [], ...loop.end !== null && at(loop.end) !== null ? [{
7698
+ time: at(loop.end),
7699
+ label: "Loop end"
7700
+ }] : []];
7701
+ const range = (share) => share === null || !duration ? format.missing : format.timecode(share * duration, { precision: "seconds" });
7702
+ let levelLine = null;
7703
+ if (matching) {
7704
+ if (levels === "failed") levelLine = "Could not measure the levels, so the clips are not matched.";
7705
+ else if (!levels || levels.key !== keyOf) levelLine = "Measuring levels…";
7706
+ else if (gains.a === 0 && gains.b === 0) levelLine = "Both clips are at the same level.";
7707
+ else {
7708
+ const [loud, quiet, cut] = gains.a < 0 ? [
7709
+ a.label,
7710
+ b.label,
7711
+ gains.a
7712
+ ] : [
7713
+ b.label,
7714
+ a.label,
7715
+ gains.b
7716
+ ];
7717
+ levelLine = `${loud} is louder than ${quiet}, so it is turned down by ${db(cut)}.`;
7718
+ }
7719
+ }
7720
+ return /* @__PURE__ */ jsxs("section", {
7721
+ "aria-label": label,
7722
+ className: cn("grid gap-3", className),
7723
+ children: [
7724
+ /* @__PURE__ */ jsx("audio", {
7725
+ ref: refA,
7726
+ src: a.media.src,
7727
+ preload: "auto",
7728
+ "aria-label": `Clip ${a.label}`
7729
+ }),
7730
+ /* @__PURE__ */ jsx("audio", {
7731
+ ref: refB,
7732
+ src: b.media.src,
7733
+ preload: "auto",
7734
+ "aria-label": `Clip ${b.label}`
7735
+ }),
7736
+ /* @__PURE__ */ jsxs("div", {
7737
+ className: "flex flex-wrap items-center gap-3",
7738
+ children: [/* @__PURE__ */ jsx(ToggleGroup, {
7739
+ label: "Listen to",
7740
+ options: [{
7741
+ value: "a",
7742
+ label: a.label
7743
+ }, {
7744
+ value: "b",
7745
+ label: b.label
7746
+ }],
7747
+ value: showing,
7748
+ onChange: (v) => hear(v)
7749
+ }), /* @__PURE__ */ jsx(Switch, {
7750
+ label: "Match loudness",
7751
+ on: matching,
7752
+ onChange: setMatching
7753
+ })]
7754
+ }),
7755
+ !blind && (a.note || b.note) && /* @__PURE__ */ jsx("p", {
7756
+ className: "type-caption text-muted-foreground",
7757
+ children: [a, b].filter((c) => c.note).map((c) => `${c.label}: ${c.note}`).join(" · ")
7758
+ }),
7759
+ failed && /* @__PURE__ */ jsx("p", {
7760
+ role: "alert",
7761
+ className: "type-body-sm text-danger",
7762
+ children: missing
7763
+ }),
7764
+ /* @__PURE__ */ jsxs(Transport, {
7765
+ playing: active.playing,
7766
+ onPlayPause: active.toggle,
7767
+ children: [
7768
+ /* @__PURE__ */ jsx(TimeReadout, {
7769
+ time: active.time,
7770
+ duration: active.duration
7771
+ }),
7772
+ /* @__PURE__ */ jsx(SeekBar, {
7773
+ time: active.time,
7774
+ duration: active.duration,
7775
+ onSeek: active.seek,
7776
+ marks,
7777
+ buffered: active.buffered,
7778
+ label: `Position in ${(showing === "a" ? a : b).label}`,
7779
+ step: 1
7780
+ }),
7781
+ /* @__PURE__ */ jsx(VolumeControl, {
7782
+ volume,
7783
+ onVolumeChange: setVolume
7784
+ })
7785
+ ]
7786
+ }),
7787
+ /* @__PURE__ */ jsxs("div", {
7788
+ className: "flex flex-wrap items-center gap-2",
7789
+ children: [
7790
+ /* @__PURE__ */ jsx(Button, {
7791
+ size: "sm",
7792
+ onPress: () => setPoint("start"),
7793
+ disabled: !duration,
7794
+ children: "Loop starts here"
7795
+ }),
7796
+ /* @__PURE__ */ jsx(Button, {
7797
+ size: "sm",
7798
+ onPress: () => setPoint("end"),
7799
+ disabled: !duration,
7800
+ children: "Loop ends here"
7801
+ }),
7802
+ /* @__PURE__ */ jsx(Button, {
7803
+ size: "sm",
7804
+ variant: "ghost",
7805
+ onPress: clearLoop,
7806
+ disabled: loop.start === null && loop.end === null,
7807
+ children: "Clear the loop"
7808
+ }),
7809
+ /* @__PURE__ */ jsx("span", {
7810
+ role: "status",
7811
+ className: "type-caption tabular-nums text-muted-foreground",
7812
+ children: looping ? `Looping ${range(loop.start)} to ${range(loop.end)}` : loop.start !== null ? `Loop starts at ${range(loop.start)}` : loop.end !== null ? `Loop ends at ${range(loop.end)}` : "No loop"
7813
+ })
7814
+ ]
7815
+ }),
7816
+ levelLine && /* @__PURE__ */ jsx("p", {
7817
+ role: "status",
7818
+ className: "type-body-sm text-muted-foreground",
7819
+ children: levelLine
7820
+ }),
7821
+ footer,
7822
+ keys && /* @__PURE__ */ jsx(KeysLegend, { shortcuts })
7823
+ ]
7824
+ });
7825
+ }
7826
+ var tokens = (text) => text.split(/(\s+)/).filter((t) => t !== "");
7827
+ var isSpace = (t) => /^\s+$/.test(t);
7828
+ /** Marks the words that differ between two texts, or returns null when the pair is too long to compare. */
7829
+ function diffWords(a, b) {
7830
+ const ta = tokens(a);
7831
+ const tb = tokens(b);
7832
+ const wa = ta.filter((t) => !isSpace(t));
7833
+ const wb = tb.filter((t) => !isSpace(t));
7834
+ if ((wa.length + 1) * (wb.length + 1) > 25e5) return null;
7835
+ const w = wb.length + 1;
7836
+ const table = new Uint32Array((wa.length + 1) * w);
7837
+ for (let i = wa.length - 1; i >= 0; i--) for (let j = wb.length - 1; j >= 0; j--) table[i * w + j] = wa[i] === wb[j] ? table[(i + 1) * w + j + 1] + 1 : Math.max(table[(i + 1) * w + j], table[i * w + j + 1]);
7838
+ const sameA = /* @__PURE__ */ new Set();
7839
+ const sameB = /* @__PURE__ */ new Set();
7840
+ for (let i = 0, j = 0; i < wa.length && j < wb.length;) if (wa[i] === wb[j]) {
7841
+ sameA.add(i++);
7842
+ sameB.add(j++);
7843
+ } else if (table[(i + 1) * w + j] >= table[i * w + j + 1]) i++;
7844
+ else j++;
7845
+ const cut = (all, same) => {
7846
+ let word = 0;
7847
+ const out = [];
7848
+ let changed = 0;
7849
+ for (const t of all) {
7850
+ if (isSpace(t)) {
7851
+ out.push({
7852
+ text: t,
7853
+ changed: false
7854
+ });
7855
+ continue;
7856
+ }
7857
+ const diff = !same.has(word++);
7858
+ if (diff) changed++;
7859
+ out.push({
7860
+ text: t,
7861
+ changed: diff
7862
+ });
7863
+ }
7864
+ return {
7865
+ out,
7866
+ changed
7867
+ };
7868
+ };
7869
+ const ra = cut(ta, sameA);
7870
+ const rb = cut(tb, sameB);
7871
+ return {
7872
+ a: ra.out,
7873
+ b: rb.out,
7874
+ changedA: ra.changed,
7875
+ changedB: rb.changed
7876
+ };
7877
+ }
7878
+ // src/components/compare-text.tsx
7879
+ function Words({ segments, changed }) {
7880
+ return /* @__PURE__ */ jsx(Fragment, { children: segments.map((s, i) => changed && s.changed ? /* @__PURE__ */ jsx("mark", {
7881
+ className: "rounded-control bg-warning-subtle text-foreground underline decoration-2 underline-offset-2",
7882
+ children: s.text
7883
+ }, i) : /* @__PURE__ */ jsx(React.Fragment, { children: s.text }, i)) });
7884
+ }
7885
+ /** Two texts side by side with scrolling together, an optional reference, and a word diff on request. */
7886
+ function CompareText({ label, a, b, blind, reference, defaultDiff = false, tooLong = "These texts are too long to compare word by word.", linkedScroll = true, keys = true, extraShortcuts = [], footer, className }) {
7887
+ const [diff, setDiff] = React.useState(defaultDiff);
7888
+ const [against, setAgainst] = React.useState(reference ? "reference" : "other");
7889
+ const boxA = React.useRef(null);
7890
+ const boxB = React.useRef(null);
7891
+ const syncing = React.useRef(false);
7892
+ const result = React.useMemo(() => {
7893
+ if (!diff) return null;
7894
+ if (against === "reference" && reference) {
7895
+ const ra = diffWords(a.media.text, reference.text);
7896
+ const rb = diffWords(b.media.text, reference.text);
7897
+ return ra && rb ? {
7898
+ a: ra.a,
7899
+ b: rb.a,
7900
+ changedA: ra.changedA,
7901
+ changedB: rb.changedA,
7902
+ missingA: ra.changedB,
7903
+ missingB: rb.changedB
7904
+ } : "long";
7905
+ }
7906
+ const r = diffWords(a.media.text, b.media.text);
7907
+ return r ? {
7908
+ ...r,
7909
+ missingA: 0,
7910
+ missingB: 0
7911
+ } : "long";
7912
+ }, [
7913
+ diff,
7914
+ against,
7915
+ reference,
7916
+ a.media.text,
7917
+ b.media.text
7918
+ ]);
7919
+ const follow = (from, to) => {
7920
+ if (!linkedScroll || !from || !to || syncing.current) return;
7921
+ const range = from.scrollHeight - from.clientHeight;
7922
+ syncing.current = true;
7923
+ to.scrollTop = range > 0 ? from.scrollTop / range * (to.scrollHeight - to.clientHeight) : 0;
7924
+ requestAnimationFrame(() => syncing.current = false);
7925
+ };
7926
+ const pane = (c, ref, other, segments) => /* @__PURE__ */ jsxs("figure", {
7927
+ className: "grid min-w-0 gap-1.5",
7928
+ children: [/* @__PURE__ */ jsxs("figcaption", {
7929
+ className: "flex items-baseline gap-2",
7930
+ children: [/* @__PURE__ */ jsx("span", {
7931
+ className: "type-label",
7932
+ children: c.label
7933
+ }), !blind && c.note && /* @__PURE__ */ jsx("span", {
7934
+ className: "type-caption text-muted-foreground",
7935
+ children: c.note
7936
+ })]
7937
+ }), /* @__PURE__ */ jsx("div", {
7938
+ ref,
7939
+ tabIndex: 0,
7940
+ role: "region",
7941
+ "aria-label": `Text ${c.label}`,
7942
+ onScroll: () => follow(ref.current, other.current),
7943
+ className: "max-h-96 overflow-auto whitespace-pre-wrap rounded-surface border border-border bg-muted p-3 type-body focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
7944
+ children: segments ? /* @__PURE__ */ jsx(Words, {
7945
+ segments,
7946
+ changed: true
7947
+ }) : c.media.text
7948
+ })]
7949
+ });
7950
+ const counts = result && result !== "long" ? result : null;
7951
+ const words = (n) => `${n} ${n === 1 ? "word" : "words"}`;
7952
+ const ref = against === "reference" && reference;
7953
+ const say = (who, differ, missing) => ref ? `${who}: ${words(differ)} ${differ === 1 ? "differs" : "differ"}, ${missing} missing.` : `${who}: ${words(differ)} ${differ === 1 ? "differs" : "differ"}.`;
7954
+ const shortcuts = [...extraShortcuts, {
7955
+ keys: ["d"],
7956
+ label: diff ? "Hide the differences" : "Mark the differences",
7957
+ run: () => setDiff((d) => !d)
7958
+ }];
7959
+ useHotkeys(shortcuts, { enabled: keys });
7960
+ return /* @__PURE__ */ jsxs("section", {
7961
+ "aria-label": label,
7962
+ className: cn("grid gap-3", className),
7963
+ children: [
7964
+ /* @__PURE__ */ jsxs("div", {
7965
+ className: "flex flex-wrap items-center gap-3",
7966
+ children: [/* @__PURE__ */ jsx(Switch, {
7967
+ label: "Mark the words that differ",
7968
+ on: diff,
7969
+ onChange: setDiff
7970
+ }), diff && reference && /* @__PURE__ */ jsx(ToggleGroup, {
7971
+ label: "Differences against",
7972
+ options: [{
7973
+ value: "other",
7974
+ label: "The other text"
7975
+ }, {
7976
+ value: "reference",
7977
+ label: reference.label
7978
+ }],
7979
+ value: against,
7980
+ onChange: (v) => setAgainst(v),
7981
+ size: "sm"
7982
+ })]
7983
+ }),
7984
+ reference && /* @__PURE__ */ jsxs("figure", {
7985
+ className: "grid gap-1.5",
7986
+ children: [/* @__PURE__ */ jsx("figcaption", {
7987
+ className: "type-label",
7988
+ children: reference.label
7989
+ }), /* @__PURE__ */ jsx("p", {
7990
+ className: "whitespace-pre-wrap rounded-surface border border-border p-3 type-body",
7991
+ children: reference.text
7992
+ })]
7993
+ }),
7994
+ /* @__PURE__ */ jsxs("div", {
7995
+ className: "grid gap-3 sm:grid-cols-2",
7996
+ children: [pane(a, boxA, boxB, counts ? counts.a : null), pane(b, boxB, boxA, counts ? counts.b : null)]
7997
+ }),
7998
+ diff && /* @__PURE__ */ jsx("p", {
7999
+ role: "status",
8000
+ className: "type-body-sm text-muted-foreground",
8001
+ children: result === "long" ? tooLong : counts && counts.changedA + counts.missingA + counts.changedB + counts.missingB === 0 ? ref && reference ? `Both match ${reference.label} word for word.` : "The texts are the same word for word." : counts ? `${say(a.label, counts.changedA, counts.missingA)} ${say(b.label, counts.changedB, counts.missingB)}` : null
8002
+ }),
8003
+ footer,
8004
+ keys && /* @__PURE__ */ jsx(KeysLegend, { shortcuts })
8005
+ ]
7438
8006
  });
7439
8007
  }
7440
8008
  // src/components/compare-grid.tsx
@@ -8169,6 +8737,6 @@ function SaveStatus({ state, onRetry, className }) {
8169
8737
  ]
8170
8738
  });
8171
8739
  }
8172
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareGrid, CompositionBar, ContextMenu, DEFAULT_TOLERANCE, DataTable, DataView, Density, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, LineChart, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, PairVote, Pane, Popover, PropertyList, PropertyRow, RateChoice, RowAction, SPEECH_RATES, SaveStatus, SeekBar, SelectableGrid, SideNav, Skeleton, Slider, SortableList, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, Transport, UndoBar, ViewportFrame, VirtualList, VolumeControl, Workspace, actualPixelsScale, buttonVariants, canFullscreen, clampViewport, cn, colorSchemeScript, commandShortcut, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, detectPlatform, differences, fetchJson, fieldErrorsOf, format, formatChord, geo, isReservedChord, isTypingTarget, labelOf, matchesAccept, matchesChord, noOverlap, parseChord, parseSort, readErrorBody, readPixels, resample, serialiseSort, staleOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toast, toastTimeout, transportShortcuts, typeSteps, useActiveItem, useAsyncAction, useAutoSave, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useLeaveGuard, useLoad, useMediaElement, useSelection, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, useWorkspaceState, zoomAt };
8740
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompositionBar, ContextMenu, DEFAULT_TOLERANCE, DataTable, DataView, Density, Dialog, Disclosure, Done, EmptyState, FIT, Field, FileButton, FileDropZone, FileOutcomes, FullscreenFrame, HttpError, IconButton, InfiniteList, Input, Inspector, InspectorSection, JobStatus, KeysLegend, LineChart, LinkCard, LinkCardList, LoadError, LoadMore, MAX_SCALE, MAX_SIDE, MIN_SCALE, MISSING, MediaPlayer, MediaStage, Menu, Meter, Metric, MetricStrip, MissingFile, NBSP, NativeSelect, NumberField, PageHeader, PairJudge, PairVote, Pane, Popover, PropertyList, PropertyRow, RateChoice, RowAction, SPEECH_RATES, SaveStatus, SeekBar, SelectableGrid, SideNav, Skeleton, Slider, SortableList, Split, StageGuides, StaleNotice, Status, StrataQueryProvider, StrataToastRegion, Switch, TableSkeleton, Tabs, Textarea, ThemeProvider, Thumbnail, ThumbnailSkeleton, TimeReadout, Timeline, TimelineZoomControls, Toggle, ToggleGroup, Toolbar, ToolbarSeparator, Tooltip, Transport, UndoBar, ViewportFrame, VirtualList, VolumeControl, Workspace, actualPixelsScale, buttonVariants, canFullscreen, clampViewport, cn, colorSchemeScript, commandShortcut, createFormat, createQueryClient, crossedThreshold, describeActionError, describeHttpError, detectPlatform, diffWords, differences, fetchJson, fieldErrorsOf, format, formatChord, gainToVolume, geo, isReservedChord, isTypingTarget, labelOf, loudnessOf, matchGains, matchesAccept, matchesChord, measureLoudness, noOverlap, parseChord, parseSort, readErrorBody, readPixels, resample, serialiseSort, staleOf, tickLabel, tickStep, ticksBetween, toDate, toLoad, toast, toastTimeout, transportShortcuts, typeSteps, useActiveItem, useAsyncAction, useAutoSave, useClientWork, useColorScheme, useCommands, useDifference, useExpanded, useFileIntake, useHistory, useHistoryState, useHotkeys, useInView, useInfiniteLoad, useJob, useLeaveGuard, useLoad, useMediaElement, useSelection, useSystemColorScheme, useTimelineZoom, useUndoable, useViewport, useWorkspaceState, zoomAt };
8173
8741
 
8174
8742
  //# sourceMappingURL=index.js.map