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