@bendyline/squisq-react 2.12.26 → 2.12.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,403 @@
1
+ import {
2
+ mermaidRenderErrorMessage,
3
+ renderMermaidSvg
4
+ } from "./chunk-ZKMBIWAA.js";
5
+
6
+ // src/mediaRecipePlayback.ts
7
+ import { useEffect, useMemo } from "react";
8
+ import {
9
+ createMediaTimeMap as createMediaTimeMap2,
10
+ serializeMediaCuts
11
+ } from "@bendyline/squisq/mediaEdit";
12
+
13
+ // src/docPlayer/renderReadiness.ts
14
+ import { createMediaTimeMap, parseMediaCuts } from "@bendyline/squisq/mediaEdit";
15
+ var DEFAULT_VIDEO_FRAME_TIMEOUT_MS = 2e3;
16
+ var VIDEO_FRAME_READINESS_POLL_MS = 16;
17
+ var VIDEO_TIME_TOLERANCE_SECONDS = 0.01;
18
+ var MAX_SEQUENTIAL_CAPTURE_STEP_SECONDS = 0.5;
19
+ var SEQUENTIAL_CAPTURE_PLAYBACK_RATE = 1;
20
+ function isCaptureDrivenVideo(video) {
21
+ return video.dataset.captureSequential === "true" || video.dataset.captureDecoded === "true";
22
+ }
23
+ function blockVideoSourceTime(video, blockElapsed) {
24
+ const clipStart = parseFloat(video.dataset.clipStart || "0");
25
+ const clipEnd = parseFloat(video.dataset.clipEnd || "0");
26
+ const played = Math.max(0, blockElapsed - parseFloat(video.dataset.startAt || "0"));
27
+ const cuts = parseMediaCuts(video.dataset.cuts);
28
+ const source = cuts ? createMediaTimeMap({ clipStart, cuts }).playedToSource(played) : clipStart + played;
29
+ return Math.min(source, clipEnd);
30
+ }
31
+ function formatMediaTime(time) {
32
+ return Number.isFinite(time) ? `${time.toFixed(3)}s` : String(time);
33
+ }
34
+ function reachableMediaTime(video, targetTime) {
35
+ const duration = video.duration;
36
+ if (!Number.isFinite(duration)) return targetTime;
37
+ return Math.max(0, Math.min(targetTime, duration));
38
+ }
39
+ function isAtReachableMediaTime(video, targetTime) {
40
+ return Math.abs(video.currentTime - reachableMediaTime(video, targetTime)) <= VIDEO_TIME_TOLERANCE_SECONDS;
41
+ }
42
+ function isVisiblyPresented(video) {
43
+ if (!video.isConnected) return false;
44
+ const view = video.ownerDocument.defaultView;
45
+ if (!view) return false;
46
+ for (let element = video; element; element = element.parentElement) {
47
+ const style = view.getComputedStyle(element);
48
+ if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse" || Number.parseFloat(style.opacity || "1") <= 0) {
49
+ return false;
50
+ }
51
+ }
52
+ return true;
53
+ }
54
+ function createCaptureWatchdog(ownerDocument, timeoutMs, expire) {
55
+ let timeout = null;
56
+ const clear = () => {
57
+ if (timeout === null) return;
58
+ clearTimeout(timeout);
59
+ timeout = null;
60
+ };
61
+ return {
62
+ arm: () => {
63
+ clear();
64
+ if (ownerDocument.visibilityState !== "visible") return;
65
+ timeout = setTimeout(expire, timeoutMs);
66
+ },
67
+ clear
68
+ };
69
+ }
70
+ function seekVideoByAssignment(video, targetTime, timeoutMs = DEFAULT_VIDEO_FRAME_TIMEOUT_MS) {
71
+ video.pause();
72
+ return new Promise((resolve, reject) => {
73
+ let settled = false;
74
+ let videoFrameRequest = null;
75
+ const ownerDocument = video.ownerDocument;
76
+ const isInactive = () => ownerDocument.visibilityState !== "visible";
77
+ const cleanup = () => {
78
+ watchdog.clear();
79
+ clearInterval(readinessPoll);
80
+ video.removeEventListener("seeked", handleMediaReady);
81
+ video.removeEventListener("loadeddata", handleMediaReady);
82
+ video.removeEventListener("canplay", handleMediaReady);
83
+ ownerDocument.removeEventListener("visibilitychange", handleVisibilityChange);
84
+ if (videoFrameRequest !== null && typeof video.cancelVideoFrameCallback === "function") {
85
+ video.cancelVideoFrameCallback(videoFrameRequest);
86
+ }
87
+ };
88
+ const finish = () => {
89
+ if (settled) return;
90
+ settled = true;
91
+ cleanup();
92
+ resolve();
93
+ };
94
+ const fail = () => {
95
+ if (settled) return;
96
+ settled = true;
97
+ cleanup();
98
+ reject(
99
+ new Error(
100
+ `Video frame did not become ready at ${formatMediaTime(targetTime)} within ${timeoutMs}ms (currentTime=${formatMediaTime(video.currentTime)}, reachableTime=${formatMediaTime(reachableMediaTime(video, targetTime))}, duration=${formatMediaTime(video.duration)}, readyState=${video.readyState}, seeking=${String(video.seeking)}, visible=${String(isVisiblyPresented(video))}).`
101
+ )
102
+ );
103
+ };
104
+ const requestPresentedFrame = () => {
105
+ if (settled || video.seeking || video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA || !isAtReachableMediaTime(video, targetTime)) {
106
+ return;
107
+ }
108
+ if (typeof video.requestVideoFrameCallback !== "function" || !isVisiblyPresented(video)) {
109
+ finish();
110
+ return;
111
+ }
112
+ if (videoFrameRequest !== null) return;
113
+ videoFrameRequest = video.requestVideoFrameCallback(() => {
114
+ videoFrameRequest = null;
115
+ finish();
116
+ });
117
+ };
118
+ function handleMediaReady() {
119
+ requestPresentedFrame();
120
+ }
121
+ const watchdog = createCaptureWatchdog(ownerDocument, timeoutMs, fail);
122
+ const assignTargetTime = () => {
123
+ try {
124
+ video.currentTime = reachableMediaTime(video, targetTime);
125
+ queueMicrotask(requestPresentedFrame);
126
+ return true;
127
+ } catch (error) {
128
+ settled = true;
129
+ cleanup();
130
+ reject(error);
131
+ return false;
132
+ }
133
+ };
134
+ function handleVisibilityChange() {
135
+ if (settled) return;
136
+ if (isInactive()) {
137
+ watchdog.clear();
138
+ return;
139
+ }
140
+ requestPresentedFrame();
141
+ if (settled) return;
142
+ if (!video.seeking && !isAtReachableMediaTime(video, targetTime) && !assignTargetTime()) {
143
+ return;
144
+ }
145
+ watchdog.arm();
146
+ }
147
+ const readinessPoll = setInterval(requestPresentedFrame, VIDEO_FRAME_READINESS_POLL_MS);
148
+ video.addEventListener("seeked", handleMediaReady);
149
+ video.addEventListener("loadeddata", handleMediaReady);
150
+ video.addEventListener("canplay", handleMediaReady);
151
+ ownerDocument.addEventListener("visibilitychange", handleVisibilityChange);
152
+ watchdog.arm();
153
+ assignTargetTime();
154
+ });
155
+ }
156
+ function advanceSequentialCaptureVideo(video, targetTime, timeoutMs) {
157
+ return new Promise((resolve, reject) => {
158
+ let settled = false;
159
+ const ownerDocument = video.ownerDocument;
160
+ const isInactive = () => ownerDocument.visibilityState !== "visible";
161
+ const cleanup = () => {
162
+ watchdog.clear();
163
+ clearInterval(readinessPoll);
164
+ video.removeEventListener("timeupdate", check);
165
+ video.removeEventListener("loadeddata", check);
166
+ video.removeEventListener("canplay", check);
167
+ video.removeEventListener("error", fail);
168
+ ownerDocument.removeEventListener("visibilitychange", handleVisibilityChange);
169
+ };
170
+ const finish = () => {
171
+ if (!settled) {
172
+ settled = true;
173
+ cleanup();
174
+ resolve();
175
+ }
176
+ };
177
+ const fallbackToSeek = () => {
178
+ if (settled) return;
179
+ settled = true;
180
+ video.pause();
181
+ cleanup();
182
+ void seekVideoByAssignment(video, targetTime, timeoutMs).then(resolve, reject);
183
+ };
184
+ const fail = () => {
185
+ if (settled) return;
186
+ settled = true;
187
+ video.pause();
188
+ cleanup();
189
+ reject(
190
+ new Error(
191
+ `Video frame did not advance to ${formatMediaTime(targetTime)} within ${timeoutMs}ms (currentTime=${formatMediaTime(video.currentTime)}, readyState=${video.readyState}).`
192
+ )
193
+ );
194
+ };
195
+ function check() {
196
+ if (video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && video.currentTime >= reachableMediaTime(video, targetTime)) {
197
+ video.pause();
198
+ finish();
199
+ }
200
+ }
201
+ const handlePlaybackFailure = () => {
202
+ if (settled || isInactive()) return;
203
+ fallbackToSeek();
204
+ };
205
+ const startPlayback = () => {
206
+ if (settled || isInactive()) return;
207
+ try {
208
+ video.playbackRate = SEQUENTIAL_CAPTURE_PLAYBACK_RATE;
209
+ if (video.paused) {
210
+ void video.play().catch(handlePlaybackFailure);
211
+ }
212
+ } catch {
213
+ handlePlaybackFailure();
214
+ }
215
+ };
216
+ const watchdog = createCaptureWatchdog(ownerDocument, timeoutMs, fail);
217
+ const pauseWhileInactive = () => {
218
+ video.pause();
219
+ watchdog.clear();
220
+ };
221
+ const resumeWhenActive = () => {
222
+ if (settled || isInactive()) return;
223
+ check();
224
+ if (settled) return;
225
+ startPlayback();
226
+ watchdog.arm();
227
+ };
228
+ function handleVisibilityChange() {
229
+ if (ownerDocument.visibilityState !== "visible") {
230
+ pauseWhileInactive();
231
+ return;
232
+ }
233
+ resumeWhenActive();
234
+ }
235
+ const readinessPoll = setInterval(check, VIDEO_FRAME_READINESS_POLL_MS);
236
+ video.addEventListener("timeupdate", check);
237
+ video.addEventListener("loadeddata", check);
238
+ video.addEventListener("canplay", check);
239
+ video.addEventListener("error", fail, { once: true });
240
+ ownerDocument.addEventListener("visibilitychange", handleVisibilityChange);
241
+ resumeWhenActive();
242
+ });
243
+ }
244
+ function seekVideoToFrame(video, targetTime, timeoutMs = DEFAULT_VIDEO_FRAME_TIMEOUT_MS) {
245
+ if (video.readyState >= HTMLMediaElement.HAVE_METADATA && video.videoWidth <= 0 && video.videoHeight <= 0) {
246
+ video.pause();
247
+ return Promise.resolve();
248
+ }
249
+ const reachableTargetTime = reachableMediaTime(video, targetTime);
250
+ const step = reachableTargetTime - video.currentTime;
251
+ if (video.dataset.captureSequential === "true") {
252
+ if (video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && step <= VIDEO_TIME_TOLERANCE_SECONDS) {
253
+ if (step < -VIDEO_TIME_TOLERANCE_SECONDS) video.pause();
254
+ return Promise.resolve();
255
+ }
256
+ if (step > 0 && step <= MAX_SEQUENTIAL_CAPTURE_STEP_SECONDS && video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
257
+ return advanceSequentialCaptureVideo(video, targetTime, timeoutMs);
258
+ }
259
+ }
260
+ video.pause();
261
+ const alreadyReady = !video.seeking && video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA && isAtReachableMediaTime(video, targetTime);
262
+ if (alreadyReady) return Promise.resolve();
263
+ return seekVideoByAssignment(video, targetTime, timeoutMs);
264
+ }
265
+
266
+ // src/mediaRecipePlayback.ts
267
+ var CUT_SKIP_TOLERANCE_SECONDS = 0.01;
268
+ function useCutTimeMap(cuts, clipStart = 0) {
269
+ const key = cuts?.length ? serializeMediaCuts(cuts) : "";
270
+ return useMemo(
271
+ () => key && cuts ? createMediaTimeMap2({ clipStart, cuts }) : null,
272
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `key` stands for `cuts`
273
+ [key, clipStart]
274
+ );
275
+ }
276
+ function useSkipCuts(ref, timeMap, source) {
277
+ useEffect(() => {
278
+ const element = ref.current;
279
+ if (!element || !timeMap) return;
280
+ let frame = requestAnimationFrame(function skipCuts() {
281
+ const captured = element instanceof HTMLVideoElement && isCaptureDrivenVideo(element);
282
+ if (!element.paused && !captured) {
283
+ const at = element.currentTime;
284
+ const kept = timeMap.playedToSource(timeMap.snapSourceToPlayed(at));
285
+ if (kept - at > CUT_SKIP_TOLERANCE_SECONDS) element.currentTime = kept;
286
+ }
287
+ frame = requestAnimationFrame(skipCuts);
288
+ });
289
+ return () => cancelAnimationFrame(frame);
290
+ }, [ref, timeMap, source]);
291
+ }
292
+ function mediaCropStyle(crop) {
293
+ if (!crop) return {};
294
+ const pct = (n) => `${(n * 100).toFixed(3)}%`;
295
+ const inset = `inset(${pct(crop.y)} ${pct(1 - crop.x - crop.w)} ${pct(1 - crop.y - crop.h)} ${pct(crop.x)})`;
296
+ return { objectViewBox: inset };
297
+ }
298
+ function recipeLevelAt(recipe, played, playedDuration) {
299
+ let level = recipe.gain ? Math.pow(10, recipe.gain / 20) : 1;
300
+ if (recipe.fadeIn && played < recipe.fadeIn) level *= Math.max(0, played / recipe.fadeIn);
301
+ if (recipe.fadeOut && played > playedDuration - recipe.fadeOut) {
302
+ level *= Math.max(0, (playedDuration - played) / recipe.fadeOut);
303
+ }
304
+ return level;
305
+ }
306
+ var boostContext = null;
307
+ var boostNodes = /* @__PURE__ */ new WeakMap();
308
+ function boostNodeFor(el) {
309
+ const existing = boostNodes.get(el);
310
+ if (existing) return existing;
311
+ if (typeof AudioContext === "undefined") return null;
312
+ try {
313
+ boostContext ?? (boostContext = new AudioContext());
314
+ const gain = boostContext.createGain();
315
+ boostContext.createMediaElementSource(el).connect(gain).connect(boostContext.destination);
316
+ boostNodes.set(el, gain);
317
+ return gain;
318
+ } catch {
319
+ return null;
320
+ }
321
+ }
322
+ function applyMediaLevel(el, level) {
323
+ const boost = level > 1 ? boostNodeFor(el) : boostNodes.get(el);
324
+ if (boost) {
325
+ el.volume = 1;
326
+ boost.gain.value = level;
327
+ if (boostContext?.state === "suspended") void boostContext.resume().catch(() => {
328
+ });
329
+ return;
330
+ }
331
+ el.volume = Math.min(1, Math.max(0, level));
332
+ }
333
+
334
+ // src/mermaid/MermaidDiagram.tsx
335
+ import { useEffect as useEffect2, useState } from "react";
336
+ import { DEFAULT_THEME } from "@bendyline/squisq/doc";
337
+ import { jsx, jsxs } from "react/jsx-runtime";
338
+ var renderSequence = 0;
339
+ function MermaidDiagram({
340
+ source,
341
+ className,
342
+ ariaLabel = "Mermaid diagram",
343
+ theme = DEFAULT_THEME
344
+ }) {
345
+ const [svg, setSvg] = useState("");
346
+ const [error, setError] = useState("");
347
+ const [rendering, setRendering] = useState(true);
348
+ useEffect2(() => {
349
+ let current = true;
350
+ const id = `squisq-rich-mermaid-${++renderSequence}`;
351
+ setRendering(true);
352
+ setError("");
353
+ void renderMermaidSvg(id, source, void 0, theme).then((result) => {
354
+ if (!current) return;
355
+ setSvg(result.svg);
356
+ }).catch((caught) => {
357
+ if (!current) return;
358
+ setSvg("");
359
+ setError(mermaidRenderErrorMessage(caught));
360
+ }).finally(() => {
361
+ if (current) setRendering(false);
362
+ });
363
+ return () => {
364
+ current = false;
365
+ };
366
+ }, [source, theme]);
367
+ const classes = ["squisq-mermaid-rendered", className].filter(Boolean).join(" ");
368
+ return /* @__PURE__ */ jsxs(
369
+ "div",
370
+ {
371
+ className: classes,
372
+ role: "img",
373
+ "aria-label": ariaLabel,
374
+ style: { background: theme.colors.backgroundLight, color: theme.colors.text },
375
+ children: [
376
+ rendering && /* @__PURE__ */ jsx("div", { className: "squisq-mermaid-render-status", children: "Rendering diagram\u2026" }),
377
+ !rendering && error && /* @__PURE__ */ jsxs("div", { className: "squisq-mermaid-render-error", role: "alert", children: [
378
+ /* @__PURE__ */ jsx("strong", { children: "Mermaid could not render this diagram." }),
379
+ /* @__PURE__ */ jsx("pre", { children: error })
380
+ ] }),
381
+ !rendering && !error && svg && /* @__PURE__ */ jsx(
382
+ "div",
383
+ {
384
+ className: "squisq-mermaid-render-svg",
385
+ dangerouslySetInnerHTML: { __html: svg }
386
+ }
387
+ )
388
+ ]
389
+ }
390
+ );
391
+ }
392
+
393
+ export {
394
+ isCaptureDrivenVideo,
395
+ blockVideoSourceTime,
396
+ seekVideoToFrame,
397
+ useCutTimeMap,
398
+ useSkipCuts,
399
+ mediaCropStyle,
400
+ recipeLevelAt,
401
+ applyMediaLevel,
402
+ MermaidDiagram
403
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  LinearDocView
3
- } from "./chunk-L3PODEKP.js";
3
+ } from "./chunk-Q66DDGKP.js";
4
4
 
5
5
  // src/PaginatedDocView.tsx
6
6
  import {
@@ -2,7 +2,7 @@ import {
2
2
  renderMermaidSvg,
3
3
  useMediaProvider,
4
4
  useResourcePolicy
5
- } from "./chunk-OTYJ4MRH.js";
5
+ } from "./chunk-ZKMBIWAA.js";
6
6
 
7
7
  // src/hooks/useMediaSchedule.ts
8
8
  import { useMemo } from "react";