strata-react 1.0.31 → 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
@@ -6724,6 +6724,21 @@ function FullscreenButton({ full, setFull }) {
6724
6724
  onPress: () => setFull(!full)
6725
6725
  });
6726
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
+ }
6727
6742
  // src/lib/image-diff.ts
6728
6743
  /** The longest side, in pixels, a picture is compared at. */
6729
6744
  var MAX_SIDE = 2048;
@@ -8065,19 +8080,8 @@ function CompareAudio({ label, a, b, blind, missing, levelMatch = true, align =
8065
8080
  ]
8066
8081
  });
8067
8082
  }
8068
- // src/components/compare-video.tsx
8069
- var MODES = [
8070
- "side",
8071
- "swipe",
8072
- "fade",
8073
- "blink"
8074
- ];
8075
- var MODE_LABEL = {
8076
- side: "Side by side",
8077
- swipe: "Swipe",
8078
- fade: "Fade",
8079
- blink: "Blink"
8080
- };
8083
+ // src/components/video-clock.tsx
8084
+ /** Speeds offered by default: slow motion for sitting on a moment. */
8081
8085
  var SLOW_RATES = [
8082
8086
  .1,
8083
8087
  .25,
@@ -8087,73 +8091,140 @@ var SLOW_RATES = [
8087
8091
  1.5,
8088
8092
  2
8089
8093
  ];
8090
- function useWidth(ref) {
8091
- const [width, setWidth] = React.useState(0);
8092
- React.useLayoutEffect(() => {
8093
- const el = ref.current;
8094
- if (!el) return;
8095
- const read = () => setWidth(el.getBoundingClientRect().width);
8096
- read();
8097
- if (typeof ResizeObserver === "undefined") return;
8098
- const ro = new ResizeObserver(read);
8099
- ro.observe(el);
8100
- return () => ro.disconnect();
8101
- });
8102
- return width;
8103
- }
8104
- /** Two videos to judge by eye on one clock: side by side, swipe, fade or blink, zoomed together, with matched sound and full screen. */
8105
- 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 }) {
8106
- const refA = React.useRef(null);
8107
- const refB = React.useRef(null);
8108
- const sa = useMediaElement(refA);
8109
- const sb = useMediaElement(refB);
8110
- const { viewport, setViewport } = useViewport();
8111
- const [full, setFull] = React.useState(false);
8112
- const [divider, setDivider] = React.useState(50);
8113
- const [blend, setBlend] = React.useState(50);
8114
- 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);
8115
8106
  const [volume, setVolume] = React.useState(100);
8116
8107
  const [muted, setMuted] = React.useState(false);
8117
- const [wanted, setWanted] = React.useState(false);
8118
- const frameRef = React.useRef(null);
8119
- const frameWidth = useWidth(frameRef);
8120
- const fps = a.media.fps ?? 30;
8121
- 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);
8122
8197
  const duration = known.length ? Math.min(...known) : null;
8123
- 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;
8124
8202
  const play = () => {
8125
8203
  setWanted(true);
8126
- sa.play();
8127
- sb.play();
8204
+ setStarted(true);
8205
+ for (const el of active()) start(el);
8128
8206
  };
8129
8207
  const pause = () => {
8130
8208
  setWanted(false);
8131
- sa.pause();
8132
- sb.pause();
8209
+ pauseAll();
8133
8210
  };
8134
8211
  const toggle = () => wanted ? pause() : play();
8135
8212
  const seek = (time) => {
8136
8213
  const t = Math.max(0, duration === null ? time : Math.min(time, duration));
8137
- sa.seek(t);
8138
- 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;
8139
8216
  };
8140
- const now = () => refA.current?.currentTime ?? sa.time;
8141
8217
  const step = (direction) => {
8142
8218
  pause();
8143
- const frame = Math.floor(now() * fps + 1e-6);
8144
- seek(Math.max(0, (frame + direction + .5) / fps));
8219
+ seek(Math.max(0, (Math.floor(now() * fps + 1e-6) + direction + .5) / fps));
8145
8220
  };
