@vivix-labs/media-tools 0.0.0-stage → 1.0.0-beta

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.
Files changed (60) hide show
  1. package/README.md +129 -2
  2. package/dist/Inter-LICENSE.txt +93 -0
  3. package/dist/UI-LICENSE.txt +21 -0
  4. package/dist/assets/35a50-G5EJUNOC.svg +6 -0
  5. package/dist/assets/369ca-BISNKZ3M.svg +6 -0
  6. package/dist/assets/441bc-BCMNQ72W.svg +6 -0
  7. package/dist/assets/483f0-T6ZAGTDG.svg +6 -0
  8. package/dist/assets/6911b-ESLYKSC6.svg +6 -0
  9. package/dist/assets/Inter-LICENSE.txt +93 -0
  10. package/dist/assets/UI-system-LICENSE.txt +21 -0
  11. package/dist/assets/add-JY533O73.svg +5 -0
  12. package/dist/assets/area-P2WOMBT5.svg +9 -0
  13. package/dist/assets/b70bb-BTTOKPOH.svg +6 -0
  14. package/dist/assets/b9919-3S3O6YOT.svg +6 -0
  15. package/dist/assets/calendar-JI6USFRJ.svg +1 -0
  16. package/dist/assets/check-JSRRIXN5.svg +5 -0
  17. package/dist/assets/check-on-content-FQUVG3IZ.svg +5 -0
  18. package/dist/assets/chevron-down-K7YKS2EY.svg +5 -0
  19. package/dist/assets/chevron-left-JQCLK2WZ.svg +3 -0
  20. package/dist/assets/chevron-right-TNE35DBJ.svg +3 -0
  21. package/dist/assets/chevron-up-VBHYAJVB.svg +5 -0
  22. package/dist/assets/clear-XNEZJKFC.svg +5 -0
  23. package/dist/assets/close-GO5F7YFS.svg +10 -0
  24. package/dist/assets/dccd4-CZJXWICW.svg +6 -0
  25. package/dist/assets/dd163-3S3O6YOT.svg +6 -0
  26. package/dist/assets/draw-FOFX5TOM.svg +6 -0
  27. package/dist/assets/e8aed-CZJXWICW.svg +6 -0
  28. package/dist/assets/ea990-CZJXWICW.svg +6 -0
  29. package/dist/assets/expand-IAV75AFA.svg +6 -0
  30. package/dist/assets/fullscreen-L2JCXIN2.svg +6 -0
  31. package/dist/assets/grid-TLG5JYWB.svg +8 -0
  32. package/dist/assets/import-AFBUV2VV.svg +4 -0
  33. package/dist/assets/inter-latin-400-normal-55WT6UWF.woff2 +0 -0
  34. package/dist/assets/inter-latin-500-normal-W62DVTXI.woff2 +0 -0
  35. package/dist/assets/inter-latin-600-normal-R6Y2SZCR.woff2 +0 -0
  36. package/dist/assets/list-5VUAOZUH.svg +9 -0
  37. package/dist/assets/magic-OMME7FOV.svg +9 -0
  38. package/dist/assets/more-AEJ5MHWV.svg +5 -0
  39. package/dist/assets/mute-SXOSCR2U.svg +6 -0
  40. package/dist/assets/pause-2E4UY4FW.svg +6 -0
  41. package/dist/assets/play-WIIT3XQK.svg +5 -0
  42. package/dist/assets/reset-JESMTEMV.svg +6 -0
  43. package/dist/assets/search-JUOSGQRM.svg +6 -0
  44. package/dist/assets/select-VU7WR7B4.svg +7 -0
  45. package/dist/assets/sound-file-YYY6VNYN.svg +3 -0
  46. package/dist/assets/volume-2TYGJL6F.svg +6 -0
  47. package/dist/client.bundle.js +1606 -0
  48. package/dist/client.css +2242 -0
  49. package/dist/client.d.ts +18 -0
  50. package/dist/client.js +3 -0
  51. package/dist/server.d.ts +10 -0
  52. package/dist/server.js +1763 -0
  53. package/dist/shared.d.ts +664 -0
  54. package/dist/shared.js +217 -0
  55. package/dist/worker.d.ts +2 -0
  56. package/dist/worker.js +189 -0
  57. package/package.json +42 -3
  58. package/skills/SKILL.md +49 -0
  59. package/skills/references/processing.md +32 -0
  60. package/studio-plugin.json +11 -0
