Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

615 linesCodeBlameRaw
1import { useSidebarLocation } from "../../lib/use-sidebar-location";
2import { ArrowLeft, BellOff, Check, ChevronDown, Compass, Globe, Hash, Lock, Pin, PinOff, Search, X } from "lucide-react";
3import { ContextMenu } from "radix-ui";
4import { type ReactNode, useEffect, useState } from "react";
5import { NavLink, useFetcher, useNavigate } from "react-router";
6
7import type { Channel, ChannelInvitation, ChatSidebarEntry, GuestChannel } from "@g1t/contracts";
8
9import { conversationCache } from "./conversation-cache";
10import { CreateChannelButton, NewMessageButton, useChatData, useChatSend, useChatSidebar } from "./actions";
11import { DndMenu } from "./dnd-menu";
12import { MemberAvatar } from "./marks";
13import { PersonStatusEmoji } from "../presence";
14import { Avatar } from "../ui/avatar";
15import { Badge } from "../ui/badge";
16import { Button } from "../ui/button";
17import { Hint } from "../ui/hint";
18import { Skeleton } from "../ui/skeleton";
19import { type ChatFilter, agentsOnlyDm, channelPath, filterEntries, g1tEntry, sections } from "../../lib/chat";
20import { feedConnected } from "../../lib/notify-client";
21import { FALLBACK_REFRESH_MS } from "../../lib/notify-store";
22import { setMutedConversations } from "../../lib/sound-events";
23
24/** How often the sidebar asks again while the tab is shown and the feed socket is down. */
25const REFRESH_MS = FALLBACK_REFRESH_MS;
26
27const ROW =
28 "group/row flex h-9 items-center gap-2 rounded-md pr-1.5 pl-2 text-[0.8125rem] transition-colors max-md:h-11 max-md:text-[0.9375rem] max-md:active:bg-raised";
29
30/** Unread on a row: lavender for a mention, quiet for the rest. */
31function Count({ entry }: { entry: ChatSidebarEntry | undefined }) {
32 if (!entry || entry.muted) return null;
33 const count = entry.mentions > 0 ? entry.mentions : entry.unread;
34 if (count <= 0) return null;
35 return (
36 <span
37 className={`min-w-5 shrink-0 rounded-full group-hover/row:invisible px-1.5 text-center text-[0.6875rem] leading-4.5 font-semibold tabular-nums ${
38 entry.mentions > 0 ? "bg-accent text-bg" : "bg-line-strong text-fg"
39 }`}
40 >
41 {count}
42 </span>
43 );
44}
45
46/**
47 * Chat mode's sidebar: what you pinned, the workspace's own channels (and a
48 * way to browse the rest), its public channels, then direct messages, the
49 * latest first. Sections fold, and
50 * stay folded on this device. All, Unread and Mentions filter every section. It refreshes
51 * itself while the tab is shown, so unread counts move without a reload.
52 */
53export function ChatSidebar({ slug: home, heading = true }: { slug: string; heading?: boolean }) {
54 const data = useChatData();
55 // The workspace whose chat is open: another one's, for a guest there.
56 const slug = data?.slug ?? home;
57 const { sidebar, refresh } = useChatSidebar();
58 const send = useChatSend(slug);
59 const [filter, setFilter] = useState<ChatFilter>("all");
60 const [query, setQuery] = useState("");
61 const navigate = useNavigate();
62 const { pathname } = useSidebarLocation();
63
64 useEffect(() => {
65 if (!data) return;
66 // Notify: counts arrive live over the feed socket; this asks again only while it is down.
67 const tick = () => {
68 if (document.visibilityState === "visible" && !feedConnected()) refresh();
69 };
70 const timer = setInterval(tick, REFRESH_MS);
71 document.addEventListener("visibilitychange", tick);
72 return () => {
73 clearInterval(timer);
74 document.removeEventListener("visibilitychange", tick);
75 };
76 }, [data, refresh]);
77
78 // Pins show at once and go back if the service refuses.
79 const [pins, setPins] = useState<Map<string, boolean>>(new Map());
80 useEffect(() => setPins(new Map()), [sidebar]);
81 // Sounds leave muted conversations alone (lib/sound-events.ts).
82 useEffect(() => {
83 if (sidebar) setMutedConversations(sidebar.entries.filter((e) => e.muted).map((e) => e.channel.id));
84 }, [sidebar]);
85 const entries = (sidebar?.entries ?? []).map((e) => (pins.has(e.channel.id) ? { ...e, starred: pins.get(e.channel.id)! } : e));
86 // The open conversation stays listed even when it is an old one with an agent alone, which Jump to otherwise finds.
87 const currentId = entries.find((e) => pathname === channelPath(slug, e.channel) || pathname.startsWith(`${channelPath(slug, e.channel)}/`))?.channel.id ?? null;
88 const shown = filterEntries(entries, filter, query, currentId);
89 const { pinned, channels, publicChannels, dms } = sections(shown);
90 const loading = !data;
91
92 // Folded sections, remembered per workspace on this device. A folded
93 // section still shows what is unread and the conversation open now.
94 const [folded, setFolded] = useState<ReadonlySet<string>>(new Set());
95 useEffect(() => setFolded(readFolded(slug)), [slug]);
96 const fold = (id: string) =>
97 setFolded((now) => {
98 const next = new Set(now);
99 if (!next.delete(id)) next.add(id);
100 writeFolded(slug, next);
101 return next;
102 });
103 const keepShown = (entry: ChatSidebarEntry) => {
104 const to = channelPath(slug, entry.channel);
105 return pathname === to || pathname.startsWith(`${to}/`) || (!entry.muted && (entry.unread > 0 || entry.mentions > 0));
106 };
107
108 const togglePin = async (entry: ChatSidebarEntry) => {
109 const next = !entry.starred;
110 setPins((now) => new Map(now).set(entry.channel.id, next));
111 const done = await send({ intent: "preferences", channel_id: entry.channel.id, starred: next });
112 if (!done.ok)
113 setPins((now) => {
114 const back = new Map(now);
115 back.delete(entry.channel.id);
116 return back;
117 });
118 };
119
120 const conversation = (entry: ChatSidebarEntry) => (
121 <ConversationRow key={entry.channel.id} entry={entry} slug={slug} pathname={pathname} onPin={() => void togglePin(entry)} />
122 );
123
124 return (
125 // The colour behind it, for the dots cut out of people's avatars.
126 <div className="flex h-full flex-col [--chat-sidebar-bg:var(--color-sidebar)]">
127 {heading && (
128 <div className="flex h-9 shrink-0 items-center justify-between pr-1 pl-3">
129 <h2 className="text-[0.6875rem] font-medium tracking-wide text-faint uppercase">Chat</h2>
130 <div className="flex items-center gap-0.5">
131 <DndMenu />
132 <NewMessageButton slug={slug} />
133 </div>
134 </div>
135 )}
136 {sidebar?.guest && sidebar.workspace && <GuestBanner workspace={sidebar.workspace} home={home} />}
137 <div className="space-y-2.5 px-2.5 pt-3">
138 <div className="flex items-center gap-2">
139 <label className="flex h-8 min-w-0 grow items-center gap-2 rounded-md bg-surface px-2.5 text-[0.8125rem] ring-1 ring-line transition-shadow focus-within:ring-accent-dim/70">
140 <Search size={14} className="shrink-0 text-faint" />
141 <input
142 value={query}
143 onChange={(event) => setQuery(event.target.value)}
144 onKeyDown={(event) => {
145 if (event.key === "Enter") {
146 const first = [...pinned, ...channels, ...publicChannels, ...dms][0];
147 if (first) {
148 navigate(channelPath(slug, first.channel));
149 setQuery("");
150 }
151 } else if (event.key === "Escape") setQuery("");
152 }}
153 placeholder="Jump to channel or person"
154 aria-label="Jump to channel or person"
155 autoComplete="off"
156 data-1p-ignore
157 className="min-w-0 grow bg-transparent text-fg outline-none placeholder:text-faint"
158 />
159 </label>
160 {/* A phone has no heading row: Do not disturb sits by the search box instead. */}
161 {!heading && <DndMenu className="size-8 max-md:size-11" />}
162 </div>
163 <div role="radiogroup" aria-label="Show" className="grid grid-cols-3 rounded-md bg-surface p-0.5 ring-1 ring-line">
164 {(["all", "unread", "mentions"] as const).map((key) => (
165 <button
166 key={key}
167 type="button"
168 role="radio"
169 aria-checked={filter === key}
170 onClick={() => setFilter(key)}
171 className={`h-6 rounded-[5px] text-xs font-medium capitalize transition-colors ${
172 filter === key ? "bg-raised text-fg shadow-sm ring-1 ring-line-strong" : "text-muted hover:text-fg"
173 }`}
174 >
175 {key}
176 </button>
177 ))}
178 </div>
179 </div>
180 {/* A phone's list (no heading): room at the end so the compose button never covers the last row. */}
181 <nav
182 aria-label="Conversations"
183 className={`min-h-0 grow overflow-y-auto px-2.5 pt-3 scrollbar-thin ${heading ? "pb-4" : "pb-[calc(5.5rem+env(safe-area-inset-bottom))]"}`}
184 >
185 {loading ? (
186 <SidebarSkeleton />
187 ) : !sidebar ? (
188 <p className="px-2 py-3 text-xs leading-relaxed text-faint">Chat didn&apos;t answer. Your conversations will show here once it does.</p>
189 ) : (
190 <>
191 {/* Open to anyone on g1t, apart from the workspace's own, and first: only when there are some, or for a guest, to find them. */}
192 {(publicChannels.length > 0 || (sidebar.guest && filter === "all" && !query)) && (
193 <Section id="public" title="Public channels" folded={folded} onFold={fold} keep={publicChannels.filter(keepShown).map(conversation)}>
194 {publicChannels.map(conversation)}
195 {sidebar.guest && filter === "all" && !query && (
196 <>
197 {publicChannels.length === 0 && <Empty>You&apos;re in none of its public channels yet.</Empty>}
198 <BrowseRow slug={slug} count={sidebar.browsable} guest />
199 </>
200 )}
201 </Section>
202 )}
203 {pinned.length > 0 && (
204 <Section id="pinned" title="Pinned" folded={folded} onFold={fold} keep={pinned.filter(keepShown).map(conversation)}>
205 {pinned.map(conversation)}
206 </Section>
207 )}
208 {/* A guest has only the channels they were asked into here; with none, the public ones are all there is. */}
209 {(!sidebar.guest || channels.length > 0) && (
210 <Section
211 id="channels"
212 title="Channels"
213 folded={folded}
214 onFold={fold}
215 action={sidebar.guest ? undefined : <CreateChannelButton slug={slug} />}
216 keep={channels.filter(keepShown).map(conversation)}
217 >
218 {channels.map(conversation)}
219 {channels.length === 0 && filter === "all" && !query && <Empty>No channels yet.</Empty>}
220 {!sidebar.guest && filter === "all" && !query && <BrowseRow slug={slug} count={sidebar.browsable} />}
221 </Section>
222 )}
223 {(sidebar.invitations?.length ?? 0) > 0 && filter === "all" && !query && (
224 <Section id="invitations" title="Invitations" folded={folded} onFold={fold}>
225 {sidebar.invitations!.map((invitation) => (
226 <InvitationRow key={invitation.id} invitation={invitation} onAnswered={refresh} />
227 ))}
228 </Section>
229 )}
230 {(sidebar.elsewhere?.length ?? 0) > 0 && (
231 <Section id="elsewhere" title="Other workspaces" folded={folded} onFold={fold}>
232 {sidebar.elsewhere!
233 .filter((entry) => (filter === "all" || (filter === "unread" ? entry.unread > 0 : entry.mentions > 0)) && (!query || entry.channel.name?.includes(query.toLowerCase())))
234 .map((entry) => (
235 <ElsewhereRow key={entry.channel.id} entry={entry} pathname={pathname} />
236 ))}
237 </Section>
238 )}
239 {/* A guest has no direct messages here: those are for the workspace's members. */}
240 {!sidebar.guest && (<Section
241 id="people"
242 title="Direct messages"
243 folded={folded}
244 onFold={fold}
245 action={<NewMessageButton slug={slug} />}
246 keep={dms.filter(keepShown).map(conversation)}
247 >
248 {/* @g1t, before the first word to it: its direct message opens on first use. */}
249 {filter === "all" && !query && !entries.some(g1tEntry) && (
250 <ExtraRow to={`/${slug}/-/chat/dm/g1t`} icon={<MemberAvatar member={{ kind: "system", id: "g1t", name: "g1t", avatar: null }} size={18} ring="var(--chat-sidebar-bg)" />}>
251 g1t
252 </ExtraRow>
253 )}
254 {dms.map(conversation)}
255 {dms.length === 0 && filter === "all" && !query && <Empty>Message a teammate.</Empty>}
256 </Section>)}
257 {shown.length === 0 && (filter !== "all" || query) && (
258 <p className="px-2 py-2 text-xs text-faint">{query ? "Nothing matches." : filter === "unread" ? "You're all caught up." : "No mentions."}</p>
259 )}
260 </>
261 )}
262 </nav>
263 </div>
264 );
265}
266
267const FOLDED_KEY = (slug: string) => `g1t:chat-folded:${slug}`;
268
269/** The sections folded in this workspace, as last left; none if storage is not there. */
270function readFolded(slug: string): ReadonlySet<string> {
271 try {
272 const saved = JSON.parse(localStorage.getItem(FOLDED_KEY(slug)) ?? "[]");
273 return new Set(Array.isArray(saved) ? saved.filter((id): id is string => typeof id === "string") : []);
274 } catch {
275 return new Set();
276 }
277}
278
279function writeFolded(slug: string, folded: ReadonlySet<string>) {
280 try {
281 if (folded.size === 0) localStorage.removeItem(FOLDED_KEY(slug));
282 else localStorage.setItem(FOLDED_KEY(slug), JSON.stringify([...folded]));
283 } catch {
284 // Private windows and blocked storage: folding still works until a reload.
285 }
286}
287
288/**
289 * A titled part of the sidebar that folds away. Folded, it keeps `keep`
290 * showing: the unread conversations and the open one.
291 */
292function Section({
293 id,
294 title,
295 folded,
296 onFold,
297 action,
298 keep,
299 children,
300}: {
301 id: string;
302 title: string;
303 folded: ReadonlySet<string>;
304 onFold: (id: string) => void;
305 action?: ReactNode;
306 keep?: ReactNode[];
307 children: ReactNode;
308}) {
309 const open = !folded.has(id);
310 const list = `chat-section-${id}`;
311 return (
312 <section className="mb-3">
313 <div className="group/head flex h-7 items-center justify-between pr-0.5 pl-1">
314 <button
315 type="button"
316 onClick={() => onFold(id)}
317 aria-expanded={open}
318 aria-controls={list}
319 className="flex min-w-0 grow items-center gap-1 rounded px-1 py-1 text-left text-[0.6875rem] font-medium tracking-wide text-faint uppercase transition-colors hover:text-muted focus-visible:ring-2 focus-visible:ring-accent focus-visible:outline-none max-md:text-[0.8125rem]"
320 >
321 <ChevronDown size={12} className={`shrink-0 transition-transform ${open ? "" : "-rotate-90"}`} />
322 {title}
323 </button>
324 <span className="opacity-70 transition-opacity group-hover/head:opacity-100 focus-within:opacity-100 [@media(hover:none)]:opacity-100">{action}</span>
325 </div>
326 {(open || (keep && keep.length > 0)) && (
327 <ul id={list} className="space-y-px">
328 {open ? children : keep}
329 </ul>
330 )}
331 </section>
332 );
333}
334
335/** A quieter row at the end of a section: somewhere to go rather than a conversation. */
336function ExtraRow({ to, icon, count, countLabel, children }: { to: string; icon: ReactNode; count?: number; countLabel?: string; children: ReactNode }) {
337 return (
338 <li>
339 <NavLink
340 to={to}
341 end
342 className={({ isActive }) => `${ROW} ${isActive ? "bg-sidebar-accent text-fg" : "text-faint hover:bg-sidebar-accent/60 hover:text-muted"}`}
343 >
344 <span className="flex w-4.5 shrink-0 justify-center">{icon}</span>
345 <span className="min-w-0 grow truncate">{children}</span>
346 {count != null && (
347 <span className="shrink-0 text-xs tabular-nums">
348 {count}
349 {countLabel && <span className="sr-only"> {countLabel}</span>}
350 </span>
351 )}
352 </NavLink>
353 </li>
354 );
355}
356
357/** Browse channels, with how many more there are to join; a guest browses the public ones. */
358function BrowseRow({ slug, count, guest = false }: { slug: string; count: number; guest?: boolean }) {
359 return (
360 <ExtraRow to={`/${slug}/-/chat/browse`} icon={<Compass size={15} />} count={count > 0 ? count : undefined} countLabel="to join">
361 {guest ? "Browse public channels" : "Browse channels"}
362 </ExtraRow>
363 );
364}
365
366function Empty({ children }: { children: ReactNode }) {
367 return <li className="px-2 py-1 text-xs text-faint">{children}</li>;
368}
369
370/** Pin or unpin, on hover or focus; the same as the context menu's first item. */
371function PinButton({ pinned, onPin, label }: { pinned: boolean; onPin: () => void; label: string }) {
372 return (
373 <Hint label={pinned ? "Unpin" : "Pin to the top"}>
374 <Button
375 type="button"
376 aria-label={`${pinned ? "Unpin" : "Pin"} ${label}`}
377 onClick={(event) => {
378 event.preventDefault();
379 event.stopPropagation();
380 onPin();
381 }}
382 variant="secondary" size="icon"
383 className="absolute top-1/2 right-1 hidden size-6 -translate-y-1/2 rounded text-faint group-hover/row:flex group-focus-within/row:flex hover:text-fg [@media(hover:none)]:hidden"
384 >
385 {pinned ? <PinOff size={13} /> : <Pin size={13} />}
386 </Button>
387 </Hint>
388 );
389}
390
391/** Right-click on a row: pin it, or open it. */
392function RowMenu({ pinned, onPin, to, children }: { pinned: boolean; onPin: () => void; to?: string; children: ReactNode }) {
393 const navigate = useNavigate();
394 const item =
395 "flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-[0.8125rem] text-fg/90 outline-none select-none data-highlighted:bg-line data-highlighted:text-fg [&_svg]:size-4 [&_svg]:text-muted";
396 return (
397 <ContextMenu.Root>
398 <ContextMenu.Trigger asChild>{children}</ContextMenu.Trigger>
399 <ContextMenu.Portal>
400 <ContextMenu.Content className="z-50 min-w-44 rounded-lg border border-line-strong bg-raised p-1 shadow-xl shadow-black/40 data-[state=open]:animate-pop-in">
401 <ContextMenu.Item className={item} onSelect={onPin}>
402 {pinned ? <PinOff /> : <Pin />}
403 {pinned ? "Unpin" : "Pin to the top"}
404 </ContextMenu.Item>
405 {to && (
406 <ContextMenu.Item className={item} onSelect={() => navigate(to)}>
407 <Hash />
408 Open
409 </ContextMenu.Item>
410 )}
411 </ContextMenu.Content>
412 </ContextMenu.Portal>
413 </ContextMenu.Root>
414 );
415}
416
417/**
418 * Reads a conversation ahead, on hover, focus or the start of a touch, so
419 * opening it draws at once (its route's `clientLoader` keeps it).
420 */
421function usePrefetchConversation(to: string) {
422 const fetcher = useFetcher();
423 const load = () => {
424 if (fetcher.state === "idle" && fetcher.data === undefined && !conversationCache.has(to)) fetcher.load(to);
425 };
426 return { onPointerEnter: load, onFocus: load, onTouchStart: load };
427}
428
429/** One channel or direct message: its mark, its name, its unread count, and a pin. */
430function ConversationRow({
431 entry,
432 slug,
433 pathname,
434 onPin,
435}: {
436 entry: ChatSidebarEntry;
437 slug: string;
438 pathname: string;
439 onPin: () => void;
440}) {
441 const to = channelPath(slug, entry.channel);
442 const current = pathname === to || pathname.startsWith(`${to}/`);
443 const prefetch = usePrefetchConversation(to);
444 const unread = !entry.muted && (entry.unread > 0 || entry.mentions > 0);
445 // People first: an old agent (agents no longer exist) shows only when nobody else is there.
446 const other = entry.others.find((m) => m.kind === "user") ?? entry.others[0];
447 // An old conversation with an agent alone (lib/chat.ts): still here to read, dimmed.
448 const former = agentsOnlyDm(entry);
449 const icon =
450 entry.channel.kind === "dm" && other ? (
451 // One person: their dot, cut out of the sidebar behind it.
452 <MemberAvatar member={other} size={18} presence={entry.others.length === 1} ring="var(--chat-sidebar-bg)" />
453 ) : (
454 <ChannelMark channel={entry.channel} />
455 );
456 return (
457 <li className="group/row relative">
458 <RowMenu pinned={entry.starred} onPin={onPin} to={to}>
459 <NavLink
460 to={to}
461 {...prefetch}
462 aria-current={current ? "page" : undefined}
463 className={`${ROW} ${
464 current ? "bg-sidebar-accent text-fg" : unread ? "text-fg hover:bg-sidebar-accent/60" : entry.muted || former ? "text-faint hover:bg-sidebar-accent/60 hover:text-muted" : "text-muted hover:bg-sidebar-accent/60 hover:text-fg"
465 }`}
466 >
467 <span className={`flex w-4.5 shrink-0 justify-center ${current || unread ? "text-muted" : "text-faint"} ${former ? "opacity-60" : ""}`}>{icon}</span>
468 <span className={`min-w-0 grow truncate ${unread ? "font-semibold" : current ? "font-medium" : ""}`}>
469 {entry.title}
470 {entry.channel.kind === "dm" && other?.kind === "user" && entry.others.length === 1 && (
471 <PersonStatusEmoji person={{ id: other.id, username: other.name }} size={13} className="ml-1.5 align-[-2px]" inert />
472 )}
473 </span>
474 {entry.muted && <BellOff size={12} className="shrink-0 text-faint" aria-label="Muted" />}
475 <Count entry={entry} />
476 </NavLink>
477 </RowMenu>
478 <PinButton pinned={entry.starred} onPin={onPin} label={entry.title} />
479 </li>
480 );
481}
482
483/** A channel's mark: a lock when private, a globe when open to anyone on g1t, else a hash. */
484export function ChannelMark({ channel, size = 15 }: { channel: Pick<Channel, "private" | "visibility">; size?: number }) {
485 if (channel.private || channel.visibility === "private") return <Lock size={size - 1} aria-label="Private channel" />;
486 if (channel.visibility === "public") return <Globe size={size - 1} aria-label="Public channel, open to anyone on g1t" />;
487 return <Hash size={size} aria-label="Workspace channel" />;
488}
489
490/**
491 * At the top of a guest's sidebar: whose chat this is, that they are not
492 * in the workspace, and the way back to their own.
493 */
494function GuestBanner({ workspace, home }: { workspace: { slug: string; name: string; avatar: string | null }; home: string }) {
495 const own = home.toLowerCase() !== workspace.slug;
496 return (
497 <div className="mx-2.5 mt-1 rounded-lg bg-surface p-2.5 ring-1 ring-line">
498 <div className="flex items-center gap-2">
499 <Avatar name={workspace.slug} image={workspace.avatar} size={20} square />
500 <span className="min-w-0 grow truncate text-[0.8125rem] font-medium">{workspace.name}</span>
501 <Badge>Guest</Badge>
502 </div>
503 <p className="mt-1.5 text-xs leading-relaxed text-muted">
504 You&apos;re not a member of this workspace. You see only the channels you&apos;re in and its public ones.
505 </p>
506 {own && (
507 <NavLink to={`/${home}/-/chat`} className="mt-2 inline-flex items-center gap-1 text-xs text-accent hover:underline">
508 <ArrowLeft size={12} />
509 Back to your chat
510 </NavLink>
511 )}
512 </div>
513 );
514}
515
516/** A channel of another workspace the viewer is a guest in: its workspace's icon, its name, its count. */
517function ElsewhereRow({ entry, pathname }: { entry: GuestChannel; pathname: string }) {
518 const to = `/${entry.workspace.slug}/-/chat/${entry.channel.name}`;
519 const current = pathname === to;
520 const count = entry.mentions > 0 ? entry.mentions : entry.unread;
521 return (
522 <li>
523 <NavLink
524 to={to}
525 aria-current={current ? "page" : undefined}
526 className={`${ROW} ${current ? "bg-sidebar-accent text-fg" : count > 0 ? "text-fg hover:bg-sidebar-accent/60" : "text-muted hover:bg-sidebar-accent/60 hover:text-fg"}`}
527 >
528 <span className="flex w-4.5 shrink-0 justify-center">
529 <Avatar name={entry.workspace.slug} image={entry.workspace.avatar} size={16} square />
530 </span>
531 <span className={`min-w-0 grow truncate ${count > 0 ? "font-semibold" : ""}`}>
532 #{entry.channel.name}
533 <span className="ml-1.5 text-xs font-normal text-faint">{entry.workspace.name}</span>
534 </span>
535 {count > 0 && (
536 <span className={`min-w-5 shrink-0 rounded-full px-1.5 text-center text-[0.6875rem] leading-4.5 font-semibold tabular-nums ${entry.mentions > 0 ? "bg-accent text-bg" : "bg-line-strong text-fg"}`}>
537 {count}
538 </span>
539 )}
540 </NavLink>
541 </li>
542 );
543}
544
545/** An invitation into another workspace's channel: who asked, and Join or Decline. */
546function InvitationRow({ invitation, onAnswered }: { invitation: ChannelInvitation; onAnswered: () => void }) {
547 const navigate = useNavigate();
548 const [busy, setBusy] = useState(false);
549 const [error, setError] = useState<string | null>(null);
550 const answer = async (accept: boolean) => {
551 setBusy(true);
552 setError(null);
553 try {
554 const response = await fetch(`/${invitation.workspace.slug}/-/chat/api`, {
555 method: "POST",
556 headers: { "content-type": "application/json" },
557 body: JSON.stringify({ intent: "answer_invitation", id: invitation.id, accept }),
558 });
559 const result = (await response.json()) as { ok: boolean; value?: { to: string | null }; error?: { message: string } };
560 if (!result.ok) {
561 setError(result.error?.message ?? "That didn't work.");
562 return;
563 }
564 onAnswered();
565 if (accept && result.value?.to) navigate(result.value.to);
566 } catch {
567 setError("Couldn't reach g1t. Try again.");
568 } finally {
569 setBusy(false);
570 }
571 };
572 return (
573 <li className="rounded-md px-2 py-1.5 text-[0.8125rem]">
574 <div className="flex items-center gap-2">
575 <Avatar name={invitation.workspace.slug} image={invitation.workspace.avatar} size={16} square />
576 <span className="min-w-0 grow truncate">
577 #{invitation.channel.name} <span className="text-xs text-faint">{invitation.workspace.name}</span>
578 </span>
579 </div>
580 <p className="mt-0.5 pl-6 text-xs text-faint">Asked in as a guest by @{invitation.invited_by.display_username ?? invitation.invited_by.name}</p>
581 <div className="mt-1.5 flex gap-1.5 pl-6">
582 <Button type="button" size="xs" disabled={busy} onClick={() => void answer(true)}>
583 <Check size={12} />
584 Join
585 </Button>
586 <Button type="button" size="xs" variant="ghost" disabled={busy} onClick={() => void answer(false)}>
587 <X size={12} />
588 Decline
589 </Button>
590 </div>
591 {error && <p className="mt-1 pl-6 text-xs text-danger">{error}</p>}
592 </li>
593 );
594}
595
596function SidebarSkeleton() {
597 return (
598 <div className="space-y-2 px-2 pt-1" aria-busy="true">
599 <Skeleton className="h-3 w-16" />
600 {[70, 52, 84, 60].map((w) => (
601 <div key={w} className="flex h-6 items-center gap-2">
602 <Skeleton className="size-4 rounded" />
603 <Skeleton className="h-3" style={{ width: `${w}%` }} />
604 </div>
605 ))}
606 <Skeleton className="mt-4 h-3 w-24" />
607 {[64, 48, 72].map((w) => (
608 <div key={w} className="flex h-6 items-center gap-2">
609 <Skeleton className="size-4 rounded-full" />
610 <Skeleton className="h-3" style={{ width: `${w}%` }} />
611 </div>
612 ))}
613 </div>
614 );
615}