cautpartener / client / src / app / views / call-ui.ts
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/**
 * Call UI (P4): the app-wide overlays for 1:1 audio/video calls, driven by
 * core/calls.ts. Two surfaces, both mounted on document.body so a call
 * survives navigation:
 *
 *  - incoming overlay: accept-audio / accept-video / decline + a WebAudio
 *    oscillator ringtone (no audio asset; best-effort — autoplay policy may
 *    keep it silent until a gesture, the overlay itself never depends on it);
 *  - in-call overlay: full-screen, remote media, local PiP for video calls,
 *    mic/camera/flip/hang-up controls, duration timer, safe-area insets.
 *
 * iOS rules honored here: accept/start run STRICTLY inside click handlers
 * (getUserMedia needs the gesture), remote videos are playsinline, and the
 * caller's name comes from LOCAL state (contact book / match list) — nothing
 * from the wire is ever rendered. Everything renders through h() text nodes
 * (XSS-safe by construction).
 */

import type { CallService } from "../../core/calls";
import { Session } from "../../core/session";
import { matchByConvId } from "../../public/match-service";
import { t } from "../i18n";
import { h, svgIcon, toast } from "../ui-kit";

const TICK_MS = 500;

const fmtDur = (sec: number): string => `${Math.floor(sec / 60)}:${String(Math.floor(sec % 60)).padStart(2, "0")}`;

/** Display name for a conversation peer — LOCAL data only. */
function convName(convId: string): string {
  const state = Session.selfroom?.state;
  const contact = state?.contacts.get(convId);
  if (contact) return contact.name;
  const match = matchByConvId(convId);
  if (match) return match.name || `${match.peer.slice(0, 8)}…`;
  return `${convId.slice(0, 8)}…`;
}

/**
 * European-cadence ringtone from a bare oscillator (425 Hz, 1 s on / 4 s off,
 * incoming; softer 425 Hz ringback for the caller). Autoplay policies may
 * suspend the context — resume is attempted, failure is silent on purpose.
 */
class Ringer {
  #ctx: AudioContext | null = null;
  #interval: ReturnType<typeof setInterval> | null = null;

  start(volume: number): void {
    if (this.#ctx) return;
    try {
      const ctx = new AudioContext();
      this.#ctx = ctx;
      void ctx.resume().catch(() => {});
      const osc = ctx.createOscillator();
      osc.type = "sine";
      osc.frequency.value = 425;
      const gain = ctx.createGain();
      gain.gain.value = 0;
      osc.connect(gain).connect(ctx.destination);
      osc.start();
      const burst = (): void => {
        const t0 = ctx.currentTime;
        gain.gain.setValueAtTime(0, t0);
        gain.gain.linearRampToValueAtTime(volume, t0 + 0.02);
        gain.gain.setValueAtTime(volume, t0 + 1.0);
        gain.gain.linearRampToValueAtTime(0, t0 + 1.05);
      };
      burst();
      this.#interval = setInterval(burst, 4000);
    } catch {
      this.#ctx = null; // no WebAudio — ring silently (the overlay still shows)
    }
  }

  stop(): void {
    if (this.#interval) clearInterval(this.#interval);
    this.#interval = null;
    void this.#ctx?.close().catch(() => {});
    this.#ctx = null;
  }
}

/** Mount the call surfaces once (boot wiring). */
export function wireCallUi(calls: CallService): void {
  const ringer = new Ringer();
  let root: HTMLElement | null = null;
  let tick: ReturnType<typeof setInterval> | null = null;
  let lastPhase = "idle";

  calls.onNotice = (kind) => {
    const key =
      kind === "declined"
        ? "callDeclinedToast"
        : kind === "busy"
          ? "callBusyToast"
          : kind === "missed"
            ? "callMissedToast"
            : kind === "ended"
              ? "callEndedToast"
              : kind === "denied"
                ? "callPermDenied"
                : kind === "nodevice"
                  ? "callNoDevice"
                  : kind === "busydevice"
                    ? "callDeviceBusy"
                    : kind === "recoverfailed"
                      ? "callRecoverFailed"
                      : "callFailedToast";
    toast(t(key));
  };

  const unmount = (): void => {
    ringer.stop();
    if (tick) clearInterval(tick);
    tick = null;
    root?.remove();
    root = null;
  };

  const render = (): void => {
    const cur = calls.current;
    const phase = cur?.phase ?? "idle";
    if (phase === "idle") {
      lastPhase = phase;
      unmount();
      return;
    }
    // phase changes rebuild the surface; stream/mute changes patch in place
    if (root && phase === lastPhase) {
      patch();
      return;
    }
    lastPhase = phase;
    unmount();
    root = phase === "incoming" ? incomingOverlay() : inCallOverlay();
    document.body.append(root);
    patch();
  };
  calls.onChange = render;

  // ---- incoming ------------------------------------------------------------

  const incomingOverlay = (): HTMLElement => {
    const cur = calls.current!;
    const name = convName(cur.convId);
    ringer.start(0.22);
    const acceptAudio = h(
      "button",
      { type: "button", class: "btn call-accept", "data-testid": "call-accept-audio" },
      t("callAcceptAudio"),
    );
    const acceptVideo = h(
      "button",
      { type: "button", class: "btn call-accept", "data-testid": "call-accept-video" },
      t("callAcceptVideo"),
    );
    const decline = h(
      "button",
      { type: "button", class: "btn danger", "data-testid": "call-decline" },
      t("callDecline"),
    );
    // STRICTLY inside the click handlers — iOS getUserMedia gesture rule
    acceptAudio.addEventListener("click", () => void calls.accept(false));
    acceptVideo.addEventListener("click", () => void calls.accept(true));
    decline.addEventListener("click", () => calls.decline());
    return h(
      "div",
      { class: "call-overlay call-incoming", "data-testid": "call-incoming" },
      h("div", { class: "call-glyph", "aria-hidden": "true" }, cur.video ? "🎥" : "📞"),
      h(
        "p",
        { class: "call-title", "data-testid": "call-incoming-title" },
        t(cur.video ? "callIncomingVideo" : "callIncoming", { name }),
      ),
      h("div", { class: "call-actions" }, decline, acceptAudio, acceptVideo),
    );
  };

  // ---- in-call -------------------------------------------------------------

  let remoteVideo: HTMLVideoElement | null = null;
  let localVideo: HTMLVideoElement | null = null;
  let statusEl: HTMLElement | null = null;
  let durEl: HTMLElement | null = null;
  let micBtn: HTMLButtonElement | null = null;
  let camBtn: HTMLButtonElement | null = null;
  let flipBtn: HTMLButtonElement | null = null;
  let nameEl: HTMLElement | null = null;

  const inCallOverlay = (): HTMLElement => {
    const cur = calls.current!;
    remoteVideo = h("video", {
      class: "call-remote",
      autoplay: true,
      playsinline: true,
      "data-testid": "call-remote-video",
    }) as HTMLVideoElement;
    localVideo = h("video", {
      class: "call-pip",
      autoplay: true,
      playsinline: true,
      muted: true,
      "data-testid": "call-local-video",
    }) as HTMLVideoElement;
    localVideo.muted = true; // the attribute alone is unreliable pre-play
    statusEl = h("span", { class: "call-status", "data-testid": "call-status" });
    durEl = h("span", { class: "call-duration", "data-testid": "call-duration" });
    nameEl = h("span", { class: "call-name" }, convName(cur.convId));
    micBtn = h(
      "button",
      { type: "button", class: "call-ctl", "aria-label": t("callMicToggle"), "data-testid": "call-mute" },
      svgIcon("M12 3a3 3 0 0 1 3 3v6a3 3 0 1 1-6 0V6a3 3 0 0 1 3-3zM6 11a6 6 0 0 0 12 0M12 17v4M9 21h6", "icon"),
    ) as HTMLButtonElement;
    camBtn = h(
      "button",
      { type: "button", class: "call-ctl", "aria-label": t("callCamToggle"), "data-testid": "call-cam" },
      svgIcon("M3 7h12v10H3zM15 10l6-3v10l-6-3", "icon"),
    ) as HTMLButtonElement;
    flipBtn = h(
      "button",
      { type: "button", class: "call-ctl", "aria-label": t("callFlip"), "data-testid": "call-flip" },
      svgIcon("M4 9a8 8 0 0 1 14-3M20 15a8 8 0 0 1-14 3M18 2v4h-4M6 22v-4h4", "icon"),
    ) as HTMLButtonElement;
    const hangBtn = h(
      "button",
      { type: "button", class: "call-ctl call-hang", "aria-label": t("callHangup"), "data-testid": "call-hangup" },
      svgIcon("M4 14c4-4 12-4 16 0l-2 3-4-1v-3a10 10 0 0 0-4 0v3l-4 1z", "icon"),
    ) as HTMLButtonElement;
    micBtn.addEventListener("click", () => calls.toggleMic());
    camBtn.addEventListener("click", () => void calls.toggleCam());
    flipBtn.addEventListener("click", () => void calls.flipCam());
    hangBtn.addEventListener("click", () => calls.hangup());
    tick = setInterval(patch, TICK_MS);
    return h(
      "div",
      { class: "call-overlay", "data-testid": "call-overlay" },
      remoteVideo,
      h("div", { class: "call-head" }, nameEl, statusEl, durEl),
      h("div", { class: "call-audio-glyph", "aria-hidden": "true", "data-testid": "call-audio-glyph" }, "📞"),
      localVideo,
      h("p", { class: "call-note muted" }, t("callP2PNote")),
      h("div", { class: "call-controls" }, micBtn, camBtn, flipBtn, hangBtn),
    );
  };

  // ---- shared patching -----------------------------------------------------

  const patch = (): void => {
    const cur = calls.current;
    if (!cur || !root) return;
    if (cur.phase === "incoming") return; // static while ringing
    if (cur.phase === "outgoing") ringer.start(0.08);
    else ringer.stop();
    if (statusEl) {
      statusEl.textContent =
        cur.phase === "outgoing" ? t("callRinging") : cur.phase === "connecting" ? t("callConnecting") : "";
      statusEl.hidden = cur.phase === "active";
    }
    if (durEl) {
      durEl.hidden = cur.phase !== "active";
      if (cur.phase === "active") durEl.textContent = fmtDur(calls.elapsedSec());
    }
    if (remoteVideo && remoteVideo.srcObject !== cur.remote) {
      remoteVideo.srcObject = cur.remote;
      void remoteVideo.play().catch(() => {});
    }
    if (localVideo) {
      const showPip = cur.camOn && cur.local !== null;
      localVideo.hidden = !showPip;
      if (showPip && localVideo.srcObject !== cur.local) {
        localVideo.srcObject = cur.local;
        void localVideo.play().catch(() => {});
      }
    }
    const remoteHasVideo = (cur.remote?.getVideoTracks().length ?? 0) > 0;
    remoteVideo?.classList.toggle("call-remote-off", !remoteHasVideo);
    root.querySelector<HTMLElement>(".call-audio-glyph")?.toggleAttribute("hidden", remoteHasVideo);
    micBtn?.classList.toggle("call-ctl-off", !cur.micOn);
    micBtn?.setAttribute("data-on", cur.micOn ? "1" : "0");
    camBtn?.classList.toggle("call-ctl-off", !cur.camOn);
    camBtn?.setAttribute("data-on", cur.camOn ? "1" : "0");
    if (flipBtn) flipBtn.hidden = !cur.camOn;
  };
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git