Skip to content

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

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