@@ -0,0 +1,1606 @@
1
+ // packages/media-tools/src/client.tsx
2
+ import * as React7 from "react";
3
+
4
+ // packages/media-tools/src/shared.ts
5
+ import { z, PluginError } from "vivix-studio/sdk/shared";
6
+ var Config = z.object({
7
+ dataInstance: z.string().min(1).default("user:data"),
8
+ studioInstance: z.string().min(1).default("studio"),
9
+ executionNamespace: z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/).default("media"),
10
+ ffmpegPath: z.string().min(1).default("ffmpeg"),
11
+ ffprobePath: z.string().min(1).default("ffprobe")
12
+ }).strict();
13
+ var versionRef = z.object({ storeId: z.uuid(), objectId: z.uuid(), versionId: z.uuid() }).strict();
14
+ var videoFileRef = z.object({ source: versionRef, fileId: z.uuid() }).strict();
15
+ var sourceInput = z.object({ kind: z.literal("source"), file: videoFileRef }).strict();
16
+ var editInput = z.object({ kind: z.literal("edit"), editRef: versionRef }).strict();
17
+ var videoInput = z.discriminatedUnion("kind", [sourceInput, editInput]);
18
+ var sequenceVideoInput = z.discriminatedUnion("kind", [
19
+ sourceInput.extend({ trimEndMs: z.number().int().positive().optional() }),
20
+ editInput
21
+ ]);
22
+ var recipe = z.object({
23
+ trim: z.object({ inMs: z.number().int().nonnegative(), outMs: z.number().int().positive() }).strict(),
24
+ crop: z.object({
25
+ x: z.number().finite().nonnegative(),
26
+ y: z.number().finite().nonnegative(),
27
+ width: z.number().finite().positive().max(1),
28
+ height: z.number().finite().positive().max(1)
29
+ }).strict()
30
+ }).strict().superRefine((v, c) => {
31
+ if (v.trim.inMs >= v.trim.outMs)
32
+ c.addIssue({ code: "custom", message: "The selected interval must have positive duration." });
33
+ if (v.crop.x + v.crop.width > 1 + 1e-9 || v.crop.y + v.crop.height > 1 + 1e-9)
34
+ c.addIssue({ code: "custom", message: "The crop must remain inside the source picture." });
35
+ });
36
+ var pixelRect = z.object({
37
+ x: z.number().int().nonnegative(),
38
+ y: z.number().int().nonnegative(),
39
+ width: z.number().int().positive(),
40
+ height: z.number().int().positive()
41
+ }).strict();
42
+ var geometry = z.object({
43
+ displayWidth: z.number().int().positive(),
44
+ displayHeight: z.number().int().positive(),
45
+ pixelRect
46
+ }).strict();
47
+ var metadata = z.object({
48
+ durationMs: z.number().int().positive(),
49
+ width: z.number().int().positive(),
50
+ height: z.number().int().positive(),
51
+ displayWidth: z.number().int().positive(),
52
+ displayHeight: z.number().int().positive(),
53
+ rotation: z.union([z.literal(0), z.literal(90), z.literal(180), z.literal(270)]),
54
+ frameRate: z.number().positive().max(60),
55
+ startTime: z.number().finite(),
56
+ hasAudio: z.boolean(),
57
+ audioSampleRate: z.number().int().nullable(),
58
+ audioChannels: z.number().int().nullable(),
59
+ audioStartTime: z.number().finite().nullable(),
60
+ sizeBytes: z.number().int().nonnegative(),
61
+ sha256: z.string().regex(/^[a-f0-9]{64}$/),
62
+ colorInterpretation: z.enum(["declared-bt709", "assumed-bt709"]).optional()
63
+ }).strict();
64
+ var editDescriptor = z.object({ format: z.literal(1), file: videoFileRef, recipe, geometry, metadata }).strict();
65
+ var saveEdit = z.object({
66
+ file: videoFileRef,
67
+ recipe,
68
+ editId: z.uuid().optional(),
69
+ expectedRevision: z.number().int().positive().optional()
70
+ }).strict().superRefine((v, c) => {
71
+ if (Boolean(v.editId) !== Boolean(v.expectedRevision))
72
+ c.addIssue({ code: "custom", message: "An edit update requires its revision." });
73
+ });
74
+ var outputName = z.string().trim().min(1).max(200);
75
+ var processVideo = z.object({ input: videoInput, outputName, retryOfJobId: z.uuid().optional() }).strict();
76
+ var canvas = z.object({ width: z.number().int().min(2).max(3840), height: z.number().int().min(2).max(3840) }).strict().refine(
77
+ (v) => v.width % 2 === 0 && v.height % 2 === 0 && Math.min(v.width, v.height) <= 2160,
78
+ "Canvas dimensions must be even and within 3840 by 2160."
79
+ );
80
+ var processSequence = z.object({
81
+ inputs: z.array(sequenceVideoInput).min(1).max(64),
82
+ outputName,
83
+ canvas,
84
+ retryOfJobId: z.uuid().optional()
85
+ }).strict();
86
+ var mediaRequest = z.discriminatedUnion("operation", [
87
+ z.object({ operation: z.literal("video.process"), input: processVideo }).strict(),
88
+ z.object({ operation: z.literal("sequence.process"), input: processSequence }).strict()
89
+ ]);
90
+ var jobsQuery = z.object({
91
+ limit: z.number().int().min(1).max(100).default(50),
92
+ offset: z.number().int().nonnegative().default(0),
93
+ request: z.object({
94
+ operation: z.enum(["video.process", "sequence.process"]),
95
+ requestKey: z.string().min(1).max(128),
96
+ intent: z.union([processVideo, processSequence])
97
+ }).strict().optional()
98
+ }).strict();
99
+ function mediaError(code, message) {
100
+ throw new PluginError(
101
+ code,
102
+ message,
103
+ "Review the fixed source, edit and current project, then retry explicitly."
104
+ );
105
+ }
106
+ function normalizeRecipe(raw, displayWidth, displayHeight, durationMs) {
107
+ const value = recipe.parse(raw);
108
+ if (![displayWidth, displayHeight, durationMs].every(Number.isSafeInteger) || displayWidth < 2 || displayHeight < 2 || durationMs < 1 || displayWidth % 2 !== 0 || displayHeight % 2 !== 0)
109
+ mediaError("UNSUPPORTED_GEOMETRY", "The source needs positive even display dimensions.");
110
+ if (value.trim.outMs > durationMs)
111
+ mediaError("INVALID_RECIPE", "The trim exceeds the fixed source duration.");
112
+ const edge = (fraction2, size) => Math.round(fraction2 * size / 2) * 2;
113
+ const x = edge(value.crop.x, displayWidth);
114
+ const y = edge(value.crop.y, displayHeight);
115
+ const right = Math.min(displayWidth, edge(value.crop.x + value.crop.width, displayWidth));
116
+ const bottom = Math.min(displayHeight, edge(value.crop.y + value.crop.height, displayHeight));
117
+ if (right - x < 2 || bottom - y < 2)
118
+ mediaError("INVALID_RECIPE", "The crop must contain at least two pixels in each dimension.");
119
+ const pixelRect2 = { x, y, width: right - x, height: bottom - y };
120
+ return {
121
+ recipe: {
122
+ trim: { ...value.trim },
123
+ crop: {
124
+ x: x / displayWidth,
125
+ y: y / displayHeight,
126
+ width: pixelRect2.width / displayWidth,
127
+ height: pixelRect2.height / displayHeight
128
+ }
129
+ },
130
+ geometry: { displayWidth, displayHeight, pixelRect: pixelRect2 }
131
+ };
132
+ }
133
+
134
+ // packages/media-tools/src/ui/context.tsx
135
+ import * as React from "react";
136
+ var MediaContext = React.createContext(null);
137
+ function useMediaClient() {
138
+ const value = React.useContext(MediaContext);
139
+ if (!value) throw Error("Resolve this component from an activated media-tools instance.");
140
+ return value;
141
+ }
142
+ function readableError(error) {
143
+ return error instanceof Error ? error.message : "The media operation could not be completed.";
144
+ }
145
+ function requestRejected(error) {
146
+ return Boolean(
147
+ error && typeof error === "object" && "code" in error && ["MEDIA_BUSY", "MEDIA_QUEUE_FULL", "PROJECT_ARCHIVED"].includes(String(error.code))
148
+ );
149
+ }
150
+ async function submitOrFind(client, instanceId, request, requestKey) {
151
+ try {
152
+ return await client.invoke(
153
+ { instanceId, operationId: request.operation },
154
+ request.input,
155
+ { requestKey }
156
+ );
157
+ } catch (error) {
158
+ const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
159
+ if (code !== void 0 && !["EXECUTION_UNKNOWN", "OPERATION_CONTRACT_CHANGED", "TRANSPORT_UNKNOWN"].includes(
160
+ String(code)
161
+ ))
162
+ throw error;
163
+ const result = await client.invoke(
164
+ { instanceId, operationId: "jobs.list" },
165
+ { request: { operation: request.operation, requestKey, intent: request.input } }
166
+ );
167
+ const accepted = result.items[0];
168
+ if (!accepted) throw Error("No accepted task was found. Keep the original request identity.");
169
+ return { jobId: accepted.jobId, state: accepted.state };
170
+ }
171
+ }
172
+
173
+ // packages/media-tools/src/ui/editor.tsx
174
+ import * as React4 from "react";
175
+
176
+ // packages/ui-system/dist/button.js
177
+ import { jsx as _jsx2, jsxs as _jsxs } from "react/jsx-runtime";
178
+
179
+ // packages/ui-system/dist/icon.js
180
+ import { jsx as _jsx } from "react/jsx-runtime";
181
+ function Icon({ name, size }) {
182
+ return _jsx("span", { "aria-hidden": "true", className: "vx-icon", "data-icon": name, style: size === void 0 ? void 0 : { "--vx-icon-size": `${size}px` } });
183
+ }
184
+
185
+ // packages/ui-system/dist/button-variants.js
186
+ var buttonVariants = {
187
+ "text-filled-sm": { size: 32, appearance: "filled", shape: "text", width: 215 },
188
+ "text-filled-leading-sm": { size: 32, appearance: "filled", shape: "text" },
189
+ "text-ghost-sm": { size: 32, appearance: "ghost", shape: "text" },
190
+ "text-on-content-sm": { size: 32, appearance: "on-content", shape: "text" },
191
+ "text-tonal-sm": { size: 32, appearance: "tonal", shape: "text" },
192
+ // The medium recipes are shared by all dialog footer actions.
193
+ "text-filled-md": { size: 40, appearance: "filled", shape: "text" },
194
+ "text-tonal-md": { size: 40, appearance: "tonal", shape: "text" },
195
+ "text-ghost-md": { size: 40, appearance: "ghost", shape: "text" },
196
+ "icon-ghost-md": { size: 40, appearance: "ghost", shape: "icon" },
197
+ "text-filled-lg": { size: 44, appearance: "filled", shape: "text", width: 412 },
198
+ "text-tonal-lg": { size: 44, appearance: "tonal", shape: "text", width: 412 },
199
+ "text-outline-lg": {
200
+ size: 44,
201
+ appearance: "outline",
202
+ shape: "text",
203
+ width: 412
204
+ },
205
+ "pill-filled": { size: 44, appearance: "filled", shape: "pill" },
206
+ "pill-plain": { size: 48, appearance: "plain", shape: "pill" },
207
+ "pill-small": { size: 32, appearance: "plain", shape: "pill" },
208
+ "icon-outline-sm": { size: 32, appearance: "outline", shape: "icon" },
209
+ "icon-on-content": { size: 24, appearance: "on-content", shape: "icon" },
210
+ "icon-outline-lg": { size: 48, appearance: "outline", shape: "icon" },
211
+ // Compact bare action: reuse the transparent/default and surface-hover ghost treatment.
212
+ "icon-bare-xs": { size: 24, appearance: "ghost", shape: "icon" },
213
+ "icon-ghost-sm": { size: 32, appearance: "ghost", shape: "icon" },
214
+ "icon-ghost-lg": { size: 48, appearance: "ghost", shape: "icon" },
215
+ "icon-circle-sm": { size: 32, appearance: "filled", shape: "circle" },
216
+ "icon-circle-lg": { size: 44, appearance: "filled", shape: "circle" }
217
+ };
218
+
219
+ // packages/ui-system/dist/button.js
220
+ function ButtonFrame({ label, variant, loading = false, width, children, disabled, type = "button", style, className, ...props }) {
221
+ const spec = buttonVariants[variant];
222
+ const buttonStyle = "width" in spec ? { ...style, "--vx-button-width": `${spec.width}px` } : style;
223
+ return _jsxs("button", { ...props, type, className: className ? `vx-button ${className}` : "vx-button", "data-variant": variant, "data-appearance": spec.appearance, "data-shape": spec.shape, "data-size": spec.size, "data-width": width, "data-state": loading ? "loading" : disabled ? "disabled" : "default", style: buttonStyle, disabled: disabled || loading, "aria-label": label, "aria-busy": loading || void 0, children: [_jsx2("span", { className: "vx-button-content", children }), loading && _jsx2("span", { className: "vx-button-loading", "aria-hidden": "true" })] });
224
+ }
225
+ function Button({ variant = "text-filled-sm", leadingIcon, trailingIcon, ...props }) {
226
+ return _jsxs(ButtonFrame, { ...props, variant, children: [leadingIcon && _jsx2(Icon, { name: leadingIcon }), _jsx2("span", { className: "vx-button-label", children: props.label }), trailingIcon && _jsx2("span", { className: "vx-button-trailing", children: _jsx2(Icon, { name: trailingIcon }) })] });
227
+ }
228
+ function IconButton({ icon, variant = "icon-ghost-sm", ...props }) {
229
+ return _jsx2(ButtonFrame, { ...props, variant, children: _jsx2(Icon, { name: icon }) });
230
+ }
231
+
232
+ // packages/ui-system/dist/segmented-control.js
233
+ import { jsx as _jsx3, jsxs as _jsxs2 } from "react/jsx-runtime";
234
+ import { useId } from "react";
235
+ function SegmentedControl({ label, items, value, onValueChange, size = "medium", width = "fixed", iconOnly = false }) {
236
+ const id = useId();
237
+ return _jsx3("div", { role: "radiogroup", "aria-label": label, className: "vx-segment", "data-size": size, "data-width": width, "data-icon-only": iconOnly, children: items.map((item) => _jsxs2("label", { children: [_jsx3("input", { type: "radio", name: id, value: item.value, disabled: item.disabled, checked: item.value === value, "aria-label": item.label, onChange: () => onValueChange(item.value) }), _jsxs2("span", { className: "vx-segment-item", children: [item.icon && _jsx3(Icon, { name: item.icon }), (!iconOnly || !item.icon) && item.label] })] }, item.value)) });
238
+ }
239
+
240
+ // packages/ui-system/dist/tag.js
241
+ import { jsx as _jsx4 } from "react/jsx-runtime";
242
+ function Tag({ children, variant = "overlay" }) {
243
+ return _jsx4("span", { className: "vx-tag", "data-variant": variant, children });
244
+ }
245
+
246
+ // packages/ui-system/dist/frame-range.js
247
+ import { jsx as _jsx5, jsxs as _jsxs3, Fragment as _Fragment } from "react/jsx-runtime";
248
+ var clamp = (value, min, max) => Math.min(max, Math.max(min, value));
249
+ function timeLabel(seconds) {
250
+ const whole = Math.floor(seconds);
251
+ return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
252
+ }
253
+ function FrameRange({ duration, thumbnail, value, step = 0.1, variant = "range", onValueChange }) {
254
+ const length = Number.isFinite(duration) && duration > 0 ? duration : 0;
255
+ const increment = Math.min(length, Number.isFinite(step) && step > 0 ? step : 0.1);
256
+ const start = clamp(Number.isFinite(value.start) ? value.start : 0, 0, length - increment);
257
+ const end = clamp(Number.isFinite(value.end) ? value.end : length, Math.min(length, start + increment), length);
258
+ function move(edge, next) {
259
+ const rounded = Math.round(next / increment) * increment;
260
+ const range = edge === "start" ? { start: clamp(rounded, 0, end - increment), end } : { start, end: clamp(next >= length ? length : rounded, start + increment, length) };
261
+ if (range.start !== start || range.end !== end)
262
+ onValueChange(range);
263
+ }
264
+ function drag(event, edge) {
265
+ if (!event.currentTarget.hasPointerCapture(event.pointerId))
266
+ return;
267
+ const box = event.currentTarget.closest(".vx-frame-range")?.getBoundingClientRect();
268
+ if (box?.width)
269
+ move(edge, (event.clientX - box.left) / box.width * length);
270
+ }
271
+ function handleKey(event, edge, current) {
272
+ const changes = {
273
+ ArrowLeft: current - increment,
274
+ ArrowDown: current - increment,
275
+ ArrowRight: current + increment,
276
+ ArrowUp: current + increment,
277
+ Home: 0,
278
+ End: length
279
+ };
280
+ const next = changes[event.key];
281
+ if (next === void 0)
282
+ return;
283
+ event.preventDefault();
284
+ move(edge, next);
285
+ }
286
+ return _jsxs3("div", { className: "vx-frame-range", "data-variant": variant, role: "group", "aria-label": "Playback range", "aria-disabled": !length, style: length ? {
287
+ "--vx-range-start": `${start / length * 100}%`,
288
+ "--vx-range-end": `${end / length * 100}%`
289
+ } : void 0, children: [thumbnail && length > 0 && _jsx5("img", { src: thumbnail, alt: "" }), length > 0 && _jsxs3(_Fragment, { children: [_jsx5("span", { className: "vx-frame-selection", "aria-hidden": "true", children: _jsxs3(Tag, { children: [timeLabel(start), " \u2013 ", timeLabel(end)] }) }), ["start", "end"].map((edge) => {
290
+ const current = edge === "start" ? start : end;
291
+ return _jsx5("div", { tabIndex: 0, role: "slider", className: "vx-frame-handle", "data-edge": edge, "aria-label": edge === "start" ? "Range start" : "Range end", "aria-valuemin": edge === "start" ? 0 : start + increment, "aria-valuemax": edge === "start" ? end - increment : length, "aria-valuenow": current, "aria-valuetext": `${Number(current.toFixed(3))} seconds`, onKeyDown: (event) => handleKey(event, edge, current), onPointerDown: (event) => {
292
+ if (event.button !== 0)
293
+ return;
294
+ event.currentTarget.focus();
295
+ event.currentTarget.setPointerCapture(event.pointerId);
296
+ }, onPointerMove: (event) => drag(event, edge) }, edge);
297
+ })] })] });
298
+ }
299
+
300
+ // packages/ui-system/dist/dialog.js
301
+ import { jsx as _jsx6, jsxs as _jsxs4 } from "react/jsx-runtime";
302
+ import { useEffect, useId as useId2, useLayoutEffect, useRef } from "react";
303
+ function Dialog({ title, open, onOpenChange, children, actions, className }) {
304
+ const ref = useRef(null);
305
+ const heading = useId2();
306
+ useEffect(() => {
307
+ const dialog = ref.current;
308
+ if (!dialog || dialog.open === open)
309
+ return;
310
+ if (open)
311
+ dialog.showModal();
312
+ else
313
+ dialog.close();
314
+ }, [open]);
315
+ useLayoutEffect(() => {
316
+ const dialog = ref.current;
317
+ return () => {
318
+ if (dialog?.open)
319
+ dialog.close();
320
+ };
321
+ }, []);
322
+ return _jsxs4("dialog", { ref, className: className ? `vx-dialog ${className}` : "vx-dialog", "aria-labelledby": heading, onCancel: (event) => {
323
+ event.preventDefault();
324
+ event.stopPropagation();
325
+ onOpenChange(false);
326
+ }, onClose: (event) => {
327
+ if (open && !event.currentTarget.open)
328
+ onOpenChange(false);
329
+ }, children: [_jsxs4("header", { children: [_jsx6("h2", { id: heading, children: title }), _jsx6(IconButton, { icon: "close", label: "Close dialog", onClick: () => onOpenChange(false) })] }), _jsx6("div", { className: "vx-dialog-body", children }), actions && _jsx6("footer", { children: actions })] });
330
+ }
331
+
332
+ // packages/ui-system/dist/menu.js
333
+ import { jsx as _jsx7, jsxs as _jsxs5 } from "react/jsx-runtime";
334
+ import { useEffect as useEffect2, useId as useId3, useLayoutEffect as useLayoutEffect2, useRef as useRef2, useState } from "react";
335
+ import { createPortal } from "react-dom";
336
+ function isEnabled(item) {
337
+ return !item.disabled && item.items?.length !== 0;
338
+ }
339
+ function Menu({ label, items, triggerIcon, floating = false }) {
340
+ const id = useId3();
341
+ const trigger = useRef2(null);
342
+ const popup = useRef2(null);
343
+ const focusIndex = useRef2(0);
344
+ const [path, setPath] = useState(null);
345
+ const [placement, setPlacement] = useState({ visibility: "hidden" });
346
+ const portalRoot = floating ? trigger.current?.closest("[data-vx-theme]") : null;
347
+ useLayoutEffect2(() => {
348
+ if (!floating || !path || !portalRoot)
349
+ return;
350
+ const position = () => {
351
+ const anchor = trigger.current, menu2 = popup.current;
352
+ if (!anchor || !menu2)
353
+ return;
354
+ const rect = anchor.getBoundingClientRect();
355
+ const width = document.documentElement.clientWidth, height = window.innerHeight;
356
+ const bounds = menu2.getBoundingClientRect();
357
+ const naturalHeight = menu2.scrollHeight + bounds.height - menu2.clientHeight;
358
+ const below = Math.max(0, height - rect.bottom - 12), above = Math.max(0, rect.top - 12);
359
+ const flip = naturalHeight > below && above > below;
360
+ const maxHeight = Math.max(0, Math.min(480, height - 16, flip ? above : below));
361
+ const menuHeight = Math.min(naturalHeight, maxHeight);
362
+ setPlacement({
363
+ position: "fixed",
364
+ visibility: "visible",
365
+ insetInlineStart: "auto",
366
+ left: Math.max(8, Math.min(rect.right - bounds.width, width - bounds.width - 8)),
367
+ top: Math.max(8, Math.min(flip ? rect.top - menuHeight - 4 : rect.bottom + 4, height - menuHeight - 8)),
368
+ maxHeight,
369
+ zIndex: 100
370
+ });
371
+ };
372
+ const outside = (event) => {
373
+ const target = event.target;
374
+ if (target && !trigger.current?.contains(target) && !popup.current?.contains(target))
375
+ setPath(null);
376
+ };
377
+ position();
378
+ window.addEventListener("resize", position);
379
+ window.addEventListener("scroll", position, true);
380
+ document.addEventListener("pointerdown", outside);
381
+ return () => {
382
+ window.removeEventListener("resize", position);
383
+ window.removeEventListener("scroll", position, true);
384
+ document.removeEventListener("pointerdown", outside);
385
+ };
386
+ }, [floating, path, portalRoot]);
387
+ let entries = items;
388
+ let menuLabel = label;
389
+ for (const key of path ?? []) {
390
+ const entry = entries.find((item) => item.id === key);
391
+ if (!entry?.items)
392
+ break;
393
+ menuLabel = entry.label;
394
+ entries = entry.items;
395
+ }
396
+ function buttons() {
397
+ return [...popup.current?.querySelectorAll("button:not(:disabled)") ?? []];
398
+ }
399
+ useEffect2(() => {
400
+ if (path && (!floating || !portalRoot || placement.visibility === "visible"))
401
+ buttons().at(focusIndex.current)?.focus();
402
+ }, [path, floating && placement.visibility, portalRoot]);
403
+ function close() {
404
+ setPath(null);
405
+ trigger.current?.focus();
406
+ }
407
+ function back() {
408
+ if (!path?.length)
409
+ return;
410
+ const parentPath = path.slice(0, -1);
411
+ const parent = parentPath.reduce((level, key) => level.find((item) => item.id === key)?.items ?? level, items);
412
+ focusIndex.current = Math.max(0, parent.filter(isEnabled).findIndex((item) => item.id === path.at(-1)));
413
+ setPath(parentPath);
414
+ }
415
+ function choose(item) {
416
+ if (item.items?.length) {
417
+ focusIndex.current = 0;
418
+ setPath([...path ?? [], item.id]);
419
+ } else if (item.onSelect) {
420
+ if (item.checked === void 0)
421
+ close();
422
+ item.onSelect();
423
+ }
424
+ }
425
+ function handleKey(event) {
426
+ if (event.key === "Tab" && floating && portalRoot) {
427
+ if (event.shiftKey)
428
+ event.preventDefault();
429
+ close();
430
+ return;
431
+ }
432
+ const available = buttons();
433
+ const index = available.findIndex((button) => button === event.target);
434
+ if (event.key === "Escape") {
435
+ event.preventDefault();
436
+ event.stopPropagation();
437
+ if (path?.length)
438
+ back();
439
+ else
440
+ close();
441
+ return;
442
+ }
443
+ if (event.key === "ArrowLeft" && path?.length) {
444
+ event.preventDefault();
445
+ back();
446
+ return;
447
+ }
448
+ if (event.key === "ArrowRight") {
449
+ const item = entries.filter(isEnabled)[index];
450
+ if (item?.items?.length) {
451
+ event.preventDefault();
452
+ choose(item);
453
+ }
454
+ return;
455
+ }
456
+ const next = {
457
+ ArrowDown: (index + 1) % available.length,
458
+ ArrowUp: (index - 1 + available.length) % available.length,
459
+ Home: 0,
460
+ End: available.length - 1
461
+ }[event.key];
462
+ if (next !== void 0) {
463
+ event.preventDefault();
464
+ available[next]?.focus();
465
+ }
466
+ }
467
+ function open(index = 0) {
468
+ focusIndex.current = index;
469
+ setPath([]);
470
+ }
471
+ function triggerKey(event) {
472
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
473
+ event.preventDefault();
474
+ open(event.key === "ArrowUp" ? -1 : 0);
475
+ }
476
+ }
477
+ const menu = _jsx7("div", { ref: popup, className: "vx-action-menu-items", role: "menu", id, "aria-label": menuLabel, hidden: !path, onKeyDown: handleKey, "data-floating": floating || void 0, style: floating && portalRoot ? placement : void 0, children: entries.map((item) => _jsxs5("button", { type: "button", role: item.checked === void 0 ? "menuitem" : "menuitemcheckbox", "aria-checked": item.checked, "aria-haspopup": item.items?.length ? "menu" : void 0, "data-size": item.size ?? "medium", disabled: !isEnabled(item), tabIndex: -1, onClick: () => choose(item), children: [item.icon && _jsx7(Icon, { name: item.icon }), _jsx7("span", { children: item.label }), item.checked && _jsx7(Icon, { name: "check" }), item.items?.length ? _jsx7(Icon, { name: "chevron-right" }) : null] }, item.id)) });
478
+ return _jsxs5("div", { className: "vx-action-menu", onBlur: (event) => {
479
+ if (!event.currentTarget.contains(event.relatedTarget) && !(floating && popup.current?.contains(event.relatedTarget)))
480
+ setPath(null);
481
+ }, children: [triggerIcon ? _jsx7(IconButton, { ref: trigger, label, icon: triggerIcon, variant: "icon-ghost-sm", "aria-haspopup": "menu", "aria-controls": id, "aria-expanded": path !== null, disabled: !items.some(isEnabled), onClick: () => path ? close() : open(), onKeyDown: triggerKey }) : _jsx7(Button, { ref: trigger, label, variant: "text-tonal-sm", trailingIcon: "chevron-down", "aria-haspopup": "menu", "aria-controls": id, "aria-expanded": path !== null, disabled: !items.some(isEnabled), onClick: () => path ? close() : open(), onKeyDown: triggerKey }), portalRoot ? createPortal(menu, portalRoot) : menu] });
482
+ }
483
+
484
+ // packages/ui-system/dist/video-player.js
485
+ import { jsx as _jsx8, jsxs as _jsxs6 } from "react/jsx-runtime";
486
+ import { useEffect as useEffect3, useRef as useRef3, useState as useState2 } from "react";
487
+ function timeLabel2(seconds) {
488
+ const whole = Math.floor(seconds);
489
+ return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, "0")}`;
490
+ }
491
+ function PlaybackControls({ playing, muted, time, duration, size = "medium", disabled, onTogglePlay, onToggleMute, onSeek, onFullscreen }) {
492
+ return _jsxs6("div", { className: "vx-playback-controls", role: "group", "aria-label": "Playback controls", "data-size": size, children: [_jsx8(IconButton, { icon: playing ? "pause" : "play", label: playing ? "Pause" : "Play", disabled, onClick: onTogglePlay }), _jsx8("input", { "aria-label": "Playback position", "aria-valuetext": `${timeLabel2(time)} of ${timeLabel2(duration)}`, type: "range", min: 0, max: duration, value: time, step: "any", disabled: disabled || !duration, onChange: (event) => onSeek(event.currentTarget.valueAsNumber) }), _jsxs6("span", { "aria-hidden": "true", children: [timeLabel2(time), " / ", timeLabel2(duration)] }), _jsx8(IconButton, { icon: muted ? "mute" : "volume", label: muted ? "Unmute" : "Mute", disabled, onClick: onToggleMute }), onFullscreen && _jsx8(IconButton, { icon: "fullscreen", label: "Toggle fullscreen", onClick: onFullscreen })] });
493
+ }
494
+ function VideoPlayer(props) {
495
+ return _jsx8(Playback, { ...props }, JSON.stringify([props.src, props.poster, props.posterDuration]));
496
+ }
497
+ function Playback({ src, poster, posterDuration = 0, title, version, durationLabel, sceneLabel, defaultMuted = false, controlsPlacement = "overlay", controlsSize, showFullscreen = true, overlay, onBeforePlay, onStateChange, onTimeChange, onEnded, onError }) {
498
+ const root = useRef3(null);
499
+ const video = useRef3(null);
500
+ const position = useRef3(0);
501
+ const callbacks = useRef3({ onTimeChange, onStateChange, onEnded });
502
+ const [time, setTime] = useState2(0);
503
+ const [metadataDuration, setMetadataDuration] = useState2(0);
504
+ const [state, setState] = useState2("cover");
505
+ const [muted, setMuted] = useState2(defaultMuted);
506
+ const stillDuration = poster && Number.isFinite(posterDuration) ? Math.max(0, posterDuration) : 0;
507
+ const duration = src ? metadataDuration : stillDuration;
508
+ useEffect3(() => {
509
+ const element = video.current;
510
+ return () => {
511
+ if (!element)
512
+ return;
513
+ element.pause();
514
+ element.removeAttribute("src");
515
+ element.load();
516
+ };
517
+ }, []);
518
+ function updateTime(next) {
519
+ position.current = next;
520
+ setTime(next);
521
+ onTimeChange?.(next);
522
+ }
523
+ function changeState(next) {
524
+ setState(next);
525
+ onStateChange?.(next);
526
+ }
527
+ useEffect3(() => {
528
+ callbacks.current = { onTimeChange, onStateChange, onEnded };
529
+ }, [onTimeChange, onStateChange, onEnded]);
530
+ useEffect3(() => {
531
+ if (src || state !== "playing" || !duration)
532
+ return;
533
+ let previous = performance.now();
534
+ let frame = requestAnimationFrame(tick);
535
+ function tick(now) {
536
+ const next = Math.min(duration, position.current + (now - previous) / 1e3);
537
+ previous = now;
538
+ position.current = next;
539
+ setTime(next);
540
+ callbacks.current.onTimeChange?.(next);
541
+ if (next < duration)
542
+ frame = requestAnimationFrame(tick);
543
+ else {
544
+ setState("paused");
545
+ callbacks.current.onStateChange?.("paused");
546
+ callbacks.current.onEnded?.();
547
+ }
548
+ }
549
+ return () => cancelAnimationFrame(frame);
550
+ }, [src, state, duration]);
551
+ function togglePlay() {
552
+ if (state === "playing") {
553
+ if (video.current)
554
+ video.current.pause();
555
+ else
556
+ changeState("paused");
557
+ return;
558
+ }
559
+ if (onBeforePlay?.() === false)
560
+ return;
561
+ if (video.current)
562
+ void video.current.play().catch((error) => onError?.(error));
563
+ else if (duration) {
564
+ if (position.current >= duration)
565
+ updateTime(0);
566
+ changeState("playing");
567
+ }
568
+ }
569
+ function seek(seconds) {
570
+ if (video.current)
571
+ video.current.currentTime = seconds;
572
+ else
573
+ updateTime(seconds);
574
+ }
575
+ async function toggleFullscreen() {
576
+ try {
577
+ const player = root.current;
578
+ if (!player?.requestFullscreen)
579
+ return;
580
+ if (player.ownerDocument.fullscreenElement === player)
581
+ await player.ownerDocument.exitFullscreen();
582
+ else
583
+ await player.requestFullscreen();
584
+ } catch (error) {
585
+ onError?.(error);
586
+ }
587
+ }
588
+ return _jsxs6("section", { ref: root, className: "vx-video-player", "aria-label": title, "data-placement": controlsPlacement, children: [_jsxs6("div", { className: "vx-video-stage", children: [src ? _jsx8("video", { ref: video, src, poster, muted, playsInline: true, preload: "metadata", onDurationChange: (event) => {
589
+ const value = event.currentTarget.duration;
590
+ setMetadataDuration(Number.isFinite(value) ? value : 0);
591
+ }, onPlay: () => changeState("playing"), onPause: (event) => {
592
+ updateTime(event.currentTarget.currentTime);
593
+ changeState("paused");
594
+ }, onTimeUpdate: (event) => updateTime(event.currentTarget.currentTime), onEnded, onError: (event) => onError?.(event.currentTarget.error) }) : poster && _jsx8("img", { src: poster, alt: "" }), overlay, state === "cover" && _jsxs6("div", { className: "vx-video-cover", children: [_jsxs6("div", { children: [_jsx8("strong", { children: title }), version && _jsx8(Tag, { children: version }), sceneLabel && _jsx8(Tag, { children: sceneLabel }), durationLabel && _jsx8(Tag, { children: durationLabel })] }), (src || duration > 0) && _jsx8(IconButton, { icon: "play", label: `Play ${title}`, variant: "icon-circle-lg", onClick: togglePlay })] })] }), _jsx8(PlaybackControls, { playing: state === "playing", muted, time: Math.min(time, duration), duration, disabled: !src && !duration, size: controlsSize, onTogglePlay: togglePlay, onToggleMute: () => setMuted(!muted), onSeek: seek, onFullscreen: showFullscreen ? () => void toggleFullscreen() : void 0 })] });
595
+ }
596
+
597
+ // packages/media-tools/src/ui/recipe-player.tsx
598
+ import * as React2 from "react";
599
+ function RecipePlayer({
600
+ video,
601
+ recipe: recipe2 = video.recipe,
602
+ editingCrop = false,
603
+ controlsPlacement = "below",
604
+ children
605
+ }) {
606
+ const root = React2.useRef(null);
607
+ const media = React2.useRef(null);
608
+ const fit = React2.useRef(null);
609
+ const [box, setBox] = React2.useState({ width: 640, height: 360 });
610
+ const [playing, setPlaying] = React2.useState(false);
611
+ const [muted, setMuted] = React2.useState(false);
612
+ const [time, setTime] = React2.useState(recipe2.trim.inMs / 1e3);
613
+ const [error, setError] = React2.useState("");
614
+ const bounds = React2.useRef(recipe2.trim);
615
+ bounds.current = recipe2.trim;
616
+ const crop = editingCrop ? { x: 0, y: 0, width: 1, height: 1 } : recipe2.crop;
617
+ const aspect = video.displayWidth * crop.width / (video.displayHeight * crop.height);
618
+ const width = Math.max(1, Math.min(box.width, box.height * aspect));
619
+ React2.useEffect(() => {
620
+ const element = fit.current;
621
+ if (!element) return;
622
+ const resize = () => setBox({ width: element.clientWidth, height: element.clientHeight });
623
+ resize();
624
+ const observer = new ResizeObserver(resize);
625
+ observer.observe(element);
626
+ return () => observer.disconnect();
627
+ }, []);
628
+ React2.useEffect(() => {
629
+ const element = media.current;
630
+ if (!element) return;
631
+ return () => {
632
+ element.pause();
633
+ element.removeAttribute("src");
634
+ element.load();
635
+ };
636
+ }, [video.previewUrl]);
637
+ React2.useEffect(() => {
638
+ const element = media.current;
639
+ if (!element || !playing) return;
640
+ let frame = 0;
641
+ const check = () => {
642
+ const range = bounds.current;
643
+ if (!element.paused && element.currentTime * 1e3 >= range.outMs - 1) {
644
+ element.pause();
645
+ element.currentTime = Math.max(range.inMs, range.outMs - 1) / 1e3;
646
+ }
647
+ frame = requestAnimationFrame(check);
648
+ };
649
+ frame = requestAnimationFrame(check);
650
+ return () => {
651
+ cancelAnimationFrame(frame);
652
+ };
653
+ }, [video.previewUrl, playing]);
654
+ React2.useEffect(() => {
655
+ const element = media.current;
656
+ if (element && Number.isFinite(element.duration)) {
657
+ const clamped = Math.max(
658
+ recipe2.trim.inMs / 1e3,
659
+ Math.min((recipe2.trim.outMs - 1) / 1e3, element.currentTime)
660
+ );
661
+ if (element.currentTime !== clamped) element.currentTime = clamped;
662
+ setTime(clamped);
663
+ }
664
+ }, [recipe2.trim.inMs, recipe2.trim.outMs]);
665
+ const seek = (seconds) => {
666
+ const element = media.current;
667
+ if (element)
668
+ element.currentTime = Math.max(
669
+ recipe2.trim.inMs,
670
+ Math.min(recipe2.trim.outMs - 1, recipe2.trim.inMs + seconds * 1e3)
671
+ ) / 1e3;
672
+ };
673
+ async function fullscreen() {
674
+ try {
675
+ if (document.fullscreenElement === root.current) await document.exitFullscreen();
676
+ else await root.current?.requestFullscreen();
677
+ } catch (failure) {
678
+ setError(readableError(failure));
679
+ }
680
+ }
681
+ return /* @__PURE__ */ React2.createElement(
682
+ "div",
683
+ {
684
+ className: "mt-player",
685
+ "data-placement": controlsPlacement,
686
+ ref: root,
687
+ "aria-label": video.name
688
+ },
689
+ /* @__PURE__ */ React2.createElement("div", { className: "mt-player-fit", ref: fit }, /* @__PURE__ */ React2.createElement("div", { className: "mt-picture", style: { width, height: width / aspect } }, /* @__PURE__ */ React2.createElement("div", { className: "mt-picture-clip" }, /* @__PURE__ */ React2.createElement(
690
+ "video",
691
+ {
692
+ ref: media,
693
+ src: video.previewUrl,
694
+ preload: "metadata",
695
+ playsInline: true,
696
+ muted,
697
+ "aria-label": video.name,
698
+ style: {
699
+ width: `${100 / crop.width}%`,
700
+ height: `${100 / crop.height}%`,
701
+ left: `${-crop.x * 100 / crop.width}%`,
702
+ top: `${-crop.y * 100 / crop.height}%`
703
+ },
704
+ onLoadedMetadata: (event) => {
705
+ event.currentTarget.currentTime = bounds.current.inMs / 1e3;
706
+ setTime(bounds.current.inMs / 1e3);
707
+ },
708
+ onSeeking: (event) => {
709
+ const element = event.currentTarget;
710
+ const value = Math.max(
711
+ bounds.current.inMs,
712
+ Math.min(bounds.current.outMs - 1, element.currentTime * 1e3)
713
+ ) / 1e3;
714
+ if (Math.abs(element.currentTime - value) > 5e-4) element.currentTime = value;
715
+ },
716
+ onPlay: () => setPlaying(true),
717
+ onPause: () => setPlaying(false),
718
+ onEnded: () => setPlaying(false),
719
+ onTimeUpdate: (event) => setTime(event.currentTarget.currentTime),
720
+ onError: () => setError("This fixed video could not be played. Reload its preview.")
721
+ }
722
+ )), children)),
723
+ /* @__PURE__ */ React2.createElement(
724
+ PlaybackControls,
725
+ {
726
+ playing,
727
+ muted,
728
+ time: Math.max(0, time - recipe2.trim.inMs / 1e3),
729
+ duration: (recipe2.trim.outMs - recipe2.trim.inMs) / 1e3,
730
+ onSeek: seek,
731
+ onToggleMute: () => setMuted(!muted),
732
+ onFullscreen: () => void fullscreen(),
733
+ onTogglePlay: () => {
734
+ const element = media.current;
735
+ if (!element) return;
736
+ if (element.paused) {
737
+ if (element.currentTime * 1e3 >= recipe2.trim.outMs - 2)
738
+ element.currentTime = recipe2.trim.inMs / 1e3;
739
+ void element.play().catch((failure) => setError(readableError(failure)));
740
+ } else element.pause();
741
+ }
742
+ }
743
+ ),
744
+ error && /* @__PURE__ */ React2.createElement("p", { role: "alert", className: "mt-error" }, error)
745
+ );
746
+ }
747
+
748
+ // packages/media-tools/src/ui/use-filmstrip.ts
749
+ import * as React3 from "react";
750
+ function useFilmstrip(src, enabled) {
751
+ const [result, setResult] = React3.useState();
752
+ React3.useEffect(() => {
753
+ if (!src || !enabled) return;
754
+ const controller = new AbortController();
755
+ const video = document.createElement("video");
756
+ const canvas2 = document.createElement("canvas");
757
+ video.crossOrigin = "anonymous";
758
+ video.muted = true;
759
+ video.playsInline = true;
760
+ video.preload = "auto";
761
+ function waitFor(event) {
762
+ return new Promise((resolve, reject) => {
763
+ function finish(error) {
764
+ clearTimeout(timer);
765
+ video.removeEventListener(event, ready);
766
+ video.removeEventListener("error", failed);
767
+ controller.signal.removeEventListener("abort", aborted);
768
+ if (error) reject(error);
769
+ else resolve();
770
+ }
771
+ const ready = () => finish();
772
+ const failed = () => finish(new Error("The source frames could not be decoded."));
773
+ const aborted = () => finish(new DOMException("Thumbnail decoding stopped.", "AbortError"));
774
+ const timer = setTimeout(() => finish(new Error("Thumbnail decoding timed out.")), 5e3);
775
+ video.addEventListener(event, ready, { once: true });
776
+ video.addEventListener("error", failed, { once: true });
777
+ controller.signal.addEventListener("abort", aborted, { once: true });
778
+ });
779
+ }
780
+ async function decode() {
781
+ const loaded = waitFor("loadeddata");
782
+ video.src = src;
783
+ video.load();
784
+ await loaded;
785
+ if (!Number.isFinite(video.duration) || video.duration <= 0) throw new Error("No duration.");
786
+ const count = 10;
787
+ const tileWidth = 80;
788
+ const tileHeight = 48;
789
+ canvas2.width = count * tileWidth;
790
+ canvas2.height = tileHeight;
791
+ const context = canvas2.getContext("2d");
792
+ if (!context || !video.videoWidth || !video.videoHeight) throw new Error("No video frames.");
793
+ for (let index = 0; index < count; index++) {
794
+ if (controller.signal.aborted) return;
795
+ const time = video.duration * (index + 0.5) / count;
796
+ const seeked = waitFor("seeked");
797
+ video.currentTime = time;
798
+ await seeked;
799
+ if (controller.signal.aborted) return;
800
+ const scale = Math.max(tileWidth / video.videoWidth, tileHeight / video.videoHeight);
801
+ const width = tileWidth / scale;
802
+ const height = tileHeight / scale;
803
+ context.drawImage(
804
+ video,
805
+ (video.videoWidth - width) / 2,
806
+ (video.videoHeight - height) / 2,
807
+ width,
808
+ height,
809
+ index * tileWidth,
810
+ 0,
811
+ tileWidth,
812
+ tileHeight
813
+ );
814
+ }
815
+ if (!controller.signal.aborted)
816
+ setResult({ src, thumbnail: canvas2.toDataURL("image/jpeg", 0.75) });
817
+ }
818
+ void decode().catch(() => {
819
+ if (!controller.signal.aborted)
820
+ setResult({
821
+ src,
822
+ error: "Thumbnail preview is unavailable. Timing controls still work."
823
+ });
824
+ }).finally(() => {
825
+ video.pause();
826
+ video.removeAttribute("src");
827
+ video.load();
828
+ canvas2.width = 0;
829
+ canvas2.height = 0;
830
+ });
831
+ return () => {
832
+ controller.abort();
833
+ video.pause();
834
+ video.removeAttribute("src");
835
+ video.load();
836
+ };
837
+ }, [src, enabled]);
838
+ return result?.src === src && enabled ? result : void 0;
839
+ }
840
+
841
+ // packages/media-tools/src/ui/editor.tsx
842
+ var ratios = ["Original", "Freeform", "9:16", "3:4", "1:1", "4:3", "16:9", "21:9"];
843
+ var clamp2 = (value, min, max) => Math.max(min, Math.min(max, value));
844
+ function gcd(a, b) {
845
+ return b ? gcd(b, a % b) : a;
846
+ }
847
+ function ratioParts(value, width, height) {
848
+ if (value === "Freeform") return null;
849
+ const [w, h] = value === "Original" ? [width, height] : value.split(":").map(Number);
850
+ const divisor = gcd(w, h);
851
+ return [w / divisor, h / divisor];
852
+ }
853
+ function fraction(rect, video) {
854
+ return {
855
+ x: rect.x / video.displayWidth,
856
+ y: rect.y / video.displayHeight,
857
+ width: rect.width / video.displayWidth,
858
+ height: rect.height / video.displayHeight
859
+ };
860
+ }
861
+ function CropFrame({
862
+ video,
863
+ crop,
864
+ ratio,
865
+ onChange
866
+ }) {
867
+ const drag = React4.useRef(null);
868
+ const parts = ratioParts(ratio, video.displayWidth, video.displayHeight);
869
+ function move(original, dx, dy, edge) {
870
+ if (edge === "move") {
871
+ onChange({
872
+ ...original,
873
+ x: clamp2(original.x + dx, 0, 1 - original.width),
874
+ y: clamp2(original.y + dy, 0, 1 - original.height)
875
+ });
876
+ return;
877
+ }
878
+ const east = edge.endsWith("e"), south = edge.startsWith("s");
879
+ const ax = east ? original.x : original.x + original.width;
880
+ const ay = south ? original.y : original.y + original.height;
881
+ const maxW = east ? 1 - ax : ax, maxH = south ? 1 - ay : ay;
882
+ let width = clamp2(original.width + (east ? dx : -dx), 2 / video.displayWidth, maxW);
883
+ let height = clamp2(original.height + (south ? dy : -dy), 2 / video.displayHeight, maxH);
884
+ if (parts) {
885
+ const [p, q] = parts;
886
+ const proposed = Math.abs(dx) >= Math.abs(dy) ? width * video.displayWidth / (2 * p) : height * video.displayHeight / (2 * q);
887
+ const maximum = Math.floor(
888
+ Math.min(maxW * video.displayWidth / (2 * p), maxH * video.displayHeight / (2 * q)) + 1e-8
889
+ );
890
+ if (maximum < 1) return;
891
+ const multiple = clamp2(Math.round(proposed), 1, maximum);
892
+ width = 2 * p * multiple / video.displayWidth;
893
+ height = 2 * q * multiple / video.displayHeight;
894
+ }
895
+ onChange({ x: east ? ax : ax - width, y: south ? ay : ay - height, width, height });
896
+ }
897
+ function start(event, edge) {
898
+ if (event.button !== 0) return;
899
+ event.stopPropagation();
900
+ event.preventDefault();
901
+ event.currentTarget.focus();
902
+ event.currentTarget.setPointerCapture(event.pointerId);
903
+ drag.current = {
904
+ element: event.currentTarget,
905
+ pointerId: event.pointerId,
906
+ x: event.clientX,
907
+ y: event.clientY,
908
+ crop,
909
+ edge
910
+ };
911
+ }
912
+ function key(event, edge) {
913
+ const step = event.shiftKey ? 10 : 1;
914
+ const x = (parts && edge !== "move" ? 2 * parts[0] : 2) * step / video.displayWidth;
915
+ const y = (parts && edge !== "move" ? 2 * parts[1] : 2) * step / video.displayHeight;
916
+ const changes = {
917
+ ArrowLeft: [-x, 0],
918
+ ArrowRight: [x, 0],
919
+ ArrowUp: [0, -y],
920
+ ArrowDown: [0, y]
921
+ };
922
+ const change = changes[event.key];
923
+ if (!change) return;
924
+ event.preventDefault();
925
+ event.stopPropagation();
926
+ move(crop, ...change, edge);
927
+ }
928
+ const position = {
929
+ left: `${crop.x * 100}%`,
930
+ top: `${crop.y * 100}%`,
931
+ width: `${crop.width * 100}%`,
932
+ height: `${crop.height * 100}%`
933
+ };
934
+ return /* @__PURE__ */ React4.createElement(React4.Fragment, null, /* @__PURE__ */ React4.createElement("div", { className: "mt-crop-shade", "aria-hidden": "true" }, /* @__PURE__ */ React4.createElement("span", { style: position })), /* @__PURE__ */ React4.createElement(
935
+ "div",
936
+ {
937
+ className: "mt-crop-frame",
938
+ tabIndex: 0,
939
+ role: "group",
940
+ "aria-label": "Crop selection",
941
+ "aria-description": "Drag to move. Arrow keys move two pixels. Shift moves ten steps.",
942
+ style: position,
943
+ onKeyDown: (event) => key(event, "move"),
944
+ onPointerDown: (event) => start(event, "move"),
945
+ onPointerMove: (event) => {
946
+ const current = drag.current;
947
+ const box = event.currentTarget.closest(".mt-picture")?.getBoundingClientRect();
948
+ if (current && current.pointerId === event.pointerId && box?.width && box.height)
949
+ move(
950
+ current.crop,
951
+ (event.clientX - current.x) / box.width,
952
+ (event.clientY - current.y) / box.height,
953
+ current.edge
954
+ );
955
+ },
956
+ onPointerUp: () => {
957
+ const current = drag.current;
958
+ if (current?.element.hasPointerCapture(current.pointerId))
959
+ current.element.releasePointerCapture(current.pointerId);
960
+ drag.current = null;
961
+ },
962
+ onPointerCancel: () => {
963
+ drag.current = null;
964
+ }
965
+ },
966
+ /* @__PURE__ */ React4.createElement("span", { className: "mt-crop-grid", "aria-hidden": "true" }),
967
+ ["nw", "ne", "sw", "se"].map((edge) => /* @__PURE__ */ React4.createElement(
968
+ "button",
969
+ {
970
+ type: "button",
971
+ key: edge,
972
+ className: "mt-crop-handle",
973
+ "data-corner": edge,
974
+ "aria-label": `Resize ${edge.startsWith("n") ? "top" : "bottom"} ${edge.endsWith("w") ? "left" : "right"}`,
975
+ onPointerDown: (event) => start(event, edge),
976
+ onKeyDown: (event) => key(event, edge)
977
+ }
978
+ ))
979
+ ));
980
+ }
981
+ function VideoEditor({ input, mode, onApply, onClose }) {
982
+ const { client, instanceId, resolve } = useMediaClient();
983
+ const [video, setVideo] = React4.useState(null);
984
+ const [draft, setDraft] = React4.useState(null);
985
+ const [ratio, setRatio] = React4.useState("Freeform");
986
+ const [error, setError] = React4.useState("");
987
+ const [saving, setSaving] = React4.useState(false);
988
+ const [reload, setReload] = React4.useState(0);
989
+ const generation = React4.useRef(0);
990
+ const edit = React4.useRef(null);
991
+ const request = React4.useRef(null);
992
+ const saved = React4.useRef(null);
993
+ const identity = JSON.stringify(input);
994
+ const filmstrip = useFilmstrip(video?.previewUrl, mode === "trim");
995
+ React4.useEffect(() => {
996
+ const current = ++generation.current;
997
+ setVideo(null);
998
+ setDraft(null);
999
+ setError("");
1000
+ setSaving(false);
1001
+ saved.current = null;
1002
+ request.current = null;
1003
+ edit.current = null;
1004
+ void resolve(input).then((value) => {
1005
+ if (generation.current !== current) return;
1006
+ setVideo(value);
1007
+ setDraft(value.recipe);
1008
+ if (value.editRef && value.revision)
1009
+ edit.current = { editId: value.editRef.objectId, expectedRevision: value.revision };
1010
+ const r = value.geometry.pixelRect;
1011
+ const known = ratios.filter((label) => label !== "Freeform").find((label) => {
1012
+ const [p, q] = ratioParts(label, value.displayWidth, value.displayHeight);
1013
+ return r.width * q === r.height * p;
1014
+ });
1015
+ setRatio(known || "Freeform");
1016
+ }).catch((failure) => {
1017
+ if (generation.current === current) setError(readableError(failure));
1018
+ });
1019
+ return () => {
1020
+ generation.current++;
1021
+ };
1022
+ }, [resolve, identity, reload]);
1023
+ function change(value) {
1024
+ if (!video) return;
1025
+ try {
1026
+ setDraft(
1027
+ normalizeRecipe(value, video.displayWidth, video.displayHeight, video.durationMs).recipe
1028
+ );
1029
+ setError("");
1030
+ } catch (failure) {
1031
+ setError(readableError(failure));
1032
+ }
1033
+ }
1034
+ function chooseRatio(value) {
1035
+ setRatio(value);
1036
+ if (!video || !draft) return;
1037
+ const parts = ratioParts(value, video.displayWidth, video.displayHeight);
1038
+ if (!parts) return;
1039
+ const [p, q] = parts;
1040
+ const multiple = Math.floor(
1041
+ Math.min(video.displayWidth / (2 * p), video.displayHeight / (2 * q))
1042
+ );
1043
+ if (!multiple) {
1044
+ setError("This picture cannot represent that ratio on the encoding grid.");
1045
+ return;
1046
+ }
1047
+ const width = 2 * p * multiple, height = 2 * q * multiple;
1048
+ const centerX = (draft.crop.x + draft.crop.width / 2) * video.displayWidth;
1049
+ const centerY = (draft.crop.y + draft.crop.height / 2) * video.displayHeight;
1050
+ const x = Math.round(clamp2(centerX - width / 2, 0, video.displayWidth - width) / 2) * 2;
1051
+ const y = Math.round(clamp2(centerY - height / 2, 0, video.displayHeight - height) / 2) * 2;
1052
+ change({ ...draft, crop: fraction({ x, y, width, height }, video) });
1053
+ }
1054
+ async function apply() {
1055
+ if (!video || !draft || saving) return;
1056
+ const current = generation.current;
1057
+ setSaving(true);
1058
+ setError("");
1059
+ try {
1060
+ const digest = JSON.stringify(draft);
1061
+ let value = saved.current?.digest === digest ? saved.current.value : null;
1062
+ if (!value) {
1063
+ const intent = { file: video.file, recipe: draft, ...edit.current || {} };
1064
+ const encoded = JSON.stringify(intent);
1065
+ if (request.current?.input !== encoded)
1066
+ request.current = { input: encoded, key: crypto.randomUUID() };
1067
+ value = await client.invoke({ instanceId, operationId: "edits.save" }, intent, {
1068
+ requestKey: request.current.key
1069
+ });
1070
+ if (generation.current !== current) return;
1071
+ saved.current = { digest, value };
1072
+ edit.current = { editId: value.editRef.objectId, expectedRevision: value.revision };
1073
+ }
1074
+ if (generation.current !== current) return;
1075
+ await onApply(value);
1076
+ if (generation.current === current) onClose();
1077
+ } catch (failure) {
1078
+ if (requestRejected(failure)) request.current = null;
1079
+ if (generation.current === current) setError(readableError(failure));
1080
+ } finally {
1081
+ if (generation.current === current) setSaving(false);
1082
+ }
1083
+ }
1084
+ const rect = video && draft ? normalizeRecipe(draft, video.displayWidth, video.displayHeight, video.durationMs).geometry.pixelRect : null;
1085
+ return /* @__PURE__ */ React4.createElement(
1086
+ "div",
1087
+ {
1088
+ className: "mt-editor",
1089
+ "data-mode": mode,
1090
+ onKeyDownCapture: (event) => {
1091
+ if (event.key === "Escape") event.stopPropagation();
1092
+ }
1093
+ },
1094
+ /* @__PURE__ */ React4.createElement(
1095
+ Dialog,
1096
+ {
1097
+ title: mode === "crop" ? "Crop Video" : "Trim Video",
1098
+ open: true,
1099
+ onOpenChange: (open) => {
1100
+ if (!open && !saving) onClose();
1101
+ },
1102
+ actions: /* @__PURE__ */ React4.createElement("div", { className: "mt-editor-actions" }, /* @__PURE__ */ React4.createElement(
1103
+ Button,
1104
+ {
1105
+ label: "Reset",
1106
+ leadingIcon: "reset",
1107
+ width: "hug",
1108
+ variant: "text-ghost-md",
1109
+ disabled: !draft || saving,
1110
+ onClick: () => {
1111
+ if (!draft || !video) return;
1112
+ if (mode === "crop") {
1113
+ setRatio("Original");
1114
+ change({ ...draft, crop: { x: 0, y: 0, width: 1, height: 1 } });
1115
+ } else change({ ...draft, trim: { inMs: 0, outMs: video.durationMs } });
1116
+ }
1117
+ }
1118
+ ), /* @__PURE__ */ React4.createElement("div", { className: "mt-editor-confirm" }, /* @__PURE__ */ React4.createElement(
1119
+ Button,
1120
+ {
1121
+ label: "Cancel",
1122
+ variant: "text-tonal-md",
1123
+ width: "hug",
1124
+ disabled: saving,
1125
+ onClick: onClose
1126
+ }
1127
+ ), /* @__PURE__ */ React4.createElement(
1128
+ Button,
1129
+ {
1130
+ variant: "text-filled-md",
1131
+ width: "hug",
1132
+ label: "Apply",
1133
+ loading: saving,
1134
+ disabled: !draft || !video,
1135
+ onClick: () => void apply()
1136
+ }
1137
+ )))
1138
+ },
1139
+ video && draft ? /* @__PURE__ */ React4.createElement("div", { inert: saving, "aria-busy": saving }, /* @__PURE__ */ React4.createElement("p", { className: "mt-subtitle" }, video.name, " \xB7 v", video.versionNumber), video.colorInterpretation === "assumed-bt709" && /* @__PURE__ */ React4.createElement("p", { className: "mt-subtitle" }, "Color information is missing. Standard SDR colors are assumed; export may differ slightly."), /* @__PURE__ */ React4.createElement(
1140
+ RecipePlayer,
1141
+ {
1142
+ video,
1143
+ recipe: draft,
1144
+ editingCrop: mode === "crop",
1145
+ controlsPlacement: mode === "crop" ? "below" : "overlay"
1146
+ },
1147
+ mode === "crop" && /* @__PURE__ */ React4.createElement(
1148
+ CropFrame,
1149
+ {
1150
+ video,
1151
+ crop: draft.crop,
1152
+ ratio,
1153
+ onChange: (crop) => change({ ...draft, crop })
1154
+ }
1155
+ )
1156
+ ), mode === "trim" ? /* @__PURE__ */ React4.createElement(React4.Fragment, null, /* @__PURE__ */ React4.createElement("p", { className: "mt-editor-hint" }, "Drag the handle to trim the video"), /* @__PURE__ */ React4.createElement(
1157
+ FrameRange,
1158
+ {
1159
+ thumbnail: filmstrip?.thumbnail,
1160
+ duration: video.durationMs / 1e3,
1161
+ variant: "trim",
1162
+ step: 1e-3,
1163
+ value: { start: draft.trim.inMs / 1e3, end: draft.trim.outMs / 1e3 },
1164
+ onValueChange: (value) => change({
1165
+ ...draft,
1166
+ trim: {
1167
+ inMs: Math.round(value.start * 1e3),
1168
+ outMs: Math.round(value.end * 1e3)
1169
+ }
1170
+ })
1171
+ }
1172
+ ), filmstrip?.error && /* @__PURE__ */ React4.createElement("p", { className: "mt-help", role: "status" }, filmstrip.error), /* @__PURE__ */ React4.createElement("details", { className: "mt-precision" }, /* @__PURE__ */ React4.createElement("summary", null, "Precise timing"), /* @__PURE__ */ React4.createElement("div", { className: "mt-fields" }, ["inMs", "outMs"].map((edge) => /* @__PURE__ */ React4.createElement("label", { key: edge }, edge === "inMs" ? "In (seconds)" : "Out (seconds)", /* @__PURE__ */ React4.createElement(
1173
+ "input",
1174
+ {
1175
+ type: "number",
1176
+ min: "0",
1177
+ max: video.durationMs / 1e3,
1178
+ step: "0.001",
1179
+ value: draft.trim[edge] / 1e3,
1180
+ disabled: saving,
1181
+ onChange: (event) => {
1182
+ if (Number.isFinite(event.currentTarget.valueAsNumber))
1183
+ change({
1184
+ ...draft,
1185
+ trim: {
1186
+ ...draft.trim,
1187
+ [edge]: Math.round(event.currentTarget.valueAsNumber * 1e3)
1188
+ }
1189
+ });
1190
+ }
1191
+ }
1192
+ )))))) : /* @__PURE__ */ React4.createElement(React4.Fragment, null, /* @__PURE__ */ React4.createElement("div", { className: "mt-editor-hint" }, /* @__PURE__ */ React4.createElement("span", null, "Drag the frame to move. Drag a corner to resize."), /* @__PURE__ */ React4.createElement("span", { role: "status" }, rect?.width, " \xD7 ", rect?.height)), /* @__PURE__ */ React4.createElement(
1193
+ SegmentedControl,
1194
+ {
1195
+ label: "Aspect ratio",
1196
+ items: ratios.map((value) => ({ value, label: value })),
1197
+ value: ratio,
1198
+ onValueChange: chooseRatio,
1199
+ size: "large",
1200
+ width: "full"
1201
+ }
1202
+ ))) : !error && /* @__PURE__ */ React4.createElement("p", { role: "status" }, "Loading fixed video\u2026"),
1203
+ error && /* @__PURE__ */ React4.createElement("div", { role: "alert", className: "mt-error" }, error, !video && /* @__PURE__ */ React4.createElement(
1204
+ Button,
1205
+ {
1206
+ label: "Reload preview",
1207
+ variant: "text-ghost-sm",
1208
+ onClick: () => setReload(reload + 1)
1209
+ }
1210
+ ))
1211
+ )
1212
+ );
1213
+ }
1214
+
1215
+ // packages/media-tools/src/ui/compare.tsx
1216
+ import * as React5 from "react";
1217
+ function formatLabel(width, height) {
1218
+ let a = width, b = height;
1219
+ while (b) {
1220
+ const remainder = a % b;
1221
+ a = b;
1222
+ b = remainder;
1223
+ }
1224
+ return `${width / a}:${height / a}`;
1225
+ }
1226
+ function Candidate({
1227
+ slot,
1228
+ menu,
1229
+ replacing,
1230
+ onChoose,
1231
+ emptyState
1232
+ }) {
1233
+ const { resolve } = useMediaClient();
1234
+ const [video, setVideo] = React5.useState(null);
1235
+ const [error, setError] = React5.useState("");
1236
+ const [revision, setRevision] = React5.useState(0);
1237
+ const identity = JSON.stringify(slot.input);
1238
+ React5.useEffect(() => {
1239
+ let active = true;
1240
+ setVideo(null);
1241
+ setError("");
1242
+ if (slot.input)
1243
+ void resolve(slot.input).then((value) => {
1244
+ if (active) setVideo(value);
1245
+ }).catch((failure) => {
1246
+ if (active) setError(readableError(failure));
1247
+ });
1248
+ return () => {
1249
+ active = false;
1250
+ };
1251
+ }, [resolve, identity, revision]);
1252
+ return /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("div", { className: "mt-compare-preview" }, replacing ? /* @__PURE__ */ React5.createElement("div", { className: "mt-empty", role: "status" }, "Choosing replacement\u2026") : !slot.input ? /* @__PURE__ */ React5.createElement("div", { className: "mt-empty" }, emptyState ?? /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("p", null, "No video selected."), /* @__PURE__ */ React5.createElement(
1253
+ Button,
1254
+ {
1255
+ label: "Choose video",
1256
+ variant: "text-tonal-sm",
1257
+ width: "hug",
1258
+ onClick: onChoose
1259
+ }
1260
+ ))) : error ? /* @__PURE__ */ React5.createElement("div", { className: "mt-empty", role: "alert" }, /* @__PURE__ */ React5.createElement("p", null, error), /* @__PURE__ */ React5.createElement(
1261
+ Button,
1262
+ {
1263
+ label: "Reload preview",
1264
+ variant: "text-ghost-sm",
1265
+ width: "hug",
1266
+ onClick: () => setRevision(revision + 1)
1267
+ }
1268
+ )) : !video ? /* @__PURE__ */ React5.createElement("div", { className: "mt-empty", role: "status" }, "Loading fixed video\u2026") : video.edited ? /* @__PURE__ */ React5.createElement(RecipePlayer, { video }) : /* @__PURE__ */ React5.createElement(
1269
+ VideoPlayer,
1270
+ {
1271
+ src: video.previewUrl,
1272
+ title: video.name,
1273
+ controlsPlacement: "below",
1274
+ onError: () => setError("This video could not be played. Reload its fixed preview.")
1275
+ }
1276
+ )), /* @__PURE__ */ React5.createElement("div", { className: "mt-candidate-caption" }, /* @__PURE__ */ React5.createElement("div", { className: "mt-candidate-heading" }, /* @__PURE__ */ React5.createElement("div", null, /* @__PURE__ */ React5.createElement("strong", null, slot.input ? slot.context?.shotName || video?.name || "Video" : "Candidate"), video && /* @__PURE__ */ React5.createElement("span", null, "Variant ", video.versionNumber, video.edited ? " \xB7 Edited" : "")), menu), video && /* @__PURE__ */ React5.createElement("span", null, slot.context?.shotName ? `${video.name} \xB7 ` : "", video.geometry.pixelRect.width, " \xD7 ", video.geometry.pixelRect.height, " \xB7", " ", (video.effectiveDurationMs / 1e3).toFixed(2), " s"), video?.colorInterpretation === "assumed-bt709" && /* @__PURE__ */ React5.createElement("span", null, "Color information is missing. Standard SDR colors are assumed; export may differ slightly.")), /* @__PURE__ */ React5.createElement("div", { className: "mt-candidate-context" }, slot.input && (video || slot.context?.hook || slot.context?.cta) && /* @__PURE__ */ React5.createElement("dl", null, slot.context?.hook && /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("dt", null, "Opening Hook"), /* @__PURE__ */ React5.createElement("dd", null, slot.context?.hook)), slot.context?.cta && /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("dt", null, "CTA"), /* @__PURE__ */ React5.createElement("dd", null, slot.context?.cta)), video && /* @__PURE__ */ React5.createElement(React5.Fragment, null, /* @__PURE__ */ React5.createElement("dt", null, "Format"), /* @__PURE__ */ React5.createElement("dd", null, formatLabel(video.geometry.pixelRect.width, video.geometry.pixelRect.height)), /* @__PURE__ */ React5.createElement("dt", null, "Duration"), /* @__PURE__ */ React5.createElement("dd", null, Number((video.effectiveDurationMs / 1e3).toFixed(2)), "s")))));
1277
+ }
1278
+ function VideoCompare(props) {
1279
+ const [generation, setGeneration] = React5.useState(0);
1280
+ const [replacing, setReplacing] = React5.useState(null);
1281
+ const [error, setError] = React5.useState("");
1282
+ const active = React5.useRef(true);
1283
+ React5.useEffect(() => {
1284
+ active.current = true;
1285
+ return () => {
1286
+ active.current = false;
1287
+ };
1288
+ }, []);
1289
+ if (props.slots.length < 2 || props.slots.length > 4 || new Set(props.slots.map((slot) => slot.id)).size !== props.slots.length)
1290
+ return /* @__PURE__ */ React5.createElement("p", { role: "alert" }, "Compare requires two to four uniquely identified columns.");
1291
+ const remove = (slot) => props.onSlotsChange(
1292
+ props.slots.length > 2 ? props.slots.filter((value) => value.id !== slot.id) : props.slots.map((value) => value.id === slot.id ? { ...value, input: null } : value)
1293
+ );
1294
+ async function replace(slot) {
1295
+ if (!props.onRequestReplacement) return;
1296
+ setReplacing(slot.id);
1297
+ setError("");
1298
+ try {
1299
+ const input = await props.onRequestReplacement(slot.id);
1300
+ if (input && active.current)
1301
+ props.onSlotsChange(
1302
+ props.slots.map((value) => value.id === slot.id ? { ...value, input } : value)
1303
+ );
1304
+ } catch (failure) {
1305
+ if (active.current) setError(readableError(failure));
1306
+ } finally {
1307
+ if (active.current) setReplacing(null);
1308
+ }
1309
+ }
1310
+ function candidateChoices(slot) {
1311
+ return (props.candidates || []).filter(
1312
+ (candidate) => !props.slots.some(
1313
+ (other) => other.id !== slot.id && JSON.stringify(other.input) === JSON.stringify(candidate.input)
1314
+ )
1315
+ ).map((candidate, index) => ({
1316
+ id: `candidate-${index}`,
1317
+ label: candidate.label,
1318
+ onSelect: () => props.onSlotsChange(
1319
+ props.slots.map(
1320
+ (value) => value.id === slot.id ? { ...value, input: candidate.input, context: candidate.context } : value
1321
+ )
1322
+ )
1323
+ }));
1324
+ }
1325
+ return /* @__PURE__ */ React5.createElement("section", { className: "mt-compare", "aria-label": "Compare videos" }, /* @__PURE__ */ React5.createElement("div", { className: "mt-toolbar" }, /* @__PURE__ */ React5.createElement("p", { className: "mt-help" }, "Each video plays independently."), /* @__PURE__ */ React5.createElement(
1326
+ Button,
1327
+ {
1328
+ label: "Add column",
1329
+ width: "hug",
1330
+ variant: "text-tonal-sm",
1331
+ disabled: props.slots.length >= 4,
1332
+ onClick: () => props.onSlotsChange([...props.slots, { id: crypto.randomUUID(), input: null }])
1333
+ }
1334
+ )), error && /* @__PURE__ */ React5.createElement("p", { role: "alert", className: "mt-error" }, error), /* @__PURE__ */ React5.createElement(
1335
+ "div",
1336
+ {
1337
+ className: "mt-compare-columns",
1338
+ style: { gridTemplateColumns: `repeat(${props.slots.length}, minmax(240px,1fr))` }
1339
+ },
1340
+ props.slots.map((slot, index) => /* @__PURE__ */ React5.createElement("article", { className: "mt-compare-column", key: slot.id, "aria-label": `Video ${index + 1}` }, /* @__PURE__ */ React5.createElement(
1341
+ Candidate,
1342
+ {
1343
+ key: JSON.stringify([slot.id, slot.input, generation]),
1344
+ slot,
1345
+ replacing: replacing === slot.id,
1346
+ onChoose: () => void replace(slot),
1347
+ emptyState: props.candidates ? candidateChoices(slot).length ? /* @__PURE__ */ React5.createElement(Menu, { label: "Choose video", floating: true, items: candidateChoices(slot) }) : /* @__PURE__ */ React5.createElement("p", null, "No other candidates yet.") : void 0,
1348
+ menu: (slot.input || props.slots.length > 2 || candidateChoices(slot).length > 0 || !props.candidates) && /* @__PURE__ */ React5.createElement(
1349
+ Menu,
1350
+ {
1351
+ label: `Options for video ${index + 1}`,
1352
+ triggerIcon: "more",
1353
+ floating: true,
1354
+ items: [
1355
+ ...props.candidates ? [
1356
+ {
1357
+ id: "replace",
1358
+ label: "Choose video",
1359
+ disabled: candidateChoices(slot).length === 0,
1360
+ items: candidateChoices(slot)
1361
+ }
1362
+ ] : [
1363
+ {
1364
+ id: "replace",
1365
+ label: slot.input ? "Replace" : "Choose video",
1366
+ disabled: replacing !== null,
1367
+ onSelect: () => void replace(slot)
1368
+ }
1369
+ ],
1370
+ ...slot.input ? [
1371
+ {
1372
+ id: "details",
1373
+ label: "Details",
1374
+ onSelect: () => {
1375
+ setGeneration((value) => value + 1);
1376
+ props.onOpenDetails(slot.input, {
1377
+ slots: props.slots,
1378
+ origin: props.origin
1379
+ });
1380
+ }
1381
+ }
1382
+ ] : [],
1383
+ { id: "remove", label: "Remove", onSelect: () => remove(slot) }
1384
+ ]
1385
+ }
1386
+ )
1387
+ }
1388
+ ), slot.input && props.renderSlotActions && /* @__PURE__ */ React5.createElement("div", { className: "mt-column-actions" }, props.renderSlotActions(slot))))
1389
+ ));
1390
+ }
1391
+
1392
+ // packages/media-tools/src/ui/jobs.tsx
1393
+ import * as React6 from "react";
1394
+ var labels = {
1395
+ queued: "Queued",
1396
+ running: "Processing",
1397
+ saving: "Saving result",
1398
+ succeeded: "Completed",
1399
+ failed: "Failed",
1400
+ canceled: "Canceled",
1401
+ interrupted: "Interrupted"
1402
+ };
1403
+ function MediaJobs({ onOpenResult }) {
1404
+ const { client, instanceId } = useMediaClient();
1405
+ const [page, setPage] = React6.useState({ items: [], nextOffset: null });
1406
+ const [offset, setOffset] = React6.useState(0);
1407
+ const [refresh, setRefresh] = React6.useState(0);
1408
+ const [error, setError] = React6.useState("");
1409
+ const [pending, setPending] = React6.useState(null);
1410
+ const keys = React6.useRef(/* @__PURE__ */ new Map());
1411
+ const live = React6.useRef(true);
1412
+ React6.useEffect(() => {
1413
+ live.current = true;
1414
+ return () => {
1415
+ live.current = false;
1416
+ };
1417
+ }, []);
1418
+ React6.useEffect(() => {
1419
+ let active = true, timer;
1420
+ async function poll() {
1421
+ try {
1422
+ const result = await client.invoke(
1423
+ { instanceId, operationId: "jobs.list" },
1424
+ { limit: 50, offset }
1425
+ );
1426
+ if (active) {
1427
+ setPage(result);
1428
+ setError("");
1429
+ }
1430
+ } catch (failure) {
1431
+ if (active) setError(readableError(failure));
1432
+ } finally {
1433
+ if (active) timer = setTimeout(() => void poll(), 1e3);
1434
+ }
1435
+ }
1436
+ void poll();
1437
+ return () => {
1438
+ active = false;
1439
+ if (timer) clearTimeout(timer);
1440
+ };
1441
+ }, [client, instanceId, offset, refresh]);
1442
+ async function act(job, action) {
1443
+ const identity = `${action}:${job.jobId}`;
1444
+ const key = keys.current.get(identity) || crypto.randomUUID();
1445
+ keys.current.set(identity, key);
1446
+ setPending(identity);
1447
+ setError("");
1448
+ try {
1449
+ if (action === "cancel")
1450
+ await client.invoke(
1451
+ { instanceId, operationId: "jobs.cancel" },
1452
+ { jobId: job.jobId },
1453
+ { requestKey: key }
1454
+ );
1455
+ else await submitOrFind(client, instanceId, job.retryRequest, key);
1456
+ keys.current.delete(identity);
1457
+ if (live.current) {
1458
+ setOffset(0);
1459
+ setRefresh((value) => value + 1);
1460
+ }
1461
+ } catch (failure) {
1462
+ if (requestRejected(failure)) keys.current.delete(identity);
1463
+ if (live.current) setError(readableError(failure));
1464
+ } finally {
1465
+ if (live.current) setPending(null);
1466
+ }
1467
+ }
1468
+ return /* @__PURE__ */ React6.createElement("section", { className: "mt-jobs", "aria-label": "Media tasks" }, /* @__PURE__ */ React6.createElement("div", { className: "mt-toolbar" }, /* @__PURE__ */ React6.createElement("div", null, /* @__PURE__ */ React6.createElement("h2", null, "Media tasks"), /* @__PURE__ */ React6.createElement("p", { className: "mt-help" }, "Processing continues when this page closes.")), /* @__PURE__ */ React6.createElement(
1469
+ Button,
1470
+ {
1471
+ label: "Refresh tasks",
1472
+ variant: "text-ghost-sm",
1473
+ width: "hug",
1474
+ onClick: () => setRefresh(refresh + 1)
1475
+ }
1476
+ )), error && /* @__PURE__ */ React6.createElement("p", { role: "alert", className: "mt-error" }, error), !page.items.length && /* @__PURE__ */ React6.createElement("p", { className: "mt-empty" }, "No media tasks on this page."), page.items.map((job) => /* @__PURE__ */ React6.createElement("article", { className: "mt-job", key: job.jobId }, /* @__PURE__ */ React6.createElement("div", null, /* @__PURE__ */ React6.createElement("strong", null, job.outputName), /* @__PURE__ */ React6.createElement("p", null, job.kind === "sequence" ? "Sequence export" : "Video processing", " \xB7", " ", job.cancelRequested && !["succeeded", "failed", "canceled", "interrupted"].includes(job.state) ? "Stopping\u2026" : labels[job.state]), job.cleanupPending && /* @__PURE__ */ React6.createElement("p", { className: "mt-error" }, "Cleanup is pending. New processing is blocked until the old process is confirmed stopped."), job.error && /* @__PURE__ */ React6.createElement("p", { className: "mt-error" }, job.error.message)), /* @__PURE__ */ React6.createElement("div", { className: "mt-job-progress" }, /* @__PURE__ */ React6.createElement(
1477
+ "progress",
1478
+ {
1479
+ "aria-label": `Progress for ${job.outputName}`,
1480
+ max: 1,
1481
+ value: job.state === "succeeded" ? 1 : job.progress === null ? void 0 : Math.min(0.99, job.progress)
1482
+ }
1483
+ ), /* @__PURE__ */ React6.createElement("span", null, job.state === "succeeded" ? "100%" : job.progress === null ? "Unknown progress" : `${Math.floor(Math.min(0.99, job.progress) * 100)}%`)), /* @__PURE__ */ React6.createElement("div", { className: "mt-column-actions" }, ["queued", "running", "saving"].includes(job.state) && /* @__PURE__ */ React6.createElement(
1484
+ Button,
1485
+ {
1486
+ label: "Cancel task",
1487
+ width: "hug",
1488
+ variant: "text-tonal-sm",
1489
+ disabled: pending !== null || job.cancelRequested,
1490
+ onClick: () => void act(job, "cancel")
1491
+ }
1492
+ ), ["failed", "canceled", "interrupted"].includes(job.state) && /* @__PURE__ */ React6.createElement(
1493
+ Button,
1494
+ {
1495
+ label: "Retry task",
1496
+ width: "hug",
1497
+ variant: "text-tonal-sm",
1498
+ disabled: pending !== null || job.cleanupPending,
1499
+ onClick: () => void act(job, "retry")
1500
+ }
1501
+ ), job.result && onOpenResult && /* @__PURE__ */ React6.createElement(Button, { label: "Open result", width: "hug", onClick: () => onOpenResult(job.result) }), /* @__PURE__ */ React6.createElement("details", null, /* @__PURE__ */ React6.createElement("summary", null, "Task identity"), /* @__PURE__ */ React6.createElement("code", null, job.jobId))))), /* @__PURE__ */ React6.createElement("div", { className: "mt-pagination" }, /* @__PURE__ */ React6.createElement(
1502
+ Button,
1503
+ {
1504
+ label: "Previous tasks",
1505
+ variant: "text-ghost-sm",
1506
+ disabled: offset === 0,
1507
+ onClick: () => setOffset(Math.max(0, offset - 50))
1508
+ }
1509
+ ), /* @__PURE__ */ React6.createElement(
1510
+ Button,
1511
+ {
1512
+ label: "Next tasks",
1513
+ variant: "text-ghost-sm",
1514
+ disabled: page.nextOffset === null,
1515
+ onClick: () => {
1516
+ if (page.nextOffset !== null) setOffset(page.nextOffset);
1517
+ }
1518
+ }
1519
+ )));
1520
+ }
1521
+
1522
+ // packages/media-tools/src/client.tsx
1523
+ var dependencies = (config) => [
1524
+ config.dataInstance,
1525
+ config.studioInstance
1526
+ ];
1527
+ async function activate(client) {
1528
+ const description = await client.describe();
1529
+ const instances = description.instances.filter(
1530
+ (value) => value.pluginId === "media-tools" && value.state === "ready"
1531
+ );
1532
+ if (instances.length !== 1)
1533
+ throw Error("Exactly one ready media-tools instance is required per project.");
1534
+ const instanceId = instances[0].id;
1535
+ let active = true;
1536
+ let resolving = Promise.resolve();
1537
+ const resolve = (input) => {
1538
+ const next = resolving.then(() => {
1539
+ if (!active) throw Error("This media-tools instance has stopped.");
1540
+ return client.invoke(
1541
+ { instanceId, operationId: "video.resolve" },
1542
+ input
1543
+ );
1544
+ });
1545
+ resolving = next.then(
1546
+ () => void 0,
1547
+ () => void 0
1548
+ );
1549
+ return next;
1550
+ };
1551
+ client.provide({
1552
+ capabilityVersion: "media-tools/client/1",
1553
+ resolve,
1554
+ submit: (request, requestKey) => submitOrFind(client, instanceId, request, requestKey)
1555
+ });
1556
+ const listeners = /* @__PURE__ */ new Set();
1557
+ const subscribe = (listener) => {
1558
+ listeners.add(listener);
1559
+ return () => {
1560
+ listeners.delete(listener);
1561
+ };
1562
+ };
1563
+ function Bound({
1564
+ component: Component,
1565
+ props
1566
+ }) {
1567
+ const ready = React7.useSyncExternalStore(
1568
+ subscribe,
1569
+ () => active,
1570
+ () => active
1571
+ );
1572
+ return ready ? /* @__PURE__ */ React7.createElement(MediaContext.Provider, { value: { client, instanceId, resolve } }, /* @__PURE__ */ React7.createElement("div", { className: "mt-root" }, /* @__PURE__ */ React7.createElement(Component, { ...props }))) : null;
1573
+ }
1574
+ client.registerUI({
1575
+ id: "media.video-editor",
1576
+ title: "Video editor",
1577
+ kind: "component",
1578
+ component: (props) => /* @__PURE__ */ React7.createElement(Bound, { component: VideoEditor, props })
1579
+ });
1580
+ client.registerUI({
1581
+ id: "media.video-compare",
1582
+ title: "Video comparison",
1583
+ kind: "component",
1584
+ component: (props) => /* @__PURE__ */ React7.createElement(Bound, { component: VideoCompare, props })
1585
+ });
1586
+ client.registerUI({
1587
+ id: "media.jobs",
1588
+ title: "Media tasks",
1589
+ kind: "component",
1590
+ component: (props) => /* @__PURE__ */ React7.createElement(Bound, { component: MediaJobs, props })
1591
+ });
1592
+ client.onDispose(() => {
1593
+ active = false;
1594
+ for (const listener of listeners) listener();
1595
+ listeners.clear();
1596
+ });
1597
+ }
1598
+ export {
1599
+ Config,
1600
+ MediaJobs,
1601
+ VideoCompare,
1602
+ VideoEditor,
1603
+ activate as default,
1604
+ dependencies,
1605
+ submitOrFind
1606
+ };