xonecas.io
8058
Ir

irvc / commit c14ee79

feat: voice channel state is not locked to its pane

xonecas2026-10-11 c14ee7962a4fbefc11caa6a07b4d0ab8616457bd parent 37a32bc

4 files changed

web/src/components/Sidebar.tsx+79−8
@@ -1,16 +1,19 @@
11 import type { ReactNode } from "react";
2-import { Hash, Volume2 } from "lucide-react";
2+import { Hash, Mic, MicOff, PhoneOff, Volume2 } from "lucide-react";
33 import { Button } from "@/components/ui/button";
44 import type { Channel } from "../lib/types";
5+import type { Voice } from "../lib/voice";
56
67 export default function Sidebar({
78 channels,
89 selected,
910 onSelect,
11+ voice,
1012 }: {
1113 channels: Channel[];
1214 selected: Channel | null;
1315 onSelect: (c: Channel) => void;
16+ voice: Voice;
1417 }) {
1518 return (
1619 <aside className="flex w-56 shrink-0 flex-col border-r border-sepia/15">
@@ -23,13 +26,20 @@ export default function Sidebar({
2326 onSelect={onSelect}
2427 icon={<Hash size={14} />}
2528 />
26- <Group
27- label="Voice"
28- channels={channels.filter((c) => c.type === "voice")}
29- selected={selected}
30- onSelect={onSelect}
31- icon={<Volume2 size={14} />}
32- />
29+ <div>
30+ <div className="px-2 py-1 text-[10px] uppercase tracking-widest text-sepia/40">Voice</div>
31+ {channels
32+ .filter((c) => c.type === "voice")
33+ .map((c) => (
34+ <VoiceChannel
35+ key={c.id}
36+ channel={c}
37+ selected={selected}
38+ onSelect={onSelect}
39+ voice={voice}
40+ />
41+ ))}
42+ </div>
3343 </nav>
3444 </aside>
3545 );
@@ -65,3 +75,64 @@ function Group({
6575 </div>
6676 );
6777 }
78+
79+function VoiceChannel({
80+ channel,
81+ selected,
82+ onSelect,
83+ voice,
84+}: {
85+ channel: Channel;
86+ selected: Channel | null;
87+ onSelect: (c: Channel) => void;
88+ voice: Voice;
89+}) {
90+ const active = voice.channel?.id === channel.id;
91+ return (
92+ <div className="pb-1">
93+ <Button
94+ variant={selected?.id === channel.id ? "secondary" : "ghost"}
95+ onClick={() => onSelect(channel)}
96+ className="w-full justify-start gap-2 font-normal"
97+ >
98+ <Volume2 size={14} />
99+ {channel.name}
100+ </Button>
101+ <div className="flex items-center gap-1 px-2 pt-0.5">
102+ {active ? (
103+ <>
104+ <span className="min-w-0 flex-1 truncate text-xs text-sepia/50">
105+ {voice.status === "connecting"
106+ ? "connecting…"
107+ : voice.error
108+ ? voice.error
109+ : voice.muted
110+ ? "in voice · muted"
111+ : "in voice"}
112+ </span>
113+ <Button
114+ size="icon-xs"
115+ variant="ghost"
116+ onClick={() => voice.toggleMute()}
117+ title={voice.muted ? "unmute" : "mute"}
118+ >
119+ {voice.muted ? <MicOff /> : <Mic />}
120+ </Button>
121+ <Button size="icon-xs" variant="ghost" onClick={() => voice.leave()} title="leave">
122+ <PhoneOff />
123+ </Button>
124+ </>
125+ ) : (
126+ <Button
127+ size="xs"
128+ variant="ghost"
129+ className="text-xs text-sepia/50"
130+ onClick={() => voice.join(channel)}
131+ >
132+ join
133+ </Button>
134+ )}
135+ </div>
136+ </div>
137+ );
138+}
web/src/components/VoiceRoom.tsx+40−80
@@ -1,104 +1,64 @@
1-import { useEffect, useRef, useState } from "react";
2-import { Mic, MicOff } from "lucide-react";
3-import { Room, RoomEvent, Track } from "livekit-client";
1+import { Mic, MicOff, PhoneOff, Volume2 } from "lucide-react";
42 import { Button } from "@/components/ui/button";
5-import { api } from "../lib/api";
63 import type { Channel } from "../lib/types";
4+import type { Voice } from "../lib/voice";
75
8-interface VoiceToken {
9- url: string;
10- token: string;
11- room: string;
12-}
13-
14-export default function VoiceRoom({ channel, username }: { channel: Channel; username: string }) {
15- const [status, setStatus] = useState<"connecting" | "live" | "error">("connecting");
16- const [error, setError] = useState("");
17- const [peers, setPeers] = useState<string[]>([]);
18- const [muted, setMuted] = useState(false);
19- const roomRef = useRef<Room | null>(null);
20-
21- useEffect(() => {
22- let room: Room | null = null;
23- let cancelled = false;
24- const audio: HTMLElement[] = [];
25-
26- (async () => {
27- try {
28- const t = await api<VoiceToken>(`/channels/${channel.id}/voice`, { method: "POST" });
29- if (cancelled) return;
30- room = new Room();
31- roomRef.current = room;
32-
33- const sync = () => {
34- setPeers([...room!.remoteParticipants.values()].map((p) => p.name || p.identity));
35- };
6+export default function VoiceRoom({
7+ channel,
8+ username,
9+ voice,
10+}: {
11+ channel: Channel;
12+ username: string;
13+ voice: Voice;
14+}) {
15+ const active = voice.channel?.id === channel.id;
3616
37- room.on(RoomEvent.ParticipantConnected, sync);
38- room.on(RoomEvent.ParticipantDisconnected, sync);
39- room.on(RoomEvent.TrackSubscribed, (track) => {
40- if (track.kind === Track.Kind.Audio) audio.push(track.attach());
41- });
42- room.on(RoomEvent.Disconnected, () => {
43- if (!cancelled) {
44- setStatus("error");
45- setError("disconnected");
46- }
47- });
48-
49- await room.connect(t.url, t.token);
50- await room.localParticipant.setMicrophoneEnabled(true);
51- setStatus("live");
52- sync();
53- } catch (err) {
54- if (!cancelled) {
55- setStatus("error");
56- setError((err as Error).message);
57- }
58- }
59- })();
60-
61- return () => {
62- cancelled = true;
63- audio.forEach((el) => el.remove());
64- room?.disconnect();
65- roomRef.current = null;
66- };
67- }, [channel.id]);
68-
69- async function toggleMute() {
70- const room = roomRef.current;
71- if (!room) return;
72- await room.localParticipant.setMicrophoneEnabled(muted);
73- setMuted(!muted);
17+ if (!active) {
18+ return (
19+ <div className="flex flex-1 flex-col items-center justify-center gap-4 text-sm">
20+ <div className="text-sepia/50">not in {channel.name}</div>
21+ <Button variant="outline" onClick={() => voice.join(channel)}>
22+ <Volume2 />
23+ join {channel.name}
24+ </Button>
25+ </div>
26+ );
7427 }
7528
7629 return (
7730 <div className="flex flex-1 flex-col items-center justify-center gap-5 text-sm">
7831 <div className="text-sepia/50">
79- {status === "live"
80- ? `connected to ${channel.name}`
81- : status === "connecting"
82- ? "connecting…"
83- : "voice error"}
32+ {voice.status === "connecting"
33+ ? "connecting…"
34+ : voice.status === "error"
35+ ? "voice error"
36+ : `connected to ${channel.name}`}
8437 </div>
85- {error && <div className="text-gold">{error}</div>}
38+ {voice.error && <div className="text-gold">{voice.error}</div>}
8639 <div className="flex w-56 flex-col gap-1 rounded border border-sepia/15 p-3">
8740 <div className="flex items-center gap-2 text-sepia">
8841 <span className="h-2 w-2 rounded-full bg-gold" />
8942 {username} <span className="text-sepia/40">(you)</span>
43+ {voice.muted && <MicOff size={12} className="text-sepia/50" />}
9044 </div>
91- {peers.map((p) => (
45+ {voice.peers.map((p) => (
9246 <div key={p} className="flex items-center gap-2 text-sepia">
9347 <span className="h-2 w-2 rounded-full bg-gold" />
9448 {p}
9549 </div>
9650 ))}
9751 </div>
98- <Button variant="outline" onClick={toggleMute}>
99- {muted ? <MicOff /> : <Mic />}
100- {muted ? "unmute" : "mute"}
101- </Button>
52+ <div className="flex gap-2">
53+ <Button variant="outline" onClick={() => voice.toggleMute()}>
54+ {voice.muted ? <MicOff /> : <Mic />}
55+ {voice.muted ? "unmute" : "mute"}
56+ </Button>
57+ <Button variant="ghost" onClick={() => voice.leave()}>
58+ <PhoneOff />
59+ leave
60+ </Button>
61+ </div>
10262 </div>
10363 );
10464 }
web/src/lib/voice.ts+109−0
@@ -0,0 +1,109 @@
1+import { useCallback, useEffect, useRef, useState } from "react";
2+import { Room, RoomEvent, Track } from "livekit-client";
3+import { api } from "./api";
4+import type { Channel } from "./types";
5+
6+interface VoiceToken {
7+ url: string;
8+ token: string;
9+ room: string;
10+}
11+
12+export type VoiceStatus = "idle" | "connecting" | "live" | "error";
13+
14+export interface Voice {
15+ channel: Channel | null;
16+ status: VoiceStatus;
17+ error: string;
18+ peers: string[];
19+ muted: boolean;
20+ join: (c: Channel) => void;
21+ leave: () => void;
22+ toggleMute: () => void;
23+}
24+
25+// useVoice owns the single LiveKit connection for the session so it survives
26+// switching panes. Chat holds it and passes it to the sidebar controls.
27+export function useVoice(): Voice {
28+ const [channel, setChannel] = useState<Channel | null>(null);
29+ const [status, setStatus] = useState<VoiceStatus>("idle");
30+ const [error, setError] = useState("");
31+ const [peers, setPeers] = useState<string[]>([]);
32+ const [muted, setMuted] = useState(false);
33+ const roomRef = useRef<Room | null>(null);
34+ const audioRef = useRef<HTMLElement[]>([]);
35+ const genRef = useRef(0);
36+
37+ const leave = useCallback(() => {
38+ genRef.current++;
39+ const room = roomRef.current;
40+ roomRef.current = null;
41+ audioRef.current.forEach((el) => el.remove());
42+ audioRef.current = [];
43+ room?.disconnect();
44+ setChannel(null);
45+ setStatus("idle");
46+ setError("");
47+ setPeers([]);
48+ setMuted(false);
49+ }, []);
50+
51+ const join = useCallback(
52+ async (c: Channel) => {
53+ leave();
54+ const gen = genRef.current;
55+ setChannel(c);
56+ setStatus("connecting");
57+ try {
58+ const t = await api<VoiceToken>(`/channels/${c.id}/voice`, { method: "POST" });
59+ if (gen !== genRef.current) return;
60+ const room = new Room();
61+ roomRef.current = room;
62+ const sync = () =>
63+ setPeers([...room.remoteParticipants.values()].map((p) => p.name || p.identity));
64+ room.on(RoomEvent.ParticipantConnected, sync);
65+ room.on(RoomEvent.ParticipantDisconnected, sync);
66+ room.on(RoomEvent.TrackSubscribed, (track) => {
67+ if (track.kind === Track.Kind.Audio) audioRef.current.push(track.attach());
68+ });
69+ room.on(RoomEvent.Disconnected, () => {
70+ if (roomRef.current === room) {
71+ roomRef.current = null;
72+ setStatus("error");
73+ setError("disconnected");
74+ }
75+ });
76+ await room.connect(t.url, t.token);
77+ if (gen !== genRef.current) {
78+ room.disconnect();
79+ return;
80+ }
81+ await room.localParticipant.setMicrophoneEnabled(true);
82+ setStatus("live");
83+ sync();
84+ } catch (err) {
85+ if (gen !== genRef.current) return;
86+ setStatus("error");
87+ setError((err as Error).message);
88+ }
89+ },
90+ [leave],
91+ );
92+
93+ const toggleMute = useCallback(async () => {
94+ const room = roomRef.current;
95+ if (!room) return;
96+ const next = !muted;
97+ await room.localParticipant.setMicrophoneEnabled(!next);
98+ setMuted(next);
99+ }, [muted]);
100+
101+ useEffect(
102+ () => () => {
103+ roomRef.current?.disconnect();
104+ },
105+ [],
106+ );
107+
108+ return { channel, status, error, peers, muted, join, leave, toggleMute };
109+}
web/src/views/Chat.tsx+10−2
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
22 import { LogOut, PanelRight, PanelRightClose } from "lucide-react";
33 import { Button } from "@/components/ui/button";
44 import { api } from "../lib/api";
5+import { useVoice } from "../lib/voice";
56 import type { Channel, Message, User, UserSummary, WSEvent } from "../lib/types";
67 import ChatPane from "../components/ChatPane";
78 import Sidebar from "../components/Sidebar";
@@ -16,6 +17,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
1617 const [messages, setMessages] = useState<Message[]>([]);
1718 const [showUsers, setShowUsers] = useState(true);
1819 const selectedId = useRef<number | null>(null);
20+ const voice = useVoice();
1921
2022 useEffect(() => {
2123 selectedId.current = selected?.id ?? null;
@@ -64,13 +66,19 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
6466
6567 return (
6668 <div className="flex h-full">
67- <Sidebar channels={channels} selected={selected} onSelect={setSelected} />
69+ <Sidebar channels={channels} selected={selected} onSelect={setSelected} voice={voice} />
6870 <main className="flex min-w-0 flex-1 flex-col">
6971 <header className="flex items-center justify-between border-b border-sepia/15 px-4 py-2">
7072 <span className="text-sm text-sepia/70">
7173 {selected ? `${selected.type === "text" ? "#" : "🔊"} ${selected.name}` : ""}
7274 </span>
7375 <div className="flex items-center gap-1">
76+ {voice.channel && (
77+ <span className="pr-2 text-xs text-sepia/50">
78+ 🔊 {voice.channel.name}
79+ {voice.muted ? " · muted" : ""}
80+ </span>
81+ )}
7482 <Button
7583 variant="ghost"
7684 size="icon-sm"
@@ -85,7 +93,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
8593 </div>
8694 </header>
8795 {selected?.type === "voice" ? (
88- <VoiceRoom channel={selected} username={user.username} />
96+ <VoiceRoom channel={selected} username={user.username} voice={voice} />
8997 ) : (
9098 <ChatPane channel={selected} messages={messages} />
9199 )}