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,322 linesCodeBlameRaw
1import { Database, Activity, BarChart3, 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, 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, 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 {/* Its work items: the workspace's Work list, filtered to it. */}
836 {shows.has("work") && (
837 <SidebarLink to={repoWorkPath(repo.namespace, repo.name)} icon={<ListTodo size={15} />} count={repo.items}>
838 Work
839 </SidebarLink>
840 )}
841 {shows.has("pulls") && (
842 <SidebarLink to={`${base}/pulls`} also={[`${base}/pull`, `${base}/queue`, `${base}/sessions`]} icon={<GitPullRequest size={15} />} count={repo.pulls}>
843 Pull requests
844 </SidebarLink>
845 )}
846 {shows.has("actions") && (
847 <SidebarLink to={`${base}/actions`} icon={<PlayCircle size={15} />}>
848 Workflows
849 </SidebarLink>
850 )}
851 </NavRows>
852 <Rule />
853 <NavRows>
854 {shows.has("deployments") ? (
855 <SidebarLink to={`${base}/deployments`} also={[`${base}/settings/deployments`, ...soonPaths(base, "Deployments")]} icon={<Rocket size={15} />}>
856 Deployments
857 </SidebarLink>
858 ) : null}
859 {repo.member && <ProjectSoonRow base={base} feature="analytics" icon={<ChartLine size={15} />} />}
860 {shows.has("observability") && (
861 <SidebarLink to={`${base}/observability`} also={soonPaths(base, "Observability")} icon={<Activity size={15} />}>
862 Observability
863 </SidebarLink>
864 )}
865 {repo.member && <ProjectSoonRow base={base} feature="firewall" icon={<BrickWall size={15} />} />}
866 {repo.member && <ProjectSoonRow base={base} feature="flags" icon={<Flag size={15} />} />}
867 {shows.has("security") ? (
868 <SidebarLink to={`${base}/security`} also={soonPaths(base, "Security")} icon={<ShieldCheck size={15} />}>
869 Security
870 </SidebarLink>
871 ) : null}
872 <SidebarLink
873 to={`${base}/contributors`}
874 also={[`${base}/activity`, `${base}/stargazers`, ...soonPaths(base, "Insights")]}
875 icon={<BarChart3 size={15} />}
876 >
877 Insights
878 </SidebarLink>
879 </NavRows>
880 {repo.member && (
881 <>
882 <Rule />
883 <NavRows>
884 {PROJECT_OPERATIONS.filter((page) => shows.has(page)).map((page) => {
885 const link = PROJECT_PAGE_LINKS[page];
886 const icons = { secrets: <KeyRound size={15} />, environments: <Layers size={15} />, domains: <Globe size={15} />, runners: <ServerCog size={15} />, webhooks: <Webhook size={15} /> };
887 return <SidebarLink key={page} to={`${base}/${link.path}`} icon={icons[page]}>{link.label}</SidebarLink>;
888 })}
889 <ProjectSoonRow base={base} feature="storage" icon={<Database size={15} />} />
890 <ProjectSoonRow base={base} feature="daemons" icon={<Repeat size={15} />} />
891 </NavRows>
892 </>
893 )}
894 {(repo.settings ?? shows.has("settings")) && (
895 <>
896 <Rule />
897 <NavRows>
898 <SidebarLink to={`${base}/settings`} end icon={<Settings size={15} />} drill>
899 Settings
900 </SidebarLink>
901 </NavRows>
902 </>
903 )}
904 </nav>
905 );
906}
907
908/**
909 * Administrative settings: repository policy, access and workflow permissions.
910 * Day-to-day operations stay in the main project menu.
911 */
912function RepoSettingsMenu({ repo }: { repo: MenuRepo }) {
913 const base = `/${repo.namespace}/${repo.name}`;
914 // Each page shows to the roles that can use it, once the role is known.
915 const shows = (page: string) => !repo.can || repo.can[SETTINGS_CAPABILITY[page] ?? "administer"];
916 const guarded = shows("guardrails");
917 return (
918 <nav aria-label={`${repo.namespace}/${repo.name} settings`} className={PANEL}>
919 <BackRow to={base} label="Settings" context={`${repo.namespace}/${repo.name}`} />
920 {shows("") && (
921 <NavRows className="mt-2">
922 <SidebarLink to={`${base}/settings`} end icon={<Settings size={15} />}>
923 General
924 </SidebarLink>
925 </NavRows>
926 )}
927 {guarded && (
928 <>
929 <Rule />
930 <NavRows>
931 {shows("guardrails") && (
932 <SidebarLink to={`${base}/settings/guardrails`} icon={<ShieldCheck size={15} />}>
933 Guardrails
934 </SidebarLink>
935 )}
936 </NavRows>
937 </>
938 )}
939 <Rule />
940 <NavRows>
941 {shows("repository") && (
942 <SidebarLink to={`${base}/settings/repository`} icon={<BookMarked size={15} />}>
943 Repository
944 </SidebarLink>
945 )}
946 {shows("access") && (
947 <SidebarLink to={`${base}/settings/access`} icon={<Users size={15} />}>
948 Access
949 </SidebarLink>
950 )}
951 {shows("keys") && (
952 <SidebarLink to={`${base}/settings/keys`} icon={<KeyRound size={15} />}>
953 Deploy keys
954 </SidebarLink>
955 )}
956 {shows("branches") && (
957 <SidebarLink to={`${base}/settings/branches`} icon={<GitBranch size={15} />}>
958 Branches and merging
959 </SidebarLink>
960 )}
961 {shows("rules") && (
962 <SidebarLink to={`${base}/settings/rules`} icon={<Scale size={15} />}>
963 Rules
964 </SidebarLink>
965 )}
966
967 {shows("actions") && (
968 <SidebarLink to={`${base}/settings/actions`} icon={<PlayCircle size={15} />}>
969 Actions
970 </SidebarLink>
971 )}
972
973
974
975 </NavRows>
976 </nav>
977 );
978}
979
980/** Your own settings, drilled into from Your settings: one page each. */
981function AccountSettingsMenu({ username }: { username: string }) {
982 const link = (page: AccountSettingsPage, icon: ReactNode) => (
983 <SidebarLink to={`/settings/${page}`} icon={icon}>
984 {ACCOUNT_SETTINGS[page].title}
985 </SidebarLink>
986 );
987 return (
988 <nav aria-label="Your settings" className={PANEL}>
989 <BackRow to="/" label="Your settings" context={username} />
990 <NavRows className="mt-2">
991 {link("profile", <CircleUserRound size={15} />)}
992 {link("emails", <Mail size={15} />)}
993 {link("invites", <Ticket size={15} />)}
994 </NavRows>
995 <Rule />
996 <NavRows>
997 {link("keys", <Fingerprint size={15} />)}
998 {link("tokens", <KeyRound size={15} />)}
999 </NavRows>
1000 <Rule />
1001 <NavRows>
1002 {link("integrations", <Blocks size={15} />)}
1003 {link("github", <GithubMark className="size-3.75" />)}
1004 {link("applications", <Plug size={15} />)}
1005 </NavRows>
1006 <Rule />
1007 <NavRows>
1008 {link("two-factor", <ShieldCheck size={15} />)}
1009 {link("security-log", <History size={15} />)}
1010 </NavRows>
1011 </nav>
1012 );
1013}
1014
1015/**
1016 * Code's sidebar: its Overview, the projects, what spans them and what is
1017 * coming; in a project, drilled into the project's own list, and its
1018 * settings one level further in. The address says which, so a link
1019 * straight to a project opens the sidebar already drilled in.
1020 */
1021function CodeSidebar({
1022 user,
1023 shell,
1024 missing = false,
1025 browsing = null,
1026}: {
1027 user: User;
1028 shell: ShellData;
1029 /** The page is a 404: the address names nothing the viewer can see. */
1030 missing?: boolean;
1031 /** g1t beyond the viewer's workspaces (lib/workspace-nav.ts `browsingOf`): Explore's list in place of Code's. */
1032 browsing?: { owner: BrowsedOwner | null } | null;
1033}) {
1034 const ws = shell.workspace;
1035 const location = useLocation();
1036 const destination = useSidebarLocation();
1037 // Where the sidebar is drilled to follows the page being gone to, so it
1038 // moves as the link is followed, not once the page arrives.
1039 const target = destination.pathname;
1040 // On a 404, the address is not a place: no list is drilled into from it,
1041 // except the project's own when the project is real and visible and only
1042 // something inside it is missing (a file, a commit, a work item).
1043 const lost = missing && destination.key === location.key;
1044 const active = shell.repo;
1045 // In a repository, or on the way into one, its own list.
1046 const repoPath = /^\/([^/]+)\/([^/-][^/]*)(\/|$)/.exec(target);
1047 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"]);
1048 // An invitation to a repository is answered before its menu means anything.
1049 const inRepo =
1050 repoPath != null &&
1051 !reserved.has(repoPath[1]) &&
1052 repoPath[2] !== "-" &&
1053 !/^\/[^/]+\/[^/]+\/invitations\/?$/.test(target) &&
1054 (!lost || sameRepo(active, { namespace: repoPath[1]!, name: repoPath[2]! }));
1055 // A project's settings, one level further in.
1056 const inRepoSettings = inRepo && REPO_SETTINGS_PAGE.test(target) && projectPageAt(target.split("/").slice(3).join("/")) === "settings";
1057 // The repository the menu is for: the one loaded if it is the one being
1058 // gone to, else what the address says, at once.
1059 const targetRepo = inRepo && repoPath ? { namespace: repoPath[1], name: repoPath[2] } : null;
1060 const guessed: MenuRepo | null = targetRepo
1061 ? sameRepo(active, targetRepo)
1062 ? active
1063 : {
1064 ...targetRepo,
1065 member: (user.workspaces ?? []).some((m) => m.slug === targetRepo.namespace.toLowerCase()),
1066 }
1067 : null;
1068 // The viewer's role there, from the repository's page once it has loaded.
1069 const page = useRouteLoaderData("routes/repo/layout") as
1070 | { repo?: { namespace: string; name: string }; access?: ViewerAccess }
1071 | undefined;
1072 const menuRepo: MenuRepo | null =
1073 guessed && page?.access && page.repo && sameRepo(page.repo, guessed)
1074 ? { ...guessed, member: page.access.insider, settings: seesSettings(page.access), can: page.access.can }
1075 : guessed;
1076
1077 // The way from Code's list (or Explore's, browsing) to the one shown.
1078 const main = browsing ? <BrowseMenu user={user} owner={browsing.owner} /> : ws ? <CodeMenu shell={shell} slug={ws.slug} /> : null;
1079 const trail: Level[] = [{ key: browsing ? "browse" : "main", node: main }];
1080 if (menuRepo) {
1081 const key = `repo:${menuRepo.namespace}/${menuRepo.name}`.toLowerCase();
1082 // Out of a project: to its workspace's projects when they are yours, or
1083 // when browsing, to the projects of the workspace it is in.
1084 const home = (user.workspaces ?? []).find((m) => m.slug === menuRepo.namespace.toLowerCase());
1085 const back = home
1086 ? { to: `/${home.slug}/-/projects`, label: "All projects" }
1087 : browsing
1088 ? { to: `/${menuRepo.namespace}/-/projects`, label: "Projects", context: menuRepo.namespace }
1089 : { to: ws ? `/${ws.slug}/-/overview` : "/explore", label: "Code" };
1090 trail.push({
1091 key,
1092 node: (
1093 <RepoMenu
1094 repo={menuRepo}
1095 isPrivate={[...shell.repos, ...(shell.shared ?? [])].some((repo) => sameRepo(repo, menuRepo) && repo.isPrivate)}
1096 back={back}
1097 />
1098 ),
1099 });
1100 if (inRepoSettings) trail.push({ key: `${key}:settings`, node: <RepoSettingsMenu repo={menuRepo} /> });
1101 }
1102
1103 return (
1104 <div className="flex h-full flex-col">
1105 {browsing && ws && (
1106 <>
1107 <BackToWorkspace workspace={ws} />
1108 <Rule />
1109 </>
1110 )}
1111 <ModeHeader title={browsing?.owner?.kind === "workspace" ? "Workspace" : browsing ? "Explore" : "Code"} />
1112 <Drill trail={trail} />
1113 </div>
1114 );
1115}
1116
1117/**
1118 * Browsing, the way back to the workspace you are in: its Home, at the top
1119 * of Explore's sidebar, at every level of it.
1120 */
1121function BackToWorkspace({ workspace }: { workspace: Membership }) {
1122 const name = displayName(workspace);
1123 return (
1124 <NavRows className="pt-0">
1125 <SidebarMenuItem>
1126 <SidebarMenuButton asChild className="gap-2 pl-1 font-medium text-fg">
1127 <Link to={homePagePath(workspace.slug)} prefetch="intent" aria-label={`Back to ${name}: Home`}>
1128 <ChevronLeft className="text-faint transition-transform group-hover/menu-button:-translate-x-0.5 group-hover/menu-button:text-muted" />
1129 <Avatar name={workspace.slug} image={workspace.avatar} size={18} square />
1130 <span className="min-w-0 truncate">Back to {name}</span>
1131 </Link>
1132 </SidebarMenuButton>
1133 </SidebarMenuItem>
1134 </NavRows>
1135 );
1136}
1137
1138/** Whose page is being browsed, as the page itself names them once it has loaded: a workspace's or a person's. */
1139function useBrowsedOwner(owner: BrowsedOwner | null): { name: string; avatar: string | null } | null {
1140 const workspace = useRouteLoaderData("routes/workspace/layout") as { workspace?: { slug: string; name?: string | null; avatar?: string | null } } | undefined;
1141 const person = useRouteLoaderData("routes/user") as { profile?: { username: string; displayUsername?: string | null; avatar: string | null } } | undefined;
1142 if (!owner) return null;
1143 if (owner.kind === "person") {
1144 const profile = person?.profile?.username.toLowerCase() === owner.name.toLowerCase() ? person.profile : null;
1145 return { name: `@${profile ? shownUsername(profile) : owner.name}`, avatar: profile?.avatar ?? null };
1146 }
1147 const page = workspace?.workspace?.slug.toLowerCase() === owner.name.toLowerCase() ? workspace.workspace : null;
1148 return { name: page?.name?.trim() || owner.name, avatar: page?.avatar ?? null };
1149}
1150
1151/**
1152 * Explore's list, beside g1t beyond your workspaces (lib/workspace-nav.ts
1153 * `browsingOf`): public projects across g1t, recently active and new,
1154 * search, and what you starred; then whose page this is, with their own
1155 * pages. A project of theirs drills into its own list, as in Code.
1156 */
1157function BrowseMenu({ user, owner }: { user: User; owner: BrowsedOwner | null }) {
1158 const location = useSidebarLocation();
1159 const path = pagePath(location.pathname);
1160 const query = new URLSearchParams(location.search);
1161 const atExplore = path === "/explore";
1162 const fresh = atExplore && query.get("sort") === "new";
1163 const mine = profilePath(user.username);
1164 // A profile's tab is its third segment: `/u/ada/stars`.
1165 const [, profileOf, profileTab] = path.toLowerCase().split("/").filter(Boolean);
1166 const atMine = path.toLowerCase().startsWith("/u/") && profileOf === user.username.toLowerCase();
1167 const stars = atMine && profileTab === "stars";
1168 const shown = useBrowsedOwner(owner);
1169 const workspace = useRouteLoaderData("routes/workspace/layout") as
1170 | { workspace: { slug: string }; projects?: (ShortcutProject & { title: string })[] }
1171 | undefined;
1172 if (owner?.kind === "workspace" && shown) {
1173 const base = `/${owner.name}`;
1174 const projects = workspace?.workspace.slug.toLowerCase() === owner.name.toLowerCase() ? workspace.projects ?? [] : [];
1175 return (
1176 <nav aria-label={`${owner.name} workspace`} className={PANEL}>
1177 <NavRows>
1178 <SidebarLink to={base} icon={<Avatar name={owner.name} image={shown.avatar} size={16} square />} current={false}>
1179 {shown.name}
1180 </SidebarLink>
1181 <SidebarLink to={base} icon={<LayoutDashboard size={15} />} current={path.toLowerCase() === base.toLowerCase()}>
1182 Overview
1183 </SidebarLink>
1184 </NavRows>
1185 <Rule />
1186 <NavGroup title="Projects">
1187 {projects.slice(0, 8).map((project) => (
1188 <SidebarLink key={project.name} to={`/${project.namespace}/${project.name}`} icon={<ProjectIcon kind={project.kind} isPrivate={project.isPrivate} lockPrivate size={15} />}>
1189 {project.title}
1190 </SidebarLink>
1191 ))}
1192 <SidebarLink to={`${base}/-/projects`} icon={<LayoutGrid size={15} />} count={projects.length || undefined}>
1193 All projects
1194 </SidebarLink>
1195 </NavGroup>
1196 <Rule />
1197 <NavRows>
1198 <SidebarLink to={`${base}/-/packages`} icon={<Package size={15} />}>Packages</SidebarLink>
1199 </NavRows>
1200 <Rule />
1201 <NavRows>
1202 <SidebarLink to="/explore" icon={<Compass size={15} />}>Explore</SidebarLink>
1203 </NavRows>
1204 </nav>
1205 );
1206 }
1207 return (
1208 <nav aria-label="Explore" className={PANEL}>
1209 <NavRows>
1210 <SidebarLink to="/explore" icon={<Compass size={15} />} current={atExplore && !fresh}>
1211 Recently active
1212 </SidebarLink>
1213 <SidebarLink to="/explore?sort=new" icon={<Sparkles size={15} />} current={fresh}>
1214 New projects
1215 </SidebarLink>
1216 <SidebarLink to="/search" icon={<Search size={15} />} current={path === "/search"}>
1217 Search
1218 </SidebarLink>
1219 </NavRows>
1220 <Rule />
1221 <NavRows>
1222 <SidebarLink to={profilePath(user.username, "stars")} icon={<Star size={15} />} current={stars}>
1223 Your stars
1224 </SidebarLink>
1225 <SidebarLink to={mine} icon={<CircleUserRound size={15} />} current={atMine && !stars}>
1226 Your profile
1227 </SidebarLink>
1228 </NavRows>
1229 {owner && shown && (
1230 <>
1231 <Rule />
1232 <NavGroup title="You are viewing">
1233 {owner.kind === "person" && (
1234 <>
1235 <SidebarLink
1236 to={`/u/${owner.name}`}
1237 icon={<Avatar name={owner.name} image={shown.avatar} size={16} />}
1238 current={profileTab !== "stars"}
1239 >
1240 {shown.name}
1241 </SidebarLink>
1242 <SidebarLink to={profilePath(owner.name, "stars")} icon={<Star size={15} />} current={profileTab === "stars"}>
1243 Stars
1244 </SidebarLink>
1245 </>
1246 )}
1247 </NavGroup>
1248 </>
1249 )}
1250 </nav>
1251 );
1252}
1253
1254/**
1255 * A mode's sidebar heading: its name, quiet, under the workspace's
1256 * switcher, with what it makes at the end.
1257 */
1258export function ModeHeader({ title, action }: { title: ReactNode; action?: ReactNode }) {
1259 return (
1260 <div className="flex h-8 shrink-0 items-center gap-1 pr-2 pl-3">
1261 <SidebarGroupLabel asChild className="min-w-0 grow truncate px-1">
1262 <h2>{title}</h2>
1263 </SidebarGroupLabel>
1264 {action}
1265 </div>
1266 );
1267}
1268
1269/**
1270 * Code's own list (beside the rail): only code. Its Overview (Mission
1271 * control's code panels), the projects, what spans them, and what is
1272 * coming. The workspace's people, money and settings are elsewhere.
1273 */
1274function CodeMenu({ shell, slug }: { shell: ShellData; slug: string }) {
1275 const { pathname: path } = useSidebarLocation();
1276 const at = (page: string) => path === `/${slug}/-/${page}` || path.startsWith(`/${slug}/-/${page}/`);
1277 const shared = shell.shared ?? [];
1278 return (
1279 <nav aria-label="Code" className={PANEL}>
1280 <NavRows>
1281 <SidebarLink to={`/${slug}/-/overview`} icon={<LayoutDashboard size={15} />} current={at("overview")}>
1282 Overview
1283 </SidebarLink>
1284 </NavRows>
1285 <Rule />
1286 <SidebarProjects slug={slug} shell={shell} current={at("projects")} />
1287 <Rule />
1288 <NavRows>
1289 <SidebarLink to={`/${slug}/-/security`} icon={<ShieldCheck size={15} />} current={at("security") && !at("security/settings")}>
1290 Security
1291 </SidebarLink>
1292 <SidebarLink to={`/${slug}/-/packages`} icon={<Package size={15} />} current={at("packages")}>
1293 Packages
1294 </SidebarLink>
1295 <SidebarLink to={`/${slug}/-/insights`} icon={<TrendingUp size={15} />} current={at("insights")}>
1296 Insights
1297 </SidebarLink>
1298 </NavRows>
1299 <Rule />
1300 <NavRows>
1301 {/* Public repositories beyond this workspace's own. */}
1302 <SidebarLink to="/explore" icon={<Compass size={15} />} current={path === "/explore" || path.startsWith("/explore/")}>
1303 Explore
1304 </SidebarLink>
1305 </NavRows>
1306 {shared.length > 0 && (
1307 <>
1308 <Rule />
1309 <NavGroup title="Shared with you">
1310 {shared.map((repo) => (
1311 <SidebarLink
1312 key={`${repo.namespace}/${repo.name}`}
1313 to={`/${repo.namespace}/${repo.name}`}
1314 icon={repo.isPrivate ? <Lock size={15} /> : <Box size={15} />}
1315 drill="hover"
1316 >
1317 <span className="font-mono text-faint">{repo.namespace}/</span>
1318 {repo.name}
1319 </SidebarLink>
1320 ))}
1321 </NavGroup>
1322 </>
1323 )}
1324 </nav>
1325 );
1326}
1327
1328/** The icon of each of Workspace mode's pages, by its key (lib/workspace-nav.ts). */
1329const WORKSPACE_PAGE_ICONS: Record<string, ReactNode> = {
1330 settings: <Settings size={15} />,
1331 members: <Users size={15} />,
1332 invitations: <Mail size={15} />,
1333 permissions: <ShieldCheck size={15} />,
1334 tokens: <KeyRound size={15} />,
1335 "personal-access-tokens": <UserRoundKey size={15} />,
1336 usage: <BarChart3 size={15} />,
1337 billing: <CreditCard size={15} />,
1338 runners: <ServerCog size={15} />,
1339 repositories: <BookMarked size={15} />,
1340 actions: <PlayCircle size={15} />,
1341 secrets: <Lock size={15} />,
1342 webhooks: <Webhook size={15} />,
1343 "chat-settings": <MessagesSquare size={15} />,
1344 emoji: <Smile size={15} />,
1345 "security-settings": <Shield size={15} />,
1346 guardrails: <Gauge size={15} />,
1347 rules: <Scale size={15} />,
1348 audit: <History size={15} />,
1349 integrations: <Plug size={15} />,
1350 ai: <Sparkles size={15} />,
1351};
1352
1353/**
1354 * A group of Workspace mode's rows that folds: its name is the button, with
1355 * a chevron that turns when it is open. The group holding the current page
1356 * is always open, and its button does nothing. Every group starts open, so
1357 * the server and the browser draw the same list.
1358 */
1359function FoldingGroup({ title, current, children }: { title: string; current: boolean; children: ReactNode }) {
1360 const [open, setOpen] = useState(true);
1361 return (
1362 <Collapsible open={open || current} onOpenChange={setOpen}>
1363 <SidebarGroup>
1364 <CollapsibleTrigger
1365 disabled={current}
1366 aria-label={`${title}: ${open || current ? "fold" : "unfold"}`}
1367 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"
1368 >
1369 <span>{title}</span>
1370 {!current && <ChevronRight size={12} aria-hidden="true" className="text-faint/70" />}
1371 </CollapsibleTrigger>
1372 <CollapsibleContent>
1373 <SidebarGroupContent>
1374 <SidebarMenu>{children}</SidebarMenu>
1375 </SidebarGroupContent>
1376 </CollapsibleContent>
1377 </SidebarGroup>
1378 </Collapsible>
1379 );
1380}
1381
1382/**
1383 * The Workspace mode's sidebar: the workspace's settings area, every page
1384 * one click away. Its overview, then the groups in lib/workspace-nav.ts
1385 * (General, Access, Money, Compute, Code, Chat, Security, Integrations),
1386 * each folding, the one you are in held open. Pages only owners open are
1387 * left out for members, and a group with none left goes with them.
1388 */
1389export function WorkspaceSidebar({ slug, owner }: { slug: string; owner: boolean }) {
1390 const { pathname: path } = useSidebarLocation();
1391 const here = workspaceSettingsPage(path, slug);
1392 const overview = path === `/${slug}/-/workspace` || path.startsWith(`/${slug}/-/workspace/`);
1393 const shown = (page: WorkspaceSettingsPage) => owner || !page.owner;
1394 return (
1395 <div className="flex h-full flex-col">
1396 <ModeHeader title="Workspace" />
1397 <nav aria-label="Workspace" className={PANEL}>
1398 <NavRows>
1399 <SidebarLink to={`/${slug}/-/workspace`} icon={<LayoutGrid size={15} />} current={overview}>
1400 Overview
1401 </SidebarLink>
1402 </NavRows>
1403 {WORKSPACE_SETTINGS_GROUPS.filter((group) => group.pages.some(shown)).map((group) => (
1404 <Fragment key={group.key}>
1405 <Rule />
1406 <FoldingGroup title={group.title} current={here?.group === group.key}>
1407 {group.pages.filter(shown).map((page) => (
1408 <SidebarLink
1409 key={page.key}
1410 to={`/${slug}/-/${page.path}`}
1411 icon={WORKSPACE_PAGE_ICONS[page.key] ?? <Settings size={15} />}
1412 current={here?.page === page.key}
1413 >
1414 {page.label}
1415 </SidebarLink>
1416 ))}
1417 </FoldingGroup>
1418 </Fragment>
1419 ))}
1420 </nav>
1421 </div>
1422 );
1423}
1424
1425/**
1426 * Work's sidebar, and its menu on a phone (the Work tab tapped again):
1427 * the views people keep coming back to, saved in the address (open, yours,
1428 * closed), then the workspace's labels and milestones, which Work holds.
1429 */
1430function WorkSidebar({ slug, username }: { slug: string; username: string }) {
1431 const { pathname: path, search } = useSidebarLocation();
1432 const list = workPath(slug);
1433 const query = new URLSearchParams(search);
1434 const onList = path === list;
1435 const view = (want: Record<string, string>) =>
1436 onList && [...query.keys()].every((key) => key in want) && Object.entries(want).every(([key, value]) => query.get(key) === value);
1437 const at = (page: string) => path === workPath(slug, page) || path.startsWith(`${workPath(slug, page)}/`);
1438 return (
1439 <div className="flex h-full flex-col">
1440 <ModeHeader title="Work" />
1441 <nav aria-label="Work" className={PANEL}>
1442 <NavRows>
1443 <SidebarLink to={list} icon={<ListTodo size={15} />} current={view({})}>
1444 Open
1445 </SidebarLink>
1446 <SidebarLink to={`${list}?assignee=${encodeURIComponent(username)}`} icon={<CircleUserRound size={15} />} current={view({ assignee: username })}>
1447 Assigned to you
1448 </SidebarLink>
1449 <SidebarLink to={`${list}?state=closed`} icon={<Check size={15} />} current={view({ state: "closed" })}>
1450 Closed
1451 </SidebarLink>
1452 <SidebarLink to={newItemPath(slug)} icon={<Plus size={15} />} current={at("new")}>
1453 New work item
1454 </SidebarLink>
1455 </NavRows>
1456 <Rule />
1457 <NavRows>
1458 <SidebarLink to={workPath(slug, "labels")} icon={<Ticket size={15} />} current={at("labels")}>
1459 Labels
1460 </SidebarLink>
1461 <SidebarLink to={workPath(slug, "milestones")} icon={<Flag size={15} />} current={at("milestones")}>
1462 Milestones
1463 </SidebarLink>
1464 </NavRows>
1465 </nav>
1466 </div>
1467 );
1468}
1469
1470/**
1471 * People's sidebar: everyone in the workspace and its teams. Who belongs, and
1472 * inviting people, is the workspace's: Workspace mode's Access group.
1473 */
1474function PeopleSidebar({ slug }: { slug: string }) {
1475 const { pathname: path } = useSidebarLocation();
1476 const at = (page: string) => path === `/${slug}/-/${page}` || path.startsWith(`/${slug}/-/${page}/`);
1477 return (
1478 <div className="flex h-full flex-col">
1479 <ModeHeader title="People" />
1480 <nav aria-label="People" className={PANEL}>
1481 <NavRows>
1482 <SidebarLink to={`/${slug}/-/people`} icon={<Users size={15} />} current={at("people")}>
1483 Everyone
1484 </SidebarLink>
1485 <SidebarLink to={`/${slug}/-/teams`} icon={<UsersRound size={15} />} current={at("teams")}>
1486 Teams
1487 </SidebarLink>
1488 </NavRows>
1489 </nav>
1490 </div>
1491 );
1492}
1493
1494/**
1495 * Notifications' sidebar: what you have not finished with, what you saved
1496 * and what is done; then why you were told, which narrows any of them.
1497 */
1498function NotificationsSidebar({ counts }: { counts: InboxCounts | null }) {
1499 const { pathname, search } = useSidebarLocation();
1500 const params = new URLSearchParams(search);
1501 // Saved and Done are paths (`/notifications/saved`); the rest narrows them.
1502 const view = notificationViewAt(pathname);
1503 const reason = inboxReason(params.get("reason"));
1504 const tab = params.get("tab");
1505 const address = (changes: { view?: string | null; reason?: string | null; before?: string | null }) =>
1506 notificationsAddress({ tab, view, reason, ...changes });
1507 const views = [
1508 { view: "inbox", label: "Everything", icon: <Bell size={15} />, count: counts?.unread },
1509 { view: "saved", label: "Saved", icon: <Bookmark size={15} /> },
1510 { view: "done", label: "Done", icon: <Check size={15} /> },
1511 ] as const;
1512 return (
1513 <div className="flex h-full flex-col">
1514 <ModeHeader title="Notifications" />
1515 <nav aria-label="Notifications" className={PANEL}>
1516 <NavRows>
1517 {views.map((entry) => (
1518 <SidebarLink
1519 key={entry.view}
1520 to={address({ view: entry.view === "inbox" ? null : entry.view, before: null })}
1521 icon={entry.icon}
1522 count={"count" in entry ? (entry.count ?? undefined) : undefined}
1523 current={view === entry.view}
1524 >
1525 {entry.label}
1526 </SidebarLink>
1527 ))}
1528 </NavRows>
1529 <Rule />
1530 <NavGroup title="Why you were told">
1531 {REASON_FILTERS.map((entry) => (
1532 <SidebarLink
1533 key={entry.reason ?? "any"}
1534 to={address({ reason: entry.reason, before: null })}
1535 icon={<span className="block size-3.75" />}
1536 current={reason === entry.reason}
1537 >
1538 {entry.reason == null ? "Any reason" : entry.label}
1539 </SidebarLink>
1540 ))}
1541 </NavGroup>
1542 </nav>
1543 </div>
1544 );
1545}
1546
1547/** Your own settings, beside the page: under the account menu, not any workspace's. */
1548export function AccountSidebar({ username }: { username: string }) {
1549 return (
1550 <div className="flex h-full flex-col">
1551 <ModeHeader title="Your account" />
1552 <div className="min-h-0 grow">
1553 <AccountSettingsMenu username={username} />
1554 </div>
1555 </div>
1556 );
1557}
1558
1559/** Words for the sections a path can end in. */
1560const SECTIONS: Record<string, string> = {
1561 milestones: "Milestones",
1562 labels: "Labels",
1563 pulls: "Pull requests",
1564 queue: "Merge queue",
1565 commits: "Commits",
1566 actions: "Workflows",
1567 soon: "Soon",
1568 deployments: "Deployments",
1569 repository: "Repository",
1570 access: "Access",
1571 invitations: "Invitation",
1572 repositories: "Repositories",
1573 branches: "Branches",
1574 tags: "Tags",
1575 compare: "Compare",
1576 code: "Files",
1577 secrets: "Secrets and variables",
1578 settings: "Settings",
1579 people: "People",
1580 members: "Members",
1581 permissions: "Permissions",
1582 projects: "Projects",
1583 teams: "Teams",
1584 tokens: "Access tokens",
1585 "personal-access-tokens": "Personal access tokens",
1586 usage: "Usage",
1587 billing: "Billing and plans",
1588 integrations: "Integrations",
1589 ai: "AI",
1590 webhooks: "Webhooks",
1591 emoji: "Emoji",
1592 domains: "Domains",
1593 guardrails: "Guardrails",
1594 rules: "Rules",
1595 audit: "Audit log",
1596 tree: "Files",
1597 blob: "Files",
1598 security: "Security",
1599 packages: "Packages",
1600 runners: "Runners",
1601 environments: "Environments",
1602 workflows: "Workflows",
1603 observability: "Observability",
1604 insights: "Insights",
1605 sessions: "Sessions",
1606 work: "Work",
1607 chat: "Chat",
1608 artifacts: "Artifacts",
1609 routines: "Routines",
1610 home: "Home",
1611 apps: "Apps",
1612 "code-access": "Code access",
1613 overview: "Overview",
1614 workspace: "Workspace",
1615};
1616
1617/** Settings pages whose name differs from the section's of the same word. */
1618const SETTINGS_SECTIONS: Record<string, string> = { branches: "Branches and merging", actions: "Actions" };
1619
1620/** Where the page is, as a trail of links: workspace / repository / section. */
1621function Breadcrumbs({
1622 pathname,
1623 missing,
1624 repo,
1625 workspace,
1626}: {
1627 pathname: string;
1628 missing?: boolean;
1629 repo?: ShellData["repo"];
1630 /** The workspace you are in: the switcher names it, so the trail starts after it. */
1631 workspace: string | null;
1632}) {
1633 // A 404 names nothing from the address, unless the project is real and
1634 // visible and only something inside it is missing.
1635 const visibleRepo = /^\/([^/]+)\/([^/-][^/]*)(\/|$)/.exec(pathname);
1636 if (missing && !(visibleRepo && sameRepo(repo ?? null, { namespace: visibleRepo[1]!, name: visibleRepo[2]! }))) {
1637 return <Here>Not found</Here>;
1638 }
1639 const parts = pathname.split("/").filter(Boolean);
1640 const reserved = ["settings", "explore", "new", "search", "workspaces", "policies", "security", "support", "status", "invite", "notifications"];
1641 if (parts.length === 0) return <Here>Home</Here>;
1642 // Your settings: Settings / Emails.
1643 if (parts[0] === "settings") {
1644 const page = accountSettingsPage(pathname);
1645 return <Trail trail={[{ label: "Settings", to: FIRST_SETTINGS_PAGE }, ...(page ? [{ label: ACCOUNT_SETTINGS[page].title, to: `/settings/${page}` }] : [])]} />;
1646 }
1647 if (reserved.includes(parts[0]!)) {
1648 const words: Record<string, string> = {
1649 settings: "Account",
1650 explore: "Explore",
1651 new: "New project",
1652 search: "Search",
1653 workspaces: "New workspace",
1654 policies: "Policies",
1655 security: "Security",
1656 support: "Support",
1657 status: "Status",
1658 invite: "Invite",
1659 notifications: "Notifications",
1660 };
1661 return <Here>{words[parts[0]!]}</Here>;
1662 }
1663 // A person's profile, by their handle.
1664 if (parts[0] === "u" && parts[1]) return <ProfileCrumb username={parts[1]} />;
1665 const [owner, second, third, fourth] = parts;
1666 const ours = workspace != null && owner!.toLowerCase() === workspace.toLowerCase();
1667 const trail: Crumb[] = ours ? [] : [{ label: owner!, to: `/${owner}`, mono: true }];
1668 if (second === "-") {
1669 const page = `/${owner}/-/${third}`;
1670 if (third === "settings" && fourth === "chat") {
1671 // Chat settings is a page of its own, not one of General's.
1672 trail.push({ label: "Chat settings", to: `${page}/chat` });
1673 } else if (third === "work") {
1674 // Work: Work / #12, Work / Labels, Work / Milestones / #3.
1675 trail.push({ label: "Work", to: page });
1676 const words: Record<string, string> = { new: "New work item", labels: "Labels", milestones: "Milestones" };
1677 if (fourth && /^\d+$/.test(fourth)) trail.push({ label: `Work item #${fourth}`, short: `#${fourth}`, to: `${page}/${fourth}` });
1678 else if (fourth && words[fourth]) trail.push({ label: words[fourth]!, to: `${page}/${fourth}` });
1679 const fifth = parts[4];
1680 if (fourth === "milestones" && fifth) trail.push({ label: `#${fifth}`, to: `${page}/milestones/${fifth}` });
1681 } else if (third) {
1682 // The workspace's settings pages each stand alone: General, Members, Permissions.
1683 trail.push({ label: third === "settings" ? "General" : (SECTIONS[third] ?? third), to: page });
1684 // Members names its invitations.
1685 const tabs: Record<string, string> = third === "members" ? { invitations: "Invitations" } : {};
1686 const tab = fourth ? tabs[fourth] : undefined;
1687 if (tab) trail.push({ label: tab, to: `${page}/${fourth}` });
1688 }
1689 } else if (second) {
1690 const repo = `/${owner}/${second}`;
1691 trail.push({ label: second, to: repo, mono: true });
1692 if (third === "pull" && fourth) trail.push({ label: `Pull request #${fourth}`, short: `#${fourth}`, to: `${repo}/pull/${fourth}` });
1693 else if (third === "commit" && fourth) trail.push({ label: fourth.slice(0, 7), to: `${repo}/commit/${fourth}`, mono: true });
1694 // A Soon page names what is coming.
1695 else if (third === "soon" && fourth && roadmapItem(fourth)) trail.push({ label: roadmapItem(fourth)!.title, to: `${repo}/soon/${fourth}` });
1696 else if (third === "settings" && fourth && projectPageAt(`settings/${fourth}`) !== "settings" && projectPageAt(`settings/${fourth}`) != null) {
1697 const page = projectPageAt(`settings/${fourth}`) as keyof typeof PROJECT_PAGE_LINKS;
1698 trail.push({ label: fourth === "deployments" ? "Build configuration" : PROJECT_PAGE_LINKS[page].label, to: `${repo}/settings/${fourth}` });
1699 }
1700 else if (third && SECTIONS[third]) {
1701 trail.push({ label: SECTIONS[third]!, to: `${repo}/${third}` });
1702 // A settings page names which one: Settings / Secrets and variables.
1703 if (third === "settings" && fourth && SECTIONS[fourth]) {
1704 trail.push({ label: SETTINGS_SECTIONS[fourth] ?? SECTIONS[fourth]!, to: `${repo}/settings/${fourth}` });
1705 }
1706 }
1707 }
1708 if (trail.length === 0) trail.push({ label: "Overview", to: `/${owner}` });
1709 return <Trail trail={trail} />;
1710}
1711
1712/** A profile's place in the top bar: the person's avatar and @handle, from the page once it has loaded. */
1713function ProfileCrumb({ username }: { username: string }) {
1714 const page = useRouteLoaderData("routes/user") as { profile?: { username: string; displayUsername?: string | null; avatar: string | null } } | undefined;
1715 const profile = page?.profile?.username.toLowerCase() === username.toLowerCase() ? page.profile : null;
1716 return (
1717 <Breadcrumb className="min-w-0">
1718 <BreadcrumbList>
1719 <BreadcrumbItem>
1720 <BreadcrumbPage asChild className="flex items-center gap-2 hover:bg-raised">
1721 <Link to={`/u/${profile?.username ?? username}`}>
1722 <Avatar name={profile?.username ?? username} image={profile?.avatar ?? null} size={20} />
1723 <span className="truncate font-mono text-[0.8125rem]">@{profile ? shownUsername(profile) : username}</span>
1724 </Link>
1725 </BreadcrumbPage>
1726 </BreadcrumbItem>
1727 </BreadcrumbList>
1728 </Breadcrumb>
1729 );
1730}
1731
1732/** A page with no trail to it, such as Today or Search: its name alone. */
1733function Here({ children }: { children: ReactNode }) {
1734 return (
1735 <Breadcrumb className="min-w-0">
1736 <BreadcrumbList>
1737 <BreadcrumbItem>
1738 <BreadcrumbPage>{children}</BreadcrumbPage>
1739 </BreadcrumbItem>
1740 </BreadcrumbList>
1741 </Breadcrumb>
1742 );
1743}
1744
1745/** One link of the trail; `short` is what a phone shows when it is the page itself. */
1746type Crumb = { label: string; to: string; mono?: boolean; short?: string };
1747
1748/**
1749 * The trail of links. On a phone there is room for one: the page itself,
1750 * with a way back to where it sits; the whole trail from a wider screen up.
1751 */
1752function Trail({ trail }: { trail: Crumb[] }) {
1753 // Up on a phone, unless up is the workspace itself: its pages are the tabs.
1754 const up = trail.length > 1 && !/^\/[^/]+$/.test(trail[trail.length - 2]!.to) ? trail[trail.length - 2]! : null;
1755 return (
1756 <Breadcrumb className="flex min-w-0 items-center">
1757 {up && (
1758 <Button asChild variant="ghost" size="icon-bar" className="-ml-1 sm:hidden">
1759 <Link to={up.to} prefetch="intent" aria-label={`Back to ${up.label}`}>
1760 <ChevronLeft size={16} />
1761 </Link>
1762 </Button>
1763 )}
1764 <BreadcrumbList>
1765 {trail.map((crumb, index) => {
1766 const last = index === trail.length - 1;
1767 const label =
1768 last && crumb.short ? (
1769 <>
1770 <span className="sm:hidden">{crumb.short}</span>
1771 <span className="hidden sm:inline">{crumb.label}</span>
1772 </>
1773 ) : (
1774 crumb.label
1775 );
1776 const mono = crumb.mono ? "font-mono text-[0.8125rem]" : "";
1777 return (
1778 <Fragment key={index}>
1779 {index > 0 && <BreadcrumbSeparator className="max-sm:hidden" />}
1780 <BreadcrumbItem className={last ? "" : "max-sm:hidden"}>
1781 {last ? (
1782 // The page you are on is still a link: to its own top, as the trail always was.
1783 <BreadcrumbPage asChild className={`hover:bg-raised ${mono}`}>
1784 <Link to={crumb.to} prefetch="intent">
1785 {label}
1786 </Link>
1787 </BreadcrumbPage>
1788 ) : (
1789 <BreadcrumbLink asChild className={mono}>
1790 <Link to={crumb.to} prefetch="intent">
1791 {label}
1792 </Link>
1793 </BreadcrumbLink>
1794 )}
1795 </BreadcrumbItem>
1796 </Fragment>
1797 );
1798 })}
1799 </BreadcrumbList>
1800 </Breadcrumb>
1801 );
1802}
1803
1804type Command = PaletteCommand;
1805
1806/** Everything the palette can jump to, from what the sidebar already knows. */
1807function commandsFor(user: User, shell: ShellData): Command[] {
1808 const ws = shell.workspace;
1809 const commands: Command[] = [
1810 ...(ws
1811 ? [
1812 { label: "Home", to: homePagePath(ws.slug), icon: <House size={15} /> },
1813 { label: "Work", hint: "The workspace's work items", to: workPath(ws.slug), icon: <ListTodo size={15} /> },
1814 { label: "New work item", to: newItemPath(ws.slug), icon: <Plus size={15} /> },
1815 { label: "Labels", hint: "Work", to: workPath(ws.slug, "labels"), icon: <ListTodo size={15} /> },
1816 { label: "Milestones", hint: "Work", to: workPath(ws.slug, "milestones"), icon: <ListTodo size={15} /> },
1817 { label: "Chat", to: `/${ws.slug}/-/chat`, icon: <MessagesSquare size={15} /> },
1818 ...(hasCodeAccess(ws) ? [{ label: "Code overview", to: `/${ws.slug}/-/overview`, icon: <Code2 size={15} /> }] : []),
1819 { label: "Artifacts", to: `/${ws.slug}/-/artifacts`, icon: <Shapes size={15} /> },
1820 { label: "Routines", hint: "Standing work for @g1t (soon)", to: `/${ws.slug}/-/routines`, icon: <Repeat size={15} /> },
1821 { label: "Apps", hint: "Everything installed that you can use", to: `/${ws.slug}/-/apps`, icon: <LayoutGrid size={15} /> },
1822 { label: "Workspace", hint: "Billing, policies, settings", to: `/${ws.slug}/-/workspace`, icon: <Building2 size={15} /> },
1823 ]
1824 : []),
1825 { label: "Explore repositories", to: "/explore", icon: <Compass size={15} /> },
1826 { label: "Search g1t", hint: "Repositories, code, work items, people", to: "/search", icon: <Search size={15} /> },
1827 { label: "Notifications", hint: "What needs you", to: "/notifications", icon: <Bell size={15} /> },
1828 { label: "New project", to: "/new", icon: <Plus size={15} /> },
1829 { label: "Your settings", to: FIRST_SETTINGS_PAGE, icon: <Settings size={15} /> },
1830 ...(Object.keys(ACCOUNT_SETTINGS) as AccountSettingsPage[])
1831 .filter((page) => page !== "profile")
1832 .map((page) => ({ label: ACCOUNT_SETTINGS[page].title, hint: "Your settings", to: `/settings/${page}`, icon: <Settings size={15} /> })),
1833 ...THEME_COMMANDS,
1834 ];
1835 const repo = shell.repo;
1836 if (repo) {
1837 const base = `/${repo.namespace}/${repo.name}`;
1838 const name = `${repo.namespace}/${repo.name}`;
1839 commands.unshift(
1840 { label: "Overview", hint: name, to: base, icon: <LayoutGrid size={15} /> },
1841 { label: "Code", hint: name, to: `${base}/code`, icon: <Code2 size={15} /> },
1842 { label: "Work", hint: name, to: repoWorkPath(repo.namespace, repo.name), icon: <ListTodo size={15} /> },
1843 { label: "New work item", hint: name, to: newItemPath(repo.namespace, repo.name), icon: <Plus size={15} /> },
1844 { label: "Pull requests", hint: name, to: `${base}/pulls`, icon: <GitPullRequest size={15} /> },
1845 { label: "Commits", hint: name, to: `${base}/commits`, icon: <History size={15} /> },
1846 ...(repo.member
1847 ? [
1848 { label: "Deployments", hint: name, to: `${base}/deployments`, icon: <Rocket size={15} /> },
1849 { label: "Environment variables", hint: name, to: `${base}/settings/secrets`, icon: <Lock size={15} /> },
1850 { label: "Project settings", hint: name, to: `${base}/settings`, icon: <Settings size={15} /> },
1851 { label: "Repository settings", hint: name, to: `${base}/settings/repository`, icon: <Settings size={15} /> },
1852 ]
1853 : []),
1854 );
1855 }
1856 for (const membership of user.workspaces ?? []) {
1857 commands.push(
1858 { label: displayName(membership), hint: `Workspace · ${membership.slug}`, to: `/${membership.slug}`, icon: <Avatar name={membership.slug} image={membership.avatar} size={15} square /> },
1859 { label: "All projects", hint: membership.slug, to: `/${membership.slug}/-/projects`, icon: <LayoutGrid size={15} /> },
1860 { label: "People", hint: membership.slug, to: `/${membership.slug}/-/people`, icon: <Users size={15} /> },
1861 { label: "Usage", hint: membership.slug, to: `/${membership.slug}/-/usage`, icon: <BarChart3 size={15} /> },
1862 { label: "Billing and plans", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/billing`, icon: <CreditCard size={15} /> },
1863 { label: "Access tokens", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/tokens`, icon: <KeyRound size={15} /> },
1864 { label: "Integrations", hint: membership.slug, to: `/${membership.slug}/-/integrations`, icon: <Plug size={15} /> },
1865 { label: "AI models", hint: `${membership.slug} · Settings`, to: `/${membership.slug}/-/ai`, icon: <Sparkles size={15} /> },
1866 { label: "Members", hint: `${membership.slug} · Access`, to: `/${membership.slug}/-/members`, icon: <Users size={15} /> },
1867 ...(membership.role === "owner"
1868 ? [
1869 { label: "Getting started", hint: `${membership.slug} · Set up the workspace`, to: setupPath(membership.slug), icon: <Rocket size={15} /> },
1870 { label: "Invitations", hint: `${membership.slug} · Access`, to: `/${membership.slug}/-/members/invitations`, icon: <Mail size={15} /> },
1871 { label: "Permissions", hint: `${membership.slug} · Access`, to: `/${membership.slug}/-/permissions`, icon: <ShieldCheck size={15} /> },
1872 ]
1873 : []),
1874 );
1875 }
1876 for (const listed of shell.repos) {
1877 commands.push({
1878 label: listed.title ?? listed.name,
1879 hint: `${listed.namespace} · Project`,
1880 to: `/${listed.namespace}/${listed.name}`,
1881 icon: <Box size={15} />,
1882 });
1883 }
1884 return commands;
1885}
1886
1887/**
1888 * The page while the next one loads: after a moment it dims, under the
1889 * bar below, so it is plainly on its way out rather than frozen, and the
1890 * next page fades up from there. Sending a form does not dim it: the
1891 * form's button says it is working. Spread on the element holding the page.
1892 */
1893export function useLeaving() {
1894 const navigation = useNavigation();
1895 const method = navigation.formMethod?.toUpperCase();
1896 const leaving = navigation.state === "loading" && (method == null || method === "GET");
1897 return {
1898 "aria-busy": leaving || undefined,
1899 className: `transition-opacity motion-reduce:transition-none ${leaving ? "opacity-60 delay-200 duration-300" : "duration-150"}`,
1900 };
1901}
1902
1903/**
1904 * A bar across the top of the page while the next one loads, as GitHub
1905 * has: it appears at once, creeps towards the end while waiting, then fills
1906 * and fades when the page arrives.
1907 */
1908export function Progress() {
1909 const navigation = useNavigation();
1910 const busy = navigation.state !== "idle";
1911 const [width, setWidth] = useState(0);
1912 const [visible, setVisible] = useState(false);
1913 useEffect(() => {
1914 if (busy) {
1915 setVisible(true);
1916 setWidth(12);
1917 // Slows as it goes, never quite arriving until the page does.
1918 const timer = setInterval(() => setWidth((now) => now + (90 - now) * 0.12), 200);
1919 return () => clearInterval(timer);
1920 }
1921 setWidth((now) => (now > 0 ? 100 : 0));
1922 const fade = setTimeout(() => setVisible(false), 250);
1923 const reset = setTimeout(() => setWidth(0), 550);
1924 return () => {
1925 clearTimeout(fade);
1926 clearTimeout(reset);
1927 };
1928 }, [busy]);
1929 return (
1930 <div
1931 aria-hidden="true"
1932 className={`pointer-events-none fixed inset-x-0 top-0 z-60 h-0.75 transition-opacity duration-300 ${
1933 visible ? "opacity-100" : "opacity-0"
1934 }`}
1935 >
1936 <div
1937 className="h-full bg-accent shadow-[0_0_10px_var(--color-accent)] transition-[width] duration-200 ease-out"
1938 style={{ width: `${width}%` }}
1939 />
1940 </div>
1941 );
1942}
1943
1944/**
1945 * Which sidebar sits beside the page: each mode's own, or none. Home,
1946 * Apps and Routines are pages at full width, and so are g1t's own pages, such as its
1947 * policies, which are no workspace's. g1t beyond your workspaces (Explore,
1948 * a profile, another workspace's projects) has Explore's. Without a
1949 * workspace, only your own settings and Notifications have one.
1950 */
1951function sidebarFor(mode: ModeKey, workspace: boolean): Panel | null {
1952 if (!workspace) return mode === "account" || mode === "notifications" ? mode : null;
1953 if (mode === "home" || mode === "apps" || mode === "routines" || mode === "site") return null;
1954 return mode;
1955}
1956
1957/** The sidebars that sit beside the page, one per mode that has one. */
1958type Panel = "work" | "chat" | "artifacts" | "code" | "notifications" | "people" | "workspace" | "account" | "browse";
1959
1960/** Each sidebar's name, for the button that opens it on a phone. */
1961const MODE_MENU: Record<Panel, string> = {
1962 browse: "Explore",
1963 work: "Work",
1964 chat: "Chat",
1965 artifacts: "Artifacts",
1966 code: "Code",
1967 notifications: "Notifications",
1968 people: "People",
1969 workspace: "Workspace",
1970 account: "Your account",
1971};
1972
1973/** Whether a key press happened in something you type into, where Ctrl B is the editor's. */
1974function typing(target: EventTarget | null): boolean {
1975 if (!(target instanceof HTMLElement)) return false;
1976 return target.isContentEditable || target.closest("input, textarea, select, [contenteditable=''], [contenteditable='true'], [role='textbox']") != null;
1977}
1978
1979/** Ctrl B (⌘B on a Mac) shows or hides the sidebar, except while typing. */
1980function useSidebarShortcut(toggle: () => void) {
1981 useEffect(() => {
1982 const onKey = (event: KeyboardEvent) => {
1983 if (event.key.toLowerCase() !== "b" || event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey)) return;
1984 if (event.defaultPrevented || typing(event.target)) return;
1985 event.preventDefault();
1986 toggle();
1987 };
1988 window.addEventListener("keydown", onKey);
1989 return () => window.removeEventListener("keydown", onKey);
1990 }, [toggle]);
1991}
1992
1993/**
1994 * Search or jump to: the command palette. On a computer it looks like the
1995 * field it opens, with its shortcut; on a phone, a magnifier.
1996 */
1997function SearchButton({ onClick, place }: { onClick: () => void; place: "bar" | "sidebar" }) {
1998 const field = (
1999 <Button
2000 variant="outline"
2001 size="sm"
2002 aria-label="Search or jump to"
2003 onClick={onClick}
2004 className={
2005 place === "sidebar"
2006 ? "w-full justify-start bg-bg font-normal text-faint hover:bg-bg hover:text-muted"
2007 : "mr-1 w-[min(18rem,26vw)] justify-start bg-surface font-normal text-faint hover:bg-surface hover:text-muted max-md:hidden"
2008 }
2009 >
2010 <Search size={15} />
2011 <span className="grow truncate text-left">Search or jump to</span>
2012 <PaletteKey className="px-1.5 text-[0.625rem] leading-4 text-muted" />
2013 </Button>
2014 );
2015 if (place === "sidebar") return field;
2016 return (
2017 <>
2018 <Button variant="ghost" size="icon-bar" aria-label="Search or jump to" onClick={onClick} className="md:hidden">
2019 <Search size={18} />
2020 </Button>
2021 {field}
2022 </>
2023 );
2024}
2025
2026/** The sidebar's shortcut, for the hint on its toggle. */
2027function useSidebarKey(): string {
2028 return sidebarKeyLabel(typeof navigator === "undefined" ? null : navigator.platform);
2029}
2030
2031/**
2032 * The app: three surfaces that never blur together. The rail, a narrow
2033 * column of icons down the window's left edge; the mode's sidebar, flat
2034 * against it with a hairline between, which folds away with Ctrl B and is
2035 * a drawer below 1024px; and the page, flat against the sidebar and
2036 * filling the rest of the window, with its top bar across the top and a
2037 * line under it: the sidebar's toggle, where you are, search, Ask, the bell and
2038 * Create new. On a phone the rail is a bar along the bottom and the page
2039 * fills the window above it, flat as well. Only for someone signed in; without a workspace yet, there
2040 * is no rail. The rail and the sidebar are drawn from the sidebar kit
2041 * (components/ui/sidebar.tsx): one provider holds whether the sidebar is
2042 * open on a computer and whether the drawer is.
2043 */
2044export function AppShell({
2045 user,
2046 shell,
2047 missing = false,
2048 banner,
2049 sidebarClosed = false,
2050 children,
2051}: {
2052 user: User;
2053 shell: ShellData;
2054 /** The page is a 404 (see CodeSidebar). */
2055 missing?: boolean;
2056 banner?: ReactNode;
2057 /** Whether the person folded the sidebar away, as their cookie says. */
2058 sidebarClosed?: boolean;
2059 children: ReactNode;
2060}) {
2061 const { pathname } = useLocation();
2062 const [drawer, setDrawer] = useState(false);
2063 const [closed, setClosed] = useState(sidebarClosed);
2064 const [palette, setPalette] = useState(false);
2065 const commands = useMemo(() => commandsFor(user, shell), [user, shell]);
2066
2067 // A new page closes the drawer.
2068 useEffect(() => setDrawer(false), [pathname]);
2069 usePaletteShortcut(() => setPalette((open) => !open));
2070 // In the desktop app, search is in the middle of its title bar, as in Slack, and not in the top bar too.
2071 const titleSearch = useTitleBarSearch(`Search ${shell.workspace?.name ?? shell.workspace?.slug ?? "g1t"}`, () => setPalette(true));
2072 const leaving = useLeaving();
2073 useVisualViewport();
2074 const target = useSidebarLocation().pathname;
2075 const ws = shell.workspace;
2076 // Beyond your workspaces (Explore, a profile, another workspace's
2077 // projects), the shell is Explore's; anything of yours is its mode's.
2078 const browsing = browsingOf(target, {
2079 slug: ws?.slug ?? null,
2080 memberships: (user.workspaces ?? []).map((membership) => membership.slug),
2081 shared: shell.shared,
2082 username: user.username,
2083 });
2084 const mode: ModeKey = browsing ? "browse" : modeOf(target, ws?.slug ?? null);
2085 const panel = sidebarFor(mode, ws != null);
2086 const { sidebar: chatSidebar } = useChatSidebar();
2087 // Notify: the feed socket's live counts (lib/notify-client.ts) once it has them; the page's until then.
2088 const live = useLiveBadges(ws?.slug);
2089 const chatUnread = chatSidebar
2090 ? unreadTotals(chatSidebar.entries)
2091 : live?.chat != null
2092 ? { unread: live.chat, mentions: live.mentions ?? 0 }
2093 : (shell.chat ?? { unread: 0, mentions: 0 });
2094 const notificationsUnread = live?.inbox ?? shell.inbox?.unread ?? 0;
2095 const unread = { notifications: notificationsUnread, chat: chatUnread.unread, mentions: chatUnread.mentions };
2096
2097 // Folding the sidebar away on a computer is remembered, so the next page is drawn the same from the server.
2098 const toggleSidebar = useCallback(() => {
2099 if (!window.matchMedia("(min-width: 1024px)").matches) {
2100 setDrawer((open) => !open);
2101 return;
2102 }
2103 setClosed((was) => {
2104 document.cookie = sidebarCookie(!was, window.location.protocol === "https:");
2105 return !was;
2106 });
2107 }, []);
2108 useSidebarShortcut(useCallback(() => {
2109 if (panel) toggleSidebar();
2110 }, [panel, toggleSidebar]));
2111
2112 const inline = panel != null && !closed;
2113 const sidebarNode = () => {
2114 if (!panel) return null;
2115 if (!ws) return panel === "notifications" ? <NotificationsSidebar counts={shell.inbox ?? null} /> : <AccountSidebar username={user.username} />;
2116 switch (panel) {
2117 case "code":
2118 return <CodeSidebar user={user} shell={shell} missing={missing} />;
2119 case "browse":
2120 return <CodeSidebar user={user} shell={shell} missing={missing} browsing={browsing} />;
2121 case "work":
2122 return <WorkSidebar slug={ws.slug} username={user.username} />;
2123 case "chat":
2124 return <ChatSidebar slug={ws.slug} />;
2125 case "artifacts":
2126 return <FoliosSidebar slug={ws.slug} />;
2127 case "notifications":
2128 return <NotificationsSidebar counts={shell.inbox ?? null} />;
2129 case "people":
2130 return <PeopleSidebar slug={ws.slug} />;
2131 case "workspace":
2132 return <WorkspaceSidebar slug={ws.slug} owner={ws.role === "owner"} />;
2133 case "account":
2134 return <AccountSidebar username={user.username} />;
2135 }
2136 };
2137 const sidebarKey = useSidebarKey();
2138 // Search or jump to sits at the top of the sidebar, except in Chat and
2139 // Artifacts, whose sidebars search their own lists: there it stays in the bar.
2140 const sidebarSearch = panel != null && panel !== "chat" && panel !== "artifacts";
2141 // The sidebar's head: the workspace and its switcher, the way to fold the
2142 // sidebar or close the drawer, and search, which opens the palette.
2143 const sidebarTop = (inDrawer: boolean) => (
2144 <SidebarHeader className="gap-1 px-2 pt-0 pb-2">
2145 <div className="flex h-14 shrink-0 items-center gap-1">
2146 {ws ? (
2147 <WorkspaceSwitcher user={user} workspace={ws} />
2148 ) : (
2149 <Link to="/" aria-label="g1t" className="mr-auto flex h-9 items-center rounded-md px-2">
2150 <Logo className="text-[1.125rem]" />
2151 </Link>
2152 )}
2153 {inDrawer ? (
2154 <Button type="button" aria-label="Close menu" onClick={() => setDrawer(false)} variant="ghost" size="icon-sm" className="text-faint">
2155 <X size={16} />
2156 </Button>
2157 ) : (
2158 <SidebarTrigger hint={`Hide the sidebar (${sidebarKey})`} className="text-faint" />
2159 )}
2160 </div>
2161 {sidebarSearch && <SearchButton place="sidebar" onClick={() => setPalette(true)} />}
2162 </SidebarHeader>
2163 );
2164
2165 // On a phone (below 768px): the bottom bar, and a conversation full screen.
2166 const conversation = isConversation(target);
2167 // Where the page panel starts: 8px past the rail (56px), or 8px past the sidebar (56 + 240px) when it is open.
2168 // The page starts where the rail (3.5rem) and, open, the sidebar (15rem) end.
2169 const pad = ws ? (inline ? "md:pl-14 lg:pl-74" : "md:pl-14") : inline ? "lg:pl-60" : "";
2170
2171 return (
2172 <SidebarProvider open={!closed} onOpenChange={(open) => setClosed(!open)} openMobile={drawer} onOpenMobileChange={setDrawer} toggleSidebar={toggleSidebar}>
2173 <Progress />
2174 {ws && (
2175 <div className="fixed top-(--frame-top) bottom-0 left-0 z-40 hidden md:block">
2176 <Rail workspace={ws} mode={mode} pins={shell.pins ?? []} unread={unread} account={<AccountMenu user={user} />} />
2177 </div>
2178 )}
2179 {panel && (
2180 <Sidebar
2181 role="complementary"
2182 aria-label={`${MODE_MENU[panel]} sidebar`}
2183 className={`fixed top-(--frame-top) bottom-0 z-40 max-lg:hidden ${ws ? "left-14" : "left-0"}`}
2184 >
2185 {sidebarTop(false)}
2186 <div className="min-h-0 grow">{sidebarNode()}</div>
2187 </Sidebar>
2188 )}
2189 {/* The drawer is a sheet: a dialog that holds focus, closes on Escape or
2190 a tap outside, and gives focus back to the button that opened it. */}
2191 {panel && (
2192 <SidebarMobile title={`${MODE_MENU[panel]} menu`} className="pb-[env(safe-area-inset-bottom)] max-md:[&_nav_a]:min-h-10">
2193 {sidebarTop(true)}
2194 <div className="min-h-0 grow">{sidebarNode()}</div>
2195 </SidebarMobile>
2196 )}
2197
2198 <div className={`min-h-dvh pt-(--frame-top) pb-(--tabbar-h) ${pad}`}>
2199 {/* The top bar always has its line, so a page's own header (data-page-head: a conversation's, a project's,
2200 a sticky one under an open artifact) sits under it as its own band. */}
2201 <div className="flex min-h-[calc(100dvh-var(--frame-top)-var(--tabbar-h))] min-w-0 flex-col bg-bg">
2202 <header
2203 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" : ""}`}
2204 >
2205 {panel && (
2206 <SidebarTrigger
2207 hint={`Show the sidebar (${sidebarKey})`}
2208 aria-label={drawer ? "Hide the sidebar" : "Show the sidebar"}
2209 aria-expanded={drawer}
2210 className={`max-md:size-11 ${inline ? "lg:hidden" : ""}`}
2211 />
2212 )}
2213 {ws && (
2214 <span className={`flex min-w-0 shrink items-center gap-1.5 ${inline ? "lg:hidden" : ""}`}>
2215 <WorkspaceSwitcher user={user} workspace={ws} compact />
2216 <span aria-hidden="true" className="text-line-strong">
2217 /
2218 </span>
2219 </span>
2220 )}
2221 <Breadcrumbs pathname={pathname} missing={missing} repo={shell.repo} workspace={ws?.slug ?? null} />
2222 {/* Search, Ask, then the bell and Create new: one height, one rhythm. */}
2223 <div className="ml-auto flex shrink-0 items-center gap-1 md:gap-1.5">
2224 {/* With the sidebar open, search is at its top. */}
2225 {!titleSearch && (
2226 <span className={`flex ${inline && sidebarSearch ? "lg:hidden" : ""}`}>
2227 <SearchButton place="bar" onClick={() => setPalette(true)} />
2228 </span>
2229 )}
2230 {ws && <AskButton key={ws.slug} slug={ws.slug} />}
2231 <Separator orientation="vertical" className="mx-1 data-[orientation=vertical]:h-5 max-md:hidden" />
2232 {/* On a phone, Notifications is in the bottom bar. */}
2233 <span className="flex max-md:hidden">
2234 <NotificationsBell counts={shell.inbox ? { ...shell.inbox, unread: notificationsUnread } : null} />
2235 </span>
2236 <CreateMenu shell={shell} />
2237 {/* Without a workspace there is no rail: the account is here. */}
2238 {!ws && <AccountMenu user={user} side="bottom" />}
2239 </div>
2240 </header>
2241 {banner}
2242 <main id="content" tabIndex={-1} {...leaving} className={`min-w-0 grow outline-none ${leaving.className}`}>
2243 <InMain.Provider value={true}>{children}</InMain.Provider>
2244 </main>
2245 </div>
2246 </div>
2247 {ws && <BottomBar user={user} workspace={ws} mode={mode} pins={shell.pins ?? []} unread={unread} onReselect={panel ? () => setDrawer(true) : undefined} />}
2248 <CommandPalette open={palette} onOpenChange={setPalette} commands={commands} repo={shell.repo ? `${shell.repo.namespace}/${shell.repo.name}` : null} />
2249 </SidebarProvider>
2250 );
2251}
2252
2253/** Create new: a work item (from the project you are in), a project, a workspace or a team. */
2254function CreateMenu({ shell }: { shell: ShellData }) {
2255 return (
2256 <DropdownMenu>
2257 <Hint label="Create new">
2258 <DropdownMenuTrigger asChild>
2259 <Button variant="ghost" size="bar" aria-label="Create new" className="gap-0.5 px-1.5 text-fg/90">
2260 <Plus size={17} className="max-md:size-5" />
2261 <ChevronDown size={12} className="text-faint max-md:hidden" />
2262 </Button>
2263 </DropdownMenuTrigger>
2264 </Hint>
2265 <DropdownMenuContent align="end" className="min-w-52">
2266 {shell.repo ? (
2267 <>
2268 <DropdownMenuLabel className="truncate">In {shell.repo.name}</DropdownMenuLabel>
2269 <DropdownMenuItem asChild>
2270 <Link to={newItemPath(shell.repo.namespace, shell.repo.name)}>
2271 <ListTodo />
2272 New work item
2273 </Link>
2274 </DropdownMenuItem>
2275 <DropdownMenuSeparator />
2276 </>
2277 ) : (
2278 shell.workspace && (
2279 <>
2280 <DropdownMenuItem asChild>
2281 <Link to={newItemPath(shell.workspace.slug)}>
2282 <ListTodo />
2283 New work item
2284 </Link>
2285 </DropdownMenuItem>
2286 <DropdownMenuSeparator />
2287 </>
2288 )
2289 )}
2290 <DropdownMenuItem asChild>
2291 <Link to="/new">
2292 <Box />
2293 New project
2294 </Link>
2295 </DropdownMenuItem>
2296 <DropdownMenuItem asChild>
2297 <Link to="/new/github">
2298 <GitBranch />
2299 Import from GitHub
2300 </Link>
2301 </DropdownMenuItem>
2302 {/* 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. */}
2303 {shell.workspace && <DropdownMenuSeparator />}
2304 {shell.workspace &&
2305 (mayCreateTeams(shell.workspace.team_creation, shell.workspace.role) ? (
2306 <DropdownMenuItem asChild>
2307 <Link to={`/${shell.workspace.slug}/-/teams/new`}>
2308 <UsersRound />
2309 New team
2310 </Link>
2311 </DropdownMenuItem>
2312 ) : (
2313 <DropdownMenuItem disabled>
2314 <UsersRound />
2315 New team
2316 <span className="ml-auto pl-3 text-xs text-faint">Owners only</span>
2317 </DropdownMenuItem>
2318 ))}
2319 </DropdownMenuContent>
2320 </DropdownMenu>
2321 );
2322}