8146
- const [ownLoop, setOwnLoop] = React.useState({
8147
- start: null,
8148
- end: null
8149
- });
8150
- const loop = loopProp ?? ownLoop;
8151
- const setLoop = (next) => {
8152
- setOwnLoop(next);
8153
- onLoopChange?.(next);
8221
+ const setRate = (rate) => {
8222
+ chosenRate.current = rate;
8223
+ for (const el of els.current.values()) {
8224
+ el.defaultPlaybackRate = rate;
8225
+ el.playbackRate = rate;
8226
+ }
8154
8227
  };
8155
- const loopRef = React.useRef(loop);
8156
- loopRef.current = loop;
8157
8228
  const setPoint = (point) => {
8158
8229
  const t = now();
8159
8230
  const other = point === "start" ? loop.end : loop.start;
@@ -8169,71 +8240,68 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8169
8240
  start: null,
8170
8241
  end: null
8171
8242
  });
8172
- const looping = loop.start !== null && loop.end !== null;
8173
- const chosenRate = React.useRef(1);
8174
- const setRate = (rate) => {
8175
- chosenRate.current = rate;
8176
- sa.setRate(rate);
8177
- sb.setRate(rate);
8178
- };
8179
- React.useEffect(() => {
8180
- if (!(sa.ended || sb.ended)) return;
8181
- const { start, end } = loopRef.current;
8182
- const A = refA.current;
8183
- const B = refB.current;
8184
- if (wanted && start !== null && end !== null && A && B) {
8185
- A.currentTime = start;
8186
- B.currentTime = start;
8187
- A.play();
8188
- B.play();
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();
8189
8249
  return;
8190
8250
  }
8191
- setWanted(false);
8192
- A?.pause();
8193
- B?.pause();
8194
- }, [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
+ };
8195
8256
  React.useEffect(() => {
8196
8257
  if (!wanted) return;
8197
8258
  let held = false;
8198
8259
  let frame = requestAnimationFrame(function tick() {
8199
- const A = refA.current;
8200
- const B = refB.current;
8201
- if (A && B && !A.ended && !B.ended) {
8202
- if (!(A.readyState >= 3 && B.readyState >= 3)) {
8203
- if (!held) {
8204
- held = true;
8205
- A.pause();
8206
- B.pause();
8207
- }
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();
8208
8267
  } else if (held) {
8209
8268
  held = false;
8210
- A.play();
8211
- B.play();
8212
- } else if (!A.paused) {
8269
+ holdRef.current = false;
8270
+ for (const el of list) startRef.current(el);
8271
+ } else if (!L.paused) {
8213
8272
  const { start, end } = loopRef.current;
8214
- if (start !== null && end !== null && A.currentTime >= end) {
8215
- A.currentTime = start;
8216
- B.currentTime = start;
8217
- frame = requestAnimationFrame(tick);
8218
- return;
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);
8219
8286
  }
8220
- const drift = B.currentTime - A.currentTime;
8221
- const one = 1 / fps;
8222
- if (Math.abs(drift) > .3) B.currentTime = A.currentTime;
8223
- else if (Math.abs(drift) > one) B.playbackRate = A.playbackRate * (drift > 0 ? .97 : 1.03);
8224
- else if (Math.abs(drift) < one / 2 && B.playbackRate !== A.playbackRate) B.playbackRate = A.playbackRate;
8225
8287
  }
8226
8288
  }
8227
8289
  frame = requestAnimationFrame(tick);
8228
8290
  });
8229
- return () => cancelAnimationFrame(frame);
8291
+ return () => {
8292
+ cancelAnimationFrame(frame);
8293
+ holdRef.current = false;
8294
+ };
8230
8295
  }, [wanted, fps]);
8296
+ React.useEffect(() => {
8297
+ if (!wanted) setBehind((prev) => prev.size ? /* @__PURE__ */ new Set() : prev);
8298
+ }, [wanted]);
8231
8299
  const resume = React.useRef({
8232
8300
  time: 0,
8233
8301
  playing: false
8234
8302
  });
8235
- if (sa.duration !== null) resume.current = {
8236
- time: sa.time,
8303
+ if (lead.duration !== null) resume.current = {
8304
+ time: lead.time,
8237
8305
  playing: wanted
8238
8306
  };
8239
8307
  const restore = (e) => {
@@ -8241,74 +8309,16 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8241
8309
  el.defaultPlaybackRate = chosenRate.current;
8242
8310
  el.playbackRate = chosenRate.current;
8243
8311
  if (resume.current.time > 0) el.currentTime = resume.current.time;
8244
- 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);
8245
8314
  };
