@kubohiroya/turbowarp-camera-source 0.18.0 → 0.19.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.
package/README.ja.md CHANGED
@@ -26,13 +26,13 @@ TurboWarp-Camera-Sourceは、MediaDevicesのカメラストリームを名前付
26
26
  次のURLをunsandboxed custom extensionとして読み込みます。
27
27
 
28
28
  ```text
29
- https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-camera-source@0.18.0/dist/camera-source.js
29
+ https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-camera-source@0.19.0/dist/camera-source.js
30
30
  ```
31
31
 
32
32
  npm hostでは次を使います。
33
33
 
34
34
  ```bash
35
- pnpm add @kubohiroya/turbowarp-camera-source@0.18.0
35
+ pnpm add @kubohiroya/turbowarp-camera-source@0.19.0
36
36
  ```
37
37
 
38
38
  ## Quick start
package/README.md CHANGED
@@ -30,13 +30,13 @@ or select separate cameras for separate roles.
30
30
  Load this URL as an unsandboxed custom extension:
31
31
 
32
32
  ```text
33
- https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-camera-source@0.18.0/dist/camera-source.js
33
+ https://cdn.jsdelivr.net/npm/@kubohiroya/turbowarp-camera-source@0.19.0/dist/camera-source.js
34
34
  ```
35
35
 
36
36
  For npm hosts:
37
37
 
38
38
  ```bash
39
- pnpm add @kubohiroya/turbowarp-camera-source@0.18.0
39
+ pnpm add @kubohiroya/turbowarp-camera-source@0.19.0
40
40
  ```
41
41
 
42
42
  ## Quick Start
@@ -16,6 +16,787 @@
16
16
  license: "MPL-2.0",
17
17
  unsandboxed: true
18
18
  };
