strata-react 1.0.29 → 1.0.32

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
@@ -2671,7 +2671,7 @@ function TimeReadout({ time, duration, precision = "seconds", fps = 30, classNam
2671
2671
  });
2672
2672
  }
2673
2673
  /** A seek bar: dragged, clicked and moved by keys (arrows `step`, Page keys `bigStep`, Home and End), with its time as the accessible value. */
2674
- function SeekBar({ time, duration: known, onSeek, marks = [], buffered, step = 5, bigStep = 30, label = "Seek", precision = "seconds", fps = 30, disabled: off, className }) {
2674
+ function SeekBar({ time, duration: known, onSeek, marks = [], onMarkPress, buffered, step = 5, bigStep = 30, label = "Seek", precision = "seconds", fps = 30, disabled: off, className }) {
2675
2675
  const duration = known && Number.isFinite(known) && known > 0 ? known : 0;
2676
2676
  const disabled = off || duration === 0;
2677
2677
  const track = React.useRef(null);
@@ -2764,7 +2764,7 @@ function SeekBar({ time, duration: known, onSeek, marks = [], buffered, step = 5
2764
2764
  })}`,
2765
2765
  onPointerDown: (e) => e.stopPropagation(),
2766
2766
  onMouseDown: (e) => e.stopPropagation(),
2767
- onClick: () => seekTo(m.time),
2767
+ onClick: () => onMarkPress ? onMarkPress(m) : seekTo(m.time),
2768
2768
  className: "absolute top-1/2 h-3 w-1 -translate-y-1/2 cursor-pointer rounded-pill bg-foreground",
2769
2769
  style: { left: `${m.time / duration * 100}%` }
2770
2770
  }, `${m.time}-${m.label}`)),
@@ -6537,6 +6537,48 @@ function actualPixelsScale(naturalWidth, fittedWidth) {
6537
6537
  function viewportTransform(v) {
6538
6538
  return `translate(${v.x}px, ${v.y}px) scale(${v.scale})`;
6539
6539
  }
6540
+ /** A region as shares of the frame, so it lands on the same part of every candidate whatever its pixel size. */
6541
+ function regionShares(region) {
6542
+ const [x, y, w, h] = region.box;
6543
+ if (!region.of) return [
6544
+ x,
6545
+ y,
6546
+ w,
6547
+ h
6548
+ ];
6549
+ const [ow, oh] = region.of;
6550
+ return [
6551
+ x / ow,
6552
+ y / oh,
6553
+ w / ow,
6554
+ h / oh
6555
+ ];
6556
+ }
6557
+ /** The viewport that fills the frame with a box (as much of it as fits, centred): the scale that fits the box, the offset that puts its centre at the frame's centre. */
6558
+ function boxViewport(box, frame) {
6559
+ const [x, y, w, h] = box;
6560
+ const scale = Math.min(32, Math.max(1, Math.min(1 / Math.max(w, 1e-6), 1 / Math.max(h, 1e-6))));
6561
+ return clampViewport({
6562
+ scale,
6563
+ x: -scale * (x + w / 2 - .5) * frame.width,
6564
+ y: -scale * (y + h / 2 - .5) * frame.height
6565
+ }, frame);
6566
+ }
6567
+ /** A rectangle drawn on the frame (pixels from its top left) as shares of the picture under the viewport now. */
6568
+ function frameBoxToShares(rect, v, frame) {
6569
+ const toShare = (p, offset, size) => size ? (p - size / 2 - offset) / v.scale / size + .5 : 0;
6570
+ const clamp = (n) => Math.min(1, Math.max(0, n));
6571
+ const xa = clamp(toShare(Math.min(rect.x0, rect.x1), v.x, frame.width));
6572
+ const xb = clamp(toShare(Math.max(rect.x0, rect.x1), v.x, frame.width));
6573
+ const ya = clamp(toShare(Math.min(rect.y0, rect.y1), v.y, frame.height));
6574
+ const yb = clamp(toShare(Math.max(rect.y0, rect.y1), v.y, frame.height));
6575
+ return [
6576
+ xa,
6577
+ ya,
6578
+ xb - xa,
6579
+ yb - ya
6580
+ ];
6581
+ }
6540
6582
  // src/components/compare-parts.tsx
6541
6583
  var VIEWPORT_HEIGHT = "max(16rem, calc(100svh - 14rem))";
6542
6584
  /** A word for a picture's name on the page: its label, with its note unless blind. */
@@ -6553,7 +6595,7 @@ function Caption({ c, blind }) {
6553
6595
  });
6554
6596
  }
6555
6597
  /** One picture inside a frame: a skeleton while it loads, the product's words if it fails. */
6556
- function Picture({ c, blind, missing, onNatural, imgRef }) {
6598
+ function Picture({ c, blind, missing, onNatural, imgRef, pixelated }) {
6557
6599
  const [state, setState] = React.useState("loading");
6558
6600
  React.useEffect(() => setState("loading"), [c.media.src]);
6559
6601
  const alt = blind ? c.label : c.media.alt;
@@ -6577,6 +6619,7 @@ function Picture({ c, blind, missing, onNatural, imgRef }) {
6577
6619
  src: c.media.src,
6578
6620
  alt,
6579
6621
  draggable: false,
6622
+ style: pixelated ? { imageRendering: "pixelated" } : void 0,
6580
6623
  onLoad: (e) => {
6581
6624
  setState("ready");
6582
6625
  onNatural?.(e.currentTarget.naturalWidth, e.currentTarget.naturalHeight);
@@ -6681,6 +6724,21 @@ function FullscreenButton({ full, setFull }) {
6681
6724
  onPress: () => setFull(!full)
6682
6725
  });
6683
6726
  }
6727
+ /** The width of an element, kept current: for "is this shown larger than its own pixels". */
6728
+ function useWidth(ref) {
6729
+ const [width, setWidth] = React.useState(0);
6730
+ React.useLayoutEffect(() => {
6731
+ const el = ref.current;
6732
+ if (!el) return;
6733
+ const read = () => setWidth(el.getBoundingClientRect().width);
6734
+ read();
6735
+ if (typeof ResizeObserver === "undefined") return;
6736
+ const ro = new ResizeObserver(read);
6737
+ ro.observe(el);
6738
+ return () => ro.disconnect();
6739
+ });
6740
+ return width;
6741
+ }
6684
6742
  // src/lib/image-diff.ts
6685
6743
  /** The longest side, in pixels, a picture is compared at. */
6686
6744
  var MAX_SIDE = 2048;
@@ -6817,12 +6875,22 @@ function useViewport(initial = FIT) {
6817
6875
  }
6818
6876
  var PAN_STEP = 48;
6819
6877
  /** A clipped frame whose children zoom and pan together; the viewport is the caller's, so frames can share one. */
6820
- var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, viewport, setViewport, children, cover, overlay, maxHeight, className }, forwardedRef) {
6878
+ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, viewport, setViewport, children, cover, overlay, maxHeight, onBox, outline, className }, forwardedRef) {
6821
6879
  const ref = React.useRef(null);
6822
6880
  React.useImperativeHandle(forwardedRef, () => ref.current);
6823
6881
  const latest = React.useRef(viewport);
6824
6882
  latest.current = viewport;
6825
6883
  const drag = React.useRef(null);
6884
+ const [band, setBand] = React.useState(null);
6885
+ const bandRef = React.useRef(band);
6886
+ bandRef.current = band;
6887
+ const inFrame = (clientX, clientY) => {
6888
+ const r = ref.current.getBoundingClientRect();
6889
+ return {
6890
+ x: clientX - r.left,
6891
+ y: clientY - r.top
6892
+ };
6893
+ };
6826
6894
  const size = () => {
6827
6895
  const r = ref.current.getBoundingClientRect();
6828
6896
  return {
@@ -6888,6 +6956,17 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
6888
6956
  tabIndex: 0,
6889
6957
  onKeyDown,
6890
6958
  onPointerDown: (e) => {
6959
+ if (e.shiftKey && onBox && e.button === 0) {
6960
+ const p = inFrame(e.clientX, e.clientY);
6961
+ setBand({
6962
+ x0: p.x,
6963
+ y0: p.y,
6964
+ x1: p.x,
6965
+ y1: p.y
6966
+ });
6967
+ e.currentTarget.setPointerCapture?.(e.pointerId);
6968
+ return;
6969
+ }
6891
6970
  if (!zoomed || e.button !== 0) return;
6892
6971
  drag.current = {
6893
6972
  x: e.clientX,
@@ -6896,6 +6975,15 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
6896
6975
  e.currentTarget.setPointerCapture?.(e.pointerId);
6897
6976
  },
6898
6977
  onPointerMove: (e) => {
6978
+ if (bandRef.current) {
6979
+ const p = inFrame(e.clientX, e.clientY);
6980
+ setBand({
6981
+ ...bandRef.current,
6982
+ x1: p.x,
6983
+ y1: p.y
6984
+ });
6985
+ return;
6986
+ }
6899
6987
  if (!drag.current) return;
6900
6988
  const dx = e.clientX - drag.current.x;
6901
6989
  const dy = e.clientY - drag.current.y;
@@ -6909,8 +6997,18 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
6909
6997
  y: latest.current.y + dy
6910
6998
  }, size()));
6911
6999
  },
6912
- onPointerUp: () => drag.current = null,
6913
- onPointerCancel: () => drag.current = null,
7000
+ onPointerUp: () => {
7001
+ drag.current = null;
7002
+ const b = bandRef.current;
7003
+ if (b) {
7004
+ setBand(null);
7005
+ if (Math.abs(b.x1 - b.x0) > 6 && Math.abs(b.y1 - b.y0) > 6) onBox?.(b);
7006
+ }
7007
+ },
7008
+ onPointerCancel: () => {
7009
+ drag.current = null;
7010
+ setBand(null);
7011
+ },
6914
7012
  onDoubleClick: (e) => {
6915
7013
  const v = latest.current;
6916
7014
  setViewport(v.scale > 1 ? FIT : zoomAt(v, 2, fromCentre(e.clientX, e.clientY), size()));
@@ -6945,6 +7043,26 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
6945
7043
  children: cover.content
6946
7044
  })
6947
7045
  }),
7046
+ outline && viewport.scale === 1 && /* @__PURE__ */ jsx("div", {
7047
+ "aria-hidden": true,
7048
+ className: "pointer-events-none absolute border-2 border-foreground ring-1 ring-background",
7049
+ style: {
7050
+ left: `${outline[0] * 100}%`,
7051
+ top: `${outline[1] * 100}%`,
7052
+ width: `${outline[2] * 100}%`,
7053
+ height: `${outline[3] * 100}%`
7054
+ }
7055
+ }),
7056
+ band && /* @__PURE__ */ jsx("div", {
7057
+ "aria-hidden": true,
7058
+ className: "pointer-events-none absolute border-2 border-dashed border-foreground",
7059
+ style: {
7060
+ left: Math.min(band.x0, band.x1),
7061
+ top: Math.min(band.y0, band.y1),
7062
+ width: Math.abs(band.x1 - band.x0),
7063
+ height: Math.abs(band.y1 - band.y0)
7064
+ }
7065
+ }),
6948
7066
  overlay != null && /* @__PURE__ */ jsx("div", {
6949
7067
  className: "pointer-events-none absolute inset-0",
6950
7068
  onPointerDown: (e) => e.stopPropagation(),
@@ -6955,6 +7073,133 @@ var ViewportFrame = React.forwardRef(function ViewportFrame({ label, aspect, vie
6955
7073
  ]
6956
7074
  });
6957
7075
  });
7076
+ // src/components/compare-regions.tsx
7077
+ var REGION_KEYS = [
7078
+ "q",
7079
+ "w",
7080
+ "e",
7081
+ "r",
7082
+ "y",
7083
+ "u"
7084
+ ];
7085
+ /** Regions for one item: `reset` is a key that changes with the item, which drops the regions drawn by hand. */
7086
+ function useRegions({ regions = [], viewport, setViewport, frame, reset }) {
7087
+ const [drawn, setDrawn] = React.useState({
7088
+ key: reset,
7089
+ list: []
7090
+ });
7091
+ const hand = drawn.key === reset ? drawn.list : [];
7092
+ const all = React.useMemo(() => [...regions, ...hand], [regions, hand]);
7093
+ const [active, setActive] = React.useState(null);
7094
+ const [peekId, setPeek] = React.useState(null);
7095
+ const size = () => {
7096
+ const r = frame.current?.getBoundingClientRect();
7097
+ return {
7098
+ width: r?.width ?? 0,
7099
+ height: r?.height ?? 0
7100
+ };
7101
+ };
7102
+ const choose = (id) => {
7103
+ const region = all.find((r) => r.id === id);
7104
+ if (!region) {
7105
+ setActive(null);
7106
+ setViewport({
7107
+ scale: 1,
7108
+ x: 0,
7109
+ y: 0
7110
+ });
7111
+ return;
7112
+ }
7113
+ applied.current = size();
7114
+ setViewport(boxViewport(regionShares(region), applied.current));
7115
+ setActive(region.id);
7116
+ setPeek(null);
7117
+ };
7118
+ React.useEffect(() => setActive(null), [reset]);
7119
+ const add = (rect) => {
7120
+ const box = frameBoxToShares(rect, viewport, size());
7121
+ if (box[2] <= 0 || box[3] <= 0) return;
7122
+ const region = {
7123
+ id: `region-${all.length + 1}`,
7124
+ label: `Region ${all.length + 1}`,
7125
+ box
7126
+ };
7127
+ setDrawn({
7128
+ key: reset,
7129
+ list: [...hand, region]
7130
+ });
7131
+ applied.current = size();
7132
+ setViewport(boxViewport(box, applied.current));
7133
+ setActive(region.id);
7134
+ };
7135
+ const applied = React.useRef({
7136
+ width: 0,
7137
+ height: 0
7138
+ });
7139
+ const [, bump] = React.useState(0);
7140
+ React.useLayoutEffect(() => {
7141
+ const now = size();
7142
+ if (now.width === applied.current.width && now.height === applied.current.height) return;
7143
+ applied.current = now;
7144
+ const region = all.find((r) => r.id === active);
7145
+ if (region && now.width > 0) setViewport(boxViewport(regionShares(region), now));
7146
+ });
7147
+ React.useLayoutEffect(() => {
7148
+ const el = frame.current;
7149
+ if (!el || typeof ResizeObserver === "undefined") return;
7150
+ const ro = new ResizeObserver(() => {
7151
+ const r = el.getBoundingClientRect();
7152
+ if (r.width !== applied.current.width || r.height !== applied.current.height) bump((n) => n + 1);
7153
+ });
7154
+ ro.observe(el);
7155
+ return () => ro.disconnect();
7156
+ });
7157
+ const peekRegion = all.find((r) => r.id === peekId);
7158
+ return {
7159
+ regions: all,
7160
+ active,
7161
+ choose,
7162
+ setViewport: (next) => {
7163
+ setActive(null);
7164
+ setViewport(next);
7165
+ },
7166
+ add,
7167
+ peek: peekRegion ? regionShares(peekRegion) : null,
7168
+ setPeek,
7169
+ shortcuts: all.slice(0, REGION_KEYS.length).map((r, i) => ({
7170
+ keys: [REGION_KEYS[i]],
7171
+ label: `Region: ${r.label}`,
7172
+ run: () => choose(r.id)
7173
+ }))
7174
+ };
7175
+ }
7176
+ /** The chip strip: the whole frame and each region, one chosen. Renders nothing when there are no regions. */
7177
+ function RegionChips({ state }) {
7178
+ if (state.regions.length === 0) return null;
7179
+ const byLabel = (target) => {
7180
+ const text = target.closest?.("[role=\"radio\"]")?.textContent;
7181
+ return state.regions.find((r) => r.label === text)?.id ?? null;
7182
+ };
7183
+ return /* @__PURE__ */ jsx("div", {
7184
+ onPointerOver: (e) => state.setPeek(byLabel(e.target)),
7185
+ onFocus: (e) => state.setPeek(byLabel(e.target)),
7186
+ onPointerLeave: () => state.setPeek(null),
7187
+ onBlur: () => state.setPeek(null),
7188
+ children: /* @__PURE__ */ jsx(ToggleGroup, {
7189
+ label: "Region",
7190
+ options: [{
7191
+ value: "",
7192
+ label: "Whole frame"
7193
+ }, ...state.regions.map((r) => ({
7194
+ value: r.id,
7195
+ label: r.label
7196
+ }))],
7197
+ value: state.active ?? "",
7198
+ onChange: (v) => state.choose(v === "" ? null : v),
7199
+ size: "sm"
7200
+ })
7201
+ });
7202
+ }
6958
7203
  // src/components/compare.tsx
6959
7204
  var MODE_LABEL$1 = {
6960
7205
  side: "Side by side",
@@ -6971,7 +7216,7 @@ var ALL_MODES = [
6971
7216
  "difference"
6972
7217
  ];
6973
7218
  /** Two pictures to judge, side by side or laid over each other, zoomed and panned together, and full screen. */
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 }) {
7219
+ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_MODES, regions, keys = true, extraShortcuts = [], footer, maxHeight, cannotCompare = "Could not read these pictures to compare their pixels.", readPixels, defaultDifference = "brightness", className }) {
6975
7220
  const { viewport, setViewport } = useViewport();
6976
7221
  const [full, setFull] = React.useState(false);
6977
7222
  const pairKey = `${a.media.src}|${b.media.src}`;
@@ -6987,10 +7232,17 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
6987
7232
  const frameRef = React.useRef(null);
6988
7233
  const imgRef = React.useRef(null);
6989
7234
  const aspect = natural ? natural[0] / natural[1] : 3 / 2;
6990
- const zoom = useZoom({
7235
+ const rg = useRegions({
7236
+ regions,
6991
7237
  viewport,
6992
7238
  setViewport,
6993
7239
  frame: frameRef,
7240
+ reset: pairKey
7241
+ });
7242
+ const zoom = useZoom({
7243
+ viewport,
7244
+ setViewport: rg.setViewport,
7245
+ frame: frameRef,
6994
7246
  natural
6995
7247
  });
6996
7248
  const flip = () => setShowing((s) => s === "a" ? "b" : "a");
@@ -7008,6 +7260,7 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7008
7260
  run: flip,
7009
7261
  disabled: mode !== "blink"
7010
7262
  },
7263
+ ...rg.shortcuts,
7011
7264
  ...zoomShortcuts(zoom, full, setFull)
7012
7265
  ];
7013
7266
  useHotkeys(shortcuts, { enabled: keys });
@@ -7016,7 +7269,8 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7016
7269
  blind,
7017
7270
  missing,
7018
7271
  imgRef: ref,
7019
- onNatural
7272
+ onNatural,
7273
+ pixelated: rg.active !== null
7020
7274
  });
7021
7275
  const learn = (w, h) => setLearned({
7022
7276
  key: pairKey,
@@ -7024,7 +7278,9 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7024
7278
  });
7025
7279
  const frameProps = {
7026
7280
  viewport,
7027
- setViewport,
7281
+ setViewport: rg.setViewport,
7282
+ onBox: rg.add,
7283
+ outline: rg.peek,
7028
7284
  aspect,
7029
7285
  maxHeight: maxHeight === "viewport" ? VIEWPORT_HEIGHT : maxHeight
7030
7286
  };
@@ -7186,6 +7442,7 @@ function Compare({ label, a, b, blind, missing, mode, onModeChange, modes = ALL_
7186
7442
  })
7187
7443
  ]
7188
7444
  }),
7445
+ /* @__PURE__ */ jsx(RegionChips, { state: rg }),
7189
7446
  mode === "fade" && /* @__PURE__ */ jsxs("div", {
7190
7447
  className: "flex items-center gap-3",
7191
7448
  children: [
@@ -7823,117 +8080,228 @@ function CompareAudio({ label, a, b, blind, missing, levelMatch = true, align =
7823
8080
  ]
7824
8081
  });
7825
8082
  }
7826
- // src/components/compare-video.tsx
7827
- var MODES = [
7828
- "side",
7829
- "swipe",
7830
- "fade",
7831
- "blink"
8083
+ // src/components/video-clock.tsx
8084
+ /** Speeds offered by default: slow motion for sitting on a moment. */
8085
+ var SLOW_RATES = [
8086
+ .1,
8087
+ .25,
8088
+ .5,
8089
+ 1,
8090
+ 1.25,
8091
+ 1.5,
8092
+ 2
7832
8093
  ];
7833
- var MODE_LABEL = {
7834
- side: "Side by side",
7835
- swipe: "Swipe",
7836
- fade: "Fade",
7837
- blink: "Blink"
7838
- };
7839
- function useWidth(ref) {
7840
- const [width, setWidth] = React.useState(0);
7841
- React.useLayoutEffect(() => {
7842
- const el = ref.current;
7843
- if (!el) return;
7844
- const read = () => setWidth(el.getBoundingClientRect().width);
7845
- read();
7846
- if (typeof ResizeObserver === "undefined") return;
7847
- const ro = new ResizeObserver(read);
7848
- ro.observe(el);
7849
- return () => ro.disconnect();
7850
- });
7851
- return width;
7852
- }
7853
- /** Two videos to judge by eye on one clock: side by side, swipe, fade or blink, zoomed together, with matched sound and full screen. */
7854
- function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio = "a", pixelated = "zoomed", maxHeight, keys = true, extraShortcuts = [], footer, className }) {
7855
- const refA = React.useRef(null);
7856
- const refB = React.useRef(null);
7857
- const sa = useMediaElement(refA);
7858
- const sb = useMediaElement(refB);
7859
- const { viewport, setViewport } = useViewport();
7860
- const [full, setFull] = React.useState(false);
7861
- const [divider, setDivider] = React.useState(50);
7862
- const [blend, setBlend] = React.useState(50);
7863
- const [showing, setShowing] = React.useState("a");
8094
+ /** Plays, pauses, seeks, steps and loops any number of videos together. */
8095
+ function useVideoClock({ fps, loop: loopProp, onLoopChange, audio }) {
8096
+ const els = React.useRef(/* @__PURE__ */ new Map());
8097
+ const leaderRef = React.useRef(null);
8098
+ const cleanups = React.useRef(/* @__PURE__ */ new Map());
8099
+ const attachers = React.useRef(/* @__PURE__ */ new Map());
8100
+ const hidden = React.useRef(/* @__PURE__ */ new Set());
8101
+ const [infos, setInfos] = React.useState({});
8102
+ const [wanted, setWanted] = React.useState(false);
8103
+ const wantedRef = React.useRef(false);
8104
+ wantedRef.current = wanted;
8105
+ const [started, setStarted] = React.useState(false);
7864
8106
  const [volume, setVolume] = React.useState(100);
7865
8107
  const [muted, setMuted] = React.useState(false);
7866
- const [wanted, setWanted] = React.useState(false);
7867
- const frameRef = React.useRef(null);
7868
- const frameWidth = useWidth(frameRef);
7869
- const fps = a.media.fps ?? 30;
7870
- const known = [sa.duration, sb.duration].filter((d) => d !== null);
8108
+ const [behind, setBehind] = React.useState(/* @__PURE__ */ new Set());
8109
+ const chosenRate = React.useRef(1);
8110
+ const holdRef = React.useRef(false);
8111
+ const lead = useMediaElement(leaderRef);
8112
+ const active = () => [...els.current.entries()].filter(([i]) => i === 0 || !hidden.current.has(i)).sort((a, b) => a[0] - b[0]).map(([, el]) => el);
8113
+ const start = (el) => {
8114
+ el.play().catch((e) => {
8115
+ if (e instanceof DOMException && e.name === "AbortError") return;
8116
+ setWanted(false);
8117
+ });
8118
+ };
8119
+ const pauseAll = () => {
8120
+ for (const el of els.current.values()) el.pause();
8121
+ };
8122
+ const [ownLoop, setOwnLoop] = React.useState({
8123
+ start: null,
8124
+ end: null
8125
+ });
8126
+ const loop = loopProp ?? ownLoop;
8127
+ const setLoop = (next) => {
8128
+ setOwnLoop(next);
8129
+ onLoopChange?.(next);
8130
+ };
8131
+ const loopRef = React.useRef(loop);
8132
+ loopRef.current = loop;
8133
+ const onEnded = () => {
8134
+ const { start, end } = loopRef.current;
8135
+ const list = active();
8136
+ if (wantedRef.current && start !== null && end !== null) {
8137
+ for (const el of list) el.currentTime = start;
8138
+ for (const el of list) startRef.current(el);
8139
+ return;
8140
+ }
8141
+ setWanted(false);
8142
+ pauseAll();
8143
+ };
8144
+ const startRef = React.useRef(start);
8145
+ startRef.current = start;
8146
+ const onEndedRef = React.useRef(onEnded);
8147
+ onEndedRef.current = onEnded;
8148
+ const refresh = () => {
8149
+ const first = [...els.current.keys()].sort((a, b) => a - b)[0];
8150
+ leaderRef.current = first === void 0 ? null : els.current.get(first) ?? null;
8151
+ };
8152
+ const attach = (index) => {
8153
+ let fn = attachers.current.get(index);
8154
+ if (fn) return fn;
8155
+ fn = (el) => {
8156
+ if (els.current.get(index) === el || !el && !els.current.has(index)) return;
8157
+ cleanups.current.get(index)?.();
8158
+ cleanups.current.delete(index);
8159
+ if (!el) {
8160
+ els.current.delete(index);
8161
+ refresh();
8162
+ setInfos((p) => {
8163
+ const { [index]: _gone, ...rest } = p;
8164
+ return rest;
8165
+ });
8166
+ return;
8167
+ }
8168
+ els.current.set(index, el);
8169
+ refresh();
8170
+ const read = () => setInfos((p) => ({
8171
+ ...p,
8172
+ [index]: {
8173
+ duration: Number.isFinite(el.duration) && el.duration > 0 ? el.duration : null,
8174
+ error: !!el.error && el.error.code !== 1
8175
+ }
8176
+ }));
8177
+ const ended = () => onEndedRef.current();
8178
+ const types = [
8179
+ "loadedmetadata",
8180
+ "durationchange",
8181
+ "error",
8182
+ "emptied",
8183
+ "loadstart"
8184
+ ];
8185
+ for (const t of types) el.addEventListener(t, read);
8186
+ el.addEventListener("ended", ended);
8187
+ cleanups.current.set(index, () => {
8188
+ for (const t of types) el.removeEventListener(t, read);
8189
+ el.removeEventListener("ended", ended);
8190
+ });
8191
+ read();
8192
+ };
8193
+ attachers.current.set(index, fn);
8194
+ return fn;
8195
+ };
8196
+ const known = Object.values(infos).map((i) => i.duration).filter((d) => d !== null);
7871
8197
  const duration = known.length ? Math.min(...known) : null;
7872
- const failed = sa.error || sb.error;
8198
+ const count = Object.keys(infos).length;
8199
+ const loaded = count > 0 && known.length === count;
8200
+ const failed = lead.error !== null || Object.values(infos).some((i) => i.error);
8201
+ const now = () => leaderRef.current?.currentTime ?? lead.time;
7873
8202
  const play = () => {
7874
8203
  setWanted(true);
7875
- sa.play();
7876
- sb.play();
8204
+ setStarted(true);
8205
+ for (const el of active()) start(el);
7877
8206
  };
7878
8207
  const pause = () => {
7879
8208
  setWanted(false);
7880
- sa.pause();
7881
- sb.pause();
8209
+ pauseAll();
7882
8210
  };
7883
8211
  const toggle = () => wanted ? pause() : play();
7884
8212
  const seek = (time) => {
7885
8213
  const t = Math.max(0, duration === null ? time : Math.min(time, duration));
7886
- sa.seek(t);
7887
- sb.seek(t);
8214
+ lead.seek(t);
8215
+ for (const [i, el] of els.current) if (el !== leaderRef.current && !hidden.current.has(i)) el.currentTime = t;
8216
+ };
8217
+ const step = (direction) => {
8218
+ pause();
8219
+ seek(Math.max(0, (Math.floor(now() * fps + 1e-6) + direction + .5) / fps));
7888
8220
  };
7889
- const chosenRate = React.useRef(1);
7890
8221
  const setRate = (rate) => {
7891
8222
  chosenRate.current = rate;
7892
- sa.setRate(rate);
7893
- sb.setRate(rate);
8223
+ for (const el of els.current.values()) {
8224
+ el.defaultPlaybackRate = rate;
8225
+ el.playbackRate = rate;
8226
+ }
7894
8227
  };
7895
- React.useEffect(() => {
7896
- if (sa.ended || sb.ended) {
7897
- setWanted(false);
7898
- refA.current?.pause();
7899
- refB.current?.pause();
8228
+ const setPoint = (point) => {
8229
+ const t = now();
8230
+ const other = point === "start" ? loop.end : loop.start;
8231
+ setLoop(other !== null && (point === "start" ? t >= other : t <= other) ? {
8232
+ start: point === "start" ? t : null,
8233
+ end: point === "end" ? t : null
8234
+ } : {
8235
+ ...loop,
8236
+ [point]: t
8237
+ });
8238
+ };
8239
+ const clearLoop = () => setLoop({
8240
+ start: null,
8241
+ end: null
8242
+ });
8243
+ const setVisible = (index, visible) => {
8244
+ if (index === 0) return;
8245
+ const el = els.current.get(index);
8246
+ if (!visible) {
8247
+ hidden.current.add(index);
8248
+ el?.pause();
8249
+ return;
7900
8250
  }
7901
- }, [sa.ended, sb.ended]);
8251
+ if (!hidden.current.delete(index) || !el) return;
8252
+ el.currentTime = now();
8253
+ el.playbackRate = chosenRate.current;
8254
+ if (wantedRef.current && !holdRef.current) start(el);
8255
+ };
7902
8256
  React.useEffect(() => {
7903
8257
  if (!wanted) return;
7904
8258
  let held = false;
7905
8259
  let frame = requestAnimationFrame(function tick() {
7906
- const A = refA.current;
7907
- const B = refB.current;
7908
- if (A && B && !A.ended && !B.ended) {
7909
- if (!(A.readyState >= 3 && B.readyState >= 3)) {
7910
- if (!held) {
7911
- held = true;
7912
- A.pause();
7913
- B.pause();
7914
- }
8260
+ const list = active();
8261
+ const [L, ...followers] = list;
8262
+ if (L && list.every((el) => !el.ended)) {
8263
+ if (!list.every((el) => el.readyState >= 3)) {
8264
+ held = true;
8265
+ holdRef.current = true;
8266
+ for (const el of list) if (!el.paused) el.pause();
7915
8267
  } else if (held) {
7916
8268
  held = false;
7917
- A.play();
7918
- B.play();
7919
- } else if (!A.paused) {
7920
- const drift = B.currentTime - A.currentTime;
7921
- const one = 1 / fps;
7922
- if (Math.abs(drift) > .3) B.currentTime = A.currentTime;
7923
- else if (Math.abs(drift) > one) B.playbackRate = A.playbackRate * (drift > 0 ? .97 : 1.03);
7924
- else if (Math.abs(drift) < one / 2 && B.playbackRate !== A.playbackRate) B.playbackRate = A.playbackRate;
8269
+ holdRef.current = false;
8270
+ for (const el of list) startRef.current(el);
8271
+ } else if (!L.paused) {
8272
+ const { start, end } = loopRef.current;
8273
+ if (start !== null && end !== null && L.currentTime >= end) for (const el of list) el.currentTime = start;
8274
+ else {
8275
+ const one = 1 / fps;
8276
+ const slow = /* @__PURE__ */ new Set();
8277
+ const indexes = [...els.current.entries()].filter(([, el]) => followers.includes(el)).map(([i]) => i);
8278
+ followers.forEach((el, k) => {
8279
+ const drift = el.currentTime - L.currentTime;
8280
+ if (Math.abs(drift) > .3) el.currentTime = L.currentTime;
8281
+ else if (Math.abs(drift) > one) el.playbackRate = L.playbackRate * (drift > 0 ? .97 : 1.03);
8282
+ else if (Math.abs(drift) < one / 2 && el.playbackRate !== L.playbackRate) el.playbackRate = L.playbackRate;
8283
+ if (Math.abs(drift) > 2 * one) slow.add(indexes[k]);
8284
+ });
8285
+ setBehind((prev) => prev.size === slow.size && [...slow].every((i) => prev.has(i)) ? prev : slow);
8286
+ }
7925
8287
  }
7926
8288
  }
7927
8289
  frame = requestAnimationFrame(tick);
7928
8290
  });
7929
- return () => cancelAnimationFrame(frame);
8291
+ return () => {
8292
+ cancelAnimationFrame(frame);
8293
+ holdRef.current = false;
8294
+ };
7930
8295
  }, [wanted, fps]);
8296
+ React.useEffect(() => {
8297
+ if (!wanted) setBehind((prev) => prev.size ? /* @__PURE__ */ new Set() : prev);
8298
+ }, [wanted]);
7931
8299
  const resume = React.useRef({
7932
8300
  time: 0,
7933
8301
  playing: false
7934
8302
  });
7935
- if (sa.duration !== null) resume.current = {
7936
- time: sa.time,
8303
+ if (lead.duration !== null) resume.current = {
8304
+ time: lead.time,
7937
8305
  playing: wanted
7938
8306
  };
7939
8307
  const restore = (e) => {
@@ -7941,48 +8309,416 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio =
7941
8309
  el.defaultPlaybackRate = chosenRate.current;
7942
8310
  el.playbackRate = chosenRate.current;
7943
8311
  if (resume.current.time > 0) el.currentTime = resume.current.time;
7944
- if (resume.current.playing) el.play();
8312
+ const index = [...els.current.entries()].find(([, e]) => e === el)?.[0];
8313
+ if (resume.current.playing && (index === void 0 || !hidden.current.has(index))) start(el);
7945
8314
  };
7946
8315
  React.useEffect(() => {
7947
- [[refA.current, "a"], [refB.current, "b"]].forEach(([el, side]) => {
7948
- if (!(el instanceof HTMLVideoElement)) return;
7949
- el.muted = audio !== side || muted || volume === 0;
8316
+ for (const [i, el] of els.current) {
8317
+ el.muted = audio !== i || muted || volume === 0;
7950
8318
  el.volume = volume / 100;
7951
- });
8319
+ }
8320
+ });
8321
+ const shortcuts = () => [
8322
+ {
8323
+ keys: [" ", "k"],
8324
+ label: "Play or pause",
8325
+ run: toggle
8326
+ },
8327
+ {
8328
+ keys: ["j"],
8329
+ label: "Back 1 s",
8330
+ run: () => seek(now() - 1),
8331
+ repeat: true
8332
+ },
8333
+ {
8334
+ keys: ["l"],
8335
+ label: "Forward 1 s",
8336
+ run: () => seek(now() + 1),
8337
+ repeat: true
8338
+ },
8339
+ {
8340
+ keys: [","],
8341
+ label: "Back one frame",
8342
+ run: () => step(-1),
8343
+ repeat: true
8344
+ },
8345
+ {
8346
+ keys: ["."],
8347
+ label: "Forward one frame",
8348
+ run: () => step(1),
8349
+ repeat: true
8350
+ },
8351
+ {
8352
+ keys: ["i"],
8353
+ label: "Loop starts here",
8354
+ run: () => setPoint("start")
8355
+ },
8356
+ {
8357
+ keys: ["o"],
8358
+ label: "Loop ends here",
8359
+ run: () => setPoint("end")
8360
+ },
8361
+ {
8362
+ keys: ["c"],
8363
+ label: "Clear the loop",
8364
+ run: clearLoop,
8365
+ disabled: loop.start === null && loop.end === null
8366
+ },
8367
+ ...audio === null ? [] : [{
8368
+ keys: ["m"],
8369
+ label: "Mute",
8370
+ run: () => setMuted((m) => !m)
8371
+ }]
8372
+ ];
8373
+ return {
8374
+ attach,
8375
+ restore,
8376
+ wanted,
8377
+ started,
8378
+ play,
8379
+ pause,
8380
+ toggle,
8381
+ seek,
8382
+ step,
8383
+ setRate,
8384
+ time: lead.time,
8385
+ rate: lead.rate,
8386
+ buffered: lead.buffered,
8387
+ duration,
8388
+ loaded,
8389
+ failed,
8390
+ loop,
8391
+ looping: loop.start !== null && loop.end !== null,
8392
+ setPoint,
8393
+ clearLoop,
8394
+ volume,
8395
+ muted,
8396
+ setVolume: (v) => (setMuted(false), setVolume(v)),
8397
+ behind,
8398
+ setVisible,
8399
+ shortcuts,
8400
+ hasAudio: audio !== null,
8401
+ fps
8402
+ };
8403
+ }
8404
+ /** The transport row (play, step, time, seek bar with moments and the loop's ends, speed, volume) and the loop row, for a clock. */
8405
+ function VideoControls({ clock, rates = SLOW_RATES, moments = [] }) {
8406
+ const { loop, fps } = clock;
8407
+ const at = (t) => t === null ? format.missing : format.timecode(t, {
8408
+ precision: "frames",
8409
+ fps
7952
8410
  });
8411
+ const marks = [
8412
+ ...moments,
8413
+ ...loop.start !== null ? [{
8414
+ time: loop.start,
8415
+ label: "Loop start"
8416
+ }] : [],
8417
+ ...loop.end !== null ? [{
8418
+ time: loop.end,
8419
+ label: "Loop end"
8420
+ }] : []
8421
+ ];
8422
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(Transport, {
8423
+ playing: clock.wanted,
8424
+ onPlayPause: clock.toggle,
8425
+ onStepBack: () => clock.step(-1),
8426
+ onStepForward: () => clock.step(1),
8427
+ children: [
8428
+ /* @__PURE__ */ jsx(TimeReadout, {
8429
+ time: clock.time,
8430
+ duration: clock.duration,
8431
+ precision: "frames",
8432
+ fps
8433
+ }),
8434
+ /* @__PURE__ */ jsx(SeekBar, {
8435
+ time: clock.time,
8436
+ duration: clock.duration,
8437
+ onSeek: clock.seek,
8438
+ marks,
8439
+ onMarkPress: (m) => (clock.pause(), clock.seek(m.time)),
8440
+ buffered: clock.buffered,
8441
+ label: "Position",
8442
+ step: 1,
8443
+ precision: "frames",
8444
+ fps
8445
+ }),
8446
+ /* @__PURE__ */ jsx(RateChoice, {
8447
+ rate: clock.rate,
8448
+ onRateChange: clock.setRate,
8449
+ rates
8450
+ }),
8451
+ clock.hasAudio && /* @__PURE__ */ jsx(VolumeControl, {
8452
+ volume: clock.muted ? 0 : clock.volume,
8453
+ onVolumeChange: clock.setVolume
8454
+ })
8455
+ ]
8456
+ }), /* @__PURE__ */ jsxs("div", {
8457
+ className: "flex flex-wrap items-center gap-2",
8458
+ children: [
8459
+ /* @__PURE__ */ jsx(Button, {
8460
+ size: "sm",
8461
+ onPress: () => clock.setPoint("start"),
8462
+ disabled: clock.duration === null,
8463
+ children: "Loop starts here"
8464
+ }),
8465
+ /* @__PURE__ */ jsx(Button, {
8466
+ size: "sm",
8467
+ onPress: () => clock.setPoint("end"),
8468
+ disabled: clock.duration === null,
8469
+ children: "Loop ends here"
8470
+ }),
8471
+ /* @__PURE__ */ jsx(Button, {
8472
+ size: "sm",
8473
+ variant: "ghost",
8474
+ onPress: clock.clearLoop,
8475
+ disabled: loop.start === null && loop.end === null,
8476
+ children: "Clear the loop"
8477
+ }),
8478
+ /* @__PURE__ */ jsx("span", {
8479
+ role: "status",
8480
+ className: "type-caption tabular-nums text-muted-foreground",
8481
+ children: clock.looping ? `Looping ${at(loop.start)} to ${at(loop.end)}` : loop.start !== null ? `Loop starts at ${at(loop.start)}` : loop.end !== null ? `Loop ends at ${at(loop.end)}` : "No loop"
8482
+ })
8483
+ ]
8484
+ })] });
8485
+ }
8486
+ // src/components/compare-video-grid.tsx
8487
+ var COLUMNS$1 = {
8488
+ 2: "sm:grid-cols-2",
8489
+ 3: "sm:grid-cols-2 lg:grid-cols-3",
8490
+ 4: "sm:grid-cols-2 lg:grid-cols-4"
8491
+ };
8492
+ function Cell$1({ c, index, clock, blind, isReference, children }) {
8493
+ const view = useInView({
8494
+ rootMargin: "200px",
8495
+ unsupported: true
8496
+ });
8497
+ const { setVisible } = clock;
8498
+ const latest = React.useRef(setVisible);
8499
+ latest.current = setVisible;
8500
+ React.useEffect(() => latest.current(index, view.inView), [index, view.inView]);
8501
+ return /* @__PURE__ */ jsxs("figure", {
8502
+ ref: view.ref,
8503
+ className: "grid content-start gap-1.5",
8504
+ children: [/* @__PURE__ */ jsx(Caption, {
8505
+ c,
8506
+ blind: blind && !isReference
8507
+ }), children(!clock.loaded)]
8508
+ });
8509
+ }
8510
+ /** Many videos in a grid on one clock, zoomed and panned together, with regions, a loop, stepping and full screen. */
8511
+ function CompareVideoGrid({ label, items, reference, blind, missing, catchingUp = "Catching up", actions, columns = 3, regions, rates = SLOW_RATES, moments = [], loop, onLoopChange, audio = null, pixelated = "zoomed", keys = true, extraShortcuts = [], footer, className }) {
8512
+ const cells = reference ? [reference, ...items] : [...items];
8513
+ const first = cells[0];
8514
+ const fps = first?.media.fps ?? 30;
8515
+ const audioIndex = audio === null ? null : cells.findIndex((c) => c.id === audio);
8516
+ const clock = useVideoClock({
8517
+ fps,
8518
+ loop,
8519
+ onLoopChange,
8520
+ audio: audioIndex === null || audioIndex < 0 ? null : audioIndex
8521
+ });
8522
+ const { viewport, setViewport } = useViewport();
8523
+ const [full, setFull] = React.useState(false);
8524
+ const frameRef = React.useRef(null);
8525
+ const frameWidth = useWidth(frameRef);
8526
+ const key = cells.map((c) => c.media.src).join("|");
8527
+ const aspect = first ? first.media.width / first.media.height : 4 / 3;
8528
+ const natural = first ? [first.media.width, first.media.height] : null;
8529
+ const rg = useRegions({
8530
+ regions,
8531
+ viewport,
8532
+ setViewport,
8533
+ frame: frameRef,
8534
+ reset: key
8535
+ });
8536
+ const zoom = useZoom({
8537
+ viewport,
8538
+ setViewport: rg.setViewport,
8539
+ frame: frameRef,
8540
+ natural
8541
+ });
8542
+ const shortcuts = [
8543
+ ...extraShortcuts,
8544
+ ...clock.shortcuts(),
8545
+ ...rg.shortcuts,
8546
+ ...zoomShortcuts(zoom, full, setFull)
8547
+ ];
8548
+ useHotkeys(shortcuts, { enabled: keys });
8549
+ const frameHeight = frameWidth / aspect;
8550
+ const sharp = (c, isReference) => {
8551
+ if (isReference || rg.active !== null) return true;
8552
+ if (pixelated !== "zoomed") return pixelated === "always";
8553
+ const drawn = Math.min(frameWidth, frameHeight * (c.media.width / c.media.height));
8554
+ return drawn > 0 && viewport.scale * drawn / c.media.width > 1;
8555
+ };
8556
+ return /* @__PURE__ */ jsx(FullscreenFrame, {
8557
+ label,
8558
+ active: full,
8559
+ onActiveChange: setFull,
8560
+ className,
8561
+ children: /* @__PURE__ */ jsxs("section", {
8562
+ "aria-label": label,
8563
+ className: cn("grid gap-3", full && "min-h-0 flex-1 content-start overflow-auto"),
8564
+ children: [
8565
+ /* @__PURE__ */ jsxs(Toolbar, {
8566
+ label: "Zoom",
8567
+ className: "items-center gap-2",
8568
+ children: [
8569
+ /* @__PURE__ */ jsx(ZoomControls, {
8570
+ viewport,
8571
+ zoom,
8572
+ natural
8573
+ }),
8574
+ /* @__PURE__ */ jsx(ToolbarSeparator, {}),
8575
+ /* @__PURE__ */ jsx(FullscreenButton, {
8576
+ full,
8577
+ setFull
8578
+ })
8579
+ ]
8580
+ }),
8581
+ /* @__PURE__ */ jsx(RegionChips, { state: rg }),
8582
+ clock.failed && /* @__PURE__ */ jsx("p", {
8583
+ role: "alert",
8584
+ className: "type-body-sm text-danger",
8585
+ children: missing
8586
+ }),
8587
+ /* @__PURE__ */ jsx("div", {
8588
+ className: cn("grid gap-3", COLUMNS$1[columns]),
8589
+ children: cells.map((c, i) => {
8590
+ const isReference = reference !== void 0 && i === 0;
8591
+ return /* @__PURE__ */ jsx(Cell$1, {
8592
+ c,
8593
+ index: i,
8594
+ clock,
8595
+ blind,
8596
+ isReference,
8597
+ children: (loading) => /* @__PURE__ */ jsxs(Fragment, { children: [
8598
+ /* @__PURE__ */ jsxs(ViewportFrame, {
8599
+ viewport,
8600
+ setViewport: rg.setViewport,
8601
+ onBox: clock.wanted ? void 0 : rg.add,
8602
+ outline: rg.peek,
8603
+ aspect,
8604
+ maxHeight: VIEWPORT_HEIGHT,
8605
+ label: `Frame ${c.label}`,
8606
+ ref: i === 0 ? frameRef : void 0,
8607
+ children: [loading && /* @__PURE__ */ jsx(Skeleton, {
8608
+ "aria-hidden": true,
8609
+ className: "absolute inset-0 size-full rounded-none"
8610
+ }), /* @__PURE__ */ jsx("video", {
8611
+ ref: clock.attach(i),
8612
+ src: c.media.src,
8613
+ poster: c.media.poster,
8614
+ preload: clock.started ? "auto" : "metadata",
8615
+ playsInline: true,
8616
+ "aria-label": `Video ${c.label}`,
8617
+ onLoadedMetadata: (e) => {
8618
+ clock.restore(e);
8619
+ const v = e.currentTarget;
8620
+ if (v.currentTime === 0 && v.readyState < 2) v.currentTime = .001;
8621
+ },
8622
+ style: sharp(c, isReference) ? { imageRendering: "pixelated" } : void 0,
8623
+ className: "absolute inset-0 size-full object-contain"
8624
+ })]
8625
+ }),
8626
+ clock.behind.has(i) && /* @__PURE__ */ jsx("p", {
8627
+ role: "status",
8628
+ className: "type-caption text-muted-foreground",
8629
+ children: catchingUp
8630
+ }),
8631
+ actions && !isReference && /* @__PURE__ */ jsx("div", {
8632
+ className: "flex flex-wrap gap-2",
8633
+ children: actions(c)
8634
+ })
8635
+ ] })
8636
+ }, c.id);
8637
+ })
8638
+ }),
8639
+ /* @__PURE__ */ jsx(VideoControls, {
8640
+ clock,
8641
+ rates,
8642
+ moments
8643
+ }),
8644
+ footer,
8645
+ keys && /* @__PURE__ */ jsx(KeysLegend, { shortcuts })
8646
+ ]
8647
+ })
8648
+ });
8649
+ }
8650
+ // src/components/compare-video.tsx
8651
+ var MODES = [
8652
+ "side",
8653
+ "swipe",
8654
+ "fade",
8655
+ "blink"
8656
+ ];
8657
+ var MODE_LABEL = {
8658
+ side: "Side by side",
8659
+ swipe: "Swipe",
8660
+ fade: "Fade",
8661
+ blink: "Blink"
8662
+ };
8663
+ /** Two videos to judge by eye on one clock: side by side, swipe, fade or blink, zoomed together, with matched sound and full screen. */
8664
+ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates = SLOW_RATES, regions, moments = [], loop: loopProp, onLoopChange, audio = "a", pixelated = "zoomed", maxHeight, keys = true, extraShortcuts = [], footer, className }) {
8665
+ const clock = useVideoClock({
8666
+ fps: a.media.fps ?? 30,
8667
+ loop: loopProp,
8668
+ onLoopChange,
8669
+ audio: audio === "none" ? null : audio === "a" ? 0 : 1
8670
+ });
8671
+ const { viewport, setViewport } = useViewport();
8672
+ const [full, setFull] = React.useState(false);
8673
+ const [divider, setDivider] = React.useState(50);
8674
+ const [blend, setBlend] = React.useState(50);
8675
+ const [showing, setShowing] = React.useState("a");
8676
+ const frameRef = React.useRef(null);
8677
+ const frameWidth = useWidth(frameRef);
8678
+ const { wanted, failed } = clock;
7953
8679
  const aspect = a.media.width / a.media.height;
7954
8680
  const natural = [a.media.width, a.media.height];
7955
8681
  const frameHeight = frameWidth / aspect;
7956
8682
  const sharpFor = (c) => {
8683
+ if (rg.active !== null) return true;
7957
8684
  if (pixelated !== "zoomed") return pixelated === "always";
7958
8685
  const drawn = Math.min(frameWidth, frameHeight * (c.media.width / c.media.height));
7959
8686
  return drawn > 0 && viewport.scale * drawn / c.media.width > 1;
7960
8687
  };
7961
- const zoom = useZoom({
8688
+ const rg = useRegions({
8689
+ regions,
7962
8690
  viewport,
7963
8691
  setViewport,
7964
8692
  frame: frameRef,
8693
+ reset: `${a.media.src}|${b.media.src}`
8694
+ });
8695
+ const zoom = useZoom({
8696
+ viewport,
8697
+ setViewport: rg.setViewport,
8698
+ frame: frameRef,
7965
8699
  natural
7966
8700
  });
7967
8701
  const flip = () => setShowing((s) => s === "a" ? "b" : "a");
7968
- const video = (c, ref) => /* @__PURE__ */ jsx("video", {
7969
- ref,
8702
+ const video = (c, index) => /* @__PURE__ */ jsx("video", {
8703
+ ref: clock.attach(index),
7970
8704
  src: c.media.src,
7971
8705
  poster: c.media.poster,
7972
8706
  preload: "auto",
7973
8707
  playsInline: true,
7974
8708
  "aria-label": `Video ${c.label}`,
7975
- onLoadedMetadata: restore,
8709
+ onLoadedMetadata: clock.restore,
7976
8710
  style: sharpFor(c) ? { imageRendering: "pixelated" } : void 0,
7977
8711
  className: "absolute inset-0 size-full object-contain"
7978
8712
  });
7979
- const skeleton = !failed && (sa.duration === null || sb.duration === null) && /* @__PURE__ */ jsx(Skeleton, {
8713
+ const skeleton = !failed && !clock.loaded && /* @__PURE__ */ jsx(Skeleton, {
7980
8714
  "aria-hidden": true,
7981
8715
  className: "absolute inset-0 size-full rounded-none"
7982
8716
  });
7983
8717
  const frameProps = {
7984
8718
  viewport,
7985
- setViewport,
8719
+ setViewport: rg.setViewport,
8720
+ onBox: wanted ? void 0 : rg.add,
8721
+ outline: rg.peek,
7986
8722
  aspect,
7987
8723
  maxHeight: maxHeight === "viewport" ? VIEWPORT_HEIGHT : maxHeight
7988
8724
  };
@@ -7999,35 +8735,15 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio =
7999
8735
  run: flip,
8000
8736
  disabled: mode !== "blink"
8001
8737
  },
8002
- {
8003
- keys: [" ", "k"],
8004
- label: "Play or pause",
8005
- run: toggle
8006
- },
8007
- {
8008
- keys: ["j"],
8009
- label: "Back 1 s",
8010
- run: () => seek(sa.time - 1),
8011
- repeat: true
8012
- },
8013
- {
8014
- keys: ["l"],
8015
- label: "Forward 1 s",
8016
- run: () => seek(sa.time + 1),
8017
- repeat: true
8018
- },
8019
- ...audio === "none" ? [] : [{
8020
- keys: ["m"],
8021
- label: "Mute",
8022
- run: () => setMuted((m) => !m)
8023
- }],
8738
+ ...clock.shortcuts(),
8739
+ ...rg.shortcuts,
8024
8740
  ...zoomShortcuts(zoom, full, setFull)
8025
8741
  ];
8026
8742
  useHotkeys(shortcuts, { enabled: keys });
8027
8743
  let body;
8028
8744
  if (mode === "side") body = /* @__PURE__ */ jsx("div", {
8029
8745
  className: "grid gap-3 sm:grid-cols-2",
8030
- children: [[a, refA], [b, refB]].map(([c, ref], i) => /* @__PURE__ */ jsxs("figure", {
8746
+ children: [a, b].map((c, i) => /* @__PURE__ */ jsxs("figure", {
8031
8747
  className: "grid gap-1.5",
8032
8748
  children: [/* @__PURE__ */ jsx(Caption, {
8033
8749
  c,
@@ -8036,7 +8752,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio =
8036
8752
  ...frameProps,
8037
8753
  label: `Frame ${c.label}`,
8038
8754
  ref: i === 0 ? frameRef : void 0,
8039
- children: [i === 0 && skeleton, video(c, ref)]
8755
+ children: [i === 0 && skeleton, video(c, i)]
8040
8756
  })]
8041
8757
  }, i))
8042
8758
  });
@@ -8058,7 +8774,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio =
8058
8774
  ...frameProps,
8059
8775
  ref: frameRef,
8060
8776
  cover: mode === "swipe" ? {
8061
- content: video(a, refA),
8777
+ content: video(a, 0),
8062
8778
  shown: divider
8063
8779
  } : void 0,
8064
8780
  label: mode === "blink" ? `Frame ${(showing === "a" ? a : b).label}` : `${a.label} over ${b.label}`,
@@ -8087,11 +8803,11 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio =
8087
8803
  }),
8088
8804
  children: [
8089
8805
  skeleton,
8090
- video(b, refB),
8806
+ video(b, 1),
8091
8807
  mode !== "swipe" && /* @__PURE__ */ jsx("div", {
8092
8808
  className: "absolute inset-0",
8093
8809
  style: mode === "fade" ? { opacity: 1 - blend / 100 } : mode === "blink" ? { opacity: showing === "a" ? 1 : 0 } : void 0,
8094
- children: video(a, refA)
8810
+ children: video(a, 0)
8095
8811
  })
8096
8812
  ]
8097
8813
  })]
@@ -8132,6 +8848,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio =
8132
8848
  })
8133
8849
  ]
8134
8850
  }),
8851
+ /* @__PURE__ */ jsx(RegionChips, { state: rg }),
8135
8852
  mode === "fade" && /* @__PURE__ */ jsxs("div", {
8136
8853
  className: "flex items-center gap-3",
8137
8854
  children: [
@@ -8175,33 +8892,10 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, audio =
8175
8892
  children: missing
8176
8893
  }),
8177
8894
  body,
8178
- /* @__PURE__ */ jsxs(Transport, {
8179
- playing: wanted,
8180
- onPlayPause: toggle,
8181
- children: [
8182
- /* @__PURE__ */ jsx(TimeReadout, {
8183
- time: sa.time,
8184
- duration
8185
- }),
8186
- /* @__PURE__ */ jsx(SeekBar, {
8187
- time: sa.time,
8188
- duration,
8189
- onSeek: seek,
8190
- buffered: sa.buffered,
8191
- label: "Position",
8192
- step: 1,
8193
- precision: "frames",
8194
- fps
8195
- }),
8196
- /* @__PURE__ */ jsx(RateChoice, {
8197
- rate: sa.rate,
8198
- onRateChange: setRate
8199
- }),
8200
- audio !== "none" && /* @__PURE__ */ jsx(VolumeControl, {
8201
- volume: muted ? 0 : volume,
8202
- onVolumeChange: (v) => (setMuted(false), setVolume(v))
8203
- })
8204
- ]
8895
+ /* @__PURE__ */ jsx(VideoControls, {
8896
+ clock,
8897
+ rates,
8898
+ moments
8205
8899
  }),
8206
8900
  footer,
8207
8901
  keys && /* @__PURE__ */ jsx(KeysLegend, { shortcuts })
@@ -8398,7 +9092,7 @@ var COLUMNS = {
8398
9092
  4: "sm:grid-cols-2 lg:grid-cols-4"
8399
9093
  };
8400
9094
  /** Many pictures in a grid, zoomed and panned together, and full screen. */
8401
- function CompareGrid({ label, items, blind, missing, actions, columns = 3, keys = true, className }) {
9095
+ function CompareGrid({ label, items, blind, missing, actions, columns = 3, regions, keys = true, className }) {
8402
9096
  const { viewport, setViewport } = useViewport();
8403
9097
  const [full, setFull] = React.useState(false);
8404
9098
  const key = items.map((i) => i.media.src).join("|");
@@ -8406,13 +9100,20 @@ function CompareGrid({ label, items, blind, missing, actions, columns = 3, keys
8406
9100
  const natural = items[0]?.media.size ?? (learned?.key === key ? learned.size : null);
8407
9101
  const aspect = natural ? natural[0] / natural[1] : 3 / 2;
8408
9102
  const first = React.useRef(null);
8409
- const zoom = useZoom({
9103
+ const rg = useRegions({
9104
+ regions,
8410
9105
  viewport,
8411
9106
  setViewport,
8412
9107
  frame: first,
9108
+ reset: key
9109
+ });
9110
+ const zoom = useZoom({
9111
+ viewport,
9112
+ setViewport: rg.setViewport,
9113
+ frame: first,
8413
9114
  natural
8414
9115
  });
8415
- const shortcuts = zoomShortcuts(zoom, full, setFull);
9116
+ const shortcuts = [...rg.shortcuts, ...zoomShortcuts(zoom, full, setFull)];
8416
9117
  useHotkeys(shortcuts, { enabled: keys });
8417
9118
  return /* @__PURE__ */ jsx(FullscreenFrame, {
8418
9119
  label,
@@ -8439,6 +9140,7 @@ function CompareGrid({ label, items, blind, missing, actions, columns = 3, keys
8439
9140
  })
8440
9141
  ]
8441
9142
  }),
9143
+ /* @__PURE__ */ jsx(RegionChips, { state: rg }),
8442
9144
  /* @__PURE__ */ jsx("div", {
8443
9145
  className: cn("grid gap-3", COLUMNS[columns]),
8444
9146
  children: items.map((c, i) => /* @__PURE__ */ jsxs("figure", {
@@ -8450,7 +9152,9 @@ function CompareGrid({ label, items, blind, missing, actions, columns = 3, keys
8450
9152
  }),
8451
9153
  /* @__PURE__ */ jsx(ViewportFrame, {
8452
9154
  viewport,
8453
- setViewport,
9155
+ setViewport: rg.setViewport,
9156
+ onBox: rg.add,
9157
+ outline: rg.peek,
8454
9158
  aspect,
8455
9159
  label: blind ? `Picture ${c.label}` : c.label,
8456
9160
  ref: i === 0 ? first : void 0,
@@ -8458,6 +9162,7 @@ function CompareGrid({ label, items, blind, missing, actions, columns = 3, keys
8458
9162
  c,
8459
9163
  blind,
8460
9164
  missing,
9165
+ pixelated: rg.active !== null,
8461
9166
  onNatural: i === 0 ? (w, h) => setLearned({
8462
9167
  key,
8463
9168
  size: [w, h]
@@ -9123,6 +9828,6 @@ function SaveStatus({ state, onRetry, className }) {
9123
9828
  ]
9124
9829
  });
9125
9830
  }
9126
- export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, 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 };
9831
+ export { ActiveList, Alert, AlertDialog, AppShell, AsyncButton, Breadcrumb, BulkBar, Button, COLOR_SCHEME_STORAGE_KEY, Checkbox, ChoiceGroup, ColorField, ColorSchemeChoice, CommandLegend, CommandMenu, Compare, CompareAudio, CompareGrid, CompareText, CompareVideo, CompareVideoGrid, 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, boxViewport, 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, regionShares, 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 };
9127
9832
 
9128
9833
  //# sourceMappingURL=index.js.map