webrtc-preview.stories.mjs (2570B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 // eslint-disable-next-line import/no-unresolved 6 import { html } from "lit.all.mjs"; 7 import "chrome://global/content/elements/moz-card.mjs"; 8 import "./webrtc-preview.mjs"; 9 10 window.MozXULElement.insertFTLIfNeeded("browser/webrtc-preview.ftl"); 11 12 export default { 13 title: "Domain-specific UI Widgets/WebRTC/Preview", 14 component: "webrtc-preview", 15 argTypes: { 16 deviceId: { 17 control: "text", 18 }, 19 mediaSource: { 20 control: "select", 21 options: ["camera", "screen", "window", "browser"], 22 }, 23 showPreviewControlButtons: { 24 control: { 25 type: "boolean", 26 }, 27 }, 28 }, 29 }; 30 31 const Template = (args, context) => { 32 // Get deviceId from loaded data if available 33 const deviceId = context?.loaded?.deviceId || args.deviceId; 34 35 // If deviceId is not available show an error message. 36 if (!deviceId) { 37 return html` 38 <moz-card style="position: relative; width: 25rem;"> 39 <div style="padding: 1rem; text-align: center;"> 40 No device or no permission granted. 41 </div> 42 </moz-card> 43 `; 44 } 45 46 const element = html` 47 <div style="position: relative; width: 25rem;"> 48 <webrtc-preview 49 .deviceId=${deviceId} 50 .mediaSource=${args.mediaSource} 51 .showPreviewControlButtons=${args.showPreviewControlButtons} 52 ></webrtc-preview> 53 </div> 54 `; 55 56 return element; 57 }; 58 59 const getDeviceId = async () => { 60 try { 61 // Request device access - this will show the permission prompt / device 62 // picker to the user 63 const stream = await navigator.mediaDevices.getUserMedia({ 64 video: true, 65 mediaSource: "camera", 66 }); 67 68 // Get the video track to extract the device ID 69 const videoTrack = stream.getVideoTracks()[0]; 70 const deviceId = videoTrack.getSettings().deviceId; 71 72 // Stop the stream since we only needed it to get the device ID 73 stream.getTracks().forEach(track => track.stop()); 74 75 return deviceId || ""; 76 } catch (error) { 77 console.warn("Could not get device:", error); 78 return ""; 79 } 80 }; 81 82 export const Camera = Template.bind({}); 83 Camera.args = { 84 deviceId: "", 85 mediaSource: "camera", 86 showPreviewControlButtons: true, 87 }; 88 Camera.loaders = [ 89 async () => { 90 const deviceId = await getDeviceId(); 91 return { deviceId }; 92 }, 93 ]; 94 Camera.play = async ({ args, loaded }) => { 95 args.deviceId = loaded.deviceId; 96 };