8246
8315
  React.useEffect(() => {
8247
- [[refA.current, "a"], [refB.current, "b"]].forEach(([el, side]) => {
8248
- if (!(el instanceof HTMLVideoElement)) return;
8249
- el.muted = audio !== side || muted || volume === 0;
8316
+ for (const [i, el] of els.current) {
8317
+ el.muted = audio !== i || muted || volume === 0;
8250
8318
  el.volume = volume / 100;
8251
- });
8252
- });
8253
- const aspect = a.media.width / a.media.height;
8254
- const natural = [a.media.width, a.media.height];
8255
- const frameHeight = frameWidth / aspect;
8256
- const sharpFor = (c) => {
8257
- if (rg.active !== null) return true;
8258
- if (pixelated !== "zoomed") return pixelated === "always";
8259
- const drawn = Math.min(frameWidth, frameHeight * (c.media.width / c.media.height));
8260
- return drawn > 0 && viewport.scale * drawn / c.media.width > 1;
8261
- };
8262
- const rg = useRegions({
8263
- regions,
8264
- viewport,
8265
- setViewport,
8266
- frame: frameRef,
8267
- reset: `${a.media.src}|${b.media.src}`
8268
- });
8269
- const zoom = useZoom({
8270
- viewport,
8271
- setViewport: rg.setViewport,
8272
- frame: frameRef,
8273
- natural
8274
- });
8275
- const flip = () => setShowing((s) => s === "a" ? "b" : "a");
8276
- const video = (c, ref) => /* @__PURE__ */ jsx("video", {
8277
- ref,
8278
- src: c.media.src,
8279
- poster: c.media.poster,
8280
- preload: "auto",
8281
- playsInline: true,
8282
- "aria-label": `Video ${c.label}`,
8283
- onLoadedMetadata: restore,
8284
- style: sharpFor(c) ? { imageRendering: "pixelated" } : void 0,
8285
- className: "absolute inset-0 size-full object-contain"
8286
- });
8287
- const skeleton = !failed && (sa.duration === null || sb.duration === null) && /* @__PURE__ */ jsx(Skeleton, {
8288
- "aria-hidden": true,
8289
- className: "absolute inset-0 size-full rounded-none"
8319
+ }
8290
8320
  });
