Repository Public
1import { useEffect, useRef, useState } from "react"2import { MAX_MESH, type Peer } from "../core/calls"3import { formatDuration } from "../core/media"4import { Avatar, I, t, useApp, useCalls } from "./bits"56function Stream({ stream, muted, mirror }: { stream: MediaStream; muted?: boolean; mirror?: boolean }) {7 const ref = useRef<HTMLVideoElement>(null)8 useEffect(() => {9 if (ref.current && ref.current.srcObject !== stream) ref.current.srcObject = stream10 }, [stream])11 return <video ref={ref} autoPlay playsInline muted={muted} style={mirror ? { transform: "scaleX(-1)" } : undefined} />12}1314function Tile({ p, name, sink }: { p: Peer; name: string; sink: string }) {15 const hasVideo = p.stream.getVideoTracks().some((x) => x.readyState === "live" && !x.muted)16 const ref = useRef<HTMLDivElement>(null)17 useEffect(() => {18 const v = ref.current?.querySelector("video") as (HTMLVideoElement & { setSinkId?: (id: string) => Promise<void> }) | null19 if (sink && v?.setSinkId) void v.setSinkId(sink).catch(() => {})20 }, [sink, p.stream])21 return (22 <div className="tile" ref={ref}>23 <Stream stream={p.stream} />24 {!hasVideo && <Avatar id={p.userId} name={name} size={96} />}25 <span className="label">{name}{p.state !== "connected" ? ` · ${p.state === "failed" ? t("reconnecting…", "reconnexion…") : t("connecting…", "connexion…")}` : ""}</span>26 </div>27 )28}2930export function CallUI() {31 const { engine } = useApp()32 const calls = useCalls()33 const cur = calls.current34 const [, tick] = useState(0)35 const [mini, setMini] = useState(false)36 const [outputs, setOutputs] = useState<MediaDeviceInfo[]>([])37 const [sink, setSink] = useState("")38 const localRef = useRef<HTMLVideoElement>(null)39 useEffect(() => {40 const timer = setInterval(() => tick((n) => n + 1), 1000)41 return () => clearInterval(timer)42 }, [])43 useEffect(() => {44 if (cur?.status !== "active") return45 navigator.mediaDevices.enumerateDevices().then((d) => setOutputs(d.filter((x) => x.kind === "audiooutput"))).catch(() => {})46 }, [cur?.status])4748 const waiting = calls.waiting && (49 <div className="toasts" style={{ zIndex: 120 }}>50 <div className="toast">51 <span className="grow"><b>{engine.userName(calls.waiting.from)}</b> {t("is calling you", "vous appelle")}</span>52 <button className="btn sm danger" onClick={() => calls.decline(true)}>{t("Decline", "Refuser")}</button>53 <button className="btn sm primary" onClick={() => calls.accept(true)}>{t("End and answer", "Raccrocher et répondre")}</button>54 </div>55 </div>56 )57 if (!cur) return waiting || null5859 const conv = engine.convs.get(cur.conv)60 const title = conv ? engine.convTitle(conv) : ""61 const peers = [...cur.peers.values()]62 const pip = async () => {63 const v = document.querySelector(".tile video") as HTMLVideoElement & { requestPictureInPicture?: () => Promise<unknown> }64 try {65 if (document.pictureInPictureElement) await document.exitPictureInPicture()66 else await v?.requestPictureInPicture?.()67 } catch {}68 }6970 if (mini && cur.status === "active")71 return (72 <>73 {waiting}74 <button className="call-mini" onClick={() => setMini(false)}>{I.phone}{title} · {formatDuration((Date.now() - cur.startedAt) / 1000)}</button>75 <div style={{ display: "none" }}>{peers.map((p) => <Stream key={p.deviceId} stream={p.stream} />)}</div>76 </>77 )7879 if (cur.status !== "active")80 return (81 <div className="call" role="dialog" aria-label={t("Call", "Appel")}>82 <div className="empty" style={{ color: "#fff" }}>83 <div className="col" style={{ alignItems: "center", gap: 18 }}>84 <span className="ring-avatar"><Avatar id={conv ? (engine.peerOf(conv) ?? conv.id) : cur.from} name={title} size={128} /></span>85 <h1 className="h1">{title}</h1>86 <span style={{ opacity: 0.7 }}>87 {cur.status === "ringing-in" ? `${engine.userName(cur.from)} · ${cur.video ? t("incoming video call", "appel vidéo entrant") : t("incoming voice call", "appel vocal entrant")}` : t("Calling…", "Appel en cours…")}88 </span>89 <span className="lock" style={{ color: "rgba(255,255,255,.6)" }}>{I.lock}{t("End-to-end encrypted", "Chiffré de bout en bout")}</span>90 </div>91 </div>92 <div className="call-bar">93 {cur.status === "ringing-in" ? (94 <>95 <button className="call-btn end" onClick={() => calls.decline()} aria-label={t("Decline", "Refuser")}>{I.hang}</button>96 <button className="call-btn go" onClick={() => calls.accept()} aria-label={t("Answer", "Répondre")}>{cur.video ? I.video : I.phone}</button>97 </>98 ) : (99 <button className="call-btn end" onClick={() => calls.hangup("cancelled")} aria-label={t("Cancel", "Annuler")}>{I.hang}</button>100 )}101 </div>102 </div>103 )104105 const n = Math.max(1, peers.length)106 const cols = n <= 1 ? 1 : n <= 4 ? 2 : 3107 return (108 <div className="call" role="dialog" aria-label={t("Call", "Appel")}>109 {waiting}110 <div className="call-grid" style={{ gridTemplateColumns: `repeat(${matchMedia("(max-width: 820px)").matches && n === 2 ? 1 : cols}, minmax(0, 1fr))` }}>111 {peers.map((p) => <Tile key={p.deviceId} p={p} name={engine.userName(p.userId)} sink={sink} />)}112 {!peers.length && <div className="tile"><div className="col" style={{ alignItems: "center" }}><span className="spinner" /><span style={{ opacity: 0.7 }}>{t("Waiting for others to join…", "En attente des autres participants…")}</span></div></div>}113 </div>114 {cur.local && cur.video && !cur.cameraOff && (115 <div className="pip"><video ref={(el) => { if (el && cur.local && el.srcObject !== cur.local) el.srcObject = cur.local; (localRef as any).current = el }} autoPlay playsInline muted style={cur.sharing ? { transform: "none" } : undefined} /></div>116 )}117 <div style={{ textAlign: "center", fontSize: 13, opacity: 0.75 }}>118 {title} · {formatDuration((Date.now() - cur.startedAt) / 1000)} · <span className="lock" style={{ color: "inherit" }}>{I.lock}{t("encrypted", "chiffré")}</span>119 {peers.length >= MAX_MESH - 1 && ` · ${t("call is full", "appel complet")}`}120 </div>121 <div className="call-bar">122 <button className={`call-btn ${cur.muted ? "off" : ""}`} onClick={() => calls.toggleMute()} aria-label={cur.muted ? t("Unmute", "Réactiver le micro") : t("Mute", "Couper le micro")} aria-pressed={cur.muted}>{cur.muted ? I.micOff : I.mic}</button>123 {cur.video && <button className={`call-btn ${cur.cameraOff ? "off" : ""}`} onClick={() => calls.toggleCamera()} aria-label={t("Camera", "Caméra")} aria-pressed={cur.cameraOff}>{cur.cameraOff ? I.camOff : I.video}</button>}124 {cur.video && matchMedia("(pointer: coarse)").matches && <button className="call-btn" onClick={() => calls.switchCamera()} aria-label={t("Switch camera", "Changer de caméra")}>{I.flip}</button>}125 {"getDisplayMedia" in (navigator.mediaDevices ?? {}) && <button className={`call-btn ${cur.sharing ? "off" : ""}`} onClick={() => calls.toggleScreen()} aria-label={t("Share screen", "Partager l’écran")} aria-pressed={cur.sharing}>{I.screen}</button>}126 {outputs.length > 1 && "setSinkId" in HTMLMediaElement.prototype && (127 <select className="call-btn" style={{ width: 58, appearance: "none", textAlign: "center", fontSize: 22 }} value={sink} onChange={(e) => setSink(e.target.value)} aria-label={t("Speaker", "Haut-parleur")}>128 <option value="">🔈</option>129 {outputs.map((o) => <option key={o.deviceId} value={o.deviceId}>{o.label || t("Speaker", "Haut-parleur")}</option>)}130 </select>131 )}132 {document.pictureInPictureEnabled && cur.video && <button className="call-btn" onClick={pip} aria-label={t("Picture in picture", "Image dans l’image")}>{I.image}</button>}133 <button className="call-btn" onClick={() => setMini(true)} aria-label={t("Back to messages", "Retour aux messages")}>{I.chat}</button>134 <button className="call-btn end" onClick={() => calls.hangup()} aria-label={t("Hang up", "Raccrocher")}>{I.hang}</button>135 </div>136 </div>137 )138}139