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.

g1t.sh
2,112 linesCodeBlameRaw
1import { Activity, BarChart3, Building2, MessagesSquare, Bell, BookMarked, BookOpen, Bookmark, Blocks, Box, Brain, Check, ChevronDown, ChevronLeft, ChevronRight, CircleDot, GripVertical, CircleUserRound, Code2, Compass, CreditCard, Fingerprint, Gauge, GitBranch, GitPullRequest, Globe, History, Keyboard, KeyRound, Layers, LayoutDashboard, LayoutGrid, LifeBuoy, Lock, LogOut, Mail, MonitorCog, MonitorDown, Package, PlayCircle, Plug, Plus, Rocket, Search, ServerCog, Settings, Shapes, Shield, ShieldCheck, Scale, Smile, Sparkles, House, Ticket, TrendingUp, UserPlus, UserRoundKey, Users, UsersRound, Webhook, X } from "lucide-react";
2import { Fragment, type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
3import { Link, useFetcher, useLocation, useNavigation, useRouteLoaderData, useSubmit } from "react-router";
4
5import { type Abilities, type ChatSidebarEntry, type InboxCounts, type Membership, type Spike, type User, hasCodeAccess, mayCreateTeams, shownUsername } from "@g1t/contracts";
6
7import { InMain } from "./landmark";
8import { CommandPalette, type PaletteCommand, PaletteKey, usePaletteShortcut } from "./command-palette";
9import { AskButton } from "./ask-composer";
10import { NotificationsBell } from "./inbox";
11import { desktopBridge, useDesktopApp, useTitleBarSearch } from "../lib/notify-client";
12import { PinButton } from "./pin-button";
13import { Hint } from "./ui/hint";
14import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
15import {
16 Sidebar,
17 SidebarGroup,
18 SidebarGroupAction,
19 SidebarGroupContent,
20 SidebarGroupLabel,
21 SidebarHeader,
22 SidebarMenu,
23 SidebarMenuBadge,
24 SidebarMenuButton,
25 SidebarMenuItem,
26 SidebarMobile,
27 SidebarProvider,
28 SidebarSeparator,
29 SidebarTrigger,
30} from "./ui/sidebar";
31import { StatusDot, useSiteStatus } from "./footer";
32import { Logo } from "./logo";
33import { SoonPill } from "./ui";
34import { Avatar } from "./ui/avatar";
35import { Skeleton } from "./ui/skeleton";
36import { Badge } from "./ui/badge";
37import { Button } from "./ui/button";
38import { Separator } from "./ui/separator";
39import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from "./ui/breadcrumb";
40import {
41 DropdownMenu,
42 DropdownMenuContent,
43 DropdownMenuGroup,
44 DropdownMenuItem,
45 DropdownMenuLabel,
46 DropdownMenuSeparator,
47 DropdownMenuTrigger,
48} from "./ui/dropdown-menu";
49import { type RoadmapItem, roadmapIn, roadmapItem } from "../lib/roadmap";
50import { type ModeKey, WORKSPACE_SETTINGS_GROUPS, type WorkspaceSettingsPage, homePagePath, modeOf, workspaceSettingsPage } from "../lib/workspace-nav";
51import { ChatSidebar } from "./chat/sidebar";
52import { FoliosSidebar } from "./folios/sidebar";
53import { Rail, ShortcutsDialog, WorkspaceSwitcher, sidebarKeyLabel } from "./rail";
54import { BottomBar, isConversation, useVisualViewport } from "./mobile";
55import { useChatSidebar } from "./chat/actions";
56import { unreadTotals } from "../lib/chat";
57import { SETTINGS_CAPABILITY, type ViewerAccess, seesSettings } from "../lib/access";
58import { projectPages } from "../lib/chrome";
59import { ACCOUNT_SETTINGS, type AccountSettingsPage, FIRST_SETTINGS_PAGE, accountSettingsPage } from "../lib/account-settings";
60import { type PinnableApp, sidebarCookie } from "../lib/apps";
61import { REASON_FILTERS, inboxReason, inboxView } from "../lib/inbox";
62import { GithubMark } from "./github";
63import { STATUS_URL, statusTitle } from "../lib/status";
64import { G1T_INVITES, leftBadge } from "../lib/invites";
65import { type ShortcutProject, movedPin, recentWith } from "../lib/pins";
66import type { AccountMenuData } from "../routes/settings-menu-json";
67import { useLiveBadges } from "../lib/notify-client";
68import { OwnPresenceDot, OwnPresenceItems, StatusDialog } from "./presence";
69import { THEME_COMMANDS, ThemeMenuSwitch } from "./theme-switch";
70
71/**
72 * What the sidebar needs, worked out by the root loader. For a visitor who
73 * is not signed in there is no workspace, no projects and no usage: only
74 * the project being looked at, if they can see it.
75 */
76export type ShellData = {
77 /** The workspace the sidebar is about: the one being looked at, or their first. */
78 workspace: Membership | null;
79 /** All its projects, by name, for the palette: `name` is the slug in their address. */
80 repos: ShortcutProject[];
81 /** The person's pinned projects in it, in their order (lib/pins.ts). */
82 pinned?: ShortcutProject[];
83 /** What they opened there last, latest first, leaving out the pinned. */
84 recent?: ShortcutProject[];
85 /** Repositories shared with them in workspaces they do not belong to. */
86 shared?: { namespace: string; name: string; isPrivate: boolean }[];
87 /** The project being looked at, if any, whoever owns it. */
88 repo: {
89 namespace: string;
90 name: string;
91 member: boolean;
92 issues: number;
93 pulls: number;
94 } | null;
95 /** Where the workspace stands against its usage limit, if billing is on. */
96 limit: {
97 exposureMicros: number;
98 ceilingMicros: number | null;
99 state: "ok" | "warning" | "stopped";
100 comped: boolean;
101 } | null;
102 /** Whether g1t charges nothing for now, while it is being built out. */
103 free?: boolean;
104 /** This month's usage: charged, or at cost while g1t is free. */
105 monthUsageMicros: number | null;
106 /** Whether new compute is paused (a spend spike or a hold), and whether the viewer can answer it. */
107 compute?: { paused: string | null; spike: Spike | null; owner: boolean } | null;
108 /** What is unread in their notifications, for the rail and the bell. Absent for a visitor. */
109 inbox?: InboxCounts | null;
110 /**
111 * Chat, for the rail's badge: what is unread, and the
112 * starred and latest conversations. Null when chat did not answer in time.
113 */
114 chat?: { unread: number; mentions: number; starred?: ChatSidebarEntry[]; recent?: ChatSidebarEntry[] } | null;
115 /** The apps this person pinned to their rail in the workspace (lib/apps.ts). */
116 pins?: PinnableApp[];
117};
118
119/** Whether `pathname` is `to` or a page under it (`end`: only `to` itself), the query left aside. */
120function under(pathname: string, to: string, end = false): boolean {
121 const path = to.split("?")[0]!;
122 return pathname === path || (!end && pathname.startsWith(path.endsWith("/") ? path : `${path}/`));
123}
124
125/**
126 * Where a row is current and where it is on its way to. A row's page is
127 * current under its own address and any `also` prefix, unless the list
128 * says itself (`current`). Rows that differ by query alone (Notifications'
129 * views and reasons) are pending only when the page on its way is that
130 * row's, query and all.
131 */
132function useRowState(to: string, { end, also, current: lit }: { end?: boolean; also?: string | string[]; current?: boolean }) {
133 const { pathname } = useLocation();
134 const going = useNavigation().location;
135 const current = lit ?? (under(pathname, to, end) || [also ?? []].flat().some((prefix) => under(pathname, prefix)));
136 const pending =
137 going != null && !current && (lit === undefined ? under(going.pathname, to, end) : `${going.pathname}${going.search}` === to);
138 return { current, pending };
139}
140
141/**
142 * One row of a mode's sidebar: an icon, its words, how many it lists
143 * (`count`) and, for a row that opens a list of its own (`drill`), a
144 * chevron, always or on hover.
145 */
146function SidebarLink({
147 to,
148 icon,
149 end,
150 count,
151 also,
152 drill,
153 current: lit,
154 action,
155 bare = false,
156 children,
157}: {
158 to: string;
159 icon: ReactNode;
160 end?: boolean;
161 count?: number;
162 /** Other path prefixes under which this link is the current one. */
163 also?: string | string[];
164 /** It opens a list of its own: a chevron says so, always or on hover. */
165 drill?: boolean | "hover";
166 /** Whether it is the current row, when the list works that out itself. */
167 current?: boolean;
168 /** A small button at the row's end, beside the words (a pin). */
169 action?: ReactNode;
170 /** The row alone, for a list item that is drawn by the list (a pinned project, which drags). */
171 bare?: boolean;
172 children: ReactNode;
173}) {
174 const { current, pending } = useRowState(to, { end, also, current: lit });
175 const Item = bare ? Fragment : SidebarMenuItem;
176 return (
177 <Item>
178 <SidebarMenuButton asChild isActive={current} isPending={pending} className={action ? "pr-7" : undefined}>
179 <Link to={to} prefetch="intent" aria-current={current ? "page" : undefined}>
180 {icon}
181 <span className="min-w-0 grow truncate">{children}</span>
182 {count != null && count > 0 && <SidebarMenuBadge>{count}</SidebarMenuBadge>}
183 {drill && (
184 <ChevronRight
185 aria-hidden="true"
186 className={`-mr-0.5 size-3.5! shrink-0 text-faint transition-opacity ${drill === "hover" ? "opacity-0 group-hover/menu-button:opacity-100 group-focus-visible/menu-button:opacity-100" : ""}`}
187 />
188 )}
189 </Link>
190 </SidebarMenuButton>
191 {action}
192 </Item>
193 );
194}
195
196/**
197 * Something a project will have, shown where it will live so people can
198 * see where g1t is going. Not a link: nothing is behind it yet.
199 */
200function SidebarSoon({ icon, children, about }: { icon: ReactNode; children: ReactNode; about: string }) {
201 return (
202 <SidebarMenuItem>
203 <Hint label={about} side="right">
204 <SidebarMenuButton asChild variant="faint">
205 <div aria-disabled="true" className="cursor-default">
206 {icon}
207 <span className="min-w-0 grow truncate">{children}</span>
208 <span className="sr-only">{about}</span>
209 <SoonPill />
210 </div>
211 </SidebarMenuButton>
212 </Hint>
213 </SidebarMenuItem>
214 );
215}
216
217/**
218 * A page that is coming, as a link to its roadmap page: faint, with Soon,
219 * and marked current on any of its section's Soon pages.
220 */
221function SidebarSoonLink({
222 to,
223 also,
224 icon,
225 about,
226 current: lit,
227 children,
228}: {
229 to: string;
230 also?: string[];
231 icon: ReactNode;
232 about: string;
233 /** Whether it is the current row, when the list works that out itself. */
234 current?: boolean;
235 children: ReactNode;
236}) {
237 const { current, pending } = useRowState(to, { also, current: lit });
238 return (
239 <SidebarMenuItem>
240 <Hint label={about} side="right">
241 <SidebarMenuButton asChild variant="faint" isActive={current} isPending={pending}>
242 <Link to={to} prefetch="intent" aria-current={current ? "page" : undefined}>
243 {icon}
244 <span className="min-w-0 grow truncate">{children}</span>
245 <SoonPill />
246 </Link>
247 </SidebarMenuButton>
248 </Hint>
249 </SidebarMenuItem>
250 );
251}
252
253/** The Soon pages of a section, as paths, so its link is current on them. */
254function soonPaths(base: string, section: RoadmapItem["section"]): string[] {
255 return roadmapIn(section).map((item) => `${base}/soon/${item.key}`);
256}
257
258/** A titled group of rows: its name in small capitals, what it makes at the end, and its menu. */
259function NavGroup({
260 title,
261 action,
262 className,
263 children,
264}: {
265 title: string;
266 /** A small button at the label's end, in its row: what the group makes (a `SidebarGroupAction` with `relative top-auto right-auto`). */
267 action?: ReactNode;
268 className?: string;
269 children: ReactNode;
270}) {
271 return (
272 <SidebarGroup className={className}>
273 <div className="flex items-center justify-between gap-2 pr-1">
274 <SidebarGroupLabel asChild>
275 <h2>{title}</h2>
276 </SidebarGroupLabel>
277 {action}
278 </div>
279 <SidebarGroupContent>
280 <SidebarMenu>{children}</SidebarMenu>
281 </SidebarGroupContent>
282 </SidebarGroup>
283 );
284}
285
286/** Rows with no name over them: the first of a list, or a run between rules. */
287function NavRows({ className, children }: { className?: string; children: ReactNode }) {
288 return (
289 <SidebarGroup className={className}>
290 <SidebarGroupContent>
291 <SidebarMenu>{children}</SidebarMenu>
292 </SidebarGroupContent>
293 </SidebarGroup>
294 );
295}
296
297/** What a workspace is called where people read it: its display name, else its slug. */
298function displayName(membership: Membership): string {
299 return membership.name?.trim() || membership.slug;
300}
301
302/**
303 * The fine print, as one quiet row at the foot of the account menu and the
304 * visitor's panel: each link a full-height target, left-aligned. In the
305 * menu each is a menu item, so the arrow keys reach it.
306 */
307const LEGAL_LINKS: [string, string][] = [
308 ["Policies", "/policies"],
309 ["Privacy", "/policies/privacy"],
310 ["Security", "/security"],
311];
312const LEGAL_LINK = "flex h-7 items-center rounded px-1.5 text-xs text-faint outline-none transition-colors";
313
314function MenuLegalRow() {
315 return (
316 <div role="group" aria-label="Legal" className="flex items-center gap-0.5 px-0.5 pt-0.5">
317 {LEGAL_LINKS.map(([label, to], index) => (
318 <span key={to} className="flex items-center gap-0.5">
319 {index > 0 && (
320 <span aria-hidden="true" className="text-[0.625rem] text-line-strong">
321 ·
322 </span>
323 )}
324 <DropdownMenuItem asChild className={`${LEGAL_LINK} py-0 data-highlighted:bg-line data-highlighted:text-fg`}>
325 <Link to={to}>{label}</Link>
326 </DropdownMenuItem>
327 </span>
328 ))}
329 </div>
330 );
331}
332
333/** Status's row: the live dot and two or three words, fetched when the menu opens. */
334function StatusSummary({ open }: { open: boolean }) {
335 const status = useSiteStatus(open);
336 const words = statusTitle(status);
337 return (
338 <span className="ml-auto flex min-w-0 items-center gap-1.5 pl-2 text-xs text-faint">
339 {/* The words say it; the dot's own words for screen readers would repeat them. */}
340 <span aria-hidden="true" className="flex">
341 <StatusDot state={status?.overall.state ?? null} />
342 </span>
343 {words ? <span className="truncate">{words}</span> : <Skeleton className="h-3 w-20" />}
344 </span>
345 );
346}
347
348/** A menu row: an icon, words, and whatever sits at its end. */
349const MENU_ROW = "h-9 gap-2.5 px-2.5 text-[0.8125rem]";
350
351/**
352 * Your account, at the foot of the rail (or in the header, before you have
353 * a workspace): who you are and your status, your profile and settings,
354 * and help: the documentation, support, status and the keyboard's
355 * shortcuts; then signing out and the fine print.
356 */
357function AccountMenu({ user, side = "right" }: { user: User; side?: "right" | "bottom" }) {
358 const submit = useSubmit();
359 const [open, setOpen] = useState(false);
360 const [keys, setKeys] = useState(false);
361 // Inside the desktop app there is nothing to get.
362 const inApp = useDesktopApp();
363 // Your status's dialog: outside the menu, so the menu closes behind it.
364 const [editing, setEditing] = useState(false);
365 // Name, primary address and invites left: asked for once, as soon as the
366 // pointer or focus reaches the button, so they are there when it opens.
367 const details = useFetcher<AccountMenuData | null>({ key: "account-menu" });
368 const prefetch = () => {
369 if (details.state === "idle" && details.data === undefined) details.load("/settings/menu.json");
370 };
371 useEffect(() => {
372 if (open) prefetch();
373 // eslint-disable-next-line react-hooks/exhaustive-deps
374 }, [open]);
375 const me = details.data ?? null;
376 // Still on its way: shapes where the words will be, the same size.
377 const loading = details.data === undefined && details.state !== "idle";
378 const profile = `/u/${user.username}`;
379 return (
380 <>
381 <DropdownMenu open={open} onOpenChange={setOpen}>
382 {/* The avatar alone, with a dot that says how others see you (components/presence.tsx). */}
383 <Hint label={side === "right" ? "Your account" : undefined} side="right">
384 <DropdownMenuTrigger
385 aria-label={`Account menu for ${shownUsername(user)}`}
386 onPointerEnter={prefetch}
387 onFocus={prefetch}
388 className={
389 side === "right"
390 ? // At the foot of the rail: a 40px rounded square, as the rail's icons are.
391 "relative flex size-10 items-center justify-center rounded-[10px] outline-none transition-colors hover:bg-sidebar-accent focus-visible:ring-2 focus-visible:ring-accent data-[state=open]:bg-sidebar-accent"
392 : "relative flex rounded-full outline-none transition-transform hover:scale-[1.04] focus-visible:ring-2 focus-visible:ring-accent data-[state=open]:ring-2 data-[state=open]:ring-line-strong"
393 }
394 >
395 <Avatar name={user.username} image={user.avatar} size={side === "right" ? 40 : 28} square={side === "right"} />
396 <OwnPresenceDot ring={side === "right" ? "var(--color-rail)" : "var(--color-bg)"} className={side === "right" ? "absolute -right-1 -bottom-1" : "absolute -right-0.5 -bottom-0.5"} />
397 </DropdownMenuTrigger>
398 </Hint>
399 <DropdownMenuContent align="end" side={side} sideOffset={side === "right" ? 14 : 6} collisionPadding={8} className="w-70 p-1.5">
400 {/* Who is signed in, and a way to their profile. */}
401 <DropdownMenuItem asChild className="gap-3 px-2 py-2">
402 <Link to={profile} aria-label={`${me?.name ?? shownUsername(user)} (@${shownUsername(user)}), your profile`}>
403 <Avatar name={user.username} image={user.avatar} size={36} />
404 <span className="flex min-w-0 grow flex-col leading-tight" aria-busy={loading}>
405 {loading ? (
406 <Skeleton className="my-0.75 h-3.5 w-28" />
407 ) : (
408 <span className="truncate text-sm font-medium text-fg">{me?.name ?? shownUsername(user)}</span>
409 )}
410 <span className="truncate font-mono text-xs text-muted">@{shownUsername(user)}</span>
411 {loading ? (
412 <Skeleton className="mt-1 h-3 w-40" />
413 ) : (
414 me?.email && <span className="mt-0.5 truncate text-xs text-faint">{me.email}</span>
415 )}
416 </span>
417 </Link>
418 </DropdownMenuItem>
419 <DropdownMenuSeparator className="my-1.5" />
420 {/* Your status, away, and pausing notifications. */}
421 <DropdownMenuGroup>
422 <OwnPresenceItems className="min-h-9 py-1.5 text-[0.8125rem]" onEdit={() => setEditing(true)} />
423 </DropdownMenuGroup>
424 <DropdownMenuSeparator className="my-1.5" />
425 <DropdownMenuGroup>
426 <DropdownMenuItem asChild className={MENU_ROW}>
427 <Link to={profile}>
428 <CircleUserRound />
429 Your profile
430 </Link>
431 </DropdownMenuItem>
432 <DropdownMenuItem asChild className={MENU_ROW}>
433 <Link to={FIRST_SETTINGS_PAGE}>
434 <Settings />
435 Your settings
436 </Link>
437 </DropdownMenuItem>
438 {/* Invite a friend to g1t: word of mouth, never needed to sign up (routes/settings/invites.tsx). */}
439 <DropdownMenuItem asChild className={MENU_ROW}>
440 <Link to="/settings/invites?new">
441 <UserPlus />
442 {G1T_INVITES.action}
443 {loading && <Skeleton className="ml-auto h-4 w-12 rounded-full" />}
444 {leftBadge(me?.invites_left) && (
445 <Badge size="sm" className="ml-auto tabular-nums">
446 {leftBadge(me?.invites_left)}
447 </Badge>
448 )}
449 </Link>
450 </DropdownMenuItem>
451 {/* The app's own: starting with the computer, closing to the tray, the badge (apps/desktop). */}
452 {inApp && desktopBridge()?.openSettings && (
453 <DropdownMenuItem className={MENU_ROW} onSelect={() => desktopBridge()?.openSettings?.()}>
454 <MonitorCog />
455 Desktop app settings
456 </DropdownMenuItem>
457 )}
458 </DropdownMenuGroup>
459 <DropdownMenuSeparator className="my-1.5" />
460 {/* Auto, Light or Dark, switched in place (lib/theme.ts). */}
461 <ThemeMenuSwitch />
462 <DropdownMenuSeparator className="my-1.5" />
463 <DropdownMenuGroup>
464 <DropdownMenuItem asChild className={MENU_ROW}>
465 <a href="https://docs.g1t.sh/">
466 <BookOpen />
467 Documentation
468 </a>
469 </DropdownMenuItem>
470 <DropdownMenuItem asChild className={MENU_ROW}>
471 <Link to="/support">
472 <LifeBuoy />
473 Support
474 </Link>
475 </DropdownMenuItem>
476 <DropdownMenuItem asChild className={MENU_ROW}>
477 <a href={STATUS_URL}>
478 <Activity />
479 Status
480 <StatusSummary open={open} />
481 </a>
482 </DropdownMenuItem>
483 <DropdownMenuItem className={MENU_ROW} onSelect={() => setKeys(true)}>
484 <Keyboard />
485 Keyboard shortcuts
486 <PaletteKey className="ml-auto font-sans text-xs text-faint" />
487 </DropdownMenuItem>
488 {!inApp && (
489 <DropdownMenuItem asChild className={MENU_ROW}>
490 <Link to="/download">
491 <MonitorDown />
492 Get the desktop app
493 </Link>
494 </DropdownMenuItem>
495 )}
496 </DropdownMenuGroup>
497 <DropdownMenuSeparator className="my-1.5" />
498 {/* Submitted from here: the menu closes on select, and a button
499 that has left the page cannot submit a form. */}
500 <DropdownMenuItem className={MENU_ROW} onSelect={() => submit(null, { method: "post", action: "/logout" })}>
501 <LogOut />
502 Sign out
503 </DropdownMenuItem>
504 <DropdownMenuSeparator className="my-1.5" />
505 <MenuLegalRow />
506 </DropdownMenuContent>
507 </DropdownMenu>
508 <StatusDialog open={editing} onOpenChange={setEditing} />
509 <ShortcutsDialog open={keys} onOpenChange={setKeys} />
510 </>
511 );
512}
513
514/** A project's settings pages, which the project's menu drills into. */
515const REPO_SETTINGS_PAGE = /^\/([^/]+)\/([^/-][^/]*)\/settings(\/|$)/;
516
517/**
518 * The sidebar's lists are a stack, the way a phone pushes a screen: one
519 * drilled into slides in from the right over the full width, while the one
520 * it covers drifts a quarter of the way left and fades, both on one long
521 * ease-out, the fade quicker than the move so the two never blur together.
522 * Going back reverses it.
523 */
524const LAYER =
525 "absolute inset-0 [transition:translate_380ms_cubic-bezier(0.32,0.72,0,1),opacity_220ms_ease-out] will-change-[translate,opacity] motion-reduce:transition-none";
526/** One list, filling its layer. */
527const PANEL = "h-full overflow-y-auto px-1 pt-1 pb-4 scrollbar-thin";
528
529/** One list in the stack: what it is, and its rows. */
530type Level = { key: string; node: ReactNode };
531
532/** True once the page has hydrated, so what the server drew never animates in. */
533function useHydrated(): boolean {
534 const [hydrated, setHydrated] = useState(false);
535 useEffect(() => setHydrated(true), []);
536 return hydrated;
537}
538
539/**
540 * Drilling in and out of the sidebar's lists. `trail` is the way from the
541 * main list to the one shown, worked out from the address, so a link
542 * straight to a settings page opens the sidebar already drilled in, and
543 * leaving it comes back out. Lists deeper than the one shown stay in
544 * place, off to the right, so going back slides them away rather than
545 * dropping them. Moving to a list at the same depth (a workspace's settings
546 * to a project) fades the new one in where it is.
547 */
548function Drill({ trail }: { trail: Level[] }) {
549 const depth = trail.length - 1;
550 const hydrated = useHydrated();
551 const stack = useRef<Level[]>(trail);
552 const before = stack.current;
553 const within = trail.every((level, index) => before[index]?.key === level.key);
554 stack.current = within ? [...trail, ...before.slice(trail.length)] : trail;
555 const levels = stack.current;
556 // What was showing last time, to tell drilling in from moving across.
557 const shown = useRef({ depth, keys: levels.map((level) => level.key) });
558 useEffect(() => {
559 shown.current = { depth, keys: levels.map((level) => level.key) };
560 });
561 return (
562 <div className="relative min-h-0 grow overflow-hidden">
563 {levels.map((level, index) => {
564 const current = index === depth;
565 const place =
566 index < depth
567 ? "pointer-events-none -translate-x-1/4 opacity-0"
568 : current
569 ? "translate-x-0 opacity-100"
570 : "pointer-events-none translate-x-full opacity-0";
571 // A list that was not there before arrives: from the right when
572 // drilling in, in place when moving across.
573 const arriving = hydrated && current && !shown.current.keys.includes(level.key);
574 const enter = arriving
575 ? depth > shown.current.depth
576 ? "starting:translate-x-full starting:opacity-0"
577 : "starting:opacity-0"
578 : "";
579 return (
580 <div key={level.key} className={`${LAYER} ${place} ${enter}`} inert={!current} aria-hidden={!current || undefined}>
581 {level.node}
582 </div>
583 );
584 })}
585 </div>
586 );
587}
588
589/**
590 * The row at the top of a list drilled into: the list's name, which goes
591 * back out, and what it belongs to, faint at the end.
592 */
593function BackRow({ to, label, context }: { to: string; label: ReactNode; context?: ReactNode }) {
594 return (
595 <NavRows className="mt-1">
596 <SidebarMenuItem>
597 <SidebarMenuButton asChild className="gap-1.5 pl-1 font-medium text-fg">
598 <Link to={to} prefetch="intent">
599 <ChevronLeft className="text-faint transition-transform group-hover/menu-button:-translate-x-0.5 group-hover/menu-button:text-muted" />
600 <span className="min-w-0 shrink-0 truncate">{label}</span>
601 {context && <span className="ml-auto min-w-0 truncate pl-2 font-mono text-[0.6875rem] font-normal text-faint">{context}</span>}
602 </Link>
603 </SidebarMenuButton>
604 </SidebarMenuItem>
605 </NavRows>
606 );
607}
608
609/** A thin rule between groups of a list. */
610function Rule() {
611 return <SidebarSeparator className="my-1.5" />;
612}
613
614/** A quiet heading inside a group: Pinned, Recent. */
615function SidebarSubhead({ children }: { children: ReactNode }) {
616 return (
617 <SidebarGroupLabel asChild className="h-6 pt-0.5">
618 <h3>{children}</h3>
619 </SidebarGroupLabel>
620 );
621}
622
623/**
624 * The workspace's projects as the sidebar keeps them, however many there
625 * are: the person's pins in their order, what they opened last, and the
626 * way to all of them. Pins move by dragging, or with Alt and the arrow
627 * keys; the projects service keeps the order.
628 */
629function SidebarProjects({ slug, shell, current }: { slug: string; shell: ShellData; current: boolean }) {
630 const reorder = useFetcher({ key: `pins:${slug}` });
631 const saved = shell.pinned ?? [];
632 // While a new order is on its way, it shows as made.
633 const asked = reorder.formData?.get("intent") === "reorder" ? reorder.formData.getAll("slug").map(String) : null;
634 const pinned = asked
635 ? asked.map((name) => saved.find((project) => project.name === name)).filter((project): project is ShortcutProject => project != null)
636 : saved;
637 const active = shell.repo ? { namespace: shell.repo.namespace, name: shell.repo.name, isPrivate: false } : null;
638 const recent = recentWith(shell.recent ?? [], pinned, active, slug);
639 const [dragging, setDragging] = useState<number | null>(null);
640 const move = (from: number, by: number) => {
641 const next = movedPin(pinned, from, by);
642 if (!next) return;
643 const form = new FormData();
644 form.set("intent", "reorder");
645 for (const project of next) form.append("slug", project.name);
646 reorder.submit(form, { method: "post", action: `/${slug}/-/pins` });
647 };
648 // Each row pins or unpins in place: the pin shows on hover or focus, and
649 // stays shown on a pinned row's hover so it reads as "unpin".
650 const row = (project: ShortcutProject, isPinned: boolean) => (
651 <SidebarLink
652 to={`/${project.namespace}/${project.name}`}
653 icon={project.isPrivate ? <Lock /> : <Box />}
654 bare={isPinned}
655 action={
656 // At the row's end, where the row's other actions sit, and only on
657 // hover or keyboard focus: a pin clicked keeps the mouse's focus,
658 // and showing it on any focus left it lit on a row no one was over.
659 <PinButton
660 workspace={slug}
661 slug={project.name}
662 name={project.title ?? project.name}
663 pinned={isPinned}
664 small
665 className="absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity group-hover/menu-item:opacity-100 has-focus-visible:opacity-100 [@media(hover:none)]:opacity-100"
666 />
667 }
668 >
669 {project.title ?? project.name}
670 </SidebarLink>
671 );
672 return (
673 <SidebarGroup>
674 {/* The label and its button share a row, so the button stays level with the words at any text size. */}
675 <div className="flex items-center justify-between gap-2 pr-1">
676 <SidebarGroupLabel asChild>
677 <h2>Projects</h2>
678 </SidebarGroupLabel>
679 <Hint label="New project">
680 <SidebarGroupAction asChild className="relative top-auto right-auto">
681 <Link to="/new" aria-label="New project">
682 <Plus />
683 </Link>
684 </SidebarGroupAction>
685 </Hint>
686 </div>
687 <SidebarGroupContent>
688 {/* Only there once something is pinned: each row below has its own pin. */}
689 {pinned.length > 0 && (
690 <>
691 <SidebarSubhead>Pinned</SidebarSubhead>
692 <SidebarMenu aria-label="Pinned projects">
693 {pinned.map((project, index) => (
694 <SidebarMenuItem
695 key={project.name}
696 draggable={pinned.length > 1}
697 onDragStart={(event) => {
698 setDragging(index);
699 event.dataTransfer.effectAllowed = "move";
700 }}
701 onDragOver={(event) => {
702 if (dragging != null) event.preventDefault();
703 }}
704 onDrop={(event) => {
705 event.preventDefault();
706 if (dragging != null && dragging !== index) move(dragging, index - dragging);
707 setDragging(null);
708 }}
709 onDragEnd={() => setDragging(null)}
710 onKeyDown={(event) => {
711 if (!event.altKey || (event.key !== "ArrowUp" && event.key !== "ArrowDown")) return;
712 event.preventDefault();
713 move(index, event.key === "ArrowUp" ? -1 : 1);
714 }}
715 className={`group/pin ${dragging === index ? "opacity-50" : ""}`}
716 >
717 {row(project, true)}
718 {pinned.length > 1 && (
719 <Hint label="Drag, or Alt and an arrow key, to reorder" side="right">
720 <span className="absolute top-1/2 -left-2 -translate-y-1/2 cursor-grab text-faint opacity-0 transition-opacity group-hover/pin:opacity-100">
721 <GripVertical size={12} aria-hidden="true" />
722 </span>
723 </Hint>
724 )}
725 </SidebarMenuItem>
726 ))}
727 </SidebarMenu>
728 </>
729 )}
730 {recent.length > 0 && (
731 <>
732 <SidebarSubhead>Recent</SidebarSubhead>
733 <SidebarMenu aria-label="Recent projects">
734 {recent.map((project) => (
735 <Fragment key={`${project.namespace}/${project.name}`}>{row(project, false)}</Fragment>
736 ))}
737 </SidebarMenu>
738 </>
739 )}
740 <SidebarMenu className="pt-1">
741 <SidebarLink to={`/${slug}/-/projects`} icon={<LayoutGrid />} count={shell.repos.length} current={current}>
742 All projects
743 </SidebarLink>
744 </SidebarMenu>
745 </SidebarGroupContent>
746 </SidebarGroup>
747 );
748}
749
750/** Insights, coming: the workspace's own page says what it will be. */
751const INSIGHTS = roadmapItem("insights");
752
753/**
754 * What the repository menu needs. Known from the address before the page's
755 * data arrives, so the menu is right from the first frame; the counts fill
756 * in once it does.
757 */
758type MenuRepo = {
759 namespace: string;
760 name: string;
761 member: boolean;
762 /** Whether they see its settings; from the repository's page once it loads. */
763 settings?: boolean;
764 /** What they may do there, once the repository's page loads. */
765 can?: Abilities;
766 issues?: number;
767 pulls?: number;
768};
769
770function sameRepo(a: { namespace: string; name: string } | null, b: { namespace: string; name: string } | null) {
771 return (
772 a != null &&
773 b != null &&
774 a.namespace.toLowerCase() === b.namespace.toLowerCase() &&
775 a.name.toLowerCase() === b.name.toLowerCase()
776 );
777}
778
779/**
780 * A project's own list, drilled into while you are in it: everything about
781 * the project, running and its code, and nothing else, with the way back
782 * out to all of them.
783 */
784function RepoMenu({
785 repo,
786 isPrivate,
787 back,
788}: {
789 repo: MenuRepo;
790 isPrivate: boolean;
791 /** Where the way back leads: the workspace's projects, mission control, or Explore. */
792 back: { to: string; label: string };
793}) {
794 const base = `/${repo.namespace}/${repo.name}`;
795 // What a member sees, and what everyone who can see the project does
796 // (lib/chrome.ts).
797 const shows = new Set(projectPages(repo.member, repo.can));
798 const { current: atOverview, pending: toOverview } = useRowState(base, { end: true });
799 return (
800 <nav aria-label={`${repo.namespace}/${repo.name}`} className={PANEL}>
801 <BackRow to={back.to} label={back.label} />
802 <NavRows className="mt-1">
803 <SidebarMenuItem>
804 <Hint label="Overview" side="right">
805 <SidebarMenuButton asChild size="lg" isActive={atOverview} isPending={toOverview} className="gap-2 font-normal">
806 <Link to={base} prefetch="intent" aria-current={atOverview ? "page" : undefined}>
807 <span className="flex size-6 shrink-0 items-center justify-center rounded-md bg-raised text-muted ring-1 ring-line [&>svg]:size-3.5">
808 {isPrivate ? <Lock /> : <Box />}
809 </span>
810 <span className="min-w-0 truncate font-mono text-[0.8125rem]">
811 <span className="text-faint">{repo.namespace}/</span>
812 <span className="font-semibold text-fg">{repo.name}</span>
813 </span>
814 </Link>
815 </SidebarMenuButton>
816 </Hint>
817 </SidebarMenuItem>
818 </NavRows>
819 {/* A project's pages, in the order people use them. A page with more
820 than one view shows them as tabs across its top. */}
821 <Rule />
822 <NavRows>
823 <SidebarLink to={`${base}/code`} also={[`${base}/tree`, `${base}/blob`, `${base}/commits`, `${base}/commit`, `${base}/branches`, `${base}/tags`, `${base}/compare`, ...soonPaths(base, "Code")]} icon={<Code2 size={15} />}>
824 Code
825 </SidebarLink>
826 {shows.has("issues") && (
827 <SidebarLink to={`${base}/issues`} also={[`${base}/milestones`, `${base}/labels`, ...soonPaths(base, "Issues")]} icon={<CircleDot size={15} />} count={repo.issues}>
828 Issues
829 </SidebarLink>
830 )}
831 {shows.has("pulls") && (
832 <SidebarLink to={`${base}/pulls`} also={[`${base}/pull`, `${base}/work`, `${base}/queue`, `${base}/sessions`]} icon={<GitPullRequest size={15} />} count={repo.pulls}>
833 Pull requests
834 </SidebarLink>
835 )}
836 {repo.member && (
837 <SidebarLink to={`${base}/memory`} icon={<Brain size={15} />}>
838 Memory
839 </SidebarLink>
840 )}
841 {shows.has("actions") && (
842 <SidebarLink to={`${base}/actions`} icon={<PlayCircle size={15} />}>
843 Workflows
844 </SidebarLink>
845 )}
846 </NavRows>
847 <Rule />
848 <NavRows>
849 {shows.has("deployments") ? (
850 <SidebarLink to={`${base}/deployments`} also={soonPaths(base, "Deployments")} icon={<Rocket size={15} />}>
851 Deployments
852 </SidebarLink>
853 ) : null}
854 {shows.has("observability") && (
855 <SidebarLink to={`${base}/observability`} also={soonPaths(base, "Observability")} icon={<Activity size={15} />}>
856 Observability
857 </SidebarLink>
858 )}
859 {shows.has("security") ? (
860 <SidebarLink to={`${base}/security`} also={soonPaths(base, "Security")} icon={<ShieldCheck size={15} />}>
861 Security
862 </SidebarLink>
863 ) : null}
864 <SidebarLink
865 to={`${base}/contributors`}
866 also={[`${base}/activity`, `${base}/stargazers`, ...soonPaths(base, "Insights")]}
867 icon={<BarChart3 size={15} />}
868 >
869 Insights
870 </SidebarLink>
871 </NavRows>
872 {(repo.settings ?? shows.has("settings")) && (
873 <>
874 <Rule />
875 <NavRows>
876 <SidebarLink to={`${base}/settings`} icon={<Settings size={15} />} drill>
877 Settings
878 </SidebarLink>
879 </NavRows>
880 </>
881 )}
882 </nav>
883 );
884}
885
886/**
887 * A project's settings, drilled into from its list: what is about running
888 * it, then its sandboxes, then its code and who can reach it. The way back
889 * leads to the project.
890 */
891function RepoSettingsMenu({ repo }: { repo: MenuRepo }) {
892 const base = `/${repo.namespace}/${repo.name}`;
893 // Each page shows to the roles that can use it, once the role is known.
894 const shows = (page: string) => !repo.can || repo.can[SETTINGS_CAPABILITY[page] ?? "administer"];
895 const running = shows("deployments");
896 const guarded = shows("guardrails");
897 return (
898 <nav aria-label={`${repo.namespace}/${repo.name} settings`} className={PANEL}>
899 <BackRow to={base} label="Settings" context={`${repo.namespace}/${repo.name}`} />
900 {shows("") && (
901 <NavRows className="mt-2">
902 <SidebarLink to={`${base}/settings`} end icon={<Settings size={15} />}>
903 General
904 </SidebarLink>
905 </NavRows>
906 )}
907 {running && (
908 <>
909 {shows("") && <Rule />}
910 <NavRows className={shows("") ? undefined : "mt-2"}>
911 <SidebarLink to={`${base}/settings/deployments`} icon={<Rocket size={15} />}>
912 Deployments
913 </SidebarLink>
914 <SidebarLink to={`${base}/settings/domains`} icon={<Globe size={15} />}>
915 Domains
916 </SidebarLink>
917 </NavRows>
918 </>
919 )}
920 {guarded && (
921 <>
922 <Rule />
923 <NavRows>
924 {shows("guardrails") && (
925 <SidebarLink to={`${base}/settings/guardrails`} icon={<ShieldCheck size={15} />}>
926 Guardrails
927 </SidebarLink>
928 )}
929 </NavRows>
930 </>
931 )}
932 <Rule />
933 <NavRows>
934 {shows("repository") && (
935 <SidebarLink to={`${base}/settings/repository`} icon={<BookMarked size={15} />}>
936 Repository
937 </SidebarLink>
938 )}
939 {shows("access") && (
940 <SidebarLink to={`${base}/settings/access`} icon={<Users size={15} />}>
941 Access
942 </SidebarLink>
943 )}
944 {shows("keys") && (
945 <SidebarLink to={`${base}/settings/keys`} icon={<KeyRound size={15} />}>
946 Deploy keys
947 </SidebarLink>
948 )}
949 {shows("branches") && (
950 <SidebarLink to={`${base}/settings/branches`} icon={<GitBranch size={15} />}>
951 Branches and merging
952 </SidebarLink>
953 )}
954 {shows("rules") && (
955 <SidebarLink to={`${base}/settings/rules`} icon={<Scale size={15} />}>
956 Rules
957 </SidebarLink>
958 )}
959 {shows("secrets") && (
960 <SidebarLink to={`${base}/settings/secrets`} icon={<Lock size={15} />}>
961 Secrets and variables
962 </SidebarLink>
963 )}
964 {shows("actions") && (
965 <SidebarLink to={`${base}/settings/actions`} icon={<PlayCircle size={15} />}>
966 Actions
967 </SidebarLink>
968 )}
969 {shows("environments") && (
970 <SidebarLink to={`${base}/settings/environments`} icon={<Layers size={15} />}>
971 Environments
972 </SidebarLink>
973 )}
974 {shows("runners") && (
975 <SidebarLink to={`${base}/settings/runners`} icon={<ServerCog size={15} />}>
976 Runners
977 </SidebarLink>
978 )}
979 {shows("webhooks") && (
980 <SidebarLink to={`${base}/settings/webhooks`} icon={<Webhook size={15} />}>
981 Webhooks
982 </SidebarLink>
983 )}
984 </NavRows>
985 </nav>
986 );
987}
988
989/** Your own settings, drilled into from Your settings: one page each. */
990function AccountSettingsMenu({ username }: { username: string }) {
991 const link = (page: AccountSettingsPage, icon: ReactNode) => (
992 <SidebarLink to={`/settings/${page}`} icon={icon}>
993 {ACCOUNT_SETTINGS[page].title}
994 </SidebarLink>
995 );
996 return (
997 <nav aria-label="Your settings" className={PANEL}>
998 <BackRow to="/" label="Your settings" context={username} />
999 <NavRows className="mt-2">
1000 {link("profile", <CircleUserRound size={15} />)}
1001 {link("emails", <Mail size={15} />)}
1002 {link("invites", <Ticket size={15} />)}
1003 </NavRows>
1004 <Rule />
1005 <NavRows>
1006 {link("keys", <Fingerprint size={15} />)}
1007 {link("tokens", <KeyRound size={15} />)}
1008 </NavRows>
1009 <Rule />
1010 <NavRows>
1011 {link("integrations", <Blocks size={15} />)}
1012 {link("github", <GithubMark className="size-3.75" />)}
1013 {link("applications", <Plug size={15} />)}
1014 </NavRows>
1015 <Rule />
1016 <NavRows>
1017 {link("two-factor", <ShieldCheck size={15} />)}
1018 {link("security-log", <History size={15} />)}
1019 </NavRows>
1020 </nav>
1021 );
1022}
1023
1024/**
1025 * Code's sidebar: its Overview, the projects, what spans them and what is
1026 * coming; in a project, drilled into the project's own list, and its
1027 * settings one level further in. The address says which, so a link
1028 * straight to a project opens the sidebar already drilled in.
1029 */
1030function CodeSidebar({
1031 user,
1032 shell,
1033 missing = false,
1034}: {
1035 user: User;
1036 shell: ShellData;
1037 /** The page is a 404: the address names nothing the viewer can see. */
1038 missing?: boolean;
1039}) {
1040 const ws = shell.workspace;
1041 const { pathname } = useLocation();
1042 const going = useNavigation().location?.pathname;
1043 // Where the sidebar is drilled to follows the page being gone to, so it
1044 // moves as the link is followed, not once the page arrives.
1045 const target = going ?? pathname;
1046 // On a 404, the address is not a place: no list is drilled into from it,
1047 // except the project's own when the project is real and visible and only
1048 // something inside it is missing (a file, a commit, an issue).
1049 const lost = missing && going == null;
1050 const active = shell.repo;
1051 // In a repository, or on the way into one, its own list.
1052 const repoPath = /^\/([^/]+)\/([^/-][^/]*)(\/|$)/.exec(target);
1053 const reserved = new Set(["settings", "explore", "search", "new", "u", "pricing", "avatars", "workspaces", "login", "logout", "register", "verify", "forgot", "reset", "device", "oauth", "policies", "security", "support", "status", "invite", "notifications", "inbox", ".well-known"]);
1054 // An invitation to a repository is answered before its menu means anything.
1055 const inRepo =
1056 repoPath != null &&
1057 !reserved.has(repoPath[1]) &&
1058 repoPath[2] !== "-" &&
1059 !/^\/[^/]+\/[^/]+\/invitations\/?$/.test(target) &&
1060 (!lost || sameRepo(active, { namespace: repoPath[1]!, name: repoPath[2]! }));
1061 // A project's settings, one level further in.
1062 const inRepoSettings = inRepo && REPO_SETTINGS_PAGE.test(target);
1063 // The repository the menu is for: the one loaded if it is the one being
1064 // gone to, else what the address says, at once.
1065 const targetRepo = inRepo && repoPath ? { namespace: repoPath[1], name: repoPath[2] } : null;
1066 const guessed: MenuRepo | null = targetRepo
1067 ? sameRepo(active, targetRepo)
1068 ? active
1069 : {
1070 ...targetRepo,
1071 member: (user.workspaces ?? []).some((m) => m.slug === targetRepo.namespace.toLowerCase()),
1072 }
1073 : null;
1074 // The viewer's role there, from the repository's page once it has loaded.
1075 const page = useRouteLoaderData("routes/repo/layout") as
1076 | { repo?: { namespace: string; name: string }; access?: ViewerAccess }
1077 | undefined;
1078 const menuRepo: MenuRepo | null =
1079 guessed && page?.access && page.repo && sameRepo(page.repo, guessed)
1080 ? { ...guessed, member: page.access.insider, settings: seesSettings(page.access), can: page.access.can }
1081 : guessed;
1082
1083 // The way from Code's list to the one shown.
1084 const trail: Level[] = [{ key: "main", node: ws ? <CodeMenu shell={shell} slug={ws.slug} /> : null }];
1085 if (menuRepo) {
1086 const key = `repo:${menuRepo.namespace}/${menuRepo.name}`.toLowerCase();
1087 // Out of a project: to its workspace's projects when they are yours.
1088 const home = (user.workspaces ?? []).find((m) => m.slug === menuRepo.namespace.toLowerCase());
1089 const back = home ? { to: `/${home.slug}/-/projects`, label: "All projects" } : { to: ws ? `/${ws.slug}/-/overview` : "/explore", label: "Code" };
1090 trail.push({
1091 key,
1092 node: (
1093 <RepoMenu
1094 repo={menuRepo}
1095 isPrivate={[...shell.repos, ...(shell.shared ?? [])].some((repo) => sameRepo(repo, menuRepo) && repo.isPrivate)}
1096 back={back}
1097 />
1098 ),
1099 });
1100 if (inRepoSettings) trail.push({ key: `${key}:settings`, node: <RepoSettingsMenu repo={menuRepo} /> });
1101 }
1102
1103 return (
1104 <div className="flex h-full flex-col">
1105 <ModeHeader title="Code" />
1106 <Drill trail={trail} />
1107 </div>
1108 );
1109}
1110
1111/**
1112 * A mode's sidebar heading: its name, quiet, under the workspace's
1113 * switcher, with what it makes at the end.
1114 */
1115export function ModeHeader({ title, action }: { title: ReactNode; action?: ReactNode }) {
1116 return (
1117 <div className="flex h-8 shrink-0 items-center gap-1 pr-2 pl-3">
1118 <SidebarGroupLabel asChild className="min-w-0 grow truncate px-1">
1119 <h2>{title}</h2>
1120 </SidebarGroupLabel>
1121 {action}
1122 </div>
1123 );
1124}
1125
1126/**
1127 * Code's own list (beside the rail): only code. Its Overview (Mission
1128 * control's code panels), the projects, what spans them, and what is
1129 * coming. The workspace's people, money and settings are elsewhere.
1130 */
1131function CodeMenu({ shell, slug }: { shell: ShellData; slug: string }) {
1132 const { pathname } = useLocation();
1133 const going = useNavigation().location?.pathname;
1134 const path = going ?? pathname;
1135 const at = (page: string) => path === `/${slug}/-/${page}` || path.startsWith(`/${slug}/-/${page}/`);
1136 const shared = shell.shared ?? [];
1137 return (
1138 <nav aria-label="Code" className={PANEL}>
1139 <NavRows>
1140 <SidebarLink to={`/${slug}/-/overview`} icon={<LayoutDashboard size={15} />} current={at("overview")}>
1141 Overview
1142 </SidebarLink>
1143 </NavRows>
1144 <Rule />
1145 <SidebarProjects slug={slug} shell={shell} current={at("projects")} />
1146 <Rule />
1147 <NavRows>
1148 <SidebarLink to={`/${slug}/-/security`} icon={<ShieldCheck size={15} />} current={at("security") && !at("security/settings")}>
1149 Security
1150 </SidebarLink>
1151 <SidebarLink to={`/${slug}/-/packages`} icon={<Package size={15} />} current={at("packages")}>
1152 Packages
1153 </SidebarLink>
1154 <SidebarLink to={`/${slug}/-/memory`} icon={<Brain size={15} />} current={at("memory")}>
1155 Memory
1156 </SidebarLink>
1157 {INSIGHTS && (
1158 <SidebarSoonLink to={`/${slug}/-/insights`} icon={<TrendingUp size={15} />} about={INSIGHTS.summary} current={at("insights")}>
1159 {INSIGHTS.title}
1160 </SidebarSoonLink>
1161 )}
1162 </NavRows>
1163 <Rule />
1164 <NavRows>
1165 {/* Public repositories beyond this workspace's own. */}
1166 <SidebarLink to="/explore" icon={<Compass size={15} />} current={path === "/explore" || path.startsWith("/explore/")}>
1167 Explore
1168 </SidebarLink>
1169 </NavRows>
1170 {shared.length > 0 && (
1171 <>
1172 <Rule />
1173 <NavGroup title="Shared with you">
1174 {shared.map((repo) => (
1175 <SidebarLink
1176 key={`${repo.namespace}/${repo.name}`}
1177 to={`/${repo.namespace}/${repo.name}`}
1178 icon={repo.isPrivate ? <Lock size={15} /> : <Box size={15} />}
1179 drill="hover"
1180 >
1181 <span className="font-mono text-faint">{repo.namespace}/</span>
1182 {repo.name}
1183 </SidebarLink>
1184 ))}
1185 </NavGroup>
1186 </>
1187 )}
1188 </nav>
1189 );
1190}
1191
1192/** The icon of each of Workspace mode's pages, by its key (lib/workspace-nav.ts). */
1193const WORKSPACE_PAGE_ICONS: Record<string, ReactNode> = {
1194 settings: <Settings size={15} />,
1195 members: <Users size={15} />,
1196 invitations: <Mail size={15} />,
1197 permissions: <ShieldCheck size={15} />,
1198 tokens: <KeyRound size={15} />,
1199 "personal-access-tokens": <UserRoundKey size={15} />,
1200 usage: <BarChart3 size={15} />,
1201 billing: <CreditCard size={15} />,
1202 runners: <ServerCog size={15} />,
1203 repositories: <BookMarked size={15} />,
1204 actions: <PlayCircle size={15} />,
1205 secrets: <Lock size={15} />,
1206 webhooks: <Webhook size={15} />,
1207 deployments: <Rocket size={15} />,
1208 projects: <Layers size={15} />,
1209 "chat-settings": <MessagesSquare size={15} />,
1210 emoji: <Smile size={15} />,
1211 "artifact-settings": <Shapes size={15} />,
1212 "security-settings": <Shield size={15} />,
1213 guardrails: <Gauge size={15} />,
1214 rules: <Scale size={15} />,
1215 audit: <History size={15} />,
1216 integrations: <Plug size={15} />,
1217 applications: <Blocks size={15} />,
1218};
1219
1220/**
1221 * A group of Workspace mode's rows that folds: its name is the button, with
1222 * a chevron that turns when it is open. The group holding the current page
1223 * is always open, and its button does nothing. Every group starts open, so
1224 * the server and the browser draw the same list.
1225 */
1226function FoldingGroup({ title, current, children }: { title: string; current: boolean; children: ReactNode }) {
1227 const [open, setOpen] = useState(true);
1228 return (
1229 <Collapsible open={open || current} onOpenChange={setOpen}>
1230 <SidebarGroup>
1231 <CollapsibleTrigger
1232 disabled={current}
1233 aria-label={`${title}: ${open || current ? "fold" : "unfold"}`}
1234 className="flex h-7 w-full shrink-0 items-center justify-between rounded-md px-2 text-[0.6875rem] font-medium tracking-wide text-faint uppercase hover:text-muted focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-default disabled:text-faint data-[state=open]:[&_svg]:rotate-90"
1235 >
1236 <span>{title}</span>
1237 {!current && <ChevronRight size={12} aria-hidden="true" className="text-faint/70" />}
1238 </CollapsibleTrigger>
1239 <CollapsibleContent>
1240 <SidebarGroupContent>
1241 <SidebarMenu>{children}</SidebarMenu>
1242 </SidebarGroupContent>
1243 </CollapsibleContent>
1244 </SidebarGroup>
1245 </Collapsible>
1246 );
1247}
1248
1249/**
1250 * The Workspace mode's sidebar: the workspace's settings area, every page
1251 * one click away. Its overview, then the groups in lib/workspace-nav.ts
1252 * (General, Access, Money, Compute, Code, Chat, Artifacts,
1253 * Security, Integrations), each folding, the one you are in held open.
1254 * Pages only owners open are left out for members, and a group with none
1255 * left goes with them; a page that is coming is a Soon row, not a link.
1256 */
1257export function WorkspaceSidebar({ slug, owner }: { slug: string; owner: boolean }) {
1258 const { pathname } = useLocation();
1259 const going = useNavigation().location?.pathname;
1260 const path = going ?? pathname;
1261 const here = workspaceSettingsPage(path, slug);
1262 const overview = path === `/${slug}/-/workspace` || path.startsWith(`/${slug}/-/workspace/`);
1263 const shown = (page: WorkspaceSettingsPage) => owner || !page.owner;
1264 return (
1265 <div className="flex h-full flex-col">
1266 <ModeHeader title="Workspace" />
1267 <nav aria-label="Workspace" className={PANEL}>
1268 <NavRows>
1269 <SidebarLink to={`/${slug}/-/workspace`} icon={<LayoutGrid size={15} />} current={overview}>
1270 Overview
1271 </SidebarLink>
1272 </NavRows>
1273 {WORKSPACE_SETTINGS_GROUPS.filter((group) => group.pages.some(shown)).map((group) => (
1274 <Fragment key={group.key}>
1275 <Rule />
1276 <FoldingGroup title={group.title} current={here?.group === group.key}>
1277 {group.pages.filter(shown).map((page) =>
1278 page.soon ? (
1279 <SidebarSoon key={page.key} icon={WORKSPACE_PAGE_ICONS[page.key] ?? <Sparkles size={15} />} about={page.soon}>
1280 {page.label}
1281 </SidebarSoon>
1282 ) : (
1283 <SidebarLink
1284 key={page.key}
1285 to={`/${slug}/-/${page.path}`}
1286 icon={WORKSPACE_PAGE_ICONS[page.key] ?? <Settings size={15} />}
1287 current={here?.page === page.key}
1288 >
1289 {page.label}
1290 </SidebarLink>
1291 ),
1292 )}
1293 </FoldingGroup>
1294 </Fragment>
1295 ))}
1296 </nav>
1297 </div>
1298 );
1299}
1300
1301/**
1302 * People's sidebar: everyone in the workspace and its teams. Who belongs, and
1303 * inviting people, is the workspace's: Workspace mode's Access group.
1304 */
1305function PeopleSidebar({ slug }: { slug: string }) {
1306 const { pathname } = useLocation();
1307 const going = useNavigation().location?.pathname;
1308 const path = going ?? pathname;
1309 const at = (page: string) => path === `/${slug}/-/${page}` || path.startsWith(`/${slug}/-/${page}/`);
1310 return (
1311 <div className="flex h-full flex-col">
1312 <ModeHeader title="People" />
1313 <nav aria-label="People" className={PANEL}>
1314 <NavRows>
1315 <SidebarLink to={`/${slug}/-/people`} icon={<Users size={15} />} current={at("people")}>
1316 Everyone
1317 </SidebarLink>
1318 <SidebarLink to={`/${slug}/-/teams`} icon={<UsersRound size={15} />} current={at("teams")}>
1319 Teams
1320 </SidebarLink>
1321 </NavRows>
1322 </nav>
1323 </div>
1324 );
1325}
1326
1327/**
1328 * Notifications' sidebar: what you have not finished with, what you saved
1329 * and what is done; then why you were told, which narrows any of them.
1330 */
1331function NotificationsSidebar({ counts }: { counts: InboxCounts | null }) {
1332 const { search } = useLocation();
1333 const params = new URLSearchParams(search);
1334 const view = inboxView(params.get("view"));
1335 const reason = inboxReason(params.get("reason"));
1336 const tab = params.get("tab");
1337 const address = (changes: Record<string, string | null>) => {
1338 const merged: Record<string, string | null> = { tab, view: view === "inbox" ? null : view, reason, ...changes };
1339 const next = new URLSearchParams();
1340 for (const [name, value] of Object.entries(merged)) if (value) next.set(name, value);
1341 const query = next.toString();
1342 return query ? `/notifications?${query}` : "/notifications";
1343 };
1344 const views = [
1345 { view: "inbox", label: "Everything", icon: <Bell size={15} />, count: counts?.unread },
1346 { view: "saved", label: "Saved", icon: <Bookmark size={15} /> },
1347 { view: "done", label: "Done", icon: <Check size={15} /> },
1348 ] as const;
1349 return (
1350 <div className="flex h-full flex-col">
1351 <ModeHeader title="Notifications" />
1352 <nav aria-label="Notifications" className={PANEL}>
1353 <NavRows>
1354 {views.map((entry) => (
1355 <SidebarLink
1356 key={entry.view}
1357 to={address({ view: entry.view === "inbox" ? null : entry.view, before: null })}
1358 icon={entry.icon}
1359 count={"count" in entry ? (entry.count ?? undefined) : undefined}
1360 current={view === entry.view}
1361 >
1362 {entry.label}
1363 </SidebarLink>
1364 ))}
1365 </NavRows>
1366 <Rule />
1367 <NavGroup title="Why you were told">
1368 {REASON_FILTERS.map((entry) => (
1369 <SidebarLink
1370 key={entry.reason ?? "any"}
1371 to={address({ reason: entry.reason, before: null })}
1372 icon={<span className="block size-3.75" />}
1373 current={reason === entry.reason}
1374 >
1375 {entry.reason == null ? "Any reason" : entry.label}
1376 </SidebarLink>
1377 ))}
1378 </NavGroup>
1379 </nav>
1380 </div>
1381 );
1382}
1383
1384/** Your own settings, beside the page: under the account menu, not any workspace's. */
1385export function AccountSidebar({ username }: { username: string }) {
1386 return (
1387 <div className="flex h-full flex-col">
1388 <ModeHeader title="Your account" />
1389 <div className="min-h-0 grow">
1390 <AccountSettingsMenu username={username} />
1391 </div>
1392 </div>
1393 );
1394}
1395
1396/** Words for the sections a path can end in. */
1397const SECTIONS: Record<string, string> = {
1398 issues: "Issues",
1399 milestones: "Milestones",
1400 labels: "Labels",
1401 pulls: "Pull requests",
1402 queue: "Merge queue",
1403 commits: "Commits",
1404 actions: "Workflows",
1405 soon: "Soon",
1406 deployments: "Deployments",
1407 repository: "Repository",
1408 access: "Access",
1409 invitations: "Invitation",
1410 repositories: "Repositories",
1411 branches: "Branches",
1412 tags: "Tags",
1413 compare: "Compare",
1414 code: "Files",
1415 secrets: "Secrets and variables",
1416 settings: "Settings",
1417 people: "People",
1418 members: "Members",
1419 permissions: "Permissions",
1420 projects: "Projects",
1421 teams: "Teams",
1422 tokens: "Access tokens",
1423 "personal-access-tokens": "Personal access tokens",
1424 usage: "Usage",
1425 billing: "Billing and plans",
1426 integrations: "Integrations",
1427 webhooks: "Webhooks",
1428 emoji: "Emoji",
1429 domains: "Domains",
1430 guardrails: "Guardrails",
1431 rules: "Rules",
1432 audit: "Audit log",
1433 tree: "Files",
1434 blob: "Files",
1435 memory: "Memory",
1436 security: "Security",
1437 packages: "Packages",
1438 runners: "Runners",
1439 environments: "Environments",
1440 workflows: "Workflows",
1441 observability: "Observability",
1442 insights: "Insights",
1443 sessions: "Sessions",
1444 work: "Work",
1445 chat: "Chat",
1446 artifacts: "Artifacts",
1447 home: "Home",
1448 apps: "Apps",
1449 "code-access": "Code access",
1450 overview: "Overview",
1451 workspace: "Workspace",
1452};
1453
1454/** Settings pages whose name differs from the section's of the same word. */
1455const SETTINGS_SECTIONS: Record<string, string> = { branches: "Branches and merging", actions: "Actions" };
1456
1457/** Where the page is, as a trail of links: workspace / repository / section. */
1458function Breadcrumbs({
1459 pathname,
1460 missing,
1461 repo,
1462 workspace,
1463}: {
1464 pathname: string;
1465 missing?: boolean;
1466 repo?: ShellData["repo"];
1467 /** The workspace you are in: the switcher names it, so the trail starts after it. */
1468 workspace: string | null;
1469}) {
1470 // A 404 names nothing from the address, unless the project is real and
1471 // visible and only something inside it is missing.
1472 const visibleRepo = /^\/([^/]+)\/([^/-][^/]*)(\/|$)/.exec(pathname);
1473 if (missing && !(visibleRepo && sameRepo(repo ?? null, { namespace: visibleRepo[1]!, name: visibleRepo[2]! }))) {
1474 return <Here>Not found</Here>;
1475 }
1476 const parts = pathname.split("/").filter(Boolean);
1477 const reserved = ["settings", "explore", "new", "search", "workspaces", "policies", "security", "support", "status", "invite", "notifications"];
1478 if (parts.length === 0) return <Here>Home</Here>;
1479 // Your settings: Settings / Emails.
1480 if (parts[0] === "settings") {
1481 const page = accountSettingsPage(pathname);
1482 return <Trail trail={[{ label: "Settings", to: FIRST_SETTINGS_PAGE }, ...(page ? [{ label: ACCOUNT_SETTINGS[page].title, to: `/settings/${page}` }] : [])]} />;
1483 }
1484 if (reserved.includes(parts[0]!)) {
1485 const words: Record<string, string> = {
1486 settings: "Account",
1487 explore: "Explore",
1488 new: "New project",
1489 search: "Search",
1490 workspaces: "New workspace",
1491 policies: "Policies",
1492 security: "Security",
1493 support: "Support",
1494 status: "Status",
1495 invite: "Invite",
1496 notifications: "Notifications",
1497 };
1498 return <Here>{words[parts[0]!]}</Here>;
1499 }
1500 // A person's profile, by their handle.
1501 if (parts[0] === "u" && parts[1]) return <ProfileCrumb username={parts[1]} />;
1502 const [owner, second, third, fourth] = parts;
1503 const ours = workspace != null && owner!.toLowerCase() === workspace.toLowerCase();
1504 const trail: Crumb[] = ours ? [] : [{ label: owner!, to: `/${owner}`, mono: true }];
1505 if (second === "-") {
1506 const page = `/${owner}/-/${third}`;
1507 if (third === "settings" && fourth === "chat") {
1508 // Chat settings is a page of its own, not one of General's.
1509 trail.push({ label: "Chat settings", to: `${page}/chat` });
1510 } else if (third) {
1511 // The workspace's settings pages each stand alone: General, Members, Permissions.
1512 trail.push({ label: third === "settings" ? "General" : (SECTIONS[third] ?? third), to: page });
1513 // Members names its invitations.
1514 const tabs: Record<string, string> = third === "members" ? { invitations: "Invitations" } : {};
1515 const tab = fourth ? tabs[fourth] : undefined;
1516 if (tab) trail.push({ label: tab, to: `${page}/${fourth}` });
1517 }
1518 } else if (second) {
1519 const repo = `/${owner}/${second}`;
1520 trail.push({ label: second, to: repo, mono: true });
1521 if (third === "pull" && fourth) trail.push({ label: `Pull request #${fourth}`, short: `#${fourth}`, to: `${repo}/pull/${fourth}` });
1522 else if (third === "issues" && fourth && fourth !== "new") trail.push({ label: `Issue #${fourth}`, short: `#${fourth}`, to: `${repo}/issues/${fourth}` });
1523 else if (third === "commit" && fourth) trail.push({ label: fourth.slice(0, 7), to: `${repo}/commit/${fourth}`, mono: true });
1524 else if (third && SECTIONS[third]) {
1525 trail.push({ label: SECTIONS[third]!, to: `${repo}/${third}` });
1526 // A settings page names which one: Settings / Secrets and variables.
1527 if (third === "settings" && fourth && SECTIONS[fourth]) {
1528 trail.push({ label: SETTINGS_SECTIONS[fourth] ?? SECTIONS[fourth]!, to: `${repo}/settings/${fourth}` });
1529 }
1530 }
1531 }
1532 if (trail.length === 0) trail.push({ label: "Overview", to: `/${owner}` });
1533 return <Trail trail={trail} />;
1534}
1535
1536/** A profile's place in the top bar: the person's avatar and @handle, from the page once it has loaded. */
1537function ProfileCrumb({ username }: { username: string }) {
1538 const page = useRouteLoaderData("routes/user") as { profile?: { username: string; displayUsername?: string | null; avatar: string | null } } | undefined;
1539 const profile = page?.profile?.username.toLowerCase() === username.toLowerCase() ? page.profile : null;
1540 return (
1541 <Breadcrumb className="min-w-0">
1542 <BreadcrumbList>
1543 <BreadcrumbItem>
1544 <BreadcrumbPage asChild className="flex items-center gap-2 hover:bg-raised">
1545 <Link to={`/u/${profile?.username ?? username}`}>
1546 <Avatar name={profile?.username ?? username} image={profile?.avatar ?? null} size={20} />
1547 <span className="truncate font-mono text-[0.8125rem]">@{profile ? shownUsername(profile) : username}</span>
1548 </Link>
1549 </BreadcrumbPage>
1550 </BreadcrumbItem>
1551 </BreadcrumbList>
1552 </Breadcrumb>
1553 );
1554}
1555
1556/** A page with no trail to it, such as Today or Search: its name alone. */
1557function Here({ children }: { children: ReactNode }) {
1558 return (
1559 <Breadcrumb className="min-w-0">
1560 <BreadcrumbList>
1561 <BreadcrumbItem>
1562 <BreadcrumbPage>{children}</BreadcrumbPage>
1563 </BreadcrumbItem>
1564 </BreadcrumbList>
1565 </Breadcrumb>
1566 );
1567}
1568
1569/** One link of the trail; `short` is what a phone shows when it is the page itself. */
1570type Crumb = { label: string; to: string; mono?: boolean; short?: string };
1571
1572/**
1573 * The trail of links. On a phone there is room for one: the page itself,
1574 * with a way back to where it sits; the whole trail from a wider screen up.
1575 */
1576function Trail({ trail }: { trail: Crumb[] }) {
1577 // Up on a phone, unless up is the workspace itself: its pages are the tabs.
1578 const up = trail.length > 1 && !/^\/[^/]+$/.test(trail[trail.length - 2]!.to) ? trail[trail.length - 2]! : null;
1579 return (
1580 <Breadcrumb className="flex min-w-0 items-center">
1581 {up && (
1582 <Button asChild variant="ghost" size="icon-bar" className="-ml-1 sm:hidden">
1583 <Link to={up.to} prefetch="intent" aria-label={`Back to ${up.label}`}>
1584 <ChevronLeft size={16} />
1585 </Link>
1586 </Button>
1587 )}
1588 <BreadcrumbList>
1589 {trail.map((crumb, index) => {
1590 const last = index === trail.length - 1;
1591 const label =
1592 last && crumb.short ? (
1593 <>
1594 <span className="sm:hidden">{crumb.short}</span>
1595 <span className="hidden sm:inline">{crumb.label}</span>
1596 </>
1597 ) : (
1598 crumb.label
1599 );
1600 const mono = crumb.mono ? "font-mono text-[0.8125rem]" : "";
1601 return (
1602 <Fragment key={index}>
1603 {index > 0 && <BreadcrumbSeparator className="max-sm:hidden" />}
1604 <BreadcrumbItem className={last ? "" : "max-sm:hidden"}>
1605 {last ? (
1606 // The page you are on is still a link: to its own top, as the trail always was.
1607 <BreadcrumbPage asChild className={`hover:bg-raised ${mono}`}>
1608 <Link to={crumb.to} prefetch="intent">
1609 {label}
1610 </Link>
1611 </BreadcrumbPage>
1612 ) : (
1613 <BreadcrumbLink asChild className={mono}>
1614 <Link to={crumb.to} prefetch="intent">
1615 {label}
1616 </Link>
1617 </BreadcrumbLink>
1618 )}
1619 </BreadcrumbItem>
1620 </Fragment>
1621 );
1622 })}
1623 </BreadcrumbList>
1624 </Breadcrumb>
1625 );
1626}
1627
1628type Command = PaletteCommand;
1629
1630/** Everything the palette can jump to, from what the sidebar already knows. */
1631function commandsFor(user: User, shell: ShellData): Command[] {
1632 const ws = shell.workspace;
1633 const commands: Command[] = [
1634 ...(ws
1635 ? [
1636 { label: "Home", to: homePagePath(ws.slug), icon: <House size={15} /> },
1637 { label: "Chat", to: `/${ws.slug}/-/chat`, icon: <MessagesSquare size={15} /> },
1638 ...(hasCodeAccess(ws) ? [{ label: "Code overview", to: `/${ws.slug}/-/overview`, icon: <Code2 size={15} /> }] : []),
1639 { label: "Artifacts", to: `/${ws.slug}/-/artifacts`, icon: <Shapes size={15} /> },
1640 { label: "Apps", hint: "Everything installed that you can use", to: `/${ws.slug}/-/apps`, icon: <LayoutGrid size={15} /> },
1641 { label: "Workspace", hint: "Billing, policies, settings", to: `/${ws.slug}/-/workspace`, icon: <Building2 size={15} /> },
1642 ]
1643 : []),
1644 { label: "Explore repositories", to: "/explore", icon: <Compass size={15} /> },
1645 { label: "Search g1t", hint: "Repositories, code, issues, people", to: "/search", icon: <Search size={15} /> },
1646 { label: "Notifications", hint: "What needs you", to: "/notifications", icon: <Bell size={15} /> },
1647 { label: "New project", to: "/new", icon: <Plus size={15} /> },
1648 { label: "Your settings", to: FIRST_SETTINGS_PAGE, icon: <Settings size={15} /> },
1649 ...(Object.keys(ACCOUNT_SETTINGS) as AccountSettingsPage[])
1650 .filter((page) => page !== "profile")
1651 .map((page) => ({ label: ACCOUNT_SETTINGS[page].title, hint: "Your settings", to: `/settings/${page}`, icon: <Settings size={15} /> })),
1652 ...THEME_COMMANDS,
1653 ];
1654 const repo = shell.repo;
1655 if (repo) {
1656 const base = `/${repo.namespace}/${repo.name}`;
1657 const name = `${repo.namespace}/${repo.name}`;
1658 commands.unshift(
1659 { label: "Overview", hint: name, to: base, icon: <LayoutGrid size={15} /> },
1660 { label: "Code", hint: name, to: `${base}/code`, icon: <Code2 size={15} /> },
1661 { label: "Issues", hint: name, to: `${base}/issues`, icon: <CircleDot size={15} /> },
1662 { label: "New issue", hint: name, to: `${base}/issues/new`, icon: <Plus size={15} /> },
1663 { label: "Pull requests", hint: name, to: `${base}/pulls`, icon: <GitPullRequest size={15} /> },
1664 { label: "Commits", hint: name, to: `${base}/commits`, icon: <History size={15} /> },
1665 ...(repo.member
1666 ? [
1667 { label: "Deployments", hint: name, to: `${base}/deployments`, icon: <Rocket size={15} /> },
1668 { label: "Secrets and variables", hint: name, to: `${base}/settings/secrets`, icon: <Lock size={15} /> },
1669 { label: "Project settings", hint: name, to: `${base}/settings`, icon: <Settings size={15} /> },
1670 { label: "Repository settings", hint: name, to: `${base}/settings/repository`, icon: <Settings size={15} /> },
1671 ]
1672 : []),
1673 );
1674 }
1675 for (const membership of user.workspaces ?? []) {
1676 commands.push(
1677 { label: displayName(membership), hint: `Workspace · ${membership.slug}`, to: `/${membership.slug}`, icon: <Avatar name={membership.slug} image={membership.avatar} size={15} square /> },
1678 { label: "All projects", hint: membership.slug, to: `/${membership.slug}/-/projects`, icon: <LayoutGrid size={15} /> },
1679 { label: "People", hint: membership.slug, to: `/${membership.slug}/-/people`, icon: <Users size={15} /> },
1680 { label: "Usage", hint: membership.slug, to: `/${membership.slug}/-/usage`, icon: <BarChart3 size={15} /> },
1681 { label: "Billing and plans", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/billing`, icon: <CreditCard size={15} /> },
1682 { label: "Access tokens", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/tokens`, icon: <KeyRound size={15} /> },
1683 { label: "Integrations", hint: membership.slug, to: `/${membership.slug}/-/integrations`, icon: <Plug size={15} /> },
1684 { label: "Members", hint: `${membership.slug} · Access`, to: `/${membership.slug}/-/members`, icon: <Users size={15} /> },
1685 ...(membership.role === "owner"
1686 ? [
1687 { label: "Invitations", hint: `${membership.slug} · Access`, to: `/${membership.slug}/-/members/invitations`, icon: <Mail size={15} /> },
1688 { label: "Permissions", hint: `${membership.slug} · Access`, to: `/${membership.slug}/-/permissions`, icon: <ShieldCheck size={15} /> },
1689 ]
1690 : []),
1691 );
1692 }
1693 for (const listed of shell.repos) {
1694 commands.push({
1695 label: listed.title ?? listed.name,
1696 hint: `${listed.namespace} · Project`,
1697 to: `/${listed.namespace}/${listed.name}`,
1698 icon: <Box size={15} />,
1699 });
1700 }
1701 return commands;
1702}
1703
1704/**
1705 * The page while the next one loads: after a moment it dims, under the
1706 * bar below, so it is plainly on its way out rather than frozen, and the
1707 * next page fades up from there. Sending a form does not dim it: the
1708 * form's button says it is working. Spread on the element holding the page.
1709 */
1710export function useLeaving() {
1711 const navigation = useNavigation();
1712 const method = navigation.formMethod?.toUpperCase();
1713 const leaving = navigation.state === "loading" && (method == null || method === "GET");
1714 return {
1715 "aria-busy": leaving || undefined,
1716 className: `transition-opacity motion-reduce:transition-none ${leaving ? "opacity-60 delay-200 duration-300" : "duration-150"}`,
1717 };
1718}
1719
1720/**
1721 * A bar across the top of the page while the next one loads, as GitHub
1722 * has: it appears at once, creeps towards the end while waiting, then fills
1723 * and fades when the page arrives.
1724 */
1725export function Progress() {
1726 const navigation = useNavigation();
1727 const busy = navigation.state !== "idle";
1728 const [width, setWidth] = useState(0);
1729 const [visible, setVisible] = useState(false);
1730 useEffect(() => {
1731 if (busy) {
1732 setVisible(true);
1733 setWidth(12);
1734 // Slows as it goes, never quite arriving until the page does.
1735 const timer = setInterval(() => setWidth((now) => now + (90 - now) * 0.12), 200);
1736 return () => clearInterval(timer);
1737 }
1738 setWidth((now) => (now > 0 ? 100 : 0));
1739 const fade = setTimeout(() => setVisible(false), 250);
1740 const reset = setTimeout(() => setWidth(0), 550);
1741 return () => {
1742 clearTimeout(fade);
1743 clearTimeout(reset);
1744 };
1745 }, [busy]);
1746 return (
1747 <div
1748 aria-hidden="true"
1749 className={`pointer-events-none fixed inset-x-0 top-0 z-60 h-0.75 transition-opacity duration-300 ${
1750 visible ? "opacity-100" : "opacity-0"
1751 }`}
1752 >
1753 <div
1754 className="h-full bg-accent shadow-[0_0_10px_var(--color-accent)] transition-[width] duration-200 ease-out"
1755 style={{ width: `${width}%` }}
1756 />
1757 </div>
1758 );
1759}
1760
1761/**
1762 * Which sidebar sits beside the page: each mode's own, or none. Home and
1763 * Apps are pages at full width, and so are g1t's public pages, such as a
1764 * profile, which are no workspace's. Without a workspace, only your own
1765 * settings and Notifications have one.
1766 */
1767function sidebarFor(mode: ModeKey, workspace: boolean): Panel | null {
1768 if (!workspace) return mode === "account" || mode === "notifications" ? mode : null;
1769 if (mode === "home" || mode === "apps" || mode === "site") return null;
1770 return mode;
1771}
1772
1773/** The sidebars that sit beside the page, one per mode that has one. */
1774type Panel = "chat" | "artifacts" | "code" | "notifications" | "people" | "workspace" | "account";
1775
1776/** Each sidebar's name, for the button that opens it on a phone. */
1777const MODE_MENU: Record<Panel, string> = {
1778 chat: "Chat",
1779 artifacts: "Artifacts",
1780 code: "Code",
1781 notifications: "Notifications",
1782 people: "People",
1783 workspace: "Workspace",
1784 account: "Your account",
1785};
1786
1787/** Whether a key press happened in something you type into, where Ctrl B is the editor's. */
1788function typing(target: EventTarget | null): boolean {
1789 if (!(target instanceof HTMLElement)) return false;
1790 return target.isContentEditable || target.closest("input, textarea, select, [contenteditable=''], [contenteditable='true'], [role='textbox']") != null;
1791}
1792
1793/** Ctrl B (⌘B on a Mac) shows or hides the sidebar, except while typing. */
1794function useSidebarShortcut(toggle: () => void) {
1795 useEffect(() => {
1796 const onKey = (event: KeyboardEvent) => {
1797 if (event.key.toLowerCase() !== "b" || event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey)) return;
1798 if (event.defaultPrevented || typing(event.target)) return;
1799 event.preventDefault();
1800 toggle();
1801 };
1802 window.addEventListener("keydown", onKey);
1803 return () => window.removeEventListener("keydown", onKey);
1804 }, [toggle]);
1805}
1806
1807/**
1808 * Search or jump to: the command palette. On a computer it looks like the
1809 * field it opens, with its shortcut; on a phone, a magnifier.
1810 */
1811function SearchButton({ onClick, place }: { onClick: () => void; place: "bar" | "sidebar" }) {
1812 const field = (
1813 <Button
1814 variant="outline"
1815 size="sm"
1816 aria-label="Search or jump to"
1817 onClick={onClick}
1818 className={
1819 place === "sidebar"
1820 ? "w-full justify-start bg-bg font-normal text-faint hover:bg-bg hover:text-muted"
1821 : "mr-1 w-[min(18rem,26vw)] justify-start bg-surface font-normal text-faint hover:bg-surface hover:text-muted max-md:hidden"
1822 }
1823 >
1824 <Search size={15} />
1825 <span className="grow truncate text-left">Search or jump to</span>
1826 <PaletteKey className="px-1.5 text-[0.625rem] leading-4 text-muted" />
1827 </Button>
1828 );
1829 if (place === "sidebar") return field;
1830 return (
1831 <>
1832 <Button variant="ghost" size="icon-bar" aria-label="Search or jump to" onClick={onClick} className="md:hidden">
1833 <Search size={18} />
1834 </Button>
1835 {field}
1836 </>
1837 );
1838}
1839
1840/** The sidebar's shortcut, for the hint on its toggle. */
1841function useSidebarKey(): string {
1842 return sidebarKeyLabel(typeof navigator === "undefined" ? null : navigator.platform);
1843}
1844
1845/**
1846 * The app: three surfaces that never blur together. The rail, a narrow
1847 * column of icons down the window's left edge; the mode's sidebar, flat
1848 * against it with a hairline between, which folds away with Ctrl B and is
1849 * a drawer below 1024px; and the page, flat against the sidebar and
1850 * filling the rest of the window, with its top bar across the top and a
1851 * line under it: the sidebar's toggle, where you are, search, Ask, the bell and
1852 * Create new. On a phone the rail is a bar along the bottom and the page
1853 * fills the window above it, flat as well. Only for someone signed in; without a workspace yet, there
1854 * is no rail. The rail and the sidebar are drawn from the sidebar kit
1855 * (components/ui/sidebar.tsx): one provider holds whether the sidebar is
1856 * open on a computer and whether the drawer is.
1857 */
1858export function AppShell({
1859 user,
1860 shell,
1861 missing = false,
1862 banner,
1863 sidebarClosed = false,
1864 children,
1865}: {
1866 user: User;
1867 shell: ShellData;
1868 /** The page is a 404 (see CodeSidebar). */
1869 missing?: boolean;
1870 banner?: ReactNode;
1871 /** Whether the person folded the sidebar away, as their cookie says. */
1872 sidebarClosed?: boolean;
1873 children: ReactNode;
1874}) {
1875 const { pathname } = useLocation();
1876 const [drawer, setDrawer] = useState(false);
1877 const [closed, setClosed] = useState(sidebarClosed);
1878 const [palette, setPalette] = useState(false);
1879 const commands = useMemo(() => commandsFor(user, shell), [user, shell]);
1880
1881 // A new page closes the drawer.
1882 useEffect(() => setDrawer(false), [pathname]);
1883 usePaletteShortcut(() => setPalette((open) => !open));
1884 // In the desktop app, search is in the middle of its title bar, as in Slack, and not in the top bar too.
1885 const titleSearch = useTitleBarSearch(`Search ${shell.workspace?.name ?? shell.workspace?.slug ?? "g1t"}`, () => setPalette(true));
1886 const leaving = useLeaving();
1887 useVisualViewport();
1888 const going = useNavigation().location?.pathname;
1889 const ws = shell.workspace;
1890 const mode = modeOf(going ?? pathname, ws?.slug ?? null);
1891 const panel = sidebarFor(mode, ws != null);
1892 const { sidebar: chatSidebar } = useChatSidebar();
1893 // Notify: the feed socket's live counts (lib/notify-client.ts) once it has them; the page's until then.
1894 const live = useLiveBadges(ws?.slug);
1895 const chatUnread = chatSidebar
1896 ? unreadTotals(chatSidebar.entries)
1897 : live?.chat != null
1898 ? { unread: live.chat, mentions: live.mentions ?? 0 }
1899 : (shell.chat ?? { unread: 0, mentions: 0 });
1900 const notificationsUnread = live?.inbox ?? shell.inbox?.unread ?? 0;
1901 const unread = { notifications: notificationsUnread, chat: chatUnread.unread, mentions: chatUnread.mentions };
1902
1903 // Folding the sidebar away on a computer is remembered, so the next page is drawn the same from the server.
1904 const toggleSidebar = useCallback(() => {
1905 if (!window.matchMedia("(min-width: 1024px)").matches) {
1906 setDrawer((open) => !open);
1907 return;
1908 }
1909 setClosed((was) => {
1910 document.cookie = sidebarCookie(!was, window.location.protocol === "https:");
1911 return !was;
1912 });
1913 }, []);
1914 useSidebarShortcut(useCallback(() => {
1915 if (panel) toggleSidebar();
1916 }, [panel, toggleSidebar]));
1917
1918 const inline = panel != null && !closed;
1919 const sidebarNode = () => {
1920 if (!panel) return null;
1921 if (!ws) return panel === "notifications" ? <NotificationsSidebar counts={shell.inbox ?? null} /> : <AccountSidebar username={user.username} />;
1922 switch (panel) {
1923 case "code":
1924 return <CodeSidebar user={user} shell={shell} missing={missing} />;
1925 case "chat":
1926 return <ChatSidebar slug={ws.slug} />;
1927 case "artifacts":
1928 return <FoliosSidebar slug={ws.slug} />;
1929 case "notifications":
1930 return <NotificationsSidebar counts={shell.inbox ?? null} />;
1931 case "people":
1932 return <PeopleSidebar slug={ws.slug} />;
1933 case "workspace":
1934 return <WorkspaceSidebar slug={ws.slug} owner={ws.role === "owner"} />;
1935 case "account":
1936 return <AccountSidebar username={user.username} />;
1937 }
1938 };
1939 const sidebarKey = useSidebarKey();
1940 // Search or jump to sits at the top of the sidebar, except in Chat and
1941 // Artifacts, whose sidebars search their own lists: there it stays in the bar.
1942 const sidebarSearch = panel != null && panel !== "chat" && panel !== "artifacts";
1943 // The sidebar's head: the workspace and its switcher, the way to fold the
1944 // sidebar or close the drawer, and search, which opens the palette.
1945 const sidebarTop = (inDrawer: boolean) => (
1946 <SidebarHeader className="gap-1 px-2 pt-0 pb-2">
1947 <div className="flex h-14 shrink-0 items-center gap-1">
1948 {ws ? (
1949 <WorkspaceSwitcher user={user} workspace={ws} />
1950 ) : (
1951 <Link to="/" aria-label="g1t" className="mr-auto flex h-9 items-center rounded-md px-2">
1952 <Logo className="text-[1.125rem]" />
1953 </Link>
1954 )}
1955 {inDrawer ? (
1956 <Button type="button" aria-label="Close menu" onClick={() => setDrawer(false)} variant="ghost" size="icon-sm" className="text-faint">
1957 <X size={16} />
1958 </Button>
1959 ) : (
1960 <SidebarTrigger hint={`Hide the sidebar (${sidebarKey})`} className="text-faint" />
1961 )}
1962 </div>
1963 {sidebarSearch && <SearchButton place="sidebar" onClick={() => setPalette(true)} />}
1964 </SidebarHeader>
1965 );
1966
1967 // On a phone (below 768px): the bottom bar, and a conversation full screen.
1968 const conversation = isConversation(going ?? pathname);
1969 // Where the page panel starts: 8px past the rail (56px), or 8px past the sidebar (56 + 240px) when it is open.
1970 // The page starts where the rail (3.5rem) and, open, the sidebar (15rem) end.
1971 const pad = ws ? (inline ? "md:pl-14 lg:pl-74" : "md:pl-14") : inline ? "lg:pl-60" : "";
1972
1973 return (
1974 <SidebarProvider open={!closed} onOpenChange={(open) => setClosed(!open)} openMobile={drawer} onOpenMobileChange={setDrawer} toggleSidebar={toggleSidebar}>
1975 <Progress />
1976 {ws && (
1977 <div className="fixed top-(--frame-top) bottom-0 left-0 z-40 hidden md:block">
1978 <Rail workspace={ws} pins={shell.pins ?? []} unread={unread} account={<AccountMenu user={user} />} />
1979 </div>
1980 )}
1981 {panel && (
1982 <Sidebar
1983 role="complementary"
1984 aria-label={`${MODE_MENU[panel]} sidebar`}
1985 className={`fixed top-(--frame-top) bottom-0 z-40 max-lg:hidden ${ws ? "left-14" : "left-0"}`}
1986 >
1987 {sidebarTop(false)}
1988 <div className="min-h-0 grow">{sidebarNode()}</div>
1989 </Sidebar>
1990 )}
1991 {/* The drawer is a sheet: a dialog that holds focus, closes on Escape or
1992 a tap outside, and gives focus back to the button that opened it. */}
1993 {panel && (
1994 <SidebarMobile title={`${MODE_MENU[panel]} menu`} className="pb-[env(safe-area-inset-bottom)] max-md:[&_nav_a]:min-h-10">
1995 {sidebarTop(true)}
1996 <div className="min-h-0 grow">{sidebarNode()}</div>
1997 </SidebarMobile>
1998 )}
1999
2000 <div className={`min-h-dvh pt-(--frame-top) pb-(--tabbar-h) ${pad}`}>
2001 {/* The top bar always has its line, so a page's own header (data-page-head: a conversation's, a project's,
2002 a sticky one under an open artifact) sits under it as its own band. */}
2003 <div className="flex min-h-[calc(100dvh-var(--frame-top)-var(--tabbar-h))] min-w-0 flex-col bg-bg">
2004 <header
2005 className={`sticky top-(--frame-top) z-30 flex h-14 items-center gap-1 border-b border-line bg-bg pr-2 pl-2 sm:pr-3 ${inline ? "lg:pl-3.5" : ""} ${conversation ? "max-md:hidden" : ""}`}
2006 >
2007 {panel && (
2008 <SidebarTrigger
2009 hint={`Show the sidebar (${sidebarKey})`}
2010 aria-label={drawer ? "Hide the sidebar" : "Show the sidebar"}
2011 aria-expanded={drawer}
2012 className={`max-md:size-11 ${inline ? "lg:hidden" : ""}`}
2013 />
2014 )}
2015 {ws && (
2016 <span className={`flex min-w-0 shrink items-center gap-1.5 ${inline ? "lg:hidden" : ""}`}>
2017 <WorkspaceSwitcher user={user} workspace={ws} compact />
2018 <span aria-hidden="true" className="text-line-strong">
2019 /
2020 </span>
2021 </span>
2022 )}
2023 <Breadcrumbs pathname={pathname} missing={missing} repo={shell.repo} workspace={ws?.slug ?? null} />
2024 {/* Search, Ask, then the bell and Create new: one height, one rhythm. */}
2025 <div className="ml-auto flex shrink-0 items-center gap-1 md:gap-1.5">
2026 {/* With the sidebar open, search is at its top. */}
2027 {!titleSearch && (
2028 <span className={`flex ${inline && sidebarSearch ? "lg:hidden" : ""}`}>
2029 <SearchButton place="bar" onClick={() => setPalette(true)} />
2030 </span>
2031 )}
2032 {ws && <AskButton key={ws.slug} slug={ws.slug} />}
2033 <Separator orientation="vertical" className="mx-1 data-[orientation=vertical]:h-5 max-md:hidden" />
2034 {/* On a phone, Notifications is in the bottom bar. */}
2035 <span className="flex max-md:hidden">
2036 <NotificationsBell counts={shell.inbox ? { ...shell.inbox, unread: notificationsUnread } : null} />
2037 </span>
2038 <CreateMenu shell={shell} />
2039 {/* Without a workspace there is no rail: the account is here. */}
2040 {!ws && <AccountMenu user={user} side="bottom" />}
2041 </div>
2042 </header>
2043 {banner}
2044 <main id="content" tabIndex={-1} {...leaving} className={`min-w-0 grow outline-none ${leaving.className}`}>
2045 <InMain.Provider value={true}>{children}</InMain.Provider>
2046 </main>
2047 </div>
2048 </div>
2049 {ws && <BottomBar user={user} workspace={ws} pins={shell.pins ?? []} unread={unread} onReselect={panel ? () => setDrawer(true) : undefined} />}
2050 <CommandPalette open={palette} onOpenChange={setPalette} commands={commands} repo={shell.repo ? `${shell.repo.namespace}/${shell.repo.name}` : null} />
2051 </SidebarProvider>
2052 );
2053}
2054
2055/** Create new: a project, an issue in the one you are in, a workspace or a team. */
2056function CreateMenu({ shell }: { shell: ShellData }) {
2057 return (
2058 <DropdownMenu>
2059 <Hint label="Create new">
2060 <DropdownMenuTrigger asChild>
2061 <Button variant="ghost" size="bar" aria-label="Create new" className="gap-0.5 px-1.5 text-fg/90">
2062 <Plus size={17} className="max-md:size-5" />
2063 <ChevronDown size={12} className="text-faint max-md:hidden" />
2064 </Button>
2065 </DropdownMenuTrigger>
2066 </Hint>
2067 <DropdownMenuContent align="end" className="min-w-52">
2068 {shell.repo && (
2069 <>
2070 <DropdownMenuLabel className="truncate">In {shell.repo.name}</DropdownMenuLabel>
2071 <DropdownMenuItem asChild>
2072 <Link to={`/${shell.repo.namespace}/${shell.repo.name}/issues/new`}>
2073 <CircleDot />
2074 New issue
2075 </Link>
2076 </DropdownMenuItem>
2077 <DropdownMenuSeparator />
2078 </>
2079 )}
2080 <DropdownMenuItem asChild>
2081 <Link to="/new">
2082 <Box />
2083 New project
2084 </Link>
2085 </DropdownMenuItem>
2086 <DropdownMenuItem asChild>
2087 <Link to="/new/github">
2088 <GitBranch />
2089 Import from GitHub
2090 </Link>
2091 </DropdownMenuItem>
2092 {/* A team in the workspace you are in, for whoever it lets create one. A new workspace is made from the workspace switcher in the rail. */}
2093 {shell.workspace && <DropdownMenuSeparator />}
2094 {shell.workspace &&
2095 (mayCreateTeams(shell.workspace.team_creation, shell.workspace.role) ? (
2096 <DropdownMenuItem asChild>
2097 <Link to={`/${shell.workspace.slug}/-/teams/new`}>
2098 <UsersRound />
2099 New team
2100 </Link>
2101 </DropdownMenuItem>
2102 ) : (
2103 <DropdownMenuItem disabled>
2104 <UsersRound />
2105 New team
2106 <span className="ml-auto pl-3 text-xs text-faint">Owners only</span>
2107 </DropdownMenuItem>
2108 ))}
2109 </DropdownMenuContent>
2110 </DropdownMenu>
2111 );
2112}