8291
- const frameProps = {
8292
- viewport,
8293
- setViewport: rg.setViewport,
8294
- onBox: wanted ? void 0 : rg.add,
8295
- outline: rg.peek,
8296
- aspect,
8297
- maxHeight: maxHeight === "viewport" ? VIEWPORT_HEIGHT : maxHeight
8298
- };
8299
- const shortcuts = [
8300
- ...extraShortcuts,
8301
- ...MODES.map((m, i) => ({
8302
- keys: [String(i + 1)],
8303
- label: MODE_LABEL[m],
8304
- run: () => onModeChange(m)
8305
- })),
8306
- {
8307
- keys: ["x"],
8308
- label: `Flip ${a.label} and ${b.label}`,
8309
- run: flip,
8310
- disabled: mode !== "blink"
8311
- },
8321
+ const shortcuts = () => [
8312
8322
  {
8313
8323
  keys: [" ", "k"],
8314
8324
  label: "Play or pause",
@@ -8317,13 +8327,13 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8317
8327
  {
8318
8328
  keys: ["j"],
8319
8329
  label: "Back 1 s",
8320
- run: () => seek(sa.time - 1),
8330
+ run: () => seek(now() - 1),
8321
8331
  repeat: true
8322
8332
  },
8323
8333
  {
8324
8334
  keys: ["l"],
8325
8335
  label: "Forward 1 s",
8326
- run: () => seek(sa.time + 1),
8336
+ run: () => seek(now() + 1),
8327
8337
  repeat: true
8328
8338
  },
8329
8339
  {
@@ -8354,15 +8364,46 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8354
8364
  run: clearLoop,
8355
8365
  disabled: loop.start === null && loop.end === null
8356
8366
  },
8357
- ...audio === "none" ? [] : [{
8367
+ ...audio === null ? [] : [{
8358
8368
  keys: ["m"],
8359
8369
  label: "Mute",
8360
8370
  run: () => setMuted((m) => !m)
8361
- }],
8362
- ...rg.shortcuts,
8363
- ...zoomShortcuts(zoom, full, setFull)
8371
+ }]
8364
8372
  ];
8365
- useHotkeys(shortcuts, { enabled: keys });
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;
8366
8407
  const at = (t) => t === null ? format.missing : format.timecode(t, {
8367
8408
  precision: "frames",
8368
8409
  fps
@@ -8378,10 +8419,331 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8378
8419
  label: "Loop end"
8379
8420
  }] : []
8380
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;
8679
+ const aspect = a.media.width / a.media.height;
8680
+ const natural = [a.media.width, a.media.height];
8681
+ const frameHeight = frameWidth / aspect;
8682
+ const sharpFor = (c) => {
8683
+ if (rg.active !== null) return true;
8684
+ if (pixelated !== "zoomed") return pixelated === "always";
8685
+ const drawn = Math.min(frameWidth, frameHeight * (c.media.width / c.media.height));
8686
+ return drawn > 0 && viewport.scale * drawn / c.media.width > 1;
8687
+ };
8688
+ const rg = useRegions({
8689
+ regions,
8690
+ viewport,
8691
+ setViewport,
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,
8699
+ natural
8700
+ });
8701
+ const flip = () => setShowing((s) => s === "a" ? "b" : "a");
8702
+ const video = (c, index) => /* @__PURE__ */ jsx("video", {
8703
+ ref: clock.attach(index),
8704
+ src: c.media.src,
8705
+ poster: c.media.poster,
8706
+ preload: "auto",
8707
+ playsInline: true,
8708
+ "aria-label": `Video ${c.label}`,
8709
+ onLoadedMetadata: clock.restore,
8710
+ style: sharpFor(c) ? { imageRendering: "pixelated" } : void 0,
8711
+ className: "absolute inset-0 size-full object-contain"
8712
+ });
8713
+ const skeleton = !failed && !clock.loaded && /* @__PURE__ */ jsx(Skeleton, {
8714
+ "aria-hidden": true,
8715
+ className: "absolute inset-0 size-full rounded-none"
8716
+ });
8717
+ const frameProps = {
8718
+ viewport,
8719
+ setViewport: rg.setViewport,
8720
+ onBox: wanted ? void 0 : rg.add,
8721
+ outline: rg.peek,
8722
+ aspect,
8723
+ maxHeight: maxHeight === "viewport" ? VIEWPORT_HEIGHT : maxHeight
8724
+ };
8725
+ const shortcuts = [
8726
+ ...extraShortcuts,
8727
+ ...MODES.map((m, i) => ({
8728
+ keys: [String(i + 1)],
8729
+ label: MODE_LABEL[m],
8730
+ run: () => onModeChange(m)
8731
+ })),
8732
+ {
8733
+ keys: ["x"],
8734
+ label: `Flip ${a.label} and ${b.label}`,
8735
+ run: flip,
8736
+ disabled: mode !== "blink"
8737
+ },
8738
+ ...clock.shortcuts(),
8739
+ ...rg.shortcuts,
8740
+ ...zoomShortcuts(zoom, full, setFull)
8741
+ ];
8742
+ useHotkeys(shortcuts, { enabled: keys });
8381
8743
  let body;
8382
8744
  if (mode === "side") body = /* @__PURE__ */ jsx("div", {
8383
8745
  className: "grid gap-3 sm:grid-cols-2",
8384
- children: [[a, refA], [b, refB]].map(([c, ref], i) => /* @__PURE__ */ jsxs("figure", {
8746
+ children: [a, b].map((c, i) => /* @__PURE__ */ jsxs("figure", {
8385
8747
  className: "grid gap-1.5",
8386
8748
  children: [/* @__PURE__ */ jsx(Caption, {
8387
8749
  c,
@@ -8390,7 +8752,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8390
8752
  ...frameProps,
8391
8753
  label: `Frame ${c.label}`,
8392
8754
  ref: i === 0 ? frameRef : void 0,
8393
- children: [i === 0 && skeleton, video(c, ref)]
8755
+ children: [i === 0 && skeleton, video(c, i)]
8394
8756
  })]
8395
8757
  }, i))
8396
8758
  });
@@ -8412,7 +8774,7 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8412
8774
  ...frameProps,
8413
8775
  ref: frameRef,
8414
8776
  cover: mode === "swipe" ? {
8415
- content: video(a, refA),
8777
+ content: video(a, 0),
8416
8778
  shown: divider
8417
8779
  } : void 0,
8418
8780
  label: mode === "blink" ? `Frame ${(showing === "a" ? a : b).label}` : `${a.label} over ${b.label}`,
@@ -8441,11 +8803,11 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8441
8803
  }),
8442
8804
  children: [
8443
8805
  skeleton,
8444
- video(b, refB),
8806
+ video(b, 1),
8445
8807
  mode !== "swipe" && /* @__PURE__ */ jsx("div", {
8446
8808
  className: "absolute inset-0",
8447
8809
  style: mode === "fade" ? { opacity: 1 - blend / 100 } : mode === "blink" ? { opacity: showing === "a" ? 1 : 0 } : void 0,
8448
- children: video(a, refA)
8810
+ children: video(a, 0)
8449
8811
  })
8450
8812
  ]
8451
8813
  })]
