@kubohiroya/turbowarp-camera-source 0.18.0 → 0.19.1

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