Skip to content

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

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