xonecas.io
8058
Ir

irvc / files

irvc / web / src / views / Chat.tsx

25.2 KB
1import { useCallback, useEffect, useRef, useState } from "react";
2import { AtSign, Hash, Menu, MoreHorizontal, PhoneOff, ScreenShare, Settings as SettingsIcon, Trash2, Video } from "lucide-react";
3import { cn } from "cn";
4import { Button, Centered, IconButton, Menu as MenuPrimitive, MenuItem } from "@/ui";
5import { api } from "../lib/api";
6import { firstChannel } from "../lib/channels";
7import { usePresence } from "../lib/presence";
8import { useSettings } from "../lib/settings";
9import { useTheme } from "../lib/theme";
10import { toast } from "../lib/toast";
11import { beep, useVoice, type VoiceState } from "../lib/voice";
12import type { Channel, Message, Reaction, User, UserSummary, VoiceOccupant } from "../lib/types";
13import CallView from "../components/CallView";
14import Composer from "../components/Composer";
15import MessageActions from "../components/MessageActions";
16import MessageList from "../components/MessageList";
17import { hasMedia } from "../lib/media";
18import ScreenShareView from "../components/ScreenShare";
19import Sidebar from "../components/Sidebar";
20import VoiceBar from "../components/VoiceBar";
21import SettingsView from "./Settings";
22
23const voiceMessage = (state: VoiceState) => JSON.stringify({ type: "voice", ...state });
24const hiddenDmsKey = "irvc.hiddenDms";
25
26function loadHiddenDms(): number[] {
27  try {
28    return JSON.parse(localStorage.getItem(hiddenDmsKey) ?? "[]");
29  } catch {
30    return [];
31  }
32}
33
34// Message ids whose images the user collapsed. Ids are global, so one flat set
35// works across channels; only the newest are kept so it can't grow forever.
36const collapsedKey = "irvc.collapsedImages";
37const collapsedMax = 2000;
38
39function loadCollapsed(): Set<number> {
40  try {
41    return new Set(JSON.parse(localStorage.getItem(collapsedKey) ?? "[]"));
42  } catch {
43    return new Set();
44  }
45}
46
47// The text channel or DM last opened, per user, so a reload lands back in it.
48// Voice is deliberately never restored: rejoining a call must be an explicit act.
49const lastChannelKey = (userId: number) => `irvc.lastChannel.${userId}`;
50
51function loadLastChannel(userId: number): number | null {
52  try {
53    const id = Number(localStorage.getItem(lastChannelKey(userId)));
54    return id > 0 ? id : null;
55  } catch {
56    return null;
57  }
58}
59
60// How long a "typing" event keeps someone listed. Clients resend every few
61// seconds while typing, so this only has to outlast that gap.
62const typingTtl = 5_000;
63const typingEvery = 3_000;
64
65// typingLabel is the line shown under the message list.
66function typingLabel(names: string[]) {
67  if (names.length === 0) return "";
68  if (names.length === 1) return `${names[0]} is typing…`;
69  if (names.length === 2) return `${names[0]} and ${names[1]} are typing…`;
70  if (names.length === 3) return `${names[0]}, ${names[1]} and ${names[2]} are typing…`;
71  return "several people are typing…";
72}
73
74// Per-message preview state the user chose by hand (true = collapsed). Anything
75// absent follows the "collapse previews by default" setting, so flipping that
76// setting never fights an explicit choice. Only the newest entries are kept.
77const previewKey = "irvc.previewCollapsed";
78const previewMax = 2000;
79
80function loadPreviewState(): Record<number, boolean> {
81  try {
82    return JSON.parse(localStorage.getItem(previewKey) ?? "{}");
83  } catch {
84    return {};
85  }
86}
87
88export default function Chat({ user, onLogout }: { user: User; onLogout: () => void }) {
89  const [channels, setChannels] = useState<Channel[]>([]);
90  const [hiddenDms, setHiddenDms] = useState<number[]>(loadHiddenDms);
91  const [selected, setSelected] = useState<Channel | null>(null);
92  const [users, setUsers] = useState<UserSummary[]>([]);
93  const [online, setOnline] = useState<Set<string>>(new Set());
94  const [messages, setMessages] = useState<Message[]>([]);
95  const [unread, setUnread] = useState<Record<number, number>>({});
96  const [collapsed, setCollapsed] = useState<Set<number>>(loadCollapsed);
97  const [previewState, setPreviewState] = useState<Record<number, boolean>>(loadPreviewState);
98  const [editing, setEditing] = useState<{ id: number; body: string } | null>(null);
99  const [active, setActive] = useState<Message | null>(null);
100  const [voiceRooms, setVoiceRooms] = useState<Record<string, VoiceOccupant[]>>({});
101  const [view, setView] = useState<"channel" | "settings">("channel");
102  const [openShare, setOpenShare] = useState<string | null>(null);
103  const [ringing, setRinging] = useState<number | null>(null);
104  const desktop = useRef(matchMedia("(min-width: 768px)").matches);
105  const [sidebarOpen, setSidebarOpen] = useState(desktop.current);
106  const selectedId = useRef<number | null>(null);
107  // The channel of the DM call we started, so we can tell the peer when it ends.
108  const rangRef = useRef<number | null>(null);
109  // The server drops our voice state when the socket dies, so keep the last
110  // thing we told it and replay that on every (re)connect.
111  const voiceState = useRef<VoiceState>({ channelId: 0, muted: false, deafened: false });
112  const { settings, update } = useSettings();
113  // channel id -> username -> when we last heard them type
114  const [typing, setTyping] = useState<Record<number, Record<string, number>>>({});
115  const lastTypingSent = useRef({ channel: 0, at: 0 });
116
117  const markRead = useCallback((id: number) => {
118    setUnread((u) => {
119      if (!u[id]) return u;
120      const next = { ...u };
121      delete next[id];
122      return next;
123    });
124    api(`/channels/${id}/read`, { method: "POST" }).catch(() => {});
125  }, []);
126
127  // Presence arrives as a snapshot on every connect, so a reconnect resyncs the
128  // roster and voice occupancy. Replay our own voice channel on connect, since
129  // the server drops occupancy when the socket dies.
130  const { connected, send } = usePresence(
131    (ev) => {
132      if (ev.type === "presence") {
133        setOnline(new Set(ev.users ?? []));
134        if (ev.roster) setUsers(ev.roster);
135        setVoiceRooms(ev.voice ?? {});
136      } else if (ev.type === "channel" && ev.channel) {
137        setChannels((cs) => (cs.some((c) => c.id === ev.channel!.id) ? cs : [...cs, ev.channel!]));
138      } else if (ev.type === "channel_delete" && ev.channelId) {
139        setChannels((cs) => cs.filter((c) => c.id !== ev.channelId));
140      } else if (ev.type === "ring" && ev.channelId) {
141        // Answering sends its own ring; ignore it when already in that call.
142        if (voice.channel?.id === ev.channelId) return;
143        setRinging(ev.channelId);
144        // Answering means opening the DM, so surface it for the callee.
145        const dm = channels.find((c) => c.id === ev.channelId);
146        if (dm) open(dm);
147        else
148          api<Channel[]>("/channels")
149            .then((cs) => {
150              setChannels(cs);
151              const c = cs.find((x) => x.id === ev.channelId);
152              if (c) open(c);
153            })
154            .catch(() => {});
155      } else if (ev.type === "typing") {
156        if (!settings.typingIndicator || !ev.channelId || !ev.username) return;
157        if (ev.username === user.username) return;
158        setTyping((t) => ({
159          ...t,
160          [ev.channelId!]: { ...t[ev.channelId!], [ev.username!]: Date.now() },
161        }));
162      } else if (ev.type === "ring_end" && ev.channelId) {
163        setRinging((r) => (r === ev.channelId ? null : r));
164      } else if (ev.message) {
165        if (ev.type === "message") {
166          // A sent message ends that person's typing.
167          setTyping((t) => {
168            const { [ev.message!.username]: _, ...rest } = t[ev.message!.channelId] ?? {};
169            return t[ev.message!.channelId] ? { ...t, [ev.message!.channelId]: rest } : t;
170          });
171          setChannels((cs) => {
172            if (!cs.some((c) => c.id === ev.message!.channelId)) {
173              api<Channel[]>("/channels")
174                .then(setChannels)
175                .catch(() => {});
176            }
177            return cs;
178          });
179          if (ev.message.channelId === selectedId.current) markRead(ev.message.channelId);
180          else if (ev.message.username !== user.username)
181            setUnread((u) => ({
182              ...u,
183              [ev.message!.channelId]: (u[ev.message!.channelId] ?? 0) + 1,
184            }));
185        }
186        if (ev.message.channelId === selectedId.current) {
187          if (ev.type === "message") setMessages((prev) => [...prev, ev.message!]);
188          else if (ev.type === "message_edit")
189            setMessages((prev) => prev.map((m) => (m.id === ev.message!.id ? ev.message! : m)));
190          else if (ev.type === "message_delete")
191            setMessages((prev) => prev.filter((m) => m.id !== ev.message!.id));
192        }
193      }
194    },
195    () => send(voiceMessage(voiceState.current)),
196  );
197
198  const voice = useVoice(settings, (state) => {
199    voiceState.current = state;
200    send(voiceMessage(state));
201  });
202  const theme = useTheme();
203
204  // Ring while a peer calls us. The slow beep repeats (when enabled) until we
205  // answer, they hang up, or the call times out as missed.
206  useEffect(() => {
207    if (ringing === null) return;
208    const timeout = setTimeout(() => setRinging(null), 30_000);
209    const sound = settings.ringSound ? (beep(880), setInterval(() => beep(880), 2000)) : 0;
210    return () => {
211      clearTimeout(timeout);
212      clearInterval(sound);
213    };
214  }, [ringing, settings.ringSound]);
215
216  // Joining the call answers the ring.
217  useEffect(() => {
218    if (ringing !== null && voice.channel?.id === ringing) setRinging(null);
219  }, [ringing, voice.channel]);
220
221  // Tell the peer when a DM call we started is over.
222  useEffect(() => {
223    const started = rangRef.current;
224    if (started === null || voice.channel?.id === started) return;
225    rangRef.current = null;
226    api(`/channels/${started}/ring`, { method: "DELETE" }).catch(() => {});
227  }, [voice.channel]);
228
229  // The watched share lives in the LiveKit room, so it vanishes when the sharer
230  // stops; the pane then falls back to the selected channel.
231  const share = voice.shares.find((s) => s.id === openShare) ?? null;
232  const totalUnread = Object.values(unread).reduce((a, b) => a + b, 0);
233
234  useEffect(() => {
235    document.title = totalUnread > 0 ? `(${totalUnread}) irvc` : "irvc";
236  }, [totalUnread]);
237
238  useEffect(() => {
239    localStorage.setItem(hiddenDmsKey, JSON.stringify(hiddenDms));
240  }, [hiddenDms]);
241
242  useEffect(() => {
243    try {
244      const ids = [...collapsed].sort((a, b) => a - b).slice(-collapsedMax);
245      localStorage.setItem(collapsedKey, JSON.stringify(ids));
246    } catch {
247      // storage unavailable; collapse state just won't persist
248    }
249  }, [collapsed]);
250
251  // Expire stale typing entries; the interval only runs while there are any.
252  const anyTyping = Object.values(typing).some((c) => Object.keys(c).length > 0);
253  useEffect(() => {
254    if (!anyTyping) return;
255    const id = setInterval(() => {
256      const cutoff = Date.now() - typingTtl;
257      setTyping((t) => {
258        let changed = false;
259        const next: typeof t = {};
260        for (const [ch, users] of Object.entries(t)) {
261          const live = Object.fromEntries(Object.entries(users).filter(([, at]) => at > cutoff));
262          if (Object.keys(live).length !== Object.keys(users).length) changed = true;
263          if (Object.keys(live).length) next[Number(ch)] = live;
264          else if (Object.keys(users).length) changed = true;
265        }
266        return changed ? next : t;
267      });
268    }, 1000);
269    return () => clearInterval(id);
270  }, [anyTyping]);
271
272  // Turning the setting off hides everything already showing.
273  useEffect(() => {
274    if (!settings.typingIndicator) setTyping({});
275  }, [settings.typingIndicator]);
276
277  function sendTyping() {
278    if (!settings.typingIndicator || !selected) return;
279    const now = Date.now();
280    const last = lastTypingSent.current;
281    if (last.channel === selected.id && now - last.at < typingEvery) return;
282    lastTypingSent.current = { channel: selected.id, at: now };
283    send(JSON.stringify({ type: "typing", channelId: selected.id }));
284  }
285
286  // Escape dismisses the message actions pane, same as its close button.
287  useEffect(() => {
288    if (!active) return;
289    const onKey = (e: KeyboardEvent) => {
290      if (e.key === "Escape") setActive(null);
291    };
292    window.addEventListener("keydown", onKey);
293    return () => window.removeEventListener("keydown", onKey);
294  }, [active]);
295
296  useEffect(() => {
297    selectedId.current = selected?.id ?? null;
298    setEditing(null);
299    setActive(null);
300  }, [selected]);
301
302  useEffect(() => {
303    if (selected?.type !== "text" && selected?.type !== "dm") return;
304    try {
305      localStorage.setItem(lastChannelKey(user.id), String(selected.id));
306    } catch {
307      // storage unavailable; the last channel just won't be remembered
308    }
309  }, [selected, user.id]);
310
311  useEffect(() => {
312    if (selected && !channels.some((c) => c.id === selected.id)) {
313      setSelected(firstChannel(channels));
314    }
315  }, [channels, selected]);
316
317  useEffect(() => {
318    api<Channel[]>("/channels")
319      .then((cs) => {
320        setChannels(cs);
321        setUnread(
322          Object.fromEntries(cs.filter((c) => c.unread).map((c) => [c.id, c.unread as number])),
323        );
324        const last = loadLastChannel(user.id);
325        const restored = cs.find(
326          (c) =>
327            c.id === last &&
328            (c.type === "text" || (c.type === "dm" && !loadHiddenDms().includes(c.id))),
329        );
330        setSelected((s) => s ?? restored ?? firstChannel(cs));
331      })
332      .catch(() => {});
333    api<UserSummary[]>("/users")
334      .then(setUsers)
335      .catch(() => {});
336  }, []);
337
338  useEffect(() => {
339    if (selected?.type !== "text" && selected?.type !== "dm") {
340      setMessages([]);
341      return;
342    }
343    api<Message[]>(`/channels/${selected.id}/messages`)
344      .then(setMessages)
345      .catch(() => {});
346  }, [selected]);
347
348  // Opening a channel clears its badge and tells the server, so the count stays
349  // right on the next cold start and on the user's other devices.
350  useEffect(() => {
351    if (selected && (selected.type === "text" || selected.type === "dm")) markRead(selected.id);
352  }, [selected, markRead]);
353
354  // Opening a share also leaves the settings pane, so the stream is visible
355  // straight away no matter where the click came from.
356  function showShare(id: string) {
357    setOpenShare(id);
358    setView("channel");
359  }
360
361  function open(c: Channel) {
362    setSelected(c);
363    if (c.type === "dm") setHiddenDms((ids) => ids.filter((id) => id !== c.id));
364    setView("channel");
365    setOpenShare(null);
366    if (!desktop.current) setSidebarOpen(false);
367  }
368
369  // startCall opens a DM video call and rings the peer. Joining leaves any
370  // voice channel first, since only one call can use the mic and camera.
371  function startCall(c: Channel) {
372    rangRef.current = c.id;
373    voice.join(c);
374    api(`/channels/${c.id}/ring`, { method: "POST" }).catch(() => {});
375  }
376
377  async function selectUser(u: UserSummary) {
378    try {
379      const dm = await api<Channel>(`/dms/${u.id}`, { method: "POST" });
380      setChannels((cs) => (cs.some((c) => c.id === dm.id) ? cs : [...cs, dm]));
381      open(dm);
382    } catch {
383      // a DM that will not open is not worth an error state
384    }
385  }
386
387  async function createChannel(type: "text" | "voice", name: string) {
388    try {
389      const channel = await api<Channel>("/channels", {
390        method: "POST",
391        body: JSON.stringify({ type, name }),
392      });
393      setChannels((cs) => (cs.some((c) => c.id === channel.id) ? cs : [...cs, channel]));
394    } catch {
395      // A rejected name keeps the sidebar form open; nothing else to do.
396    }
397  }
398
399  async function deleteChannel(c: Channel) {
400    if (c.type === "text" && !confirm(`Delete #${c.name} and all its messages?`)) return;
401    await api(`/channels/${c.id}`, { method: "DELETE" }).catch(() => {});
402  }
403
404  function react(m: Message, reaction: Reaction) {
405    api(`/messages/${m.id}/reactions`, {
406      method: "POST",
407      body: JSON.stringify({ reaction }),
408    }).catch(() => {});
409  }
410
411  function startEdit(m: Message) {
412    setEditing({ id: m.id, body: m.body });
413    setActive(null);
414  }
415
416  function startEditLast() {
417    const last = [...messages].reverse().find((m) => m.username === user.username);
418    if (last) setEditing({ id: last.id, body: last.body });
419  }
420
421  async function saveEdit() {
422    if (!editing) return;
423    const { id } = editing;
424    const body = editing.body.trim();
425    setEditing(null);
426    if (!body || body === messages.find((m) => m.id === id)?.body) return;
427    await api(`/messages/${id}`, { method: "PATCH", body: JSON.stringify({ body }) }).catch(
428      (e: Error) => toast(e.message),
429    );
430  }
431
432  // Removing a preview removes it for everyone; the server pushes the updated
433  // message to all clients, so only failures need handling here.
434  function removePreview(m: Message) {
435    setActive(null);
436    api<Message>(`/messages/${m.id}/preview`, { method: "DELETE" }).catch((e) =>
437      toast(e instanceof Error ? e.message : "could not remove preview"),
438    );
439  }
440
441  // /collapse: fold every image and link preview in the open channel.
442  function collapseAll() {
443    setCollapsed(
444      (prev) => new Set([...prev, ...messages.filter((m) => hasMedia(m.body)).map((m) => m.id)]),
445    );
446    const cards = messages.filter((m) => m.preview?.kind === "card").map((m) => [m.id, true]);
447    setPreviewState((prev) => ({ ...prev, ...Object.fromEntries(cards) }));
448  }
449
450  function deleteMessage(m: Message) {
451    setActive(null);
452    api(`/messages/${m.id}`, { method: "DELETE" }).catch(() => {});
453  }
454
455  useEffect(() => {
456    try {
457      const keep = Object.keys(previewState)
458        .map(Number)
459        .sort((a, b) => a - b)
460        .slice(-previewMax);
461      localStorage.setItem(previewKey, JSON.stringify(Object.fromEntries(keep.map((k) => [k, previewState[k]]))));
462    } catch {
463      // storage unavailable; choices just won't persist
464    }
465  }, [previewState]);
466
467  const previewCollapsed = (id: number) => previewState[id] ?? settings.collapsePreviews;
468
469  function togglePreview(id: number) {
470    setPreviewState((prev) => ({ ...prev, [id]: !(prev[id] ?? settings.collapsePreviews) }));
471  }
472
473  function toggleImages(id: number) {
474    setCollapsed((prev) => {
475      const next = new Set(prev);
476      if (next.has(id)) next.delete(id);
477      else next.add(id);
478      return next;
479    });
480  }
481
482  async function logout() {
483    await api("/logout", { method: "POST" }).catch(() => {});
484    onLogout();
485  }
486
487  const chat = selected?.type === "text" || selected?.type === "dm";
488  const showingShare = view === "channel" && share !== null;
489  const inCall = selected?.type === "dm" && voice.channel?.id === selected.id;
490
491  return (
492    <div className="flex h-dvh overflow-hidden">
493      {sidebarOpen && (
494        <div
495          className="fixed inset-0 z-30 bg-scrim md:hidden"
496          onClick={() => setSidebarOpen(false)}
497        />
498      )}
499      <div
500        inert={!sidebarOpen}
501        className={cn(
502          "z-40 w-64 shrink-0 transition-transform duration-200",
503          "max-md:fixed max-md:inset-y-0 max-md:left-0 max-md:w-[80vw] max-md:max-w-72",
504          !sidebarOpen && "max-md:-translate-x-full",
505        )}
506      >
507        <Sidebar
508          channels={channels.filter(
509            (c) => c.type !== "dm" || !hiddenDms.includes(c.id) || unread[c.id],
510          )}
511          unread={unread}
512          selected={selected}
513          users={users}
514          online={online}
515          username={user.username}
516          voice={voice}
517          voiceRooms={voiceRooms}
518          deafened={settings.deafened}
519          onDeafen={(v) => update({ deafened: v })}
520          openShare={openShare}
521          onOpenShare={showShare}
522          onSelect={open}
523          onSelectUser={selectUser}
524          onCloseDM={(dm) => {
525            setHiddenDms((ids) => (ids.includes(dm.id) ? ids : [...ids, dm.id]));
526            if (selected?.id === dm.id) setSelected(firstChannel(channels));
527          }}
528          onCreateChannel={createChannel}
529          onDeleteChannel={deleteChannel}
530          onOpenSettings={() => {
531            setView("settings");
532            if (!desktop.current) setSidebarOpen(false);
533          }}
534          onLogout={logout}
535        />
536      </div>
537
538      <main className="flex min-w-0 flex-1 flex-col">
539        <header className="flex h-12 shrink-0 items-center gap-1.5 border-b border-line px-2 md:px-3">
540          <IconButton
541            label={sidebarOpen ? "close navigation" : "open navigation"}
542            className="md:hidden"
543            onClick={() => setSidebarOpen((v) => !v)}
544          >
545            <Menu />
546          </IconButton>
547          {view === "settings" ? (
548            <>
549              <SettingsIcon size={16} className="text-faint" />
550              <span className="truncate text-sm font-medium">settings</span>
551            </>
552           ) : showingShare && share ? (
553            <>
554              <ScreenShare size={16} className="text-faint" />
555              <span className="truncate text-sm font-medium">
556                {share.self ? "your screen" : `${share.name}'s screen`}
557              </span>
558              <Button
559                variant="ghost"
560                size="sm"
561                className="ml-auto"
562                onClick={() => setOpenShare(null)}
563              >
564                close
565              </Button>
566            </>
567          ) : (
568            <>
569              {selected &&
570                (selected.type === "dm" ? (
571                  <AtSign size={16} className="text-faint" />
572                ) : (
573                  <Hash size={16} className="text-faint" />
574                ))}
575              <span className="truncate text-sm font-medium">{selected?.name}</span>
576              {selected?.type === "dm" && (
577                <IconButton
578                  label={inCall ? "leave call" : ringing === selected.id ? "answer call" : "start video call"}
579                  variant={inCall ? "danger" : ringing === selected.id ? "primary" : "ghost"}
580                  size="sm"
581                  onClick={() => (inCall ? voice.leave() : startCall(selected))}
582                >
583                  {inCall ? <PhoneOff /> : <Video />}
584                </IconButton>
585              )}
586              {selected?.type === "text" && !selected.permanent && (
587                <MenuPrimitive
588                  className="ml-auto"
589                  trigger={
590                    <IconButton label="channel actions" size="sm">
591                      <MoreHorizontal />
592                    </IconButton>
593                  }
594                >
595                  {(close) => (
596                    <MenuItem danger onClick={() => (close(), deleteChannel(selected))}>
597                      <Trash2 size={14} /> delete channel
598                    </MenuItem>
599                  )}
600                </MenuPrimitive>
601              )}
602            </>
603          )}
604          {!connected && <span className="ml-auto pr-1 text-xs text-faint">reconnecting…</span>}
605        </header>
606
607        {view === "settings" ? (
608          <div className="min-h-0 flex-1 overflow-y-auto">
609            <SettingsView settings={settings} update={update} voice={voice} theme={theme} />
610          </div>
611         ) : showingShare && share ? (
612          <ScreenShareView track={share.track} />
613        ) : chat && selected ? (
614          <>
615            {inCall && <CallView voice={voice} className="flex-[3]" />}
616            <div className={cn("flex min-h-0 flex-1 flex-col", inCall && "flex-[1] border-t border-line")}>
617              <MessageList
618                key={selected.id}
619                messages={messages}
620                username={user.username}
621                collapsed={collapsed}
622                previewCollapsed={previewCollapsed}
623                hidePreviews={settings.hidePreviews}
624                onTogglePreview={togglePreview}
625                onRemovePreview={removePreview}
626                editing={editing}
627                activeId={active?.id ?? null}
628                onSelect={(m) => setActive((a) => (a?.id === m.id ? null : m))}
629                onToggleImages={toggleImages}
630                onEditBody={(body) => setEditing((e) => (e ? { ...e, body } : e))}
631                onCancelEdit={() => setEditing(null)}
632                onSaveEdit={saveEdit}
633              />
634              <div className="h-5 shrink-0 truncate px-3 text-xs text-faint md:px-4" aria-live="polite">
635                {settings.typingIndicator &&
636                  typingLabel(Object.keys(typing[selected.id] ?? {}).sort())}
637              </div>
638              {active && !editing && (
639                <MessageActions
640                  message={active}
641                  own={active.username === user.username}
642                  onReact={(r) => react(active, r)}
643                  onEdit={() => startEdit(active)}
644                  onDelete={() => deleteMessage(active)}
645                  onRemovePreview={() => removePreview(active)}
646                  onClose={() => setActive(null)}
647                />
648              )}
649              <Composer
650                channel={selected}
651                users={users}
652                onEditLast={startEditLast}
653                onTyping={sendTyping}
654                onCollapse={collapseAll}
655              />
656            </div>
657          </>
658        ) : (
659          <Centered>select a channel</Centered>
660        )}
661
662        {voice.channel && (
663          <div className="shrink-0 px-2 pb-2 md:hidden">
664            <VoiceBar
665              voice={voice}
666              self={user.username}
667              deafened={settings.deafened}
668              onDeafen={(v) => update({ deafened: v })}
669              openShare={openShare}
670              onOpenShare={showShare}
671              occupants={voiceRooms[String(voice.channel.id)] ?? []}
672            />
673          </div>
674        )}
675      </main>
676    </div>
677  );
678}