19
+ var registry = Symbol.for("@kubohiroya/turbowarp-app-shell/runtime-controls-dock/v1");
20
+ var edges = [
21
+ "top",
22
+ "bottom",
23
+ "left",
24
+ "right"
25
+ ];
26
+ /** App-neutral, optional controls for standalone players that have no Editor toolbar. */
27
+ function createRuntimeControlsDock(options) {
28
+ const { document } = options;
29
+ const view = document.defaultView;
30
+ const labels = /^ja(?:-|$)/iu.test(options.locale || document.documentElement.lang || view?.navigator.language || "") ? {
31
+ tools: "ツール",
32
+ settings: "Dockの設定",
33
+ edge: "表示位置",
34
+ autoHide: "自動的に隠す",
35
+ close: "閉じる",
36
+ top: "上",
37
+ bottom: "下",
38
+ left: "左",
39
+ right: "右"
40
+ } : {
41
+ tools: "Tools",
42
+ settings: "Dock settings",
43
+ edge: "Position",
44
+ autoHide: "Automatically hide",
45
+ close: "Close",
46
+ top: "Top",
47
+ bottom: "Bottom",
48
+ left: "Left",
49
+ right: "Right"
50
+ };
51
+ const storageKey = options.storageKey || "turbowarp.runtime-controls-dock.v1";
52
+ let edge = "bottom";
53
+ let autoHide = true;
54
+ try {
55
+ const stored = JSON.parse(view?.localStorage.getItem(storageKey) || "null");
56
+ if (stored && edges.includes(stored.edge)) edge = stored.edge;
57
+ if (typeof stored?.autoHide === "boolean") autoHide = stored.autoHide;
58
+ } catch {}
59
+ const root = document.createElement("div");
60
+ root.setAttribute("data-runtime-controls-dock", "true");
61
+ const style = document.createElement("style");
62
+ style.textContent = `[data-runtime-controls-dock] {position:fixed;z-index:2147483000;display:flex;align-items:center;gap:4px;font:14px/1.4 sans-serif;color:#25354a;max-width:100vw;max-height:100vh}
63
+ [data-runtime-controls-dock][hidden], [data-runtime-controls-dock] [hidden] {display:none!important}
64
+ [data-runtime-controls-dock] button, [data-runtime-controls-dock] select {font:inherit;color:inherit;cursor:pointer}
65
+ [data-runtime-controls-dock] button:focus-visible, [data-runtime-controls-dock] select:focus-visible {outline:3px solid #2864bd;outline-offset:2px}
66
+ [data-runtime-dock-bar] {display:flex;gap:6px;padding:8px;border:1px solid #9aa8b8;border-radius:14px;background:#f5f8fceF;box-shadow:0 3px 16px #0003;backdrop-filter:blur(16px);overflow:auto;max-width:calc(100vw - 16px);max-height:calc(100vh - 48px)}
67
+ [data-runtime-dock-bar] button {min-width:48px;min-height:48px;border:1px solid transparent;border-radius:8px;background:transparent;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;font-size:12px}
68
+ [data-runtime-dock-bar] button:hover {background:#dae5f4}
69
+ [data-runtime-dock-bar] button[aria-expanded=true] {border-color:#2864bd;background:#e8effb}
70
+ [data-runtime-dock-icon] {font-size:24px;line-height:1}
71
+ [data-runtime-dock-handle] {min-width:48px;min-height:28px;border:1px solid #9aa8b8;border-radius:8px;background:#f5f8fc;color:#25354a}
72
+ [data-runtime-dock-settings] {position:fixed;z-index:2147483001;box-sizing:border-box;width:280px;max-width:calc(100vw - 24px);padding:16px;border:1px solid #9aa8b8;border-radius:12px;background:#fff;box-shadow:0 4px 16px #0003;display:flex;flex-direction:column;gap:12px}
73
+ [data-runtime-dock-panel] {box-sizing:border-box;display:flex;flex-direction:column;width:min(28rem,calc(100vw - 24px));background:#fff;color:#25354a;border:1px solid #9aa8b8;border-radius:12px;box-shadow:0 4px 16px #0003;z-index:2147483001!important;font:14px/1.5 sans-serif;overflow:hidden!important}
74
+ [data-runtime-dock-panel][hidden] {display:none!important}
75
+ [data-runtime-dock-panel] > :first-child {display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 16px;border-bottom:1px solid #d8e0ea}
76
+ [data-runtime-dock-panel] > :nth-child(2) {overflow:auto;min-height:0;padding:0 16px}
77
+ [data-runtime-dock-panel] > :last-child {padding:12px 16px;border-top:1px solid #d8e0ea}
78
+ [data-runtime-dock-panel] h2 {font-size:18px;margin:0}
79
+ [data-runtime-dock-panel] h3 {font-size:15px}
80
+ [data-runtime-dock-panel] button {font:inherit;min-height:36px;padding:6px 10px;margin:3px;border:1px solid #9aa8b8;border-radius:6px;background:#f5f8fc;color:#25354a;cursor:pointer}
81
+ [data-runtime-dock-panel] button[aria-checked=true] {border-color:#2864bd;box-shadow:inset 0 0 0 1px #2864bd;background:#e8effb}
82
+ [data-runtime-dock-panel] button:focus-visible {outline:3px solid #2864bd;outline-offset:1px}
83
+ [data-runtime-dock-settings] label {display:flex;align-items:center;justify-content:space-between;gap:12px}
84
+ [data-runtime-dock-settings] select, [data-runtime-dock-settings] button {min-height:36px;padding:6px 10px;border:1px solid #9aa8b8;border-radius:6px;background:#f5f8fc}
85
+ `;
86
+ const handle = document.createElement("button");
87
+ handle.type = "button";
88
+ handle.textContent = labels.tools;
89
+ handle.setAttribute("data-runtime-dock-handle", "true");
90
+ handle.setAttribute("aria-label", labels.tools);
91
+ const bar = document.createElement("div");
92
+ bar.setAttribute("data-runtime-dock-bar", "true");
93
+ bar.setAttribute("role", "toolbar");
94
+ bar.setAttribute("aria-label", labels.tools);
95
+ const settings = document.createElement("div");
96
+ settings.setAttribute("data-runtime-dock-settings", "true");
97
+ settings.setAttribute("role", "dialog");
98
+ settings.setAttribute("aria-label", labels.settings);
99
+ const heading = document.createElement("strong");
100
+ heading.textContent = labels.settings;
101
+ const edgeLabel = document.createElement("label");
102
+ edgeLabel.textContent = labels.edge;
103
+ const edgeSelect = document.createElement("select");
104
+ edgeSelect.setAttribute("aria-label", labels.edge);
105
+ for (const position of edges) {
106
+ const option = document.createElement("option");
107
+ option.value = position;
108
+ option.textContent = labels[position];
109
+ edgeSelect.append(option);
110
+ }
111
+ edgeLabel.append(edgeSelect);
112
+ const autoLabel = document.createElement("label");
113
+ autoLabel.textContent = labels.autoHide;
114
+ const autoCheck = document.createElement("input");
115
+ autoCheck.type = "checkbox";
116
+ autoLabel.append(autoCheck);
117
+ const close = document.createElement("button");
118
+ close.type = "button";
119
+ close.textContent = labels.close;
120
+ settings.append(heading, edgeLabel, autoLabel, close);
121
+ const gear = document.createElement("button");
122
+ gear.type = "button";
123
+ gear.textContent = "⚙";
124
+ gear.setAttribute("aria-label", labels.settings);
125
+ gear.title = labels.settings;
126
+ root.append(style, handle, bar, settings);
127
+ const entries = /* @__PURE__ */ new Map();
128
+ const listeners = /* @__PURE__ */ new Set();
129
+ let hovered = false, manual = false, settingsOpen = false, disposed = false;
130
+ let timer;
131
+ let keyboardInput = false;
132
+ const hasFocus = () => keyboardInput && root.contains(document.activeElement);
133
+ const expanded = () => !autoHide || hovered || manual || settingsOpen || hasFocus() || [...entries.values()].some((entry) => entry.state.visible && entry.state.expanded);
134
+ const persist = () => {
135
+ try {
136
+ view?.localStorage.setItem(storageKey, JSON.stringify({
137
+ edge,
138
+ autoHide
139
+ }));
140
+ } catch {}
141
+ };
142
+ const placePanel = (panel) => {
143
+ const rect = root.getBoundingClientRect();
144
+ const width = panel.offsetWidth || 320, height = panel.offsetHeight || 240;
145
+ const vw = view?.innerWidth || 480, vh = view?.innerHeight || 360;
146
+ let left = (vw - width) / 2, top = (vh - height) / 2;
147
+ if (edge === "bottom") top = rect.top - height - 8;
148
+ if (edge === "top") top = rect.bottom + 8;
149
+ if (edge === "left") left = rect.right + 8;
150
+ if (edge === "right") left = rect.left - width - 8;
151
+ Object.assign(panel.style, {
152
+ position: "fixed",
153
+ left: `${Math.max(8, Math.min(left, vw - width - 8))}px`,
154
+ top: `${Math.max(8, Math.min(top, vh - height - 8))}px`,
155
+ maxHeight: "calc(100vh - 16px)",
156
+ overflowY: "auto"
157
+ });
158
+ };
159
+ function render() {
160
+ if (disposed) return;
161
+ const visible = [...entries.values()].filter((entry) => entry.state.visible);
162
+ root.hidden = !visible.length;
163
+ if (!visible.length) {
164
+ settingsOpen = false;
165
+ manual = false;
166
+ hovered = false;
167
+ }
168
+ const showing = expanded();
169
+ bar.hidden = !showing;
170
+ settings.hidden = !settingsOpen;
171
+ handle.hidden = !autoHide;
172
+ handle.setAttribute("aria-expanded", String(showing));
173
+ root.setAttribute("data-edge", edge);
174
+ root.setAttribute("data-auto-hide", String(autoHide));
175
+ root.setAttribute("data-expanded", String(showing));
176
+ const vertical = edge === "left" || edge === "right";
177
+ Object.assign(root.style, {
178
+ left: edge === "right" ? "auto" : "0",
179
+ right: edge === "left" ? "auto" : "0",
180
+ top: edge === "bottom" ? "auto" : "0",
181
+ bottom: edge === "top" ? "auto" : "0",
182
+ width: "max-content",
183
+ height: "max-content",
184
+ margin: vertical ? "auto 0" : "0 auto",
185
+ transform: "none",
186
+ flexDirection: edge === "bottom" ? "column" : edge === "top" ? "column-reverse" : edge === "left" ? "row-reverse" : "row"
187
+ });
188
+ bar.style.flexDirection = vertical ? "column" : "row";
189
+ for (const entry of entries.values()) {
190
+ entry.button.hidden = !entry.state.visible;
191
+ entry.label.textContent = entry.state.text || entry.state.label;
192
+ entry.button.setAttribute("aria-label", entry.state.label);
193
+ entry.button.title = entry.state.label;
194
+ entry.button.setAttribute("aria-expanded", String(entry.state.expanded));
195
+ }
196
+ edgeSelect.value = edge;
197
+ autoCheck.checked = autoHide;
198
+ gear.setAttribute("aria-expanded", String(settingsOpen));
199
+ if (settingsOpen) placePanel(settings);
200
+ for (const entry of entries.values()) if (entry.panel && entry.state.expanded && !entry.panel.hidden) placePanel(entry.panel);
201
+ listeners.forEach((listener) => listener());
202
+ }
203
+ const scheduleHide = () => {
204
+ clearTimeout(timer);
205
+ timer = setTimeout(() => {
206
+ hovered = false;
207
+ manual = false;
208
+ render();
209
+ }, 600);
210
+ };
211
+ root.addEventListener("pointerenter", (event) => {
212
+ clearTimeout(timer);
213
+ hovered = event.pointerType !== "touch";
214
+ render();
215
+ });
216
+ root.addEventListener("pointerleave", (event) => {
217
+ if (event.pointerType !== "touch") scheduleHide();
218
+ });
219
+ root.addEventListener("focusin", render);
220
+ root.addEventListener("focusout", (event) => {
221
+ if (root.contains(event.relatedTarget)) return;
222
+ queueMicrotask(() => {
223
+ if (!root.contains(document.activeElement)) manual = false;
224
+ render();
225
+ });
226
+ });
227
+ handle.addEventListener("click", () => {
228
+ manual = !manual;
229
+ render();
230
+ });
231
+ gear.addEventListener("click", () => {
232
+ settingsOpen = !settingsOpen;
233
+ render();
234
+ if (settingsOpen) edgeSelect.focus();
235
+ });
236
+ close.addEventListener("click", () => {
237
+ settingsOpen = false;
238
+ render();
239
+ gear.focus();
240
+ });
241
+ edgeSelect.addEventListener("change", () => {
242
+ if (edges.includes(edgeSelect.value)) edge = edgeSelect.value;
243
+ persist();
244
+ render();
245
+ });
246
+ autoCheck.addEventListener("change", () => {
247
+ autoHide = autoCheck.checked;
248
+ persist();
249
+ render();
250
+ });
251
+ const onKey = (event) => {
252
+ keyboardInput = true;
253
+ if (settingsOpen && event.key === "Escape") {
254
+ event.preventDefault();
255
+ event.stopPropagation();
256
+ settingsOpen = false;
257
+ render();
258
+ gear.focus();
259
+ }
260
+ };
261
+ const onPointer = (event) => {
262
+ keyboardInput = false;
263
+ if (!root.contains(event.target)) {
264
+ manual = false;
265
+ hovered = false;
266
+ render();
267
+ }
268
+ };
269
+ const fullscreen = () => {
270
+ (document.fullscreenElement || document.body).append(root);
271
+ render();
272
+ };
273
+ document.addEventListener("keydown", onKey, true);
274
+ document.addEventListener("pointerdown", onPointer, true);
275
+ document.addEventListener("fullscreenchange", fullscreen);
276
+ view?.addEventListener("resize", render);
277
+ (document.fullscreenElement || document.body).append(root);
278
+ const stageControls = { addButton(options) {
279
+ if (disposed) throw new Error("The Dock has been disposed");
280
+ if (!options.id || !options.label || typeof options.onClick !== "function") throw new TypeError("Invalid Dock control");
281
+ entries.get(options.id)?.button.remove();
282
+ const button = document.createElement("button");
283
+ button.type = "button";
284
+ button.setAttribute("data-runtime-dock-control", options.id);
285
+ const icon = document.createElement("span");
286
+ icon.setAttribute("data-runtime-dock-icon", "true");
287
+ icon.setAttribute("aria-hidden", "true");
288
+ icon.textContent = options.icon || "•";
289
+ const label = document.createElement("span");
290
+ button.append(icon, label);
291
+ button.addEventListener("click", options.onClick);
292
+ const entry = {
293
+ button,
294
+ label,
295
+ state: {
296
+ label: options.label,
297
+ text: options.text || "",
298
+ visible: false,
299
+ expanded: false
300
+ }
301
+ };
302
+ entries.set(options.id, entry);
303
+ bar.insertBefore(button, gear.parentNode === bar ? gear : null);
304
+ if (gear.parentNode !== bar) bar.append(gear);
305
+ render();
306
+ return {
307
+ update(state) {
308
+ if (entries.get(options.id) !== entry) return;
309
+ let changed = false;
310
+ for (const key of [
311
+ "label",
312
+ "text",
313
+ "visible",
314
+ "expanded"
315
+ ]) {
316
+ const value = state[key];
317
+ if (typeof value === typeof entry.state[key] && entry.state[key] !== value) {
318
+ Object.assign(entry.state, { [key]: value });
319
+ changed = true;
320
+ }
321
+ }
322
+ if (changed) render();
323
+ },
324
+ placePanel(element) {
325
+ const panel = element;
326
+ if (!panel || typeof panel.setAttribute !== "function" || !panel.style) throw new TypeError("Invalid Dock panel");
327
+ entry.panel = panel;
328
+ panel.setAttribute("data-runtime-dock-panel", "true");
329
+ placePanel(panel);
330
+ },
331
+ focus() {
332
+ if (entry.state.visible && entries.get(options.id) === entry) {
333
+ manual = true;
334
+ render();
335
+ button.focus();
336
+ }
337
+ },
338
+ dispose() {
339
+ if (entries.get(options.id) !== entry) return;
340
+ entries.delete(options.id);
341
+ button.remove();
342
+ render();
343
+ }
344
+ };
345
+ } };
346
+ render();
347
+ return {
348
+ stageControls,
349
+ placePanel,
350
+ subscribe(listener) {
351
+ listeners.add(listener);
352
+ return () => listeners.delete(listener);
353
+ },
354
+ getSnapshot: () => ({
355
+ edge,
356
+ autoHide,
357
+ expanded: expanded(),
358
+ count: [...entries.values()].filter((entry) => entry.state.visible).length
359
+ }),
360
+ dispose() {
361
+ if (disposed) return;
362
+ disposed = true;
363
+ clearTimeout(timer);
364
+ entries.clear();
365
+ listeners.clear();
366
+ root.remove();
367
+ document.removeEventListener("keydown", onKey, true);
368
+ document.removeEventListener("pointerdown", onPointer, true);
369
+ document.removeEventListener("fullscreenchange", fullscreen);
370
+ view?.removeEventListener("resize", render);
371
+ }
372
+ };
373
+ }
374
+ /** Sharing on the document also covers independently bundled copies of this package. */
375
+ function getRuntimeControlsDock(options) {
376
+ const document = options.document;
377
+ if (document[registry]) return document[registry];
378
+ const dock = createRuntimeControlsDock(options);
379
+ const dispose = dock.dispose;
380
+ dock.dispose = () => {
381
+ dispose();
382
+ if (document[registry] === dock) delete document[registry];
383
+ };
384
+ document[registry] = dock;
385
+ return dock;
386
+ }
387
+ /** A host adapter for packaged HTML, independent of the player's optional control bar. */
388
+ function createStandaloneCameraControlsHost(document, locale) {
389
+ const ja = /^ja(?:-|$)/iu.test(locale);
390
+ const label = ja ? "カメラ" : "Camera";
391
+ const dock = getRuntimeControlsDock({
392
+ document,
393
+ locale
394
+ });
395
+ let dockButton = null;
396
+ let unsubscribeDock = null;
397
+ const providers = /* @__PURE__ */ new Map();
398
+ let root = null;
399
+ let panel;
400
+ let chooser;
401
+ let content;
402
+ let mounted = null;
403
+ let mountedRunning = false;
404
+ let cameraId = "";
405
+ let open = false;
406
+ let disposed = false;
407
+ const detachContent = () => {
408
+ const previous = mounted;
409
+ mounted = null;
410
+ try {
411
+ previous?.onClose?.();
412
+ } finally {
413
+ if (previous && previous.element.parentNode === content) content.removeChild(previous.element);
414
+ }
415
+ };
416
+ const close = (focus = false) => {
417
+ open = false;
418
+ render();
419
+ if (focus) dockButton?.focus();
420
+ };
421
+ const onKey = (event) => {
422
+ if (open && event.key === "Escape") {
423
+ event.preventDefault();
424
+ event.stopPropagation();
425
+ close(true);
426
+ }
427
+ };
428
+ const onPointer = (event) => {
429
+ if (open && root && !root.contains(event.target) && !event.target.closest?.("[data-runtime-dock-control=\"camera\"]")) close();
430
+ };
431
+ const onFullscreen = () => {
432
+ if (root) (document.fullscreenElement || document.body).appendChild(root);
433
+ };
434
+ const removeRoot = () => {
435
+ detachContent();
436
+ root?.remove();
437
+ root = null;
438
+ unsubscribeDock?.();
439
+ unsubscribeDock = null;
440
+ dockButton?.dispose();
441
+ dockButton = null;
442
+ document.removeEventListener("keydown", onKey, true);
443
+ document.removeEventListener("pointerdown", onPointer, true);
444
+ document.removeEventListener("fullscreenchange", onFullscreen);
445
+ };
446
+ const selectProvider = (visible) => {
447
+ const candidates = visible.filter((provider) => provider.cameraId === cameraId);
448
+ return candidates.filter((provider) => provider.kind === "settings" && provider.running).at(-1) || candidates.find((provider) => provider.kind === "permission") || candidates.at(-1);
449
+ };
450
+ const buttonStyle = {
451
+ minHeight: "36px",
452
+ padding: "6px 12px",
453
+ border: "1px solid #617184",
454
+ borderRadius: "6px",
455
+ background: "#fff",
456
+ color: "#25354a",
457
+ font: "inherit",
458
+ cursor: "pointer"
459
+ };
460
+ const createRoot = () => {
461
+ root = document.createElement("div");
462
+ root.setAttribute("data-camera-source-entry-host", "standalone");
463
+ Object.assign(root.style, {
464
+ position: "fixed",
465
+ right: "auto",
466
+ bottom: "auto",
467
+ width: "320px",
468
+ zIndex: "2147483647",
469
+ display: "flex",
470
+ flexDirection: "column",
471
+ alignItems: "flex-end",
472
+ gap: "8px",
473
+ color: "#25354a",
474
+ font: "14px/1.5 sans-serif",
475
+ maxWidth: "calc(100vw - 32px)"
476
+ });
477
+ panel = document.createElement("div");
478
+ panel.setAttribute("role", "dialog");
479
+ panel.setAttribute("aria-label", label);
480
+ panel.setAttribute("data-camera-source-panel", "standalone");
481
+ Object.assign(panel.style, {
482
+ boxSizing: "border-box",
483
+ width: "320px",
484
+ maxWidth: "100%",
485
+ maxHeight: "calc(100vh - 96px)",
486
+ overflowY: "auto",
487
+ padding: "16px",
488
+ border: "1px solid #617184",
489
+ borderRadius: "8px",
490
+ background: "#fff",
491
+ boxShadow: "0 4px 16px #0004"
492
+ });
493
+ const header = document.createElement("div");
494
+ Object.assign(header.style, {
495
+ display: "flex",
496
+ alignItems: "center",
497
+ justifyContent: "space-between",
498
+ marginBottom: "12px"
499
+ });
500
+ const title = document.createElement("strong");
501
+ title.textContent = label;
502
+ const dismiss = document.createElement("button");
503
+ dismiss.type = "button";
504
+ dismiss.textContent = "×";
505
+ dismiss.setAttribute("aria-label", ja ? "閉じる" : "Close");
506
+ Object.assign(dismiss.style, buttonStyle);
507
+ dismiss.addEventListener("click", () => close(true));
508
+ header.append(title, dismiss);
509
+ chooser = document.createElement("select");
510
+ chooser.setAttribute("aria-label", ja ? "カメラID" : "Camera ID");
511
+ Object.assign(chooser.style, {
512
+ ...buttonStyle,
513
+ width: "100%",
514
+ marginBottom: "8px"
515
+ });
516
+ chooser.addEventListener("change", () => {
517
+ cameraId = chooser.value;
518
+ render();
519
+ });
520
+ content = document.createElement("div");
521
+ panel.append(header, chooser, content);
522
+ dockButton = dock.stageControls.addButton({
523
+ id: "camera",
524
+ label,
525
+ text: label,
526
+ icon: "📷",
527
+ onClick: () => {
528
+ const starting = !open ? selectProvider([...providers.values()].filter((provider) => provider.visible)) : null;
529
+ open = !open;
530
+ render();
531
+ if (starting?.kind === "settings" && !starting.running) Promise.resolve().then(() => starting.onStart?.()).catch(() => {});
532
+ }
533
+ });
534
+ dockButton.update({ visible: true });
535
+ unsubscribeDock = dock.subscribe(() => {
536
+ if (open && root) dock.placePanel(root);
537
+ });
538
+ const style = document.createElement("style");
539
+ style.textContent = `[data-camera-source-entry-host] [data-camera-source-settings] {display:flex;flex-direction:column;gap:12px}
540
+ [data-camera-source-entry-host] [data-camera-source-settings] p {margin:0}
541
+ [data-camera-source-entry-host] [data-camera-source-settings] label {display:flex;flex-direction:column;gap:4px}
542
+ [data-camera-source-entry-host] [data-camera-source-settings] select,
543
+ [data-camera-source-entry-host] [data-camera-source-settings] button {min-height:36px;padding:6px 12px;border:1px solid #617184;border-radius:6px;background:#fff;color:#25354a;font:inherit}
544
+ [data-camera-source-entry-host] [data-camera-source-settings] [hidden] {display:none}`;
545
+ root.append(style, panel);
546
+ (document.fullscreenElement || document.body).appendChild(root);
547
+ document.addEventListener("keydown", onKey, true);
548
+ document.addEventListener("pointerdown", onPointer, true);
549
+ document.addEventListener("fullscreenchange", onFullscreen);
550
+ };
551
+ function render() {
552
+ if (disposed) return;
553
+ const visible = [...providers.values()].filter((provider) => provider.visible);
554
+ const ids = [...new Set(visible.map((provider) => provider.cameraId))];
555
+ if (!ids.includes(cameraId)) cameraId = ids[0] || "";
556
+ if (!visible.length) {
557
+ open = false;
558
+ removeRoot();
559
+ return;
560
+ }
561
+ if (!root) createRoot();
562
+ const selected = selectProvider(visible);
563
+ dockButton?.update({ expanded: open });
564
+ panel.hidden = !open;
565
+ if (open && root) dock.placePanel(root);
566
+ chooser.hidden = ids.length < 2;
567
+ chooser.replaceChildren(...ids.map((id) => {
568
+ const option = document.createElement("option");
569
+ option.value = id;
570
+ option.textContent = id;
571
+ return option;
572
+ }));
573
+ chooser.value = cameraId;
574
+ panel.setAttribute("data-camera-mode", selected.kind === "permission" || !selected.running ? "permission" : "settings");
575
+ if (!open) {
576
+ detachContent();
577
+ return;
578
+ }
579
+ if (mounted !== selected || mountedRunning !== selected.running) {
580
+ detachContent();
581
+ mounted = selected;
582
+ mountedRunning = selected.running;
583
+ content.appendChild(selected.element);
584
+ Promise.resolve().then(() => {
585
+ if (mounted === selected && open) return selected.onOpen?.();
586
+ }).catch(() => {});
587
+ if (root) dock.placePanel(root);
588
+ }
589
+ }
590
+ return {
591
+ host: { registerProvider(options) {
592
+ if (disposed) throw new Error("The standalone camera host has been disposed");
593
+ const provider = {
594
+ ...options,
595
+ visible: options.visible !== false,
596
+ running: options.running === true
597
+ };
598
+ providers.set(options.id, provider);
599
+ render();
600
+ return {
601
+ update(state) {
602
+ if (providers.get(options.id) !== provider) return;
603
+ let changed = false;
604
+ for (const key of ["visible", "running"]) if (typeof state[key] === "boolean" && provider[key] !== state[key]) {
605
+ provider[key] = state[key];
606
+ changed = true;
607
+ }
608
+ if (changed) render();
609
+ },
610
+ dispose() {
611
+ if (providers.get(options.id) !== provider) return;
612
+ providers.delete(options.id);
613
+ render();
614
+ }
615
+ };
616
+ } },
617
+ dispose() {
618
+ if (disposed) return;
619
+ disposed = true;
620
+ providers.clear();
621
+ open = false;
622
+ removeRoot();
623
+ }
624
+ };
625
+ }
626
+ /** Camera UI shared by all consumers; the GUI only supplies the entry and panel location. */
627
+ function createCameraControls(options) {
628
+ const ja = /^ja(?:-|$)/iu.test(options.locale || options.document.documentElement?.lang || globalThis.navigator?.language || "");
629
+ const labels = {
630
+ permission: ja ? "カメラの許可・開始を待っています。" : "Waiting to enable the camera.",
631
+ running: ja ? "カメラは起動しています。" : "The camera is running.",
632
+ select: ja ? "使用するカメラ" : "Camera device",
633
+ default: ja ? "既定のカメラ" : "Default camera",
634
+ front: ja ? "前面カメラ" : "Front camera",
635
+ back: ja ? "背面カメラ" : "Back camera",
636
+ mirror: ja ? "左右反転" : "Mirror preview",
637
+ mirrored: ja ? "左右反転:オン" : "Mirroring: on",
638
+ unmirrored: ja ? "左右反転:オフ" : "Mirroring: off",
639
+ ...options.labels
640
+ };
641
+ const panel = options.document.createElement("div");
642
+ panel.setAttribute("data-camera-source-settings", "true");
643
+ const status = options.document.createElement("p");
644
+ const label = options.document.createElement("label");
645
+ label.textContent = labels.select;
646
+ const select = options.document.createElement("select");
647
+ select.setAttribute("aria-label", labels.select);
648
+ label.appendChild(select);
649
+ const mirror = options.document.createElement("button");
650
+ mirror.type = "button";
651
+ mirror.setAttribute("aria-label", labels.mirror);
652
+ panel.append(status, label, mirror);
653
+ let enabled = false;
654
+ let disposed = false;
655
+ let generation = 0;
656
+ let mirroring = options.mirroring === "unmirrored" ? "unmirrored" : "mirrored";
657
+ let selectionTokens = /* @__PURE__ */ new Map();
658
+ let failureMessage = "";
659
+ const error = (failure) => {
660
+ failureMessage = failure instanceof Error ? failure.message : String(failure);
661
+ status.textContent = failureMessage;
662
+ };
663
+ const renderMirror = () => {
664
+ mirror.textContent = mirroring === "mirrored" ? labels.mirrored : labels.unmirrored;
665
+ mirror.setAttribute("aria-pressed", String(mirroring === "mirrored"));
666
+ };
667
+ const refresh = () => {
668
+ if (disposed) return;
669
+ const running = options.port.isCameraRunning();
670
+ registration.update({
671
+ visible: enabled,
672
+ running
673
+ });
674
+ status.textContent = failureMessage || (running ? labels.running : labels.permission);
675
+ label.hidden = !running || !options.port.selectCamera || !options.port.listCameraDevices;
676
+ mirror.hidden = !running || !options.port.setPreviewMirroring;
677
+ renderMirror();
678
+ };
679
+ const open = async () => {
680
+ failureMessage = "";
681
+ const revision = ++generation;
682
+ refresh();
683
+ if (!options.port.isCameraRunning() || !options.port.listCameraDevices || !options.port.selectCamera) return;
684
+ select.disabled = true;
685
+ try {
686
+ const devices = await options.port.listCameraDevices();
687
+ if (disposed || revision !== generation) return;
688
+ const tokens = /* @__PURE__ */ new Map();
689
+ select.replaceChildren();
690
+ const append = (token, text, value) => {
691
+ const option = options.document.createElement("option");
692
+ option.value = token;
693
+ option.textContent = text;
694
+ select.appendChild(option);
695
+ tokens.set(token, value);
696
+ };
697
+ for (const preference of [
698
+ "default",
699
+ "front",
700
+ "back"
701
+ ]) append(preference, labels[preference], preference);
702
+ if (Array.isArray(devices)) devices.forEach((device, index) => {
703
+ if (device.deviceId) append(`device:${index}`, device.label || `${ja ? "カメラ" : "Camera"} ${index + 1}`, { deviceId: device.deviceId });
704
+ });
705
+ const active = options.port.getActiveCamera?.();
706
+ if (active?.deviceId && !Array.from(tokens.values()).some((value) => typeof value === "object" && value && value.deviceId === active.deviceId)) append("device:current", active.label || (ja ? "現在のカメラ" : "Current camera"), { deviceId: active.deviceId });
707
+ selectionTokens = tokens;
708
+ const selected = options.port.getCameraSelection?.();
709
+ const deviceId = typeof selected === "object" && selected ? selected.deviceId : null;
710
+ select.value = Array.from(tokens).find(([, value]) => value === selected || deviceId && typeof value === "object" && value && value.deviceId === deviceId)?.[0] || "default";
711
+ } catch (failure) {
712
+ error(failure);
713
+ } finally {
714
+ if (!disposed && revision === generation) select.disabled = false;
715
+ }
716
+ };
717
+ const registration = options.host.registerProvider({
718
+ id: `camera-source-settings:${options.owner}`,
719
+ cameraId: options.cameraId || "default",
720
+ visible: false,
721
+ kind: "settings",
722
+ element: panel,
723
+ running: options.port.isCameraRunning(),
724
+ onOpen: open,
725
+ onClose: () => {
726
+ generation++;
727
+ },
728
+ onStart: async () => {
729
+ failureMessage = "";
730
+ try {
731
+ await options.requestStart();
732
+ refresh();
733
+ } catch (failure) {
734
+ error(failure);
735
+ }
736
+ }
737
+ });
738
+ const handleSelection = async () => {
739
+ if (disposed || !enabled || !selectionTokens.has(select.value)) return;
740
+ failureMessage = "";
741
+ const revision = generation;
742
+ select.disabled = true;
743
+ try {
744
+ await options.port.selectCamera?.(selectionTokens.get(select.value));
745
+ } catch (failure) {
746
+ error(failure);
747
+ } finally {
748
+ if (!disposed && revision === generation) select.disabled = false;
749
+ }
750
+ };
751
+ const handleMirror = async () => {
752
+ if (disposed || !enabled) return;
753
+ failureMessage = "";
754
+ mirror.disabled = true;
755
+ const next = mirroring === "mirrored" ? "unmirrored" : "mirrored";
756
+ try {
757
+ await options.port.setPreviewMirroring?.(next);
758
+ mirroring = next;
759
+ renderMirror();
760
+ } catch (failure) {
761
+ error(failure);
762
+ } finally {
763
+ if (!disposed) mirror.disabled = false;
764
+ }
765
+ };
766
+ select.addEventListener("change", handleSelection);
767
+ mirror.addEventListener("click", handleMirror);
768
+ const timer = setInterval(refresh, 100);
769
+ refresh();
770
+ return {
771
+ element: panel,
772
+ start() {
773
+ enabled = true;
774
+ refresh();
775
+ },
776
+ stop() {
777
+ enabled = false;
778
+ generation++;
779
+ registration.update({ visible: false });
780
+ },
781
+ refresh,
782
+ setMirroring(mode) {
783
+ if (mode === "mirrored" || mode === "unmirrored") {
784
+ mirroring = mode;
785
+ renderMirror();
786
+ }
787
+ },
788
+ dispose() {
789
+ if (disposed) return;
790
+ disposed = true;
791
+ generation++;
792
+ clearInterval(timer);
793
+ registration.dispose();
794
+ panel.remove();
795
+ select.removeEventListener("change", handleSelection);
796
+ mirror.removeEventListener("click", handleMirror);
797
+ }
798
+ };
799
+ }
19
800
  var block_editor_fixed_inputs_schema_default = {
20
801
  $schema: "https://json-schema.org/draft/2020-12/schema",
21
802
  $id: "https://kubohiroya.github.io/turbowarp-camera-source/schemas/block-editor-fixed-inputs.schema.json",
@@ -2884,22 +3665,26 @@
2884
3665
  button.type = "button";
2885
3666
  button.textContent = options.label;
2886
3667
  element.append(button);
2887
- element.style.position = "absolute";
2888
- element.style.left = "50%";
2889
- element.style.top = "50%";
2890
- element.style.transform = "translate(-50%, -50%)";
2891
- element.style.zIndex = "2";
3668
+ if (!options.cameraControls) {
3669
+ element.style.position = "absolute";
3670
+ element.style.left = "50%";
3671
+ element.style.top = "50%";
3672
+ element.style.transform = "translate(-50%, -50%)";
3673
+ element.style.zIndex = "2";
3674
+ }
2892
3675
  try {
2893
- element.setConstraints?.({ video: {} });
3676
+ element.setConstraints?.(options.constraints ?? { video: {} });
2894
3677
  } catch {}
2895
3678
  let settle = () => {};
2896
3679
  const settled = new Promise((resolve) => {
2897
3680
  settle = resolve;
2898
3681
  });
3682
+ let registration;
2899
3683
  let done = false;
2900
3684
  const finish = (outcome) => {
2901
3685
  if (done) return;
2902
3686
  done = true;
3687
+ registration?.dispose();
2903
3688
  element.remove();
2904
3689
  settle(outcome);
2905
3690
  };
@@ -2917,8 +3702,9 @@
2917
3702
  });
