xonecas.io
8058
Ir

irvc / files

irvc / web / src / components / Sidebar.tsx

11.7 KB
1import { useState, type ReactNode } from "react";
2import {
3  AtSign,
4  Check,
5  ChevronDown,
6  ChevronRight,
7  Hash,
8  LogOut,
9  MoreHorizontal,
10  Plus,
11  Settings as SettingsIcon,
12  Trash2,
13  UserPlus,
14  Volume2,
15} from "lucide-react";
16import { cn } from "cn";
17import { IconButton, Menu, MenuItem, Dot, VoiceMarks } from "@/ui";
18import { api } from "../lib/api";
19import { byName } from "../lib/channels";
20import type { Channel, UserSummary, VoiceOccupant } from "../lib/types";
21import type { Voice } from "../lib/voice";
22import VoiceBar from "./VoiceBar";
23import { userColor } from "../lib/scheme";
24
25interface Props {
26  channels: Channel[];
27  unread: Record<number, number>;
28  selected: Channel | null;
29  users: UserSummary[];
30  online: Set<string>;
31  username: string;
32  voice: Voice;
33  voiceRooms: Record<string, VoiceOccupant[]>;
34  deafened: boolean;
35  onDeafen: (value: boolean) => void;
36  openShare: string | null;
37  onOpenShare: (id: string) => void;
38  onSelect: (c: Channel) => void;
39  onSelectUser: (u: UserSummary) => void;
40  onCloseDM: (c: Channel) => void;
41  onCreateChannel: (type: "text" | "voice", name: string) => Promise<void>;
42  onDeleteChannel: (c: Channel) => void;
43  onOpenSettings: () => void;
44  onLogout: () => void;
45}
46
47export default function Sidebar({
48  channels,
49  unread,
50  selected,
51  users,
52  online,
53  username,
54  voice,
55  voiceRooms,
56  deafened,
57  onDeafen,
58  openShare,
59  onOpenShare,
60  onSelect,
61  onSelectUser,
62  onCloseDM,
63  onCreateChannel,
64  onDeleteChannel,
65  onOpenSettings,
66  onLogout,
67}: Props) {
68  const [creating, setCreating] = useState<"text" | "voice" | null>(null);
69  const [showUsers, setShowUsers] = useState(true);
70
71  const texts = channels.filter((c) => c.type === "text").sort(byName);
72  const voices = channels.filter((c) => c.type === "voice").sort(byName);
73  const dms = channels.filter((c) => c.type === "dm").sort(byName);
74
75  return (
76    <aside className="flex h-full w-64 shrink-0 flex-col border-r border-line bg-surface">
77      <div className="flex h-12 shrink-0 items-center px-4 text-sm font-semibold tracking-wide text-accent">
78        irvc
79      </div>
80
81      <nav className="flex-1 space-y-5 overflow-y-auto px-2 pb-2">
82        <Group label="Text" onAdd={() => setCreating("text")}>
83          {texts.map((c) => (
84            <ChannelRow
85              key={c.id}
86              icon={<Hash size={14} />}
87              name={c.name}
88              badge={unread[c.id]}
89              active={selected?.id === c.id}
90              onSelect={() => onSelect(c)}
91              actions={
92                c.permanent
93                  ? undefined
94                  : (close) => (
95                      <MenuItem onClick={() => (close(), onDeleteChannel(c))} danger>
96                        <Trash2 size={14} /> delete channel
97                      </MenuItem>
98                    )
99              }
100            />
101          ))}
102          {creating === "text" && (
103            <NewChannel
104              onCancel={() => setCreating(null)}
105              onSubmit={async (name) => {
106                await onCreateChannel("text", name);
107                setCreating(null);
108              }}
109            />
110          )}
111        </Group>
112
113        <Group label="Voice" onAdd={() => setCreating("voice")}>
114          {voices.map((c) => (
115            <VoiceRow
116              key={c.id}
117              channel={c}
118              voice={voice}
119              occupants={voiceRooms[String(c.id)] ?? []}
120              self={username}
121              deafened={deafened}
122              onDeafen={onDeafen}
123              openShare={openShare}
124              onOpenShare={onOpenShare}
125              onDelete={() => onDeleteChannel(c)}
126            />
127          ))}
128          {creating === "voice" && (
129            <NewChannel
130              onCancel={() => setCreating(null)}
131              onSubmit={async (name) => {
132                await onCreateChannel("voice", name);
133                setCreating(null);
134              }}
135            />
136          )}
137        </Group>
138
139        {dms.length > 0 && (
140          <Group label="Direct messages">
141            {dms.map((c) => (
142              <ChannelRow
143                key={c.id}
144                icon={<AtSign size={14} />}
145                name={c.name}
146                badge={unread[c.id]}
147                active={selected?.id === c.id}
148                onSelect={() => onSelect(c)}
149                actions={(close) => (
150                  <MenuItem onClick={() => (close(), onCloseDM(c))}>close</MenuItem>
151                )}
152              />
153            ))}
154          </Group>
155        )}
156
157        <Group label="People" toggle={{ open: showUsers, set: () => setShowUsers((v) => !v) }}>
158          {showUsers && <UserList users={users} online={online} onSelectUser={onSelectUser} />}
159        </Group>
160      </nav>
161
162      <div className="shrink-0 px-2 pb-2">
163        {/* Voice channel calls render in place in the Voice list; DM calls have no row. */}
164        {voice.channel?.type === "dm" && (
165          <VoiceBar
166            voice={voice}
167            self={username}
168            deafened={deafened}
169            onDeafen={onDeafen}
170            openShare={openShare}
171            onOpenShare={onOpenShare}
172            occupants={voiceRooms[String(voice.channel.id)] ?? []}
173            className="mb-2"
174          />
175        )}
176        <div className="flex items-center gap-2 rounded-md px-2 py-1.5">
177          <Dot on />
178          <span className="min-w-0 flex-1 truncate text-sm">{username}</span>
179          <InviteButton />
180          <IconButton label="settings" size="sm" onClick={onOpenSettings}>
181            <SettingsIcon />
182          </IconButton>
183          <IconButton label="log out" size="sm" onClick={onLogout}>
184            <LogOut />
185          </IconButton>
186        </div>
187      </div>
188    </aside>
189  );
190}
191
192function Group({
193  label,
194  onAdd,
195  toggle,
196  children,
197}: {
198  label: string;
199  onAdd?: () => void;
200  toggle?: { open: boolean; set: () => void };
201  children: ReactNode;
202}) {
203  return (
204    <div className="space-y-0.5">
205      <div className="flex h-8 items-center justify-between pl-2">
206        {toggle ? (
207          <button
208            type="button"
209            onClick={toggle.set}
210            className="section-label flex items-center gap-1 px-0 hover:text-muted"
211          >
212            {toggle.open ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
213            {label}
214          </button>
215        ) : (
216          <span className="section-label px-0">{label}</span>
217        )}
218        {onAdd && (
219          <IconButton label={`new ${label.toLowerCase()} channel`} size="sm" onClick={onAdd}>
220            <Plus />
221          </IconButton>
222        )}
223      </div>
224      {children}
225    </div>
226  );
227}
228
229function ChannelRow({
230  icon,
231  name,
232  badge,
233  hint,
234  active,
235  onSelect,
236  actions,
237}: {
238  icon: ReactNode;
239  name: string;
240  badge?: number;
241  hint?: string;
242  active: boolean;
243  onSelect: () => void;
244  actions?: (close: () => void) => ReactNode;
245}) {
246  return (
247    // The wrapper carries the active/hover chrome so it surrounds the actions button too.
248    <div
249      className={cn(
250        "flex items-center rounded-md border pr-1 transition-colors",
251        active ? "border-line bg-raised" : "border-transparent hover:bg-raised",
252      )}
253    >
254      <button
255        type="button"
256        onClick={onSelect}
257        className={cn(
258          "row flex-1 hover:bg-transparent",
259          active && "font-medium text-fg",
260          !active && !!badge && "row-unread",
261        )}
262      >
263        <span className="text-faint">{icon}</span>
264        <span className="flex-1 truncate">{name}</span>
265        {!!badge && <span className="badge">{badge > 99 ? "99+" : badge}</span>}
266        {hint && <span className="text-xs text-faint">{hint}</span>}
267      </button>
268      {actions && <Menu trigger={<MoreButton />}>{actions}</Menu>}
269    </div>
270  );
271}
272
273function VoiceRow({
274  channel,
275  voice,
276  occupants,
277  self,
278  deafened,
279  onDeafen,
280  openShare,
281  onOpenShare,
282  onDelete,
283}: {
284  channel: Channel;
285  voice: Voice;
286  occupants: VoiceOccupant[];
287  self: string;
288  deafened: boolean;
289  onDeafen: (value: boolean) => void;
290  openShare?: string | null;
291  onOpenShare?: (id: string) => void;
292  onDelete: () => void;
293}) {
294  const active = voice.channel?.id === channel.id;
295  // Once joined, the row becomes the call panel: same outline, roster and controls.
296  if (active)
297    return (
298      <VoiceBar
299        voice={voice}
300        self={self}
301        deafened={deafened}
302        onDeafen={onDeafen}
303        openShare={openShare}
304        onOpenShare={onOpenShare}
305        occupants={occupants}
306        className="my-1"
307      />
308    );
309  return (
310    <div>
311      <ChannelRow
312        icon={<Volume2 size={14} />}
313        name={channel.name}
314        hint="join"
315        active={false}
316        onSelect={() => voice.join(channel)}
317        actions={
318          !channel.permanent && occupants.length === 0
319            ? (close) => (
320                <MenuItem onClick={() => (close(), onDelete())} danger>
321                  <Trash2 size={14} /> delete channel
322                </MenuItem>
323              )
324            : undefined
325        }
326      />
327      {occupants.length > 0 && (
328        <ul className="space-y-0.5 pb-1 pl-7">
329          {occupants.map((o) => (
330            <li key={o.name} className="flex items-center gap-2 text-sm text-muted">
331              <Dot on={false} />
332              <span className="min-w-0 flex-1 truncate" style={{ color: userColor(o.name) }}>
333                {o.name}
334              </span>
335              <VoiceMarks muted={o.muted} deafened={o.deafened} className="pr-1" />
336            </li>
337          ))}
338        </ul>
339      )}
340    </div>
341  );
342}
343
344function UserList({
345  users,
346  online,
347  onSelectUser,
348}: {
349  users: UserSummary[];
350  online: Set<string>;
351  onSelectUser: (u: UserSummary) => void;
352}) {
353  const sorted = [...users].sort(
354    (a, b) =>
355      Number(online.has(b.username)) - Number(online.has(a.username)) ||
356      a.username.localeCompare(b.username),
357  );
358  return (
359    <ul className="space-y-0.5">
360      {sorted.map((u) => (
361        <li key={u.id}>
362          <button
363            type="button"
364            onClick={() => onSelectUser(u)}
365            className={cn("row w-full", !online.has(u.username) && "text-faint")}
366          >
367            <Dot on={online.has(u.username)} />
368            <span
369              className="flex-1 truncate"
370              style={online.has(u.username) ? { color: userColor(u.username) } : undefined}
371            >
372              {u.username}
373            </span>
374          </button>
375        </li>
376      ))}
377    </ul>
378  );
379}
380
381function NewChannel({
382  onSubmit,
383  onCancel,
384}: {
385  onSubmit: (name: string) => void;
386  onCancel: () => void;
387}) {
388  const [name, setName] = useState("");
389  return (
390    <form
391      className="px-1 py-1"
392      onSubmit={(e) => {
393        e.preventDefault();
394        if (name.trim()) onSubmit(name.trim());
395      }}
396    >
397      <input
398        autoFocus
399        value={name}
400        placeholder="channel name"
401        onChange={(e) => setName(e.target.value)}
402        onKeyDown={(e) => e.key === "Escape" && onCancel()}
403        onBlur={onCancel}
404        className="input input-md"
405      />
406    </form>
407  );
408}
409
410function MoreButton() {
411  return (
412    <IconButton label="more actions" size="sm" className="hover:bg-surface">
413      <MoreHorizontal />
414    </IconButton>
415  );
416}
417
418function InviteButton() {
419  const [copied, setCopied] = useState(false);
420  async function invite() {
421    try {
422      const { token } = await api<{ token: string }>("/invites", { method: "POST" });
423      await navigator.clipboard.writeText(`${window.location.origin}/join?token=${token}`);
424      setCopied(true);
425      setTimeout(() => setCopied(false), 2000);
426    } catch {
427      // clipboard or API refused; nothing useful to show here
428    }
429  }
430  return (
431    <IconButton label={copied ? "invite link copied" : "create invite link"} size="sm" onClick={invite}>
432      {copied ? <Check /> : <UserPlus />}
433    </IconButton>
434  );
435}