@@ -8530,69 +8892,10 @@ function CompareVideo({ label, a, b, blind, missing, mode, onModeChange, rates =
8530
8892
  children: missing
8531
8893
  }),
8532
8894
  body,
8533
- /* @__PURE__ */ jsxs(Transport, {
8534
- playing: wanted,
8535
- onPlayPause: toggle,
8536
- onStepBack: () => step(-1),
8537
- onStepForward: () => step(1),
8538
- children: [
8539
- /* @__PURE__ */ jsx(TimeReadout, {
8540
- time: sa.time,
8541
- duration,
8542
- precision: "frames",
8543
- fps
8544
- }),
8545
- /* @__PURE__ */ jsx(SeekBar, {
8546
- time: sa.time,
8547
- duration,
8548
- onSeek: seek,
8549
- marks,
8550
- onMarkPress: (m) => (pause(), seek(m.time)),
8551
- buffered: sa.buffered,
8552
- label: "Position",
8553
- step: 1,
8554
- precision: "frames",
8555
- fps
8556
- }),
8557
- /* @__PURE__ */ jsx(RateChoice, {
8558
- rate: sa.rate,
8559
- onRateChange: setRate,
8560
- rates
8561
- }),
8562
- audio !== "none" && /* @__PURE__ */ jsx(VolumeControl, {
8563
- volume: muted ? 0 : volume,
8564
- onVolumeChange: (v) => (setMuted(false), setVolume(v))
8565
- })
8566
- ]
8567
- }),
8568
- /* @__PURE__ */ jsxs("div", {
8569
- className: "flex flex-wrap items-center gap-2",
8570
- children: [
8571
- /* @__PURE__ */ jsx(Button, {
8572
- size: "sm",
8573
- onPress: () => setPoint("start"),
8574
- disabled: duration === null,
8575
- children: "Loop starts here"
8576
- }),
8577
- /* @__PURE__ */ jsx(Button, {
8578
- size: "sm",
8579
- onPress: () => setPoint("end"),
8580
- disabled: duration === null,
8581
- children: "Loop ends here"
8582
- }),
8583
- /* @__PURE__ */ jsx(Button, {
8584
- size: "sm",
8585
- variant: "ghost",
8586
- onPress: clearLoop,
8587
- disabled: loop.start === null && loop.end === null,
8588
- children: "Clear the loop"
8589
- }),
8590
- /* @__PURE__ */ jsx("span", {
8591
- role: "status",
8592
- className: "type-caption tabular-nums text-muted-foreground",
8593
- children: 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"
8594
- })
8595
- ]
8895
+ /* @__PURE__ */ jsx(VideoControls, {
8896
+ clock,
8897
+ rates,
8898
+ moments
8596
8899
  }),
8597
8900
  footer,
8598
8901
  keys && /* @__PURE__ */ jsx(KeysLegend, { shortcuts })
@@ -9525,6 +9828,6 @@ function SaveStatus({ state, onRetry, className }) {
9525
9828
  ]
9526
9829
  });
9527
9830
  }
9528
- 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, 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 };
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 };
9529
9832
 
9530
9833
  //# sourceMappingURL=index.js.map