2918
3703
  element.addEventListener("cancel", () => finish({ kind: "cancelled" }));
2919
3704
  element.addEventListener("error", (event) => {
2920
- const detail = event.error;
3705
+ const detail = element.error ?? event.error;
2921
3706
  const code = typeof detail?.name === "string" && detail.name.length > 0 ? detail.name : "usermedia-error";
3707
+ if (code === "InvalidStateError") return;
2922
3708
  const message = typeof detail?.message === "string" && detail.message.length > 0 ? detail.message : "The camera button could not open the camera.";
2923
3709
  finish({
2924
3710
  kind: "error",
@@ -2926,7 +3712,14 @@
2926
3712
  message
2927
3713
  });
2928
3714
  });
2929
- options.container.append(element);
3715
+ if (options.cameraControls) registration = options.cameraControls.registerProvider({
3716
+ id: `camera-source-permission:${options.owner || options.cameraId || "default"}`,
3717
+ cameraId: options.cameraId || "default",
3718
+ kind: "permission",
3719
+ element
3720
+ });
3721
+ else if (options.container) options.container.append(element);
3722
+ else throw new TypeError("Camera permission requires a host or container");
2930
3723
  return Object.freeze({
2931
3724
  dismiss: () => finish({ kind: "cancelled" }),
2932
3725
  settled
@@ -3306,6 +4099,8 @@
3306
4099
  this.blockPreviewLeases = /* @__PURE__ */ new Map();
3307
4100
  this.blockPreviewRevisions = /* @__PURE__ */ new Map();
3308
4101
  this.cameraFailures = /* @__PURE__ */ new Map();
4102
+ this.controls = /* @__PURE__ */ new Set();
4103
+ this.standaloneControls = null;
3309
4104
  this.cameraButtons = /* @__PURE__ */ new Map();
3310
4105
  this.profiles = new CameraProfileRegistry();
3311
4106
  this.generations = /* @__PURE__ */ new Map();
@@ -3319,6 +4114,8 @@
3319
4114
  this.removeFixedEditors();
3320
4115
  this.removeSourceEditors();
3321
4116
  this.stopAllCameras();
4117
+ this.standaloneControls?.dispose();
4118
+ this.standaloneControls = null;
3322
4119
  const runtime = Scratch.vm.runtime;
3323
4120
  if (runtime["kubohiroyaCameraSourceCapability"] === this.capability) delete runtime[cameraSourceCapabilityKey];
3324
4121
  this.profileChannel?.close();
@@ -3514,6 +4311,8 @@
3514
4311
  return this.devices[indexFrom(args.INDEX)]?.label ?? "";
3515
4312
  }
3516
4313
  stopAllCameras() {
4314
+ for (const control of [...this.controls]) control.dispose();
4315
+ this.controls.clear();
3517
4316
  for (const request of [...this.cameraButtons.values()]) request.dismiss();
3518
4317
  this.cameraButtons.clear();
3519
4318
  for (const cameraId of [...this.sessions.keys()]) this.stopCameraSession(cameraId);
@@ -3700,8 +4499,9 @@
3700
4499
  });
