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