| 1 | import { useEffect, useMemo, useRef, useState } from "react"; |
| 2 | import { |
| 3 | isRouteErrorResponse, |
| 4 | Link, |
| 5 | Links, |
| 6 | Meta, |
| 7 | Outlet, |
| 8 | Scripts, |
| 9 | ScrollRestoration, |
| 10 | type ShouldRevalidateFunctionArgs, |
| 11 | useLocation, |
| 12 | useMatches, |
| 13 | useRouteError, |
| 14 | useRouteLoaderData, |
| 15 | } from "react-router"; |
| 16 | |
| 17 | import { |
| 18 | type User, |
| 19 | awaitsConfirmation, |
| 20 | hasAccessIn, |
| 21 | sharedWorkspaces, |
| 22 | } from "@g1t/contracts"; |
| 23 | |
| 24 | import type { Route } from "./+types/root"; |
| 25 | import appCss from "./app.css?url"; |
| 26 | import displayFont from "@g1t/theme/fonts/bricolage-grotesque-latin.woff2?url"; |
| 27 | import sansFont from "@g1t/theme/fonts/hanken-grotesk-latin.woff2?url"; |
| 28 | import { ButtonLink } from "./components/ui"; |
| 29 | import { |
| 30 | AppShell, |
| 31 | Progress, |
| 32 | type ShellData, |
| 33 | useLeaving, |
| 34 | } from "./components/shell"; |
| 35 | import { SiteFooter } from "./components/footer"; |
| 36 | import { PublicHeader } from "./components/public-header"; |
| 37 | import { SpikeBanner } from "./components/spike-banner"; |
| 38 | import { PolicyNotice } from "./components/policy-notice"; |
| 39 | import { identify } from "./lib/analytics.client"; |
| 40 | import { visitorAsksFirst } from "./lib/analytics-consent"; |
| 41 | import { AnalyticsConsent } from "./components/analytics-consent"; |
| 42 | import { readCookie } from "./lib/mission"; |
| 43 | import { WORKSPACE_COOKIE, workspaceFor } from "./lib/workspace-choice"; |
| 44 | import { PageMain } from "./components/landmark"; |
| 45 | import { NotFound } from "./components/not-found"; |
| 46 | import { frameOf } from "./lib/chrome"; |
| 47 | import { |
| 48 | DOCK_COOKIE, |
| 49 | SIDEBAR_COOKIE, |
| 50 | pinsToShow, |
| 51 | sidebarClosed, |
| 52 | } from "./lib/apps"; |
| 53 | import { savedPins } from "./lib/dock.server"; |
| 54 | import { StandaloneFrame } from "./components/standalone"; |
| 55 | import { |
| 56 | ai, |
| 57 | billing, |
| 58 | chat, |
| 59 | identity, |
| 60 | inbox, |
| 61 | projects, |
| 62 | } from "./lib/services.server"; |
| 63 | import { unreadTotals } from "./lib/chat"; |
| 64 | import { countsFor, readableRepos } from "./lib/access.server"; |
| 65 | import { agentForProviders, DEFAULT_AGENT, parseAgent, rememberAgentDefault } from "./lib/agent-setup"; |
| 66 | import { shortCache } from "./lib/cache.server"; |
| 67 | import { getViewer, viewerMiddleware } from "./lib/session.server"; |
| 68 | import { shortcutOf, workspaceProjects } from "./lib/workspace-projects.server"; |
| 69 | import { addresses } from "./lib/addresses.server"; |
| 70 | import { orElse, part } from "./lib/partial"; |
| 71 | import { |
| 72 | RELOADED_KEY, |
| 73 | RELOAD_GIVE_UP_MS, |
| 74 | clientNavigated, |
| 75 | reloadFixes, |
| 76 | reloadedBefore, |
| 77 | } from "./lib/stale-build"; |
| 78 | import { useNonce } from "./lib/nonce"; |
| 79 | import { useStuckNavigationRescue } from "./lib/stuck"; |
| 80 | import { isNeedsSignIn } from "./lib/website-token"; |
| 81 | import { offerTicket, setLiveViaToken } from "./lib/live-socket"; |
| 82 | import { socketTicketFor } from "./lib/socket-ticket.server"; |
| 83 | import { DesktopApp } from "./components/desktop-app"; |
| 84 | import { DesktopRunnerLink } from "./components/desktop-runner-link"; |
| 85 | import { LiveNotifications } from "./components/notifications/live-notifications"; |
| 86 | import { |
| 87 | THEME_COLOR, |
| 88 | THEME_COOKIE, |
| 89 | readTheme, |
| 90 | themeAttribute, |
| 91 | useThemeChoice, |
| 92 | } from "./lib/theme"; |
| 93 | import { |
| 94 | DEVELOPER_COOKIE, |
| 95 | readDeveloperMode, |
| 96 | useDeveloperMode, |
| 97 | } from "./lib/developer-mode"; |
| 98 | import { RouteError } from "./components/route-error"; |
| 99 | import { ConnectionToast } from "./components/connection-toast"; |
| 100 | import { NavigationRecovery } from "./components/navigation-recovery"; |
| 101 | import { isNetworkFailure } from "./lib/resilient-fetch"; |
| 102 | import { useReconnect } from "./lib/reconnect"; |
| 103 | import { buildVersionMiddleware } from "./lib/build-version.server"; |
| 104 | |
| 105 | export const links: Route.LinksFunction = () => [ |
| 106 | { rel: "icon", href: "/favicon.ico", sizes: "32x32" }, |
| 107 | { rel: "icon", type: "image/svg+xml", href: "/favicon.svg" }, |
| 108 | { rel: "icon", type: "image/png", sizes: "192x192", href: "/icon-192.png" }, |
| 109 | { rel: "icon", type: "image/png", sizes: "512x512", href: "/icon-512.png" }, |
| 110 | // Home screens and password managers look for a square, opaque 180px tile; |
| 111 | // the "-precomposed" name is served too, for the ones that ask for it. |
| 112 | { rel: "apple-touch-icon", sizes: "180x180", href: "/apple-touch-icon.png" }, |
| 113 | // Installable: name, icons and colours for "Add to Home Screen" (public/site.webmanifest; |
| 114 | // manifest.webmanifest is the same file, kept for installs that already point at it). |
| 115 | { rel: "manifest", href: "/site.webmanifest" }, |
| 116 | // The text and headline faces are wanted on every page, so they start |
| 117 | // loading with the stylesheet; mono waits until something uses it. |
| 118 | { |
| 119 | rel: "preload", |
| 120 | href: sansFont, |
| 121 | as: "font", |
| 122 | type: "font/woff2", |
| 123 | crossOrigin: "anonymous", |
| 124 | }, |
| 125 | { |
| 126 | rel: "preload", |
| 127 | href: displayFont, |
| 128 | as: "font", |
| 129 | type: "font/woff2", |
| 130 | crossOrigin: "anonymous", |
| 131 | }, |
| 132 | ]; |
| 133 | |
| 134 | export const middleware: Route.MiddlewareFunction[] = [buildVersionMiddleware, viewerMiddleware]; |
| 135 | |
| 136 | export async function loader({ context, params, request }: Route.LoaderArgs) { |
| 137 | const user = getViewer(context); |
| 138 | const cookies = request.headers.get("cookie"); |
| 139 | const chosen = readCookie(cookies, WORKSPACE_COOKIE); |
| 140 | const dock = readCookie(cookies, DOCK_COOKIE); |
| 141 | const [shell, sounds] = await Promise.all([ |
| 142 | // An account still confirming its address sees only the pages that |
| 143 | // allows (lib/confirm-gate.ts), in the visitor's frame. |
| 144 | user && !awaitsConfirmation(user) |
| 145 | ? shellFor(user, params, chosen, context).catch((error: unknown) => { |
| 146 | // A sidebar that could not be read is no reason to lose the page, |
| 147 | // or to draw it as if they were signed out. |
| 148 | console.error("root: the sidebar could not be read", error); |
| 149 | return bareShell(user, params, chosen); |
| 150 | }) |
| 151 | : visitorShell(params, context), |
| 152 | // Their chat sounds, with the page, so the first live event already |
| 153 | // respects them (lib/sounds.ts); the defaults when identity is slow. |
| 154 | user && !awaitsConfirmation(user) |
| 155 | ? identity.soundSettings(user).catch(() => null) |
| 156 | : Promise.resolve(null), |
| 157 | ]); |
| 158 | // The apps this person pinned to their rail here: as their account keeps |
| 159 | // them (read with the rest of the shell), else as this device's cookie |
| 160 | // remembers them (lib/apps.ts). |
| 161 | if (shell.workspace) |
| 162 | shell.pins = pinsToShow(shell.pins, dock, shell.workspace.slug); |
| 163 | // Where this g1t lives, for clone lines, agent setup and link previews. |
| 164 | return { |
| 165 | user, |
| 166 | shell, |
| 167 | // Cache only the derived UI default, scoped to this viewer and workspace. |
| 168 | // shortCache bypasses old answers after settings writes; failures are not cached. |
| 169 | agentChoice: parseAgent(readCookie(cookies, "g1t_agent")), |
| 170 | agentDefault: user && shell.workspace |
| 171 | ? await shortCache(`agent-default:${user.id}:${shell.workspace.slug}`, 300_000, async () => { |
| 172 | const result = await ai.list(shell.workspace!.slug, user); |
| 173 | if (!result.ok) throw new Error("AI providers unavailable"); |
| 174 | return agentForProviders(result.value); |
| 175 | }).catch(() => DEFAULT_AGENT) |
| 176 | : DEFAULT_AGENT, |
| 177 | // For a page opened with an access token: the feed socket's ticket, |
| 178 | // minted here so the feed opens without asking for one (lib/live-socket.ts). |
| 179 | // Without one the feed asks for its own ticket, so a ticket that could |
| 180 | // not be minted is no reason to lose the page. |
| 181 | liveTicket: user?.token?.website |
| 182 | ? orElse(await part(socketTicketFor(context, request, "/-/live"), "The live feed's ticket"), null) |
| 183 | : null, |
| 184 | // Whether they folded the sidebar away, so the page is drawn that way from the start. |
| 185 | sidebarClosed: sidebarClosed(readCookie(cookies, SIDEBAR_COOKIE)), |
| 186 | // Their Appearance, so the page is drawn in it from the first byte (lib/theme.ts). |
| 187 | theme: readTheme(readCookie(cookies, THEME_COOKIE)), |
| 188 | // Whether a page that fails says why, in full (lib/developer-mode.ts). |
| 189 | developer: readDeveloperMode(readCookie(cookies, DEVELOPER_COOKIE)), |
| 190 | // What they hear when chat moves (components/notifications/sounds.tsx). |
| 191 | sounds, |
| 192 | addresses: addresses(), |
| 193 | // Visitors from where the law asks first are asked before analytics runs. |
| 194 | analyticsConsent: visitorAsksFirst(request), |
| 195 | }; |
| 196 | } |
| 197 | |
| 198 | /** |
| 199 | * The sidebar for someone not signed in: nothing of their own, only the |
| 200 | * open counts of the project being looked at. One call, and only in a |
| 201 | * project; it answers the same for a private project as a missing one. |
| 202 | */ |
| 203 | async function visitorShell( |
| 204 | params: { owner?: string; repo?: string }, |
| 205 | context: Route.LoaderArgs["context"], |
| 206 | ): Promise<ShellData> { |
| 207 | const path = |
| 208 | params.owner && params.repo |
| 209 | ? { namespace: params.owner, name: params.repo } |
| 210 | : null; |
| 211 | // The counts are the sidebar's, never the page's: without them it shows none. |
| 212 | const counts = path ? orElse(await part(countsFor(context, params), "Open counts"), null) : null; |
| 213 | return { |
| 214 | workspace: null, |
| 215 | repos: [], |
| 216 | repo: |
| 217 | path && counts?.ok |
| 218 | ? { |
| 219 | ...path, |
| 220 | member: false, |
| 221 | issues: counts.value.issues, |
| 222 | pulls: counts.value.pulls, |
| 223 | } |
| 224 | : null, |
| 225 | limit: null, |
| 226 | monthUsageMicros: null, |
| 227 | }; |
| 228 | } |
| 229 | |
| 230 | /** The sidebar from what the session already says, with no service asked. */ |
| 231 | function bareShell( |
| 232 | user: User, |
| 233 | params: { owner?: string; repo?: string }, |
| 234 | chosen: string | null, |
| 235 | ): ShellData { |
| 236 | return { |
| 237 | workspace: workspaceFor(user.workspaces ?? [], chosen, params), |
| 238 | repos: [], |
| 239 | repo: null, |
| 240 | limit: null, |
| 241 | monthUsageMicros: null, |
| 242 | }; |
| 243 | } |
| 244 | |
| 245 | /** |
| 246 | * The sidebar only changes with the workspace or repository being looked |
| 247 | * at, or after something was submitted: not on every page within them. |
| 248 | */ |
| 249 | export function shouldRevalidate({ |
| 250 | currentParams, |
| 251 | nextParams, |
| 252 | formMethod, |
| 253 | defaultShouldRevalidate, |
| 254 | }: ShouldRevalidateFunctionArgs) { |
| 255 | if (formMethod && formMethod !== "GET") return defaultShouldRevalidate; |
| 256 | return ( |
| 257 | currentParams.owner !== nextParams.owner || |
| 258 | currentParams.repo !== nextParams.repo |
| 259 | ); |
| 260 | } |
| 261 | |
| 262 | /** |
| 263 | * The sidebar: the workspace whose pages or project these are when it is |
| 264 | * one of yours, else the one you chose (lib/workspace-choice.ts); its |
| 265 | * projects; and the repository being looked at. |
| 266 | */ |
| 267 | async function shellFor( |
| 268 | user: User, |
| 269 | params: { owner?: string; repo?: string }, |
| 270 | chosen: string | null, |
| 271 | context: Route.LoaderArgs["context"], |
| 272 | ): Promise<ShellData> { |
| 273 | const memberships = user.workspaces ?? []; |
| 274 | const workspace = workspaceFor(memberships, chosen, params); |
| 275 | const path = |
| 276 | params.owner && params.repo |
| 277 | ? { namespace: params.owner, name: params.repo } |
| 278 | : null; |
| 279 | const now = new Date(); |
| 280 | const monthStart = new Date( |
| 281 | Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1), |
| 282 | ).toISOString(); |
| 283 | // What the sidebar shows of the workspace changes rarely: kept for a few |
| 284 | // seconds per person and workspace, except just after they changed |
| 285 | // something (lib/cache.server.ts). |
| 286 | const kept = <T,>(what: string, load: () => Promise<T>) => |
| 287 | workspace |
| 288 | ? shortCache( |
| 289 | `shell:${what}:${user.id}:${workspace.slug}`, |
| 290 | SHELL_TTL_MS, |
| 291 | load, |
| 292 | ) |
| 293 | : Promise.resolve(null); |
| 294 | const [ |
| 295 | listed, |
| 296 | counts, |
| 297 | status, |
| 298 | usage, |
| 299 | limit, |
| 300 | entitlements, |
| 301 | shared, |
| 302 | unread, |
| 303 | shortcuts, |
| 304 | chatUnread, |
| 305 | dockPins, |
| 306 | ] = await Promise.all([ |
| 307 | // Every project, for the palette and the count; the sidebar lists only |
| 308 | // the person's pinned and recent ones (lib/pins.ts). |
| 309 | // Each of these is one part of the sidebar: one that fails leaves only |
| 310 | // itself out (logged by `part`), never the rest of the sidebar with it. |
| 311 | workspace |
| 312 | ? part(workspaceProjects(workspace.slug, user), "Projects").then((value) => orElse(value, null)) |
| 313 | : Promise.resolve(null), |
| 314 | path |
| 315 | ? part(countsFor(context, params), "Open counts").then((value) => orElse(value, null)) |
| 316 | : Promise.resolve(null), |
| 317 | // Whether billing is on, without reading the account: that asks the |
| 318 | // card processor about the workspace's cards, too slow for every page. |
| 319 | kept("status", () => billing.status()).catch(() => null), |
| 320 | kept(`usage:${monthStart}`, () => |
| 321 | billing.usage(workspace!.slug, user, monthStart), |
| 322 | ).catch(() => null), |
| 323 | kept("limit", () => billing.limit(workspace!.slug, user)).catch(() => null), |
| 324 | kept("entitlements", () => billing.entitlements(workspace!.slug)).catch( |
| 325 | () => null, |
| 326 | ), |
| 327 | part(sharedRepos(user), "Shared with you").then((value) => orElse(value, [])), |
| 328 | // The bell's count: one query, never kept, so marking an item shows at once. |
| 329 | inbox.counts(user.username).catch(() => null), |
| 330 | // Never kept: opening a project moves it up Recent. |
| 331 | workspace |
| 332 | ? projects.shortcuts(workspace.slug, user).catch(() => null) |
| 333 | : Promise.resolve(null), |
| 334 | // The rail's Chat badge: never kept, and never waited on for long. |
| 335 | workspace ? chatUnreadFor(workspace.slug, user) : Promise.resolve(null), |
| 336 | // The rail's pins, kept with the account so every device shows the same |
| 337 | // rail; never kept here, so a pin shows the moment it is made. Null |
| 338 | // falls back to the cookie (lib/dock.server.ts). |
| 339 | workspace ? savedPins(user, workspace.slug) : Promise.resolve(null), |
| 340 | ]); |
| 341 | return { |
| 342 | workspace, |
| 343 | // Projects are what the sidebar lists: what the workspace builds and runs. |
| 344 | repos: listed?.ok ? listed.value.map(shortcutOf) : [], |
| 345 | pinned: (shortcuts?.pinned ?? []).map(shortcutOf), |
| 346 | recent: (shortcuts?.recent ?? []).map(shortcutOf), |
| 347 | repo: |
| 348 | path && counts?.ok |
| 349 | ? { |
| 350 | ...path, |
| 351 | // Until the repository's own page says what their role is. |
| 352 | member: hasAccessIn(user, path.namespace), |
| 353 | issues: counts.value.issues, |
| 354 | pulls: counts.value.pulls, |
| 355 | } |
| 356 | : null, |
| 357 | // Where the workspace stands against its usage limit, once billing is on. |
| 358 | limit: |
| 359 | status?.enabled && limit?.ok |
| 360 | ? { |
| 361 | exposureMicros: limit.value.exposureMicros, |
| 362 | ceilingMicros: limit.value.ceilingMicros, |
| 363 | state: limit.value.state, |
| 364 | comped: limit.value.trust === "internal", |
| 365 | } |
| 366 | : null, |
| 367 | free: Boolean(status?.free), |
| 368 | // A spend spike or a hold pauses new compute: the shell says so on every page. |
| 369 | compute: |
| 370 | workspace && |
| 371 | entitlements && |
| 372 | (entitlements.paused || entitlements.spike?.status === "open") |
| 373 | ? { |
| 374 | paused: entitlements.paused, |
| 375 | spike: entitlements.spike ?? null, |
| 376 | owner: workspace.role === "owner", |
| 377 | } |
| 378 | : null, |
| 379 | shared, |
| 380 | inbox: unread, |
| 381 | chat: chatUnread, |
| 382 | pins: dockPins ?? undefined, |
| 383 | // While g1t is free every charge is zero, so usage is shown at cost. |
| 384 | // Usage at price, the one figure every page shows. |
| 385 | monthUsageMicros: usage?.ok |
| 386 | ? usage.value.free |
| 387 | ? usage.value.usedMicros |
| 388 | : (usage.value.priceMicros ?? usage.value.spentMicros) |
| 389 | : null, |
| 390 | }; |
| 391 | } |
| 392 | |
| 393 | /** Starred and recent conversations Home's sidebar lists. */ |
| 394 | const SHELL_CONVERSATIONS = 8; |
| 395 | |
| 396 | /** |
| 397 | * What is unread in chat, for the rail, and the starred and latest |
| 398 | * conversations, for Home's sidebar; null when chat is slow to answer or |
| 399 | * does not. |
| 400 | */ |
| 401 | async function chatUnreadFor( |
| 402 | slug: string, |
| 403 | user: User, |
| 404 | ): Promise<ShellData["chat"]> { |
| 405 | const timeout = new Promise<null>((resolve) => |
| 406 | setTimeout(() => resolve(null), CHAT_BADGE_WAIT_MS), |
| 407 | ); |
| 408 | const read = chat |
| 409 | .sidebar(slug, user) |
| 410 | .then((result) => { |
| 411 | if (!result.ok) return null; |
| 412 | const entries = result.value.entries; |
| 413 | const latest = [...entries].sort((a, b) => |
| 414 | (b.channel.last_message_at ?? "").localeCompare( |
| 415 | a.channel.last_message_at ?? "", |
| 416 | ), |
| 417 | ); |
| 418 | return { |
| 419 | ...unreadTotals(entries), |
| 420 | starred: entries.filter((e) => e.starred).slice(0, SHELL_CONVERSATIONS), |
| 421 | recent: latest.slice(0, SHELL_CONVERSATIONS), |
| 422 | }; |
| 423 | }) |
| 424 | .catch(() => null); |
| 425 | return Promise.race([read, timeout]); |
| 426 | } |
| 427 | |
| 428 | /** The longest the rail's Chat badge holds up a page. */ |
| 429 | const CHAT_BADGE_WAIT_MS = 300; |
| 430 | |
| 431 | /** |
| 432 | * How long the sidebar's workspace answers are kept: as long as someone's |
| 433 | * own changes read fresh anyway (lib/perf.ts `PRIMARY_WINDOW_SECONDS`). |
| 434 | */ |
| 435 | const SHELL_TTL_MS = 30_000; |
| 436 | |
| 437 | /** Most repositories listed under Shared with you. */ |
| 438 | const MAX_SHARED = 20; |
| 439 | |
| 440 | /** |
| 441 | * Repositories shared with the user in workspaces they do not belong to, |
| 442 | * by their grants: only those, never the workspace's other repositories. |
| 443 | */ |
| 444 | async function sharedRepos(user: User): Promise<ShellData["shared"]> { |
| 445 | const outside = new Set(sharedWorkspaces(user)); |
| 446 | if (outside.size === 0) return []; |
| 447 | const ids = (user.grants ?? []) |
| 448 | .filter((grant) => outside.has(grant.workspace)) |
| 449 | .map((grant) => grant.repo_id) |
| 450 | .slice(0, MAX_SHARED); |
| 451 | const found = await readableRepos(ids, user); |
| 452 | return found |
| 453 | .map((repo) => ({ |
| 454 | namespace: repo.namespace, |
| 455 | name: repo.name, |
| 456 | isPrivate: repo.isPrivate, |
| 457 | })) |
| 458 | .sort((a, b) => |
| 459 | `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`), |
| 460 | ); |
| 461 | } |
| 462 | |
| 463 | /** |
| 464 | * The root's data as the browser last had it. When a navigation fails in a |
| 465 | * way that takes the root's data with it, the error is still drawn in the |
| 466 | * person's own frame, signed in, not the visitor's. Never kept on the |
| 467 | * server, where one module serves everyone. |
| 468 | */ |
| 469 | let lastRoot: Awaited<ReturnType<typeof loader>> | undefined; |
| 470 | |
| 471 | export function Layout({ children }: { children: React.ReactNode }) { |
| 472 | const nonce = useNonce(); |
| 473 | // Undefined when the root loader itself failed. |
| 474 | const loaded = useRouteLoaderData<typeof loader>("root"); |
| 475 | const inBrowser = typeof document !== "undefined"; |
| 476 | if (loaded && inBrowser) lastRoot = loaded; |
| 477 | const root = loaded ?? (inBrowser ? lastRoot : undefined); |
| 478 | const user = root?.user; |
| 479 | // A page opened with an access token signs its live sockets in with tickets (lib/live-socket.ts). |
| 480 | if (inBrowser) { |
| 481 | setLiveViaToken(Boolean(user?.token?.website)); |
| 482 | offerTicket("/-/live", root?.liveTicket); |
| 483 | } |
| 484 | const { pathname } = useLocation(); |
| 485 | // Drawn around the error page too: a 404 keeps the sidebar out of a |
| 486 | // project or workspace the viewer cannot see. |
| 487 | const error = useRouteError(); |
| 488 | const missing = isRouteErrorResponse(error) && error.status === 404; |
| 489 | // The billing page shows the full banner itself. |
| 490 | const paused = root?.shell?.compute && |
| 491 | root.shell.workspace && |
| 492 | !pathname.endsWith("/-/billing") && ( |
| 493 | <SpikeBanner |
| 494 | compact |
| 495 | slug={root.shell.workspace.slug} |
| 496 | entitlements={{ |
| 497 | paused: root.shell.compute.paused, |
| 498 | spike: root.shell.compute.spike, |
| 499 | }} |
| 500 | owner={root.shell.compute.owner} |
| 501 | /> |
| 502 | ); |
| 503 | // On the few pages an account still confirming its address can open |
| 504 | // besides /confirm-email (policies, support, signing in): the way back. |
| 505 | const verify = user && |
| 506 | awaitsConfirmation(user) && |
| 507 | pathname !== "/confirm-email" && ( |
| 508 | <p |
| 509 | role="status" |
| 510 | className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-warn/30 bg-warn/10 px-4 py-2 text-sm" |
| 511 | > |
| 512 | <span>Confirm your email address to start using g1t.</span> |
| 513 | <Link |
| 514 | to="/confirm-email" |
| 515 | className="font-medium underline underline-offset-4" |
| 516 | > |
| 517 | Enter your code |
| 518 | </Link> |
| 519 | </p> |
| 520 | ); |
| 521 | // A workspace that requires two-factor authentication of someone who |
| 522 | // has not turned it on: they keep their place, and cannot use it yet. |
| 523 | const held = user?.held && |
| 524 | user.held.length > 0 && |
| 525 | pathname !== "/settings/two-factor" && <PolicyNotice held={user.held} />; |
| 526 | const leaving = useLeaving(); |
| 527 | // Auto, Light or Dark: as the cookie said when the page was drawn, or as just switched. |
| 528 | const theme = useThemeChoice(root?.theme); |
| 529 | // Which frame the page is drawn in (lib/chrome.ts): on its own, the app's, or the public one. |
| 530 | const frame = frameOf(pathname, { |
| 531 | signedIn: user != null && !awaitsConfirmation(user), |
| 532 | workspace: (user?.workspaces ?? []).length > 0, |
| 533 | }); |
| 534 | const banner = |
| 535 | paused || verify || held ? ( |
| 536 | <> |
| 537 | {paused} |
| 538 | {verify} |
| 539 | {held} |
| 540 | </> |
| 541 | ) : null; |
| 542 | return ( |
| 543 | <html lang="en" data-theme={themeAttribute(theme)}> |
| 544 | <head> |
| 545 | <meta charSet="utf-8" /> |
| 546 | <meta |
| 547 | name="viewport" |
| 548 | content="width=device-width, initial-scale=1, viewport-fit=cover" |
| 549 | /> |
| 550 | {/* The browser bar matches the page: one colour for a chosen theme, the system's for Auto. */} |
| 551 | {theme === "auto" ? ( |
| 552 | <> |
| 553 | <meta |
| 554 | name="theme-color" |
| 555 | media="(prefers-color-scheme: light)" |
| 556 | content={THEME_COLOR.light} |
| 557 | /> |
| 558 | <meta |
| 559 | name="theme-color" |
| 560 | media="(prefers-color-scheme: dark)" |
| 561 | content={THEME_COLOR.dark} |
| 562 | /> |
| 563 | </> |
| 564 | ) : ( |
| 565 | <meta name="theme-color" content={THEME_COLOR[theme]} /> |
| 566 | )} |
| 567 | <meta name="mobile-web-app-capable" content="yes" /> |
| 568 | <meta name="apple-mobile-web-app-capable" content="yes" /> |
| 569 | <meta |
| 570 | name="apple-mobile-web-app-status-bar-style" |
| 571 | content="black-translucent" |
| 572 | /> |
| 573 | {/* The stylesheet before everything React Router preloads, so a slow |
| 574 | connection paints sooner. */} |
| 575 | <link rel="stylesheet" href={appCss} precedence="default" /> |
| 576 | {root?.analyticsConsent && ( |
| 577 | <meta name="g1t-analytics" content="consent" /> |
| 578 | )} |
| 579 | <Meta /> |
| 580 | <Links nonce={nonce} /> |
| 581 | </head> |
| 582 | <body |
| 583 | className="flex min-h-screen flex-col" |
| 584 | data-frame={frame === "app" && user && root?.shell ? "app" : frame} |
| 585 | > |
| 586 | {/* The first stop for the keyboard: past the menus, to the page. */} |
| 587 | <a |
| 588 | href="#content" |
| 589 | className="sr-only rounded-md bg-fg px-3 py-2 text-sm font-medium text-bg focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-70" |
| 590 | > |
| 591 | Skip to content |
| 592 | </a> |
| 593 | {frame === "standalone" ? ( |
| 594 | <StandaloneFrame>{children}</StandaloneFrame> |
| 595 | ) : frame === "app" && user && root?.shell ? ( |
| 596 | <AppShell |
| 597 | user={user} |
| 598 | shell={root.shell} |
| 599 | missing={missing} |
| 600 | banner={banner} |
| 601 | sidebarClosed={root.sidebarClosed} |
| 602 | > |
| 603 | {children} |
| 604 | </AppShell> |
| 605 | ) : ( |
| 606 | <> |
| 607 | <Progress /> |
| 608 | <PublicHeader user={user} /> |
| 609 | {banner} |
| 610 | <div |
| 611 | id="content" |
| 612 | tabIndex={-1} |
| 613 | {...leaving} |
| 614 | className={`grow outline-none ${leaving.className}`} |
| 615 | > |
| 616 | {children} |
| 617 | </div> |
| 618 | <SiteFooter user={user} /> |
| 619 | </> |
| 620 | )} |
| 621 | {/* A page that cannot reach g1t says so, and keeps what it shows (lib/resilient-fetch.ts). */} |
| 622 | <ConnectionToast /> |
| 623 | <NavigationRecovery /> |
| 624 | {/* Live notifications for the signed-in: the feed socket, toasts, the tab's count (components/notifications). */} |
| 625 | {user && !awaitsConfirmation(user) && ( |
| 626 | <LiveNotifications |
| 627 | workspace={root?.shell?.workspace?.slug ?? null} |
| 628 | inbox={root?.shell?.inbox?.unread ?? null} |
| 629 | sounds={root?.sounds ?? null} |
| 630 | me={{ id: user.id, username: user.username }} |
| 631 | /> |
| 632 | )} |
| 633 | {/* Inside the desktop app: who its runner runs for, and its registration (lib/desktop-runner.ts). */} |
| 634 | {(!user || !awaitsConfirmation(user)) && ( |
| 635 | <DesktopRunnerLink |
| 636 | offer={{ |
| 637 | signedIn: user != null, |
| 638 | workspaces: (user?.workspaces ?? []) |
| 639 | .filter((m) => m.role === "owner") |
| 640 | .map((m) => ({ slug: m.slug, name: m.name ?? null })), |
| 641 | current: root?.shell?.workspace?.slug ?? null, |
| 642 | }} |
| 643 | /> |
| 644 | )} |
| 645 | {/* Inside the desktop app: its settings dialog, and the runner's menu under the title bar's dot. */} |
| 646 | <DesktopApp /> |
| 647 | <AnalyticsConsent /> |
| 648 | <ScrollRestoration nonce={nonce} /> |
| 649 | <Scripts nonce={nonce} /> |
| 650 | </body> |
| 651 | </html> |
| 652 | ); |
| 653 | } |
| 654 | |
| 655 | export default function App() { |
| 656 | const root = useRouteLoaderData<typeof loader>("root"); |
| 657 | const userId = root?.user?.id ?? null; |
| 658 | const agentDefault = root?.agentDefault ?? DEFAULT_AGENT; |
| 659 | useEffect(() => { rememberAgentDefault(agentDefault); }, [agentDefault]); |
| 660 | // Tell analytics who is signed in, once per change; signing out forgets them. |
| 661 | const lastUserId = useRef<string | null>(null); |
| 662 | useEffect(() => { |
| 663 | identify(userId, lastUserId.current); |
| 664 | lastUserId.current = userId; |
| 665 | }, [userId]); |
| 666 | // A navigation that never arrives is loaded as a whole page (lib/stuck.ts). |
| 667 | useStuckNavigationRescue(); |
| 668 | return <Outlet />; |
| 669 | } |
| 670 | |
| 671 | export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) { |
| 672 | return <RouteError error={error} />; |
| 673 | } |