3701
4500
  return;
3702
4501
  }
3703
- const container = this.cameraButtonContainer();
3704
- if (!container) {
4502
+ const host = this.cameraControlsHost();
4503
+ const container = host ? null : this.cameraButtonContainer();
4504
+ if (!host && !container) {
3705
4505
  this.cameraFailures.set(cameraId, {
3706
4506
  code: "usermedia-no-stage",
3707
4507
  message: "The stage the camera button would be placed on was not found."
@@ -3711,7 +4511,10 @@
3711
4511
  this.cameraButtons.get(cameraId)?.dismiss();
3712
4512
  const request = requestUserMedia({
3713
4513
  document,
3714
- container,
4514
+ ...host ? {
4515
+ cameraControls: host,
4516
+ cameraId
4517
+ } : { container },
3715
4518
  label: Scratch.translate("Allow the camera")
3716
4519
  });
3717
4520
  this.cameraButtons.set(cameraId, request);
@@ -3742,6 +4545,84 @@
3742
4545
  this.cameraFailures.set(cameraId, cameraFailure(error));
3743
4546
  }
3744
4547
  }
4548
+ cameraControlsHost() {
4549
+ if (Scratch.gui?.cameraControls) return Scratch.gui.cameraControls;
4550
+ if (typeof document === "undefined" || !document.body) return null;
4551
+ this.standaloneControls ?? (this.standaloneControls = createStandaloneCameraControlsHost(document, Scratch.translate.language || document.documentElement?.lang || globalThis.navigator?.language || "en"));
4552
+ return this.standaloneControls.host;
4553
+ }
4554
+ /** Generic controls live here; consumers supply only preview-specific operations. */
4555
+ registerCameraControls(options) {
4556
+ const host = this.cameraControlsHost();
4557
+ if (!host || typeof document === "undefined") return null;
4558
+ const cameraId = normalizeId(options.cameraId);
4559
+ let stream = null;
4560
+ let lease = null;
4561
+ let request = null;
4562
+ let disposed = false;
4563
+ const port = options.port || { isCameraRunning: () => this.isCameraRunning({ CAMERA_ID: cameraId }) };
4564
+ const panel = createCameraControls({
4565
+ ...options,
4566
+ locale: options.locale || Scratch.translate.language || "",
4567
+ cameraId,
4568
+ document,
4569
+ host,
4570
+ port: {
4571
+ ...port,
4572
+ isCameraRunning: () => this.isCameraRunning({ CAMERA_ID: cameraId }) || port.isCameraRunning()
4573
+ },
4574
+ requestStart: async () => {
4575
+ if (disposed || request || this.isCameraRunning({ CAMERA_ID: cameraId })) return;
4576
+ if (!supportsUserMediaElement()) throw new Error(Scratch.translate("This browser has no camera button element."));
4577
+ request = requestUserMedia({
4578
+ document,
4579
+ cameraControls: host,
4580
+ cameraId,
4581
+ owner: options.owner,
4582
+ label: Scratch.translate("Allow the camera")
4583
+ });
4584
+ const outcome = await request.settled;
4585
+ request = null;
4586
+ if (outcome.kind === "error") throw new Error(outcome.message);
4587
+ if (outcome.kind !== "stream") return;
4588
+ if (disposed) {
4589
+ outcome.stream.getTracks().forEach((track) => track.stop());
4590
+ return;
4591
+ }
4592
+ stream = outcome.stream;
4593
+ try {
4594
+ const adopted = await this.adoptCamera({
4595
+ cameraId,
4596
+ owner: options.owner,
4597
+ stream
4598
+ });
4599
+ if (disposed) {
4600
+ adopted.release();
4601
+ return;
4602
+ }
4603
+ lease = adopted;
4604
+ } catch (failure) {
4605
+ stream.getTracks().forEach((track) => track.stop());
4606
+ stream = null;
4607
+ throw failure;
4608
+ }
4609
+ }
4610
+ });
4611
+ const control = {
4612
+ ...panel,
4613
+ dispose: () => {
4614
+ if (disposed) return;
4615
+ disposed = true;
4616
+ request?.dismiss();
4617
+ panel.dispose();
4618
+ lease?.release();
4619
+ stream?.getTracks().forEach((track) => track.stop());
4620
+ this.controls.delete(control);
4621
+ }
4622
+ };
4623
+ this.controls.add(control);
4624
+ return control;
4625
+ }
3745
4626
  /** Removes a camera button still waiting for an answer; the script waiting on it continues. */
3746
4627
  hideCameraButton(args = {}) {
3747
4628
  this.cameraButtons.get(normalizeId(args.CAMERA_ID))?.dismiss();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-camera-source",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "author": "Hiroya Kubo <hiroya@cuc.ac.jp>",
5
5
  "description": "A TurboWarp capability extension for sharing one MediaDevices camera stream across extensions.",
6
6
  "type": "module",
@@ -71,6 +71,7 @@
71
71
  "prepare": "npm run build"
72
72
  },
73
73
  "devDependencies": {
74
+ "@kubohiroya/turbowarp-app-shell": "0.3.0",
74
75
  "@eslint/js": "^9.39.5",
75
76
  "@kubohiroya/turbowarp-extension-manifest": "0.3.2",
76
77
  "@kubohiroya/vite-plugin-turbowarp-extension": "0.6.1",