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.

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