Files
CatoandClaude be943e2647 feat(messenger): voice messages people find, and that play everywhere (0.37.0) (#102)
The empty box's send slot records a voice message in the box's place; one
tap sends it. A voice note plays in the thread in the bubble's own colours.
AAC in MP4 first, so every phone plays it. Its length travels with it.

Fix: the timer rounded to 0:01 at half a second and a short take was
dropped without a word.


Claude-Session: https://claude.ai/code/session_019MDtmsmMXvM981mcszxEA6

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-15 01:41:03 +01:00

235 lines
11 KiB
JavaScript

"use client";
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useRef, useState } from "react";
import { formatDuration } from "../messenger.js";
import { IconArrowUp, IconMic, IconStop, IconTrash } from "./icons.js";
/** The longest voice message: five minutes. Past it the take ends by itself. */
export const VOICE_MESSAGE_MAX_MS = 5 * 60 * 1000;
/** Shorter than this is a slip of the finger, not a message. */
export const VOICE_MESSAGE_MIN_MS = 500;
/**
* The container the browser records a voice in, best first.
*
* AAC in MP4 first: it is the one recording every phone plays, iPhones
* included. A voice recorded as WebM on an Android phone and sent to an
* iPhone is a message the other person may not be able to open. Opus in WebM
* where AAC is not offered (Firefox), then whatever is left.
*/
export function voiceMimeType(supported = (type) => typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(type)) {
for (const type of [
"audio/mp4;codecs=mp4a.40.2",
"audio/webm;codecs=opus",
"audio/webm",
"audio/mp4",
"audio/ogg",
]) {
if (supported(type))
return type;
}
return null;
}
/** Can this browser record a voice message at all? */
export function canRecordVoice() {
return (typeof navigator !== "undefined" &&
Boolean(navigator.mediaDevices?.getUserMedia) &&
voiceMimeType() !== null);
}
/** "voice-2026-11-13-2004.m4a": a name a person can find again in a folder. */
export function voiceFileName(at, mimeType) {
const pad = (n) => String(n).padStart(2, "0");
const stamp = `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}`;
const bare = mimeType.split(";")[0] ?? "";
const ext = bare === "audio/mp4" ? "m4a" : bare === "audio/ogg" ? "ogg" : "webm";
return `voice-${stamp}.${ext}`;
}
/**
* Recording a voice, without any markup: the microphone is open only while
* recording and is closed on every way out (finish, cancel, the five-minute
* limit, the component going away). One request at a time, so a second tap
* while the microphone is still opening cannot open a second one.
*/
export function useVoiceRecording(maxMs = VOICE_MESSAGE_MAX_MS) {
const [phase, setPhase] = useState("idle");
const [elapsedMs, setElapsed] = useState(0);
const recorder = useRef(null);
const stream = useRef(null);
const chunks = useRef([]);
const began = useRef(0);
const tick = useRef(null);
const settle = useRef(null);
const keep = useRef(true);
const opening = useRef(false);
const mounted = useRef(true);
const mime = useRef("");
const closeMicrophone = useCallback(() => {
if (tick.current)
clearInterval(tick.current);
tick.current = null;
for (const track of stream.current?.getTracks() ?? [])
track.stop();
stream.current = null;
}, []);
const stopWith = useCallback((keepTake) => {
keep.current = keepTake;
const active = recorder.current;
if (active && active.state !== "inactive")
active.stop();
}, []);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
const active = recorder.current;
recorder.current = null;
if (active && active.state !== "inactive") {
active.ondataavailable = null;
active.onstop = null;
active.stop();
}
closeMicrophone();
settle.current?.(null);
settle.current = null;
};
}, [closeMicrophone]);
const start = useCallback(async () => {
const type = voiceMimeType();
if (opening.current || recorder.current || !type)
return;
opening.current = true;
mime.current = type;
setElapsed(0);
setPhase("opening");
try {
const opened = await navigator.mediaDevices.getUserMedia({
audio: { echoCancellation: true, noiseSuppression: true },
});
if (!mounted.current) {
for (const track of opened.getTracks())
track.stop();
return;
}
stream.current = opened;
chunks.current = [];
keep.current = true;
const next = new MediaRecorder(opened, { mimeType: type });
recorder.current = next;
next.ondataavailable = (event) => {
if (event.data.size > 0)
chunks.current.push(event.data);
};
next.onstop = () => {
const durationMs = Date.now() - began.current;
closeMicrophone();
recorder.current = null;
const blob = new Blob(chunks.current, { type: type.split(";")[0] });
chunks.current = [];
const take = keep.current && blob.size > 0 && durationMs >= VOICE_MESSAGE_MIN_MS
? {
file: new File([blob], voiceFileName(new Date(), type), { type: blob.type }),
durationMs: Math.min(durationMs, maxMs),
}
: null;
if (mounted.current)
setPhase("idle");
settle.current?.(take);
settle.current = null;
};
// A slice a second: a take cut short by a closed tab still has its data.
next.start(1000);
began.current = Date.now();
setPhase("recording");
tick.current = setInterval(() => {
const ms = Date.now() - began.current;
setElapsed(ms);
if (ms >= maxMs)
stopWith(true);
}, 200);
}
catch {
closeMicrophone();
recorder.current = null;
if (mounted.current)
setPhase("failed");
}
finally {
opening.current = false;
}
}, [closeMicrophone, maxMs, stopWith]);
const finish = useCallback(() => {
if (!recorder.current)
return Promise.resolve(null);
return new Promise((resolve) => {
settle.current = resolve;
stopWith(true);
});
}, [stopWith]);
const cancel = useCallback(() => {
if (recorder.current)
stopWith(false);
else
setPhase("idle");
}, [stopWith]);
return { phase, elapsedMs, start, finish, cancel };
}
/**
* The message box while a voice is recorded: Delete, the time with a red
* dot, Send. It takes the box's place, so the thread above stays where it
* was and the thumb that started the recording ends it in the same spot.
* Recording starts as soon as it is shown.
*/
export function VoiceBar({ onSend, onClose, onTooShort, labels, maxMs = VOICE_MESSAGE_MAX_MS, }) {
const voice = useVoiceRecording(maxMs);
const { start } = voice;
const started = useRef(false);
useEffect(() => {
if (started.current)
return;
started.current = true;
void start();
}, [start]);
const failed = voice.phase === "failed";
return (_jsxs("div", { className: "ck-msgr-voicebar", "data-phase": voice.phase, role: "group", "aria-label": labels.voiceMessage, children: [_jsx("button", { type: "button", className: "ck-icon-btn", onClick: () => {
voice.cancel();
onClose();
}, "aria-label": failed ? labels.close : labels.voiceDiscard, title: failed ? labels.close : labels.voiceDiscard, children: _jsx(IconTrash, {}) }), _jsx("p", { className: "ck-msgr-voicebar-line", role: "status", "aria-live": "polite", children: failed ? (labels.voiceFailed) : (_jsxs(_Fragment, { children: [_jsx("span", { className: "ck-msgr-voicebar-dot", "aria-hidden": "true" }), _jsx("span", { className: "ck-msgr-voicebar-time", children: formatDuration(Math.floor(voice.elapsedMs / 1000) * 1000) }), _jsx("span", { className: "ck-msgr-voicebar-hint ck-truncate", children: labels.voiceRecordingHint })] })) }), failed ? (_jsx("button", { type: "button", className: "ck-send", onClick: () => void voice.start(), "aria-label": labels.voiceStart, title: labels.voiceStart, children: _jsx(IconMic, {}) })) : (_jsx("button", { type: "button", className: "ck-send ck-msgr-voicebar-send", disabled: voice.phase !== "recording", onClick: async () => {
const take = await voice.finish();
onClose();
if (take)
onSend(take);
else
onTooShort?.();
}, "aria-label": labels.voiceSend, title: labels.voiceSend, children: _jsx(IconArrowUp, {}) }))] }));
}
/**
* The recorder in a sheet: start, stop, listen, then add. For an app with its
* own arrangement; the Messenger itself records in the box (`VoiceBar`).
*/
export function VoiceRecorder({ onDone, labels, maxMs = VOICE_MESSAGE_MAX_MS, }) {
const voice = useVoiceRecording(maxMs);
const [take, setTake] = useState(null);
useEffect(() => {
const url = take?.url;
return () => {
if (url)
URL.revokeObjectURL(url);
};
}, [take]);
const recording = voice.phase === "recording";
return (_jsxs("div", { className: "ck-msgr-voice", "data-phase": take ? "recorded" : voice.phase, children: [!take && (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: recording ? "ck-msgr-voice-btn ck-msgr-voice-btn-on" : "ck-msgr-voice-btn", onClick: async () => {
if (!recording) {
void voice.start();
return;
}
const done = await voice.finish();
if (done)
setTake({ ...done, url: URL.createObjectURL(done.file) });
}, disabled: voice.phase === "opening", "aria-label": recording ? labels.voiceStop : labels.voiceStart, children: recording ? _jsx(IconStop, {}) : _jsx(IconMic, {}) }), _jsx("p", { className: "ck-msgr-voice-line", role: "status", children: recording
? labels.voiceRecording.replace("{time}", formatDuration(Math.floor(voice.elapsedMs / 1000) * 1000))
: voice.phase === "failed"
? labels.voiceFailed
: labels.voiceStart })] })), take && (_jsxs(_Fragment, { children: [_jsx("audio", { className: "ck-msgr-audio", controls: true, src: take.url, "aria-label": labels.voiceTake }), _jsxs("div", { className: "ck-msgr-confirm", children: [_jsx("button", { type: "button", className: "ck-msgr-btn", onClick: () => {
setTake(null);
void voice.start();
}, children: labels.voiceAgain }), _jsx("button", { type: "button", className: "ck-msgr-btn ck-msgr-btn-primary", onClick: () => onDone(take.file, take.durationMs), children: labels.voiceAdd })] })] }))] }));
}
//# sourceMappingURL=VoiceRecorder.js.map