@openartifactsai/editor-kit 0.0.0-stage → 0.23.0-rc.0

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 (120) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +143 -2
  4. package/package.json +67 -4
  5. package/src/Announcer.d.ts +2 -0
  6. package/src/Announcer.js +8 -0
  7. package/src/FindBar.d.ts +31 -0
  8. package/src/FindBar.js +37 -0
  9. package/src/FoldToolbar.d.ts +58 -0
  10. package/src/FoldToolbar.js +438 -0
  11. package/src/PanelEdge.d.ts +20 -0
  12. package/src/PanelEdge.js +74 -0
  13. package/src/VideoShrinkNotice.d.ts +10 -0
  14. package/src/VideoShrinkNotice.js +81 -0
  15. package/src/WheelZoomItem.d.ts +12 -0
  16. package/src/WheelZoomItem.js +18 -0
  17. package/src/agent.d.ts +68 -0
  18. package/src/agent.js +113 -0
  19. package/src/announce.d.ts +21 -0
  20. package/src/announce.js +31 -0
  21. package/src/chrome.d.ts +208 -0
  22. package/src/chrome.js +148 -0
  23. package/src/clipboard.d.ts +19 -0
  24. package/src/clipboard.js +48 -0
  25. package/src/collab/CommentList.d.ts +32 -0
  26. package/src/collab/CommentList.js +165 -0
  27. package/src/collab/CommentViews.d.ts +131 -0
  28. package/src/collab/CommentViews.js +619 -0
  29. package/src/collab/HistoryViews.d.ts +38 -0
  30. package/src/collab/HistoryViews.js +103 -0
  31. package/src/collab/PresenceViews.d.ts +53 -0
  32. package/src/collab/PresenceViews.js +48 -0
  33. package/src/collab/cds/cds.d.ts +151 -0
  34. package/src/collab/cds/cds.js +231 -0
  35. package/src/collab/cds/comment-card.d.ts +113 -0
  36. package/src/collab/cds/comment-card.js +230 -0
  37. package/src/collab/cds/comment-composer.d.ts +35 -0
  38. package/src/collab/cds/comment-composer.js +125 -0
  39. package/src/collab/cds/comments-css.d.ts +2 -0
  40. package/src/collab/cds/comments-css.js +3 -0
  41. package/src/collab/cds/comments.css +504 -0
  42. package/src/collab/cds/edge-piles.d.ts +69 -0
  43. package/src/collab/cds/edge-piles.js +178 -0
  44. package/src/collab/cds/layer.d.ts +41 -0
  45. package/src/collab/cds/layer.js +144 -0
  46. package/src/collab/cds/markdown.d.ts +20 -0
  47. package/src/collab/cds/markdown.js +534 -0
  48. package/src/collab/cds/shield.d.ts +28 -0
  49. package/src/collab/cds/shield.js +114 -0
  50. package/src/collab/cds/time.d.ts +2 -0
  51. package/src/collab/cds/time.js +41 -0
  52. package/src/collab/collab.d.ts +102 -0
  53. package/src/collab/collab.js +121 -0
  54. package/src/collab/comments.d.ts +272 -0
  55. package/src/collab/comments.js +596 -0
  56. package/src/collab/history-wiring.d.ts +32 -0
  57. package/src/collab/history-wiring.js +53 -0
  58. package/src/collab/history.d.ts +59 -0
  59. package/src/collab/history.js +96 -0
  60. package/src/collab/mentions/mention-list.d.ts +63 -0
  61. package/src/collab/mentions/mention-list.js +257 -0
  62. package/src/collab/mentions.d.ts +112 -0
  63. package/src/collab/mentions.js +164 -0
  64. package/src/collab/peer-colors.d.ts +123 -0
  65. package/src/collab/peer-colors.js +273 -0
  66. package/src/collab/pins.d.ts +70 -0
  67. package/src/collab/pins.js +44 -0
  68. package/src/collab/presence.d.ts +92 -0
  69. package/src/collab/presence.js +158 -0
  70. package/src/design-systems.d.ts +46 -0
  71. package/src/design-systems.js +61 -0
  72. package/src/downloads.d.ts +31 -0
  73. package/src/downloads.js +46 -0
  74. package/src/file-drop.d.ts +33 -0
  75. package/src/file-drop.js +36 -0
  76. package/src/find.d.ts +64 -0
  77. package/src/find.js +147 -0
  78. package/src/follow.d.ts +141 -0
  79. package/src/follow.js +389 -0
  80. package/src/index.d.ts +32 -0
  81. package/src/index.js +32 -0
  82. package/src/keys.d.ts +18 -0
  83. package/src/keys.js +42 -0
  84. package/src/menu-fit.d.ts +12 -0
  85. package/src/menu-fit.js +9 -0
  86. package/src/merge.d.ts +23 -0
  87. package/src/merge.js +116 -0
  88. package/src/page-link.d.ts +33 -0
  89. package/src/page-link.js +75 -0
  90. package/src/project-sync.d.ts +161 -0
  91. package/src/project-sync.js +319 -0
  92. package/src/react.d.ts +20 -0
  93. package/src/react.js +20 -0
  94. package/src/read-retries.d.ts +55 -0
  95. package/src/read-retries.js +125 -0
  96. package/src/right-drag-pan.d.ts +128 -0
  97. package/src/right-drag-pan.js +253 -0
  98. package/src/roles.d.ts +39 -0
  99. package/src/roles.js +27 -0
  100. package/src/session.d.ts +56 -0
  101. package/src/session.js +57 -0
  102. package/src/shell.d.ts +60 -0
  103. package/src/shell.js +111 -0
  104. package/src/stash.d.ts +26 -0
  105. package/src/stash.js +69 -0
  106. package/src/styles.css +17 -0
  107. package/src/toolbar-fold.d.ts +106 -0
  108. package/src/toolbar-fold.js +130 -0
  109. package/src/video-shrink/index.d.ts +8 -0
  110. package/src/video-shrink/index.js +7 -0
  111. package/src/video-shrink/plan.d.ts +92 -0
  112. package/src/video-shrink/plan.js +133 -0
  113. package/src/video-shrink/protocol.d.ts +29 -0
  114. package/src/video-shrink/protocol.js +2 -0
  115. package/src/video-shrink/queue.d.ts +69 -0
  116. package/src/video-shrink/queue.js +287 -0
  117. package/src/video-shrink/worker.d.ts +8 -0
  118. package/src/video-shrink/worker.js +223 -0
  119. package/src/wheel-zoom.d.ts +14 -0
  120. package/src/wheel-zoom.js +48 -0
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Videos over the upload limit are written again smaller before they are
3
+ * stored: one at a time, in a worker, in order. While any are queued, the
4
+ * tab asks before it is closed and holds a web lock so the browser does not
5
+ * put it to sleep. The progress notice reads {@link useVideoShrink}.
6
+ */
7
+ import { create } from 'zustand';
8
+ import { firstShrinkPlan, SHRINK_ATTEMPTS, SHRINK_WORDS, shrinkTarget, smallerShrinkPlan, videoLimit, } from "./plan.js";
9
+ export const useVideoShrink = create(() => ({ jobs: [] }));
10
+ /** The video could not be made small enough (or, `sound-dropped`, only without its sound). */
11
+ export class ShrinkFailed extends Error {
12
+ failure;
13
+ constructor(failure) {
14
+ super(failure);
15
+ this.failure = failure;
16
+ }
17
+ }
18
+ /** The person cancelled it from the notice. */
19
+ export class ShrinkCancelled extends Error {
20
+ constructor() {
21
+ super('cancelled');
22
+ }
23
+ }
24
+ /** The worker could not be started. */
25
+ export class EncoderMissing extends Error {
26
+ constructor() {
27
+ super(SHRINK_WORDS.encoderMissing);
28
+ }
29
+ }
30
+ /** Whether this browser can shrink videos at all. */
31
+ export function canShrinkVideos() {
32
+ return typeof Worker === 'function' && typeof VideoEncoder !== 'undefined';
33
+ }
34
+ let startWorker = () => new Worker(new URL('./worker.js', import.meta.url), { type: 'module', name: 'video-shrink' });
35
+ /** Replaces how workers are made (tests). */
36
+ export function setShrinkWorkerFactory(make) {
37
+ startWorker = make;
38
+ }
39
+ /** How long a worker may stay silent: a probe answers once, an encode reports progress as it goes. */
40
+ const PROBE_QUIET_MS = 30_000;
41
+ const ENCODE_QUIET_MS = 90_000;
42
+ /** When a worker that never answered is started again, and for how long that is tried. */
43
+ export const WORKER_RETRY_MS = [1500, 6000];
44
+ const WORKER_RETRY_WINDOW_MS = 30_000;
45
+ class WorkerFailedToStart extends Error {
46
+ }
47
+ /** An H.264 encoder that needed the Baseline profile once gets it from then on. */
48
+ let useBaseline = false;
49
+ /** Runs one job in a new worker; a worker that errors before its first answer rejects with {@link WorkerFailedToStart}. */
50
+ function runOnce(job, quietMs, signal, onProgress) {
51
+ return new Promise((resolve, reject) => {
52
+ if (signal.aborted) {
53
+ reject(new ShrinkCancelled());
54
+ return;
55
+ }
56
+ let worker;
57
+ try {
58
+ worker = startWorker();
59
+ }
60
+ catch {
61
+ reject(new WorkerFailedToStart());
62
+ return;
63
+ }
64
+ let answered = false;
65
+ let quiet;
66
+ const finish = () => {
67
+ clearTimeout(quiet);
68
+ signal.removeEventListener('abort', cancel);
69
+ worker.onmessage = null;
70
+ worker.onerror = null;
71
+ worker.terminate();
72
+ };
73
+ const arm = () => {
74
+ clearTimeout(quiet);
75
+ quiet = setTimeout(() => {
76
+ finish();
77
+ reject(new Error('the video worker stopped answering'));
78
+ }, quietMs);
79
+ };
80
+ const cancel = () => {
81
+ finish();
82
+ reject(new ShrinkCancelled());
83
+ };
84
+ signal.addEventListener('abort', cancel, { once: true });
85
+ worker.onerror = (event) => {
86
+ event.preventDefault();
87
+ finish();
88
+ reject(answered ? new Error('the video worker failed') : new WorkerFailedToStart());
89
+ };
90
+ worker.onmessage = (event) => {
91
+ answered = true;
92
+ const message = event.data;
93
+ if (message.kind === 'progress') {
94
+ arm();
95
+ onProgress(message.value);
96
+ return;
97
+ }
98
+ finish();
99
+ if (message.kind === 'failed')
100
+ reject(new Error(message.message));
101
+ else
102
+ resolve(message);
103
+ };
104
+ arm();
105
+ worker.postMessage(job);
106
+ });
107
+ }
108
+ const pause = (ms, signal) => new Promise((resolve, reject) => {
109
+ const timer = setTimeout(done, ms);
110
+ function done() {
111
+ signal.removeEventListener('abort', stop);
112
+ resolve();
113
+ }
114
+ function stop() {
115
+ clearTimeout(timer);
116
+ reject(new ShrinkCancelled());
117
+ }
118
+ signal.addEventListener('abort', stop, { once: true });
119
+ });
120
+ /** {@link runOnce}, started again after 1.5 s and 6 s when the worker could not load (a dropped connection, a busy server). */
121
+ async function run(job, quietMs, signal, onProgress) {
122
+ const started = Date.now();
123
+ for (let retry = 0;; retry++) {
124
+ try {
125
+ return await runOnce(job, quietMs, signal, onProgress);
126
+ }
127
+ catch (error) {
128
+ if (!(error instanceof WorkerFailedToStart))
129
+ throw error;
130
+ const wait = WORKER_RETRY_MS[retry];
131
+ if (wait === undefined || Date.now() - started + wait > WORKER_RETRY_WINDOW_MS)
132
+ throw new EncoderMissing();
133
+ await pause(wait, signal);
134
+ }
135
+ }
136
+ }
137
+ const queue = [];
138
+ let nextId = 1;
139
+ let releaseGuard = null;
140
+ const publish = () => useVideoShrink.setState({ jobs: queue.map((job) => ({ ...job.entry })) });
141
+ function update(job, change) {
142
+ Object.assign(job.entry, change);
143
+ publish();
144
+ }
145
+ const askBeforeLeaving = (event) => {
146
+ event.preventDefault();
147
+ };
148
+ /** Keeps the tab from closing quietly or being put to sleep while videos are queued. */
149
+ function holdTab() {
150
+ let release = () => undefined;
151
+ const held = new Promise((resolve) => {
152
+ release = resolve;
153
+ });
154
+ void globalThis.navigator?.locks?.request(`video-shrink-${Date.now()}-${Math.random().toString(36).slice(2)}`, () => held).catch(() => undefined);
155
+ globalThis.addEventListener?.('beforeunload', askBeforeLeaving);
156
+ return () => {
157
+ globalThis.removeEventListener?.('beforeunload', askBeforeLeaving);
158
+ release();
159
+ };
160
+ }
161
+ function remove(job) {
162
+ const at = queue.indexOf(job);
163
+ if (at < 0)
164
+ return;
165
+ queue.splice(at, 1);
166
+ publish();
167
+ if (queue.length === 0) {
168
+ releaseGuard?.();
169
+ releaseGuard = null;
170
+ }
171
+ startNext();
172
+ }
173
+ const extension = (type) => (type === 'video/webm' ? 'webm' : 'mp4');
174
+ const baseName = (name) => name.replace(/\.[^./\\]+$/, '') || 'Video';
175
+ /** Probes, then writes smaller until it fits or the tries run out. */
176
+ async function shrink(job) {
177
+ const { signal } = job.abort;
178
+ let probed;
179
+ try {
180
+ probed = await run({ kind: 'probe', file: job.file }, PROBE_QUIET_MS, signal, () => undefined);
181
+ }
182
+ catch (error) {
183
+ if (error instanceof ShrinkCancelled || error instanceof EncoderMissing)
184
+ throw error;
185
+ throw new ShrinkFailed('too-large');
186
+ }
187
+ if (probed.kind !== 'probed')
188
+ throw new ShrinkFailed('too-large');
189
+ const probe = probed.probe;
190
+ const limit = videoLimit();
191
+ const target = shrinkTarget(limit);
192
+ const first = firstShrinkPlan(probe, target);
193
+ if (first === 'too-long')
194
+ throw new ShrinkFailed('too-long');
195
+ if (typeof first === 'string')
196
+ throw new ShrinkFailed('too-large');
197
+ let plan = first;
198
+ for (let attempt = 1; plan && attempt <= SHRINK_ATTEMPTS; attempt++) {
199
+ update(job, { attempt, progress: 0 });
200
+ let written;
201
+ try {
202
+ written = await run({ kind: 'encode', file: job.file, plan, baseline: useBaseline }, ENCODE_QUIET_MS, signal, (progress) => update(job, { progress }));
203
+ }
204
+ catch (error) {
205
+ if (error instanceof ShrinkCancelled || error instanceof EncoderMissing)
206
+ throw error;
207
+ throw new ShrinkFailed('failed');
208
+ }
209
+ if (written.kind !== 'encoded')
210
+ throw new ShrinkFailed('failed');
211
+ if (written.baseline)
212
+ useBaseline = true;
213
+ if (written.bytes.byteLength <= limit) {
214
+ const file = new File([written.bytes], `${baseName(job.file.name)}.${extension(written.type)}`, { type: written.type });
215
+ return { file, sound: written.sound };
216
+ }
217
+ plan = smallerShrinkPlan(probe, plan, written.bytes.byteLength, target);
218
+ }
219
+ throw new ShrinkFailed('too-big');
220
+ }
221
+ function startNext() {
222
+ const job = queue.find((queued) => queued.entry.phase !== 'placing');
223
+ if (!job || job.entry.phase !== 'queued')
224
+ return;
225
+ if (queue.some((queued) => queued.entry.phase === 'shrinking'))
226
+ return;
227
+ update(job, { phase: 'shrinking', attempt: 1, progress: 0 });
228
+ shrink(job).then((video) => {
229
+ if (job.abort.signal.aborted) {
230
+ job.reject(new ShrinkCancelled());
231
+ remove(job);
232
+ return;
233
+ }
234
+ update(job, { phase: 'placing', progress: 1 });
235
+ job.resolve(video);
236
+ startNext();
237
+ }, (error) => {
238
+ job.reject(error);
239
+ remove(job);
240
+ });
241
+ }
242
+ /** Queues `file` to be made small enough to store. */
243
+ export function queueShrink(file) {
244
+ const abort = new AbortController();
245
+ let resolve;
246
+ let reject;
247
+ const result = new Promise((ok, fail) => {
248
+ resolve = ok;
249
+ reject = fail;
250
+ });
251
+ // Callers handle the result; a cancelled or failed one is still settled here.
252
+ result.catch(() => undefined);
253
+ const job = { entry: { id: nextId++, name: file.name, phase: 'queued', attempt: 1, progress: 0, waiting: false }, file, abort, resolve, reject };
254
+ queue.push(job);
255
+ releaseGuard ??= holdTab();
256
+ publish();
257
+ startNext();
258
+ return { id: job.entry.id, result, placed: () => remove(job) };
259
+ }
260
+ /** Marks a shrunk video as held until the text box is left (the notice says so). */
261
+ export function setShrinkWaiting(id, waiting) {
262
+ const job = queue.find((queued) => queued.entry.id === id);
263
+ if (job)
264
+ update(job, { waiting });
265
+ }
266
+ /** True while the video `id` has been cancelled. */
267
+ export function shrinkCancelled(id) {
268
+ return queue.find((queued) => queued.entry.id === id)?.abort.signal.aborted ?? true;
269
+ }
270
+ /** Cancels the video `id`: a queued or shrinking one stops, a finished one is not placed. */
271
+ export function cancelShrink(id) {
272
+ const job = queue.find((queued) => queued.entry.id === id);
273
+ if (!job)
274
+ return;
275
+ job.abort.abort();
276
+ if (job.entry.phase === 'queued') {
277
+ job.reject(new ShrinkCancelled());
278
+ remove(job);
279
+ }
280
+ else if (job.entry.phase === 'placing') {
281
+ remove(job);
282
+ }
283
+ }
284
+ /** The job the notice is about: the one being shrunk or placed, else the first queued. */
285
+ export function leadingShrink(jobs) {
286
+ return jobs.find((job) => job.phase !== 'queued') ?? jobs[0];
287
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The video shrink worker: reads a video (`probe`) or writes it again to a
3
+ * plan (`encode`). Writing falls back three ways: an H.264 encoder that stops
4
+ * answering is tried again on the Baseline profile, an H.264 write that fails
5
+ * early is tried as VP9 (WebM), and a write that fails over its sound is
6
+ * tried without it.
7
+ */
8
+ export {};
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The video shrink worker: reads a video (`probe`) or writes it again to a
3
+ * plan (`encode`). Writing falls back three ways: an H.264 encoder that stops
4
+ * answering is tried again on the Baseline profile, an H.264 write that fails
5
+ * early is tried as VP9 (WebM), and a write that fails over its sound is
6
+ * tried without it.
7
+ */
8
+ import { ALL_FORMATS, BlobSource, BufferTarget, canEncodeVideo, Conversion, getFirstEncodableAudioCodec, Input, Mp4OutputFormat, Output, WebMOutputFormat, } from 'mediabunny';
9
+ import { baselineCodec, SHRINK_SOUND_BITRATE } from "./plan.js";
10
+ const scope = self;
11
+ const answer = (message, transfer = []) => scope.postMessage(message, { transfer });
12
+ /** The encoder took frames and has given nothing back for this long. */
13
+ const STALL_MS = 5000;
14
+ /** An H.264 write that fails before this much of it is done is tried as VP9. */
15
+ const EARLY = 0.1;
16
+ class EncoderStalled extends Error {
17
+ constructor() {
18
+ super('the video encoder stopped answering');
19
+ }
20
+ }
21
+ /** Frames handed to the browser's encoders and chunks they gave back, and whether H.264 is held to Baseline. */
22
+ const encoders = { baseline: false, framesIn: 0, chunksOut: 0, lastAnswer: 0 };
23
+ const NativeEncoder = globalThis.VideoEncoder;
24
+ if (NativeEncoder) {
25
+ class CountingEncoder extends NativeEncoder {
26
+ constructor(init) {
27
+ super({
28
+ error: init.error,
29
+ output: (chunk, metadata) => {
30
+ encoders.chunksOut++;
31
+ encoders.lastAnswer = performance.now();
32
+ init.output(chunk, metadata);
33
+ },
34
+ });
35
+ }
36
+ configure(config) {
37
+ super.configure(encoders.baseline ? { ...config, codec: baselineCodec(config.codec) } : config);
38
+ }
39
+ encode(frame, options) {
40
+ if (encoders.framesIn === encoders.chunksOut)
41
+ encoders.lastAnswer = performance.now();
42
+ encoders.framesIn++;
43
+ super.encode(frame, options);
44
+ }
45
+ }
46
+ globalThis.VideoEncoder = CountingEncoder;
47
+ }
48
+ const openInput = (file) => new Input({ source: new BlobSource(file), formats: ALL_FORMATS });
49
+ const SOUND_FOR = { avc: ['aac', 'opus'], vp9: ['opus'] };
50
+ const SOUND_IN = { avc: 'aac', vp9: 'opus' };
51
+ /** How the sound goes into a `codec` file: written again, copied as it is, or not at all. */
52
+ async function soundOptions(input, codec) {
53
+ try {
54
+ const track = await input.getPrimaryAudioTrack();
55
+ if (!track)
56
+ return null;
57
+ if (typeof AudioEncoder !== 'undefined' && (await track.canDecode())) {
58
+ const numberOfChannels = Math.max(1, Math.min(2, track.numberOfChannels));
59
+ const written = await getFirstEncodableAudioCodec(SOUND_FOR[codec], { numberOfChannels, sampleRate: 48_000, bitrate: SHRINK_SOUND_BITRATE });
60
+ if (written)
61
+ return { codec: written, numberOfChannels, sampleRate: 48_000, bitrate: SHRINK_SOUND_BITRATE, forceTranscode: true };
62
+ }
63
+ return track.codec === SOUND_IN[codec] ? {} : null;
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ }
69
+ const even = (value) => Math.max(2, Math.round(value / 2) * 2);
70
+ /** The first codec that writes the picture, at the largest of 1080/720/480 short sides it takes. */
71
+ async function encodableSizes(width, height) {
72
+ if (typeof VideoEncoder === 'undefined')
73
+ return { codec: null };
74
+ const short = Math.min(width, height);
75
+ const largest = Math.min(1080, short);
76
+ const sides = [largest, ...[720, 480].filter((side) => side < largest)];
77
+ for (const codec of ['avc', 'vp9']) {
78
+ for (const side of sides) {
79
+ const ok = await canEncodeVideo(codec, { width: even((width * side) / short), height: even((height * side) / short), bitrate: 4_000_000 }).catch(() => false);
80
+ if (ok)
81
+ return side < largest ? { codec, largestShort: side } : { codec };
82
+ }
83
+ }
84
+ return { codec: null };
85
+ }
86
+ async function probe(file) {
87
+ const input = openInput(file);
88
+ try {
89
+ const video = await input.getPrimaryVideoTrack();
90
+ if (!video)
91
+ return { width: 0, height: 0, duration: 0, fps: 0, decodable: false, codec: null, sound: false };
92
+ const [decodable, duration, stats] = await Promise.all([video.canDecode(), input.computeDuration(), video.computePacketStats(120).catch(() => null)]);
93
+ const { codec, largestShort } = await encodableSizes(video.displayWidth, video.displayHeight);
94
+ const sound = codec !== null && (await soundOptions(input, codec)) !== null;
95
+ return {
96
+ width: video.displayWidth,
97
+ height: video.displayHeight,
98
+ duration,
99
+ fps: stats?.averagePacketRate ?? 0,
100
+ decodable,
101
+ codec,
102
+ ...(largestShort !== undefined ? { largestShort } : {}),
103
+ sound,
104
+ };
105
+ }
106
+ finally {
107
+ input.dispose();
108
+ }
109
+ }
110
+ async function writeOnce(file, plan, codec, withSound, attempt) {
111
+ const input = openInput(file);
112
+ attempt.progress = 0;
113
+ encoders.framesIn = 0;
114
+ encoders.chunksOut = 0;
115
+ encoders.lastAnswer = performance.now();
116
+ let conversion;
117
+ let watch;
118
+ try {
119
+ const hadSound = (await input.getPrimaryAudioTrack().catch(() => null)) !== null;
120
+ const sound = withSound && plan.withSound ? await soundOptions(input, codec) : null;
121
+ attempt.writingSound = sound !== null && sound.codec !== undefined;
122
+ const output = new Output({ format: codec === 'avc' ? new Mp4OutputFormat({ fastStart: 'in-memory' }) : new WebMOutputFormat(), target: new BufferTarget() });
123
+ conversion = await Conversion.init({
124
+ input,
125
+ output,
126
+ tracks: 'primary',
127
+ video: {
128
+ codec,
129
+ width: plan.width,
130
+ height: plan.height,
131
+ fit: 'fill',
132
+ allowRotationMetadata: false,
133
+ bitrate: plan.bitrate,
134
+ forceTranscode: true,
135
+ ...(plan.fps !== undefined ? { frameRate: plan.fps } : {}),
136
+ },
137
+ audio: sound ?? { discard: true },
138
+ tags: {},
139
+ showWarnings: false,
140
+ });
141
+ const made = conversion;
142
+ if (!made.isValid || !made.utilizedTracks.some((track) => track.isVideoTrack())) {
143
+ throw new Error(made.discardedTracks.map((track) => track.reason).join(', ') || 'nothing to write');
144
+ }
145
+ let shown = -1;
146
+ made.onProgress = (progress) => {
147
+ const value = Math.floor(progress * 100) / 100;
148
+ if (value === shown)
149
+ return;
150
+ shown = value;
151
+ attempt.progress = value;
152
+ answer({ kind: 'progress', value });
153
+ };
154
+ const stalled = new Promise((_, reject) => {
155
+ watch = setInterval(() => {
156
+ if (encoders.framesIn > encoders.chunksOut && performance.now() - encoders.lastAnswer > STALL_MS)
157
+ reject(new EncoderStalled());
158
+ }, 500);
159
+ });
160
+ await Promise.race([made.execute(), stalled]);
161
+ const bytes = output.target.buffer;
162
+ if (!bytes)
163
+ throw new Error('the encoder wrote nothing');
164
+ const keptSound = made.utilizedTracks.some((track) => track.isAudioTrack());
165
+ return { bytes, type: codec === 'avc' ? 'video/mp4' : 'video/webm', sound: !hadSound ? 'none' : keptSound ? 'kept' : 'dropped' };
166
+ }
167
+ catch (error) {
168
+ void conversion?.cancel().catch(() => undefined);
169
+ throw error;
170
+ }
171
+ finally {
172
+ clearInterval(watch);
173
+ input.dispose();
174
+ }
175
+ }
176
+ /** One codec, with the Baseline retry for a stalled H.264 encoder (remembered for later jobs through the page). */
177
+ async function writeAs(file, plan, codec, withSound, attempt) {
178
+ try {
179
+ return await writeOnce(file, plan, codec, withSound, attempt);
180
+ }
181
+ catch (error) {
182
+ if (codec !== 'avc' || encoders.baseline || !(error instanceof EncoderStalled))
183
+ throw error;
184
+ encoders.baseline = true;
185
+ return writeOnce(file, plan, codec, withSound, attempt);
186
+ }
187
+ }
188
+ /** With sound first; a failure (other than a stall) while writing sound is tried again silent. */
189
+ async function writeWithSound(file, plan, codec, attempt) {
190
+ try {
191
+ return await writeAs(file, plan, codec, true, attempt);
192
+ }
193
+ catch (error) {
194
+ if (!attempt.writingSound || error instanceof EncoderStalled)
195
+ throw error;
196
+ return writeAs(file, plan, codec, false, attempt);
197
+ }
198
+ }
199
+ async function vp9Fits(plan) {
200
+ const check = canEncodeVideo('vp9', { width: plan.width, height: plan.height, bitrate: plan.bitrate }).catch(() => false);
201
+ return Promise.race([check, new Promise((resolve) => setTimeout(() => resolve(false), 2000))]);
202
+ }
203
+ async function encode(file, plan) {
204
+ const attempt = { progress: 0, writingSound: false };
205
+ try {
206
+ return await writeWithSound(file, plan, plan.codec, attempt);
207
+ }
208
+ catch (error) {
209
+ if (plan.codec !== 'avc' || (attempt.progress >= EARLY && !(error instanceof EncoderStalled)) || !(await vp9Fits(plan)))
210
+ throw error;
211
+ return writeWithSound(file, { ...plan, codec: 'vp9' }, 'vp9', attempt);
212
+ }
213
+ }
214
+ const failed = (error) => answer({ kind: 'failed', message: error instanceof Error ? error.message : String(error) });
215
+ scope.onmessage = (event) => {
216
+ const job = event.data;
217
+ if (job.kind === 'probe') {
218
+ probe(job.file).then((found) => answer({ kind: 'probed', probe: found }), failed);
219
+ return;
220
+ }
221
+ encoders.baseline = job.baseline;
222
+ encode(job.file, job.plan).then((written) => answer({ kind: 'encoded', ...written, baseline: encoders.baseline }, [written.bytes]), failed);
223
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * "Scroll to zoom": a choice kept in this browser and shared by the design
3
+ * canvas, the whiteboard and the slides Canvas view. Off (the default), the
4
+ * wheel pans and ⌘/Ctrl + wheel zooms. On, the wheel zooms at the pointer
5
+ * without a modifier key, and panning is a drag with the right or middle
6
+ * button or with Space held. It is meant for a mouse: while it is on, a
7
+ * trackpad's two-finger scroll zooms too. A pinch zooms either way.
8
+ */
9
+ /** Whether a plain wheel zooms. */
10
+ export declare function wheelZooms(): boolean;
11
+ /** Turns "Scroll to zoom" on or off for this browser. */
12
+ export declare function setWheelZooms(on: boolean): void;
13
+ /** Calls `listener` when the choice changes here or in another tab. */
14
+ export declare function onWheelZoomsChange(listener: () => void): () => void;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * "Scroll to zoom": a choice kept in this browser and shared by the design
3
+ * canvas, the whiteboard and the slides Canvas view. Off (the default), the
4
+ * wheel pans and ⌘/Ctrl + wheel zooms. On, the wheel zooms at the pointer
5
+ * without a modifier key, and panning is a drag with the right or middle
6
+ * button or with Space held. It is meant for a mouse: while it is on, a
7
+ * trackpad's two-finger scroll zooms too. A pinch zooms either way.
8
+ */
9
+ const KEY = 'open-artifacts-canvas-wheel-zoom';
10
+ const listeners = new Set();
11
+ /** Whether a plain wheel zooms. */
12
+ export function wheelZooms() {
13
+ try {
14
+ return typeof localStorage !== 'undefined' && localStorage.getItem(KEY) === '1';
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ /** Turns "Scroll to zoom" on or off for this browser. */
21
+ export function setWheelZooms(on) {
22
+ try {
23
+ if (on)
24
+ localStorage.setItem(KEY, '1');
25
+ else
26
+ localStorage.removeItem(KEY);
27
+ }
28
+ catch {
29
+ /* storage may be unavailable */
30
+ }
31
+ for (const listener of [...listeners])
32
+ listener();
33
+ }
34
+ /** Calls `listener` when the choice changes here or in another tab. */
35
+ export function onWheelZoomsChange(listener) {
36
+ listeners.add(listener);
37
+ const storage = (event) => {
38
+ if (event.key === KEY || event.key === null)
39
+ listener();
40
+ };
41
+ if (typeof window !== 'undefined')
42
+ window.addEventListener('storage', storage);
43
+ return () => {
44
+ listeners.delete(listener);
45
+ if (typeof window !== 'undefined')
46
+ window.removeEventListener('storage', storage);
47
+ };
48
+ }