← ui

ide

ui

a VS Code window: a project's tree, tabs, highlighted code, an edit typed on the playhead

npx shadcn add @ag/ide
Already installed? Preview an update
npx shadcn add @ag/ide --dry-run

Your installed source stays unchanged until you update it. How updates work

Latest changes · 2026-11-05
  • Added: onOpen(path), the tabs and the explorer's files pressable, as terminal-editor's bufferline. A press asks for that file in front; the page answers (Ide: active and open; IdeSession: { kind: "open", path } appended to steps), so what is drawn stays the page's instant. Without it they are display-only, as before.
  • The window buttons are app-window's TrafficLights (new dependency @ag/app-window); their data-slot is app-window-lights (was ide-window-buttons).
  • diagnose reads the whole workspace (code-session), in Ide too: a still's squiggles and counts can come from another file.
  • A .cell has its glyph in the explorer and tabs, and is named Cells in the status bar.
  • The language server in VS Code's idiom: squiggles by severity, the hover card with the problem over the type, the suggest widget with its kind icons and the pick's detail, signature help with the active parameter, the rename box, the line gone to lit, the Problems panel, the status bar's error and warning counts. IdeSession and Ide take diagnose; IdeSession plays the new steps.
  • Fixed: ide.css declares Tailwind's properties layer first, as telegram-chat explains.
Updated 2026-11-05 · release notes

also called code editor, vs code, vscode, editor window

shelf devices & demos

uses code-session, code, material, playback, app-window

the demo above, verbatim

ide.demo.tsx
"use client"

import * as React from "react"
import { Sample } from "@/app/samples"
import {
  type BrowserStep,
  browserTimeline,
} from "@/registry/base-nova/lib/browser-session"
import { read } from "@/registry/base-nova/lib/cells"
import {
  type CodeDiagnose,
  type CodeDiagnostic,
  type CodeFile,
  type CodeStep,
  codeTimeline,
  diagnoseWords,
} from "@/registry/base-nova/lib/code-session"
import type { Art, Timeline } from "@/registry/base-nova/lib/macos-session"
import type { Playable } from "@/registry/base-nova/lib/playable"
import { BrowserSession } from "@/registry/base-nova/ui/browser"
import { Ide, IdeSession } from "@/registry/base-nova/ui/ide"
import { Macos } from "@/registry/base-nova/ui/macos"
import { usePlayhead } from "@/registry/base-nova/ui/playback"
import { Player } from "@/registry/base-nova/ui/player"

// #region project
// The project as it is before the edit: its files, by path.
const FILES: CodeFile[] = [
  {
    path: "index.html",
    text: `<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>example</title>
  </head>
  <body>
    <h1>hello</h1>
  </body>
</html>
`,
  },
  {
    path: "README.md",
    text: "# example\n\nOne page, one card.\n",
  },
  {
    path: "src/card.css",
    text: "e-id-card {\n  max-width: 22rem;\n}\n",
  },
]
// #endregion

// #region edit
// What the developer does: open the page, add the embed's script to the head and the
// card to the body, save. A line is counted in the file as it is when its step starts.
const EDIT: CodeStep[] = [
  { kind: "open", path: "index.html" },
  {
    kind: "type",
    line: 5,
    text: '\n    <script type="module" src="https://e-id.to/embed.js"></script>',
    delay: 700,
  },
  {
    kind: "type",
    line: 9,
    text: '\n    <e-id-card handle="adriangalilea"></e-id-card>',
    delay: 500,
  },
  { kind: "save", delay: 400 },
]
const EDIT_PLAYABLE = codeTimeline(FILES, EDIT).playable
// #endregion

// #region language
// A project and what its language server says. The diagnostics are computed by an
// engine run on the text at each instant (here a word list standing in for one), so
// the typo's squiggle comes with the typo and goes with the fix.
const SOURCES: CodeFile[] = [
  {
    path: "src/main.ts",
    text: `import { greet, names } from "./names"

for (const name of names) console.log(greet(name))
`,
  },
  {
    path: "src/names.ts",
    text: `export const names = ["ada", "grace", "edsger"]

export function greet(name: string) {
  return \`hello, \${name}\`
}
`,
  },
]
const TS = diagnoseWords([
  {
    word: "lenght",
    message:
      "Property 'lenght' does not exist on type 'string[]'. Did you mean 'length'?",
    source: "ts(2551)",
  },
])
const SERVER: CodeStep[] = [
  { kind: "open", path: "src/main.ts" },
  { kind: "type", line: 3, text: "\nconsole.log(names.lenght)", delay: 300 },
  { kind: "problems", delay: 300 },
  { kind: "hover", line: 4, column: 20, text: "any" },
  {
    kind: "complete",
    line: 4,
    column: 25,
    items: [
      {
        label: "lastIndexOf",
        kind: "method",
        detail: "(searchElement: string) => number",
      },
      { label: "length", kind: "property", detail: "number" },
      { label: "lenses", kind: "text" },
    ],
    pick: 1,
  },
  {
    kind: "signature",
    line: 4,
    column: 13,
    label: "log(...data: any[]): void",
    active: "...data: any[]",
  },
  { kind: "goto", path: "src/names.ts", line: 3, column: 17, delay: 200 },
  { kind: "rename", line: 3, column: 17, to: "welcome", delay: 300 },
]
const SERVER_TIMELINE = codeTimeline(SOURCES, SERVER, { diagnose: TS })
// #endregion

// #region workspace
// The Cells engine as the language server. Each `.cells` file is read with every other
// file of the workspace as it stands at the instant, saved or not, so a reference in
// money.cells to an account accounts.cells lacks is money.cells's problem, and it goes
// the moment accounts.cells has the account.
const CELLS: CodeDiagnose = (path, workspace) => {
  if (!path.endsWith(".cells")) return []
  const { [path]: text, ...files } = workspace
  const { doc, problems, broken } = read(text as string, { at: path, files })
  const said: CodeDiagnostic[] = [
    ...broken.flatMap((b) =>
      b.span
        ? [
            {
              from: b.span[0],
              to: b.span[0] + b.span[1],
              severity: "error" as const,
              message: b.why,
              source: "cells",
            },
          ]
        : [],
    ),
    ...problems.map((p) => ({
      from: p.span[0],
      to: p.span[0] + p.span[1],
      severity: "error" as const,
      message: `${p.column}: ${p.reason}`,
      source: "cells",
    })),
  ]
  doc.free()
  return said
}
const BOOKS: CodeFile[] = [
  {
    path: "accounts.cells",
    text: `account: text!,kind: text
assets:bank,assets
expenses:home,expenses
`,
  },
  {
    path: "money.cells",
    text: `---
import accounts from "./accounts.cells"
---
what: text,amount: EUR>0,to: accounts.account
rent,950.00,expenses:home
coffee,3.20,expenses:food
`,
  },
]
const FIX: CodeStep[] = [
  { kind: "open", path: "money.cells" },
  { kind: "problems", delay: 300 },
  { kind: "open", path: "accounts.cells", delay: 300 },
  { kind: "type", line: 3, text: "\nexpenses:food,expenses", delay: 400 },
  { kind: "save", delay: 300 },
  { kind: "open", path: "money.cells", delay: 500 },
  { kind: "problems", delay: 300 },
]
const FIX_PLAYABLE = codeTimeline(BOOKS, FIX, { diagnose: CELLS }).playable
// #endregion

// #region pressed
/** The edit's last frame, its tabs and files the reader's to press: each press is
 *  the edit's own next step, an `open` appended, so the frame is still the edit's. */
function Pressed() {
  const [opened, setOpened] = React.useState<CodeStep[]>([])
  return (
    <IdeSession
      project="books"
      files={BOOKS}
      steps={[...FIX, ...opened]}
      diagnose={CELLS}
      progress={1}
      onOpen={(path) => setOpened((o) => [...o, { kind: "open", path }])}
      alt="VS Code on books: money.cells and accounts.cells, a tab each; press a tab or a file to bring it in front"
    />
  )
}
// #endregion

// #region pages
/** The page as the browser draws unstyled HTML: Times, 8 px of margin, a 2em h1. */
function Served({ card }: { card: boolean }) {
  return (
    <div className="min-h-full bg-white p-2 font-serif text-black">
      <h1 className="my-[0.67em] font-bold text-[2em]">hello</h1>
      {card && <IdCard />}
    </div>
  )
}

/** A mock of what `<e-id-card>` draws: the person, their handle, their links. */
function IdCard() {
  return (
    <div className="max-w-[22rem] rounded-2xl border border-zinc-200 bg-white p-4 font-sans shadow-[0_8px_24px_-12px_rgb(0_0_0/0.25)]">
      <div className="flex items-center gap-3">
        <div className="flex size-12 shrink-0 items-center justify-center rounded-full bg-zinc-900 font-semibold text-sm text-white">
          AG
        </div>
        <div className="min-w-0">
          <p className="font-semibold text-[15px] text-zinc-900">
            Adrian Galilea
          </p>
          <p className="text-[13px] text-zinc-500">e-id.to/adriangalilea</p>
        </div>
      </div>
      <div className="mt-3 grid grid-cols-3 gap-2 text-center text-[12px] text-zinc-700">
        {["github", "telegram", "web"].map((link) => (
          <span key={link} className="rounded-lg bg-zinc-100 py-1.5">
            {link}
          </span>
        ))}
      </div>
    </div>
  )
}
// #endregion

// #region desktop
// The browser reloads once the save has landed: its first step waits for the edit,
// and the editor holds its last frame to the visit's end, so one clock runs both.
const SAVED = codeTimeline(FILES, EDIT).ends.at(-1) as number
const VISIT: BrowserStep[] = [{ kind: "reload", delay: SAVED + 300 }]
const VISIT_TIMELINE = browserTimeline("example.com", VISIT)
const CLOCK = VISIT_TIMELINE.total
const BOTH: Playable = {
  duration: CLOCK,
  chapters: [
    ...EDIT_PLAYABLE.chapters,
    { start: VISIT_TIMELINE.starts[0] as number, title: "reload" },
  ],
}
// The pages by address: a function of the serving, since the file changed between
// the first load and the reload.
const PAGES = {
  "example.com": (serving: number) => <Served card={serving > 0} />,
}
const DESKTOP: Timeline = { app: "Code", chord: "", steps: [] }
const NO_ART: Art = { icon: "", glyphs: {} }

/** The Mac on the shared clock: the app in front follows the hand, Code while it
 *  types, Safari from the reload on. */
function Desktop() {
  const ms = usePlayhead(undefined).at * CLOCK
  const browsing = ms >= (VISIT_TIMELINE.starts[0] as number)
  return (
    <Macos
      timeline={DESKTOP}
      art={NO_ART}
      front={browsing ? "Safari" : "Code"}
      device="macbook"
      captions={false}
      alt="A Mac with VS Code and Safari side by side: the embed's script and card typed into index.html, saved, and Safari reloading example.com to show the card"
    >
      <IdeSession
        project="example"
        files={FILES}
        steps={EDIT}
        duration={CLOCK}
        explorer={false}
        alt=""
        className="absolute top-[40px] left-[16px] aspect-auto h-[540px] w-[590px]"
      />
      <BrowserSession
        start="example.com"
        steps={VISIT}
        pages={PAGES}
        alt=""
        className="absolute top-[40px] left-[614px] aspect-auto h-[540px] w-[330px]"
      />
    </Macos>
  )
}
// #endregion

export default function IdeDemo() {
  return (
    <div className="space-y-16">
      <Sample
        name="typed"
        glance="large"
        title="an edit, played"
        description="open a file, type at a line, save: the tab's dot comes and goes"
        with="project edit"
      >
        <Player playable={EDIT_PLAYABLE} label="an edit of index.html">
          <IdeSession
            project="example"
            files={FILES}
            steps={EDIT}
            alt="VS Code: the embed's script typed into the head of index.html, the card into its body, then saved"
          />
        </Player>
      </Sample>

      <Sample
        name="language"
        title="the language server"
        description="a typo squiggled and listed in Problems, its hover, the suggest widget fixing it, signature help, go to definition, a rename across two files"
        with="language"
      >
        <Player
          playable={SERVER_TIMELINE.playable}
          label="VS Code's language server, step by step"
        >
          <IdeSession
            project="names"
            files={SOURCES}
            steps={SERVER}
            diagnose={TS}
            alt="VS Code: a typo typed and squiggled, the Problems panel, a hover, the suggest widget picking length, signature help, go to definition, a rename to welcome"
          />
        </Player>
      </Sample>

      <Sample
        name="problem"
        title="a still: the problem said"
        description="a fixed progress, the squiggle and the Problems panel"
        with="language"
      >
        <IdeSession
          project="names"
          files={SOURCES}
          steps={SERVER}
          diagnose={TS}
          progress={
            ((SERVER_TIMELINE.starts[2] as number) + 1200) /
            SERVER_TIMELINE.total
          }
          alt="VS Code with a squiggled typo and the Problems panel listing it"
        />
      </Sample>

      <Sample
        name="workspace"
        title="a problem another file causes"
        description="diagnose is given every file as it stands: money.cells's unknown account goes once accounts.cells has it"
        with="workspace"
      >
        <Player
          playable={FIX_PLAYABLE}
          label="a problem in money.cells fixed in accounts.cells"
        >
          <IdeSession
            project="books"
            files={BOOKS}
            steps={FIX}
            diagnose={CELLS}
            alt="VS Code: money.cells squiggles expenses:food, no key of accounts, and Problems lists it; the account is typed into accounts.cells, and Problems is empty"
          />
        </Player>
      </Sample>

      <Sample
        name="pressed"
        title="tabs you can press"
        description="onOpen: a tab or an explorer file pressed asks for that file in front, and the page appends the edit's own open step"
        with="workspace pressed"
      >
        <Pressed />
      </Sample>

      <Sample
        name="schemes"
        title="dark and light"
        description="Dark Modern and Light Modern, whatever the page is"
        with="project"
      >
        <div className="grid gap-8 lg:grid-cols-2">
          <Ide
            project="example"
            files={FILES}
            open={["index.html", "src/card.css"]}
            active="src/card.css"
            caret={{ line: 2, column: 19 }}
            scheme="dark"
          />
          <Ide
            project="example"
            files={FILES}
            open={["index.html", "src/card.css"]}
            active="index.html"
            dirty={["index.html"]}
            caret={{ line: 8, column: 18 }}
            scheme="light"
          />
        </div>
      </Sample>

      <Sample
        name="marked"
        title="lines marked, the caret blinking"
        description="a still pointing at what to paste: highlight as code spells it"
        with="project"
      >
        <Ide
          project="example"
          files={[
            {
              path: "index.html",
              text: codeTimeline(FILES, EDIT).final["index.html"] as string,
            },
          ]}
          active="index.html"
          highlight="6,10"
          caret={{ line: 10, column: 51 }}
          blink
          explorer={false}
        />
      </Sample>

      <Sample
        name="mac"
        title="on a mac, with the result"
        description="the edit and the reload on one playhead: the browser waits for the save"
        with="project edit pages desktop"
      >
        <Player playable={BOTH} label="an edit, then the page reloaded">
          <Desktop />
        </Player>
      </Sample>
    </div>
  )
}

the source, every file an install writes

ide.tsx
"use client"

// A CODE EDITOR WINDOW, Visual Studio Code's: the title bar with the window buttons
// and the command centre, the activity bar, the explorer's tree of the project, the
// tabs, the editor with its line numbers, the caret and the code highlighted, the
// language server's say (squiggles, the hover card, the suggest widget, signature
// help, the rename box, the Problems panel), and the status bar with its counts.
// Display-only: a depiction, one picture to assistive tech, zero focusables.
//
// `Ide` draws one instant by hand (a file open, the caret somewhere). `IdeSession`
// plays an edit on the playhead (lib/code-session: open a file, type, replace, save,
// hover, complete, go to a definition, rename), the way `BrowserSession` plays a
// visit and `Terminal` a session, so it can be recorded alone or set on a Mac's
// desktop beside the browser that shows the result.
//
// The code is coloured by `code`'s highlighter (Shiki, lib/code-tokens), read in the
// browser: plain at once, coloured once it has loaded. Each state an edit passes
// through is highlighted once and each character wears its colour there, so nothing
// is highlighted again as keys land and a removal leaves no stale colour.
//
// THE LOOK is VS Code's default themes, Dark Modern and Light Modern, picked by the
// scheme it stands in (the page's, or its own `scheme`), and their token colours
// (Dark+ and Light+). Every length is VS Code's own on a Mac, in CSS px: a window
// laid in `macos`'s stage keeps its proportions with the rest of the desktop. Plain
// only: VS Code draws no glass of its own, and a face it does not have would be ours.

import {
  Blocks,
  Box,
  Braces,
  Bug,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  CircleUserRound,
  CircleX,
  CodeXml,
  Component,
  File,
  Files,
  GitBranch,
  Hash,
  Info,
  Key,
  Package,
  Search,
  Settings,
  Sheet,
  TriangleAlert,
  Type,
  Variable,
  Wrench,
  X,
} from "lucide-react"
import * as React from "react"
import { cn } from "@/lib/utils"
import {
  type CodeCompletionKind,
  type CodeDiagnose,
  type CodeDiagnostic,
  type CodeFile,
  type CodeFrame,
  type CodePopup,
  type CodeSeverity,
  type CodeStep,
  codeFrameAt,
  codeTimeline,
  placeOf,
  problemsOf,
} from "@/registry/base-nova/lib/code-session"
import {
  type CodeColours,
  langOf,
  linesOf,
  paintRuns,
  runsOf,
  VSCODE_THEMES,
} from "@/registry/base-nova/lib/code-tokens"
import { TrafficLights } from "@/registry/base-nova/ui/app-window"
import { type Scheme, useSurfaceScheme } from "@/registry/base-nova/ui/material"
import { schemeOf } from "@/registry/base-nova/ui/material-glass"
import { usePlayhead } from "@/registry/base-nova/ui/playback"
import {
  useCodeColours,
  useCodeColoursOf,
} from "@/registry/base-nova/ui/use-code-colours"
import "./ide.css"

/** The editor's face on a Mac, as VS Code ships it. */
const MONO = "Menlo, Monaco, 'Courier New', monospace"
/** The OS's face, which VS Code's chrome speaks in. */
const SYSTEM = "-apple-system, BlinkMacSystemFont, system-ui, sans-serif"
/** VS Code's editor type on a Mac: 12 px on an 18 px line. */
const LINE_PX = 18

// The two themes' colours, the light half bare and the dark under `scheme-dark:`
// (the scheme the window stands in). One constant per surface.
const BORDER = "border-[#e5e5e5] scheme-dark:border-[#2b2b2b]"
const CHROME = cn(
  "bg-[#f8f8f8] text-[#3b3b3b] scheme-dark:bg-[#181818] scheme-dark:text-[#cccccc]",
  BORDER,
)
const EDITOR =
  "bg-white text-[#3b3b3b] scheme-dark:bg-[#1f1f1f] scheme-dark:text-[#cccccc]"
/** A row's selection where the editor holds the focus (the explorer's file). */
const SELECTED = "bg-[#e4e6f1] scheme-dark:bg-[#37373d]"
/** A pressable row or tab under the pointer: VS Code's list hover. */
const HOVER = "hover:bg-[#f2f2f2] scheme-dark:hover:bg-[#2a2d2e]"
/** The accent: the active tab's top edge, the activity bar's, the remote corner. */
const ACCENT = "bg-[#005fb8] scheme-dark:bg-[#0078d4]"
const ICON_ON = "text-[#1f1f1f] scheme-dark:text-[#d7d7d7]"
const ICON_OFF = "text-[#616161] scheme-dark:text-[#868686]"
/** A widget over the code (hover, suggest, signature, rename): VS Code's
 *  editorWidget and editorHoverWidget. */
const WIDGET =
  "rounded-[3px] border border-[#c8c8c8] bg-[#f8f8f8] text-[#3b3b3b] shadow-[0_2px_8px_rgb(0_0_0/0.16)] scheme-dark:border-[#454545] scheme-dark:bg-[#202020] scheme-dark:text-[#cccccc] scheme-dark:shadow-[0_2px_8px_rgb(0_0_0/0.36)]"
/** The text selected, and a range lit (a definition gone to, a name renamed). */
const SELECTION = "bg-[#add6ff] scheme-dark:bg-[#264f78]"
const RANGE_LIT = "bg-[#fdff0033] scheme-dark:bg-[#ffffff14]"

/** Each severity's ink, as Dark Modern and Light Modern draw its squiggle and its
 *  icon. A hint is a few dots under the start, as VS Code draws it. */
const SEVERITY: Record<
  CodeSeverity,
  {
    squiggle: string
    ink: string
    Icon: React.ComponentType<React.SVGProps<SVGSVGElement>>
  }
> = {
  error: {
    squiggle:
      "underline decoration-wavy decoration-[#e51400] scheme-dark:decoration-[#f14c4c]",
    ink: "text-[#e51400] scheme-dark:text-[#f14c4c]",
    Icon: CircleX,
  },
  warning: {
    squiggle:
      "underline decoration-wavy decoration-[#bf8803] scheme-dark:decoration-[#cca700]",
    ink: "text-[#bf8803] scheme-dark:text-[#cca700]",
    Icon: TriangleAlert,
  },
  info: {
    squiggle:
      "underline decoration-wavy decoration-[#1a85ff] scheme-dark:decoration-[#3794ff]",
    ink: "text-[#1a85ff] scheme-dark:text-[#3794ff]",
    Icon: Info,
  },
  hint: {
    squiggle:
      "underline decoration-dotted decoration-[#6c6c6c] scheme-dark:decoration-[#b5b5b5]",
    ink: "text-[#6c6c6c] scheme-dark:text-[#b5b5b5]",
    Icon: Info,
  },
}
/** The order a list of problems is read in, worst first. */
const WORST: CodeSeverity[] = ["error", "warning", "info", "hint"]

/** A completion's kind as the suggest widget draws it: its codicon's shape and
 *  colour (lucide's nearest shapes, VS Code's colours). */
const KINDS: Record<
  CodeCompletionKind,
  { Icon: React.ComponentType<React.SVGProps<SVGSVGElement>>; ink: string }
> = {
  function: { Icon: Box, ink: "text-[#652d90] scheme-dark:text-[#b180d7]" },
  method: { Icon: Box, ink: "text-[#652d90] scheme-dark:text-[#b180d7]" },
  variable: {
    Icon: Variable,
    ink: "text-[#007acc] scheme-dark:text-[#75beff]",
  },
  constant: {
    Icon: Variable,
    ink: "text-[#007acc] scheme-dark:text-[#75beff]",
  },
  property: { Icon: Wrench, ink: "text-[#424242] scheme-dark:text-[#c5c5c5]" },
  field: { Icon: Wrench, ink: "text-[#007acc] scheme-dark:text-[#75beff]" },
  class: { Icon: Component, ink: "text-[#d67e00] scheme-dark:text-[#ee9d28]" },
  interface: {
    Icon: Component,
    ink: "text-[#007acc] scheme-dark:text-[#75beff]",
  },
  module: { Icon: Package, ink: "text-[#424242] scheme-dark:text-[#c5c5c5]" },
  keyword: { Icon: Key, ink: "text-[#424242] scheme-dark:text-[#c5c5c5]" },
  snippet: { Icon: Braces, ink: "text-[#424242] scheme-dark:text-[#c5c5c5]" },
  text: { Icon: Type, ink: "text-[#424242] scheme-dark:text-[#c5c5c5]" },
}
/** The rows the suggest widget shows before it scrolls. */
const SUGGEST_ROWS = 8

/** A file's glyph, as VS Code's Seti icons colour them by kind. Solid colours, so
 *  a stroke crossing itself never darkens. */
const FILE_GLYPHS: Record<
  string,
  { Icon: React.ComponentType<React.SVGProps<SVGSVGElement>>; colour: string }
> = {
  html: { Icon: CodeXml, colour: "#e37933" },
  css: { Icon: Hash, colour: "#519aba" },
  md: { Icon: File, colour: "#519aba" },
  cells: { Icon: Sheet, colour: "#8dc149" },
}
/** How the status bar names a language. */
const LANG_NAMES: Record<string, string> = {
  html: "HTML",
  css: "CSS",
  js: "JavaScript",
  mjs: "JavaScript",
  ts: "TypeScript",
  tsx: "TypeScript JSX",
  jsx: "JavaScript JSX",
  json: "JSON",
  md: "Markdown",
  py: "Python",
  rs: "Rust",
  go: "Go",
  sh: "Shell Script",
  cells: "Cells",
  text: "Plain Text",
}

const nameOf = (path: string) => path.split("/").at(-1) as string

function FileGlyph({ path }: { path: string }) {
  const ext = langOf(path)
  const glyph = FILE_GLYPHS[ext]
  if (!glyph)
    return (
      <span
        data-slot="ide-file-glyph"
        className="w-4 shrink-0 text-center font-bold text-[8.5px] leading-none tracking-tight"
        style={{
          color:
            ext === "js" || ext === "json" || ext === "mjs"
              ? "#cbcb41"
              : "#519aba",
          fontFamily: SYSTEM,
        }}
      >
        {ext === "json" ? "{}" : ext.slice(0, 3).toUpperCase()}
      </span>
    )
  return (
    <glyph.Icon
      data-slot="ide-file-glyph"
      aria-hidden
      className="size-4 shrink-0"
      style={{ color: glyph.colour }}
      strokeWidth={2.25}
    />
  )
}

/** What the language server shows at an instant (lib/code-session's frame). */
type Said = Pick<
  CodeFrame,
  | "diagnostics"
  | "problems"
  | "popup"
  | "selection"
  | "flash"
  | "prompt"
  | "panel"
>

export interface IdeProps
  extends Omit<React.ComponentProps<"div">, "children"> {
  /** The project's name: the command centre's and the explorer's. */
  project: string
  /** The project's files (`/` between folders): the explorer's tree, and what the
   *  tabs hold. */
  files: CodeFile[]
  /** The file in front, a path of `files`. Absent: the empty editor. */
  active?: string
  /** The tabs, in order. Default: the file in front, alone. */
  open?: string[]
  /** Files with unsaved changes: their tabs show the dot. */
  dirty?: string[]
  /** The caret, in the file in front (both from 1). Absent: the file's start. */
  caret?: { line: number; column: number }
  /** Lines of the file in front to mark, as `code` spells them: `"2"` or
   *  `"1,4-6"`, from 1. What a still points at (the lines a reader pastes). */
  highlight?: string
  /** The caret blinks, as VS Code's does in a focused editor: for a still, where
   *  a caret held on reads as a stuck frame. Off while an edit plays (VS Code
   *  holds it on as keys land). */
  blink?: boolean
  /** The language server's diagnostics of every file, each given the whole
   *  workspace (lib/code-session `CodeDiagnose`): the squiggles, the status bar's
   *  counts. */
  diagnose?: CodeDiagnose
  /** The file in front's colours, read ahead on the server (lib/code-tokens,
   *  `codeColours(text, langOf(path), VSCODE_THEMES)`): a still drawn coloured at
   *  once, and the browser loads no highlighter. Absent, they are read in the
   *  browser after it renders. */
  colours?: CodeColours
  /** The explorer beside the editor. Off, the editor takes the room (a narrow
   *  window); the activity bar stays. */
  explorer?: boolean
  scheme?: Scheme
  /** The tabs and the explorer's files pressable: a press asks for that file in
   *  front, and the page answers (`Ide`: `active` and `open` set to it;
   *  `IdeSession`: `{ kind: "open", path }` appended to `steps`), so what is drawn
   *  stays the page's instant. Absent, display-only. */
  onOpen?: (path: string) => void
}

/** VS Code at one instant: a file open, the caret where `caret` says. */
export function Ide({
  project,
  files,
  active,
  open,
  dirty = [],
  caret,
  highlight,
  blink = false,
  diagnose,
  colours: given,
  explorer = true,
  ...rest
}: IdeProps) {
  const file = active ? files.find((f) => f.path === active) : undefined
  if (active && !file)
    throw new Error(`ide: active ${active} is not one of files`)
  const text = file?.text ?? ""
  const marked = highlight ? linesOf(highlight) : undefined
  const count = text.split("\n").length
  for (const n of marked ?? [])
    if (n < 1 || n > count)
      throw new Error(`ide: highlight ${n} is outside ${active ?? "no file"}`)
  let offset = 0
  if (caret) {
    const lines = text.split("\n")
    const line = lines[caret.line - 1]
    if (
      line === undefined ||
      caret.column < 1 ||
      caret.column > line.length + 1
    )
      throw new Error(
        `ide: caret ${caret.line}:${caret.column} is outside ${active}`,
      )
    offset =
      lines.slice(0, caret.line - 1).reduce((n, l) => n + l.length + 1, 0) +
      caret.column -
      1
  }
  const lang = active ? langOf(active) : "text"
  const colours = useCodeColours(text, lang, VSCODE_THEMES, given)
  const problems = React.useMemo(
    () =>
      diagnose
        ? problemsOf(
            files.map((f) => f.path),
            Object.fromEntries(files.map((f) => [f.path, f.text])),
            diagnose,
          )
        : [],
    [files, diagnose],
  )
  return (
    <IdeWindow
      project={project}
      paths={files.map((f) => f.path)}
      open={open ?? (active ? [active] : [])}
      active={active ?? null}
      text={text}
      origin={undefined}
      colours={colours}
      caret={offset}
      marked={marked}
      blink={blink}
      dirty={dirty}
      explorer={explorer}
      said={{
        ...NOTHING_SAID,
        problems,
        diagnostics: problems.find((p) => p.path === active)?.diagnostics ?? [],
      }}
      {...rest}
    />
  )
}

const NOTHING_SAID: Said = {
  diagnostics: [],
  problems: [],
  popup: null,
  selection: null,
  flash: [],
  prompt: null,
  panel: null,
}

export interface IdeSessionProps
  extends Omit<
    IdeProps,
    | "active"
    | "open"
    | "dirty"
    | "caret"
    | "highlight"
    | "blink"
    | "colours"
    | "role"
    | "aria-label"
  > {
  steps: CodeStep[]
  /** The instant drawn, 0..1 of the edit, for a still. Inside a driver (a Player)
   *  omit it: the driver provides it. */
  progress?: number
  /** The clock's length when the edit shares it with something longer (a browser
   *  that loads the result after the save), ms: the last frame holds to it. The
   *  driver's clip is then that longer one's. */
  duration?: number
  /** Accessible description (a recording is one picture). */
  alt: string
}

/** An edit played on the playhead: the frame at the instant (lib/code-session)
 *  drawn as VS Code. Its playable, for the driver: `codeTimeline(files, steps).playable`. */
export function IdeSession({
  project,
  files,
  steps,
  progress,
  duration,
  diagnose,
  alt,
  explorer = true,
  ...rest
}: IdeSessionProps) {
  const timeline = React.useMemo(
    () => codeTimeline(files, steps, { duration, diagnose }),
    [files, steps, duration, diagnose],
  )
  const f: CodeFrame = codeFrameAt(
    timeline,
    usePlayhead(progress).at * timeline.total,
  )
  const texts = React.useMemo(
    () => timeline.states.map((s) => ({ text: s.text, lang: langOf(s.path) })),
    [timeline],
  )
  const colours = useCodeColoursOf(texts, VSCODE_THEMES)[f.state] ?? null
  return (
    <IdeWindow
      project={project}
      paths={files.map((x) => x.path)}
      open={f.open}
      active={f.active}
      text={f.text}
      origin={f.origin}
      colours={colours}
      caret={f.caret}
      marked={undefined}
      blink={false}
      dirty={f.dirty}
      explorer={explorer}
      said={f}
      role="img"
      aria-label={alt}
      {...rest}
    />
  )
}

interface WindowProps extends Omit<React.ComponentProps<"div">, "children"> {
  project: string
  paths: string[]
  open: string[]
  active: string | null
  /** The front file's text as drawn. */
  text: string
  /** Each drawn character's offset in the text its colours were read from;
   *  absent, its own. */
  origin: number[] | undefined
  colours: CodeColours | null
  caret: number
  /** The lines marked, from 1. */
  marked: Set<number> | undefined
  blink: boolean
  dirty: string[]
  explorer: boolean
  said: Said
  scheme?: Scheme
  onOpen?: (path: string) => void
}

function IdeWindow({
  project,
  paths,
  open,
  active,
  text,
  origin,
  colours,
  caret,
  marked,
  blink,
  dirty,
  explorer,
  said,
  scheme,
  onOpen,
  className,
  style,
  ref,
  ...props
}: WindowProps) {
  const [worn, root] = useSurfaceScheme<HTMLDivElement>(scheme, ref)
  const lang = active ? langOf(active) : "text"
  const place = placeOf(text, caret)
  const count = (s: CodeSeverity) =>
    said.problems.reduce(
      (n, p) => n + p.diagnostics.filter((d) => d.severity === s).length,
      0,
    )
  return (
    <div
      ref={root}
      data-slot="ide"
      className={cn(
        "relative isolate flex aspect-[16/10] w-full select-none flex-col overflow-hidden rounded-[16px] text-[13px]",
        "shadow-[0_0_0_0.5px_rgb(0_0_0/0.22),0_24px_60px_-16px_rgb(0_0_0/0.45)] scheme-dark:shadow-[0_0_0_0.5px_rgb(255_255_255/0.16)]",
        EDITOR,
        schemeOf(worn),
        className,
      )}
      style={{ fontFamily: SYSTEM, ...style }}
      {...props}
    >
      <TitleBar project={project} />
      <div className="flex min-h-0 flex-1">
        <ActivityBar />
        {explorer && (
          <Explorer
            project={project}
            paths={paths}
            active={active}
            onOpen={onOpen}
          />
        )}
        <div className="flex min-w-0 flex-1 flex-col">
          {active ? (
            <>
              <Tabs open={open} active={active} dirty={dirty} onOpen={onOpen} />
              <Breadcrumbs path={active} />
              <Editor
                text={text}
                origin={origin}
                colours={colours}
                caret={place}
                marked={marked}
                blink={blink}
                said={said}
              />
            </>
          ) : (
            <Empty />
          )}
          {said.panel === "problems" && <Problems said={said} />}
        </div>
      </div>
      <StatusBar
        place={active ? place : null}
        lang={LANG_NAMES[lang] ?? lang.toUpperCase()}
        errors={count("error")}
        warnings={count("warning")}
      />
    </div>
  )
}

function TitleBar({ project }: { project: string }) {
  return (
    <div
      data-slot="ide-title-bar"
      className={cn(
        "grid h-[35px] shrink-0 grid-cols-[1fr_minmax(0,320px)_1fr] items-center gap-2 border-b px-3",
        CHROME,
      )}
    >
      <div className="flex items-center gap-4">
        <TrafficLights />
        <span className={cn("flex items-center gap-1", ICON_OFF)}>
          <ChevronLeft aria-hidden className="size-4" />
          <ChevronRight aria-hidden className="size-4" />
        </span>
      </div>
      <div
        data-slot="ide-command-centre"
        className={cn(
          "flex h-[22px] min-w-0 items-center justify-center gap-1.5 rounded-[6px] border bg-[#ffffff] px-2 text-[12px] scheme-dark:bg-[#222222]",
          BORDER,
        )}
      >
        <Search aria-hidden className={cn("size-3.5 shrink-0", ICON_OFF)} />
        <span className="truncate">{project}</span>
      </div>
      <div />
    </div>
  )
}

function ActivityBar() {
  const item = "flex h-12 w-12 items-center justify-center [&_svg]:size-6"
  return (
    <div
      data-slot="ide-activity-bar"
      className={cn("flex w-12 shrink-0 flex-col border-r", CHROME)}
    >
      <span
        className={cn(item, ICON_ON, "relative")}
        data-slot="ide-activity-active"
      >
        <span className={cn("absolute inset-y-0 left-0 w-[2px]", ACCENT)} />
        <Files aria-hidden strokeWidth={1.5} />
      </span>
      {[Search, GitBranch, Bug, Blocks].map((Icon) => (
        <span key={Icon.displayName} className={cn(item, ICON_OFF)}>
          <Icon aria-hidden strokeWidth={1.5} />
        </span>
      ))}
      <span className="flex-1" />
      {[CircleUserRound, Settings].map((Icon) => (
        <span key={Icon.displayName} className={cn(item, ICON_OFF)}>
          <Icon aria-hidden strokeWidth={1.5} />
        </span>
      ))}
    </div>
  )
}

/** A node of the explorer's tree: a folder and what it holds, or a file. */
interface TreeNode {
  name: string
  path: string
  children: TreeNode[] | null
}

/** The paths as VS Code's explorer lists them: folders first, then files, each by
 *  name. */
function treeOf(paths: string[]): TreeNode[] {
  const root: TreeNode[] = []
  for (const path of paths) {
    const parts = path.split("/")
    let level = root
    for (const [i, name] of parts.entries()) {
      const last = i === parts.length - 1
      let node = level.find((n) => n.name === name)
      if (!node) {
        node = {
          name,
          path: parts.slice(0, i + 1).join("/"),
          children: last ? null : [],
        }
        level.push(node)
      }
      if (!last) {
        if (!node.children)
          throw new Error(`ide: ${node.path} is both a file and a folder`)
        level = node.children
      }
    }
  }
  const sort = (nodes: TreeNode[]): TreeNode[] =>
    nodes
      .map((n) => (n.children ? { ...n, children: sort(n.children) } : n))
      .sort(
        (a, b) =>
          Number(!a.children) - Number(!b.children) ||
          a.name.localeCompare(b.name),
      )
  return sort(root)
}

/** A file's tab or explorer row: a button when `onOpen` makes it pressable, pressed
 *  by the pointer only (a recording is one picture to assistive tech, so never a
 *  focus stop), the file in front asking for nothing; else a plain element. */
function FileRow({
  path,
  front,
  onOpen,
  className,
  ...props
}: Omit<React.ComponentProps<"div">, "onClick"> & {
  path: string
  front: boolean
  onOpen?: (path: string) => void
}) {
  if (!onOpen) return <div className={className} {...props} />
  return (
    <button
      type="button"
      tabIndex={-1}
      onClick={() => front || onOpen(path)}
      className={cn("cursor-pointer text-left", className)}
      {...(props as React.ComponentProps<"button">)}
    />
  )
}

function Explorer({
  project,
  paths,
  active,
  onOpen,
}: {
  project: string
  paths: string[]
  active: string | null
  onOpen?: (path: string) => void
}) {
  const tree = React.useMemo(() => treeOf(paths), [paths])
  const rows: React.ReactNode[] = []
  const walk = (nodes: TreeNode[], depth: number) => {
    for (const n of nodes) {
      rows.push(
        <FileRow
          key={n.path}
          path={n.path}
          front={n.path === active}
          onOpen={n.children ? undefined : onOpen}
          data-slot="ide-explorer-row"
          className={cn(
            "flex h-[22px] w-full items-center gap-1.5 pr-2 whitespace-nowrap",
            n.path === active && SELECTED,
            onOpen && !n.children && n.path !== active && HOVER,
          )}
          style={{ paddingLeft: 8 + depth * 8 }}
        >
          {n.children ? (
            <ChevronDown aria-hidden className="size-4 shrink-0" />
          ) : (
            <span className="w-4 shrink-0" />
          )}
          {!n.children && <FileGlyph path={n.path} />}
          <span className="truncate">{n.name}</span>
        </FileRow>,
      )
      if (n.children) walk(n.children, depth + 1)
    }
  }
  walk(tree, 0)
  return (
    <div
      data-slot="ide-explorer"
      className={cn("flex w-[200px] shrink-0 flex-col border-r", CHROME)}
    >
      <div className="flex h-[35px] shrink-0 items-center px-5 text-[11px] tracking-[0.02em]">
        EXPLORER
      </div>
      <div className="flex h-[22px] shrink-0 items-center gap-0.5 px-1 font-bold text-[11px]">
        <ChevronDown aria-hidden className="size-4 shrink-0" />
        <span className="truncate">{project.toUpperCase()}</span>
      </div>
      <div className="min-h-0 flex-1 overflow-hidden">{rows}</div>
    </div>
  )
}

function Tabs({
  open,
  active,
  dirty,
  onOpen,
}: {
  open: string[]
  active: string
  dirty: string[]
  onOpen?: (path: string) => void
}) {
  return (
    <div
      data-slot="ide-tabs"
      className={cn("flex h-[35px] shrink-0 border-b", CHROME)}
    >
      {open.map((path) => {
        const front = path === active
        return (
          <FileRow
            key={path}
            path={path}
            front={front}
            onOpen={onOpen}
            data-slot="ide-tab"
            data-active={front || undefined}
            className={cn(
              "relative -mb-px flex min-w-0 items-center gap-1.5 border-r pr-2 pl-3",
              BORDER,
              front
                ? "bg-white text-[#3b3b3b] scheme-dark:bg-[#1f1f1f] scheme-dark:text-white"
                : "text-[#868686] scheme-dark:text-[#9d9d9d]",
              onOpen &&
                !front &&
                "hover:text-[#3b3b3b] scheme-dark:hover:text-white",
            )}
          >
            {front && (
              <span className={cn("absolute inset-x-0 top-0 h-px", ACCENT)} />
            )}
            <FileGlyph path={path} />
            <span className="truncate">{nameOf(path)}</span>
            <span className="flex size-5 shrink-0 items-center justify-center">
              {dirty.includes(path) ? (
                <span
                  data-slot="ide-tab-dirty"
                  className="size-2 rounded-full bg-current"
                />
              ) : front ? (
                <X aria-hidden className="size-4" />
              ) : null}
            </span>
          </FileRow>
        )
      })}
    </div>
  )
}

function Breadcrumbs({ path }: { path: string }) {
  const parts = path.split("/")
  return (
    <div
      data-slot="ide-breadcrumbs"
      className="flex h-[22px] shrink-0 items-center gap-1 px-4 text-[12px] text-[#616161] scheme-dark:text-[#a9a9a9]"
    >
      {parts.map((p, i) => (
        <React.Fragment key={parts.slice(0, i + 1).join("/")}>
          {i > 0 && <ChevronRight aria-hidden className="size-3.5" />}
          {i === parts.length - 1 && <FileGlyph path={path} />}
          <span>{p}</span>
        </React.Fragment>
      ))}
    </div>
  )
}

/** A marked line, as `code` marks one (code.css `.line.highlighted`): a wash of the
 *  ink, and a bar of it at the line's left edge. */
const MARKED =
  "bg-[color-mix(in_oklab,var(--brand,var(--foreground))_10%,transparent)] shadow-[inset_2px_0_0_color-mix(in_oklab,var(--brand,var(--foreground))_55%,transparent)]"

/** What lies over a piece of a line: a diagnostic's severity, the selection, a
 *  range lit. */
type Mark = CodeSeverity | "selection" | "lit"

/** The editor: the gutter's numbers, each line's runs in their ink under what lies
 *  over them, the current line's frame and the caret, and the widgets the language
 *  server opens over it. It keeps the caret's line in view as VS Code does,
 *  scrolling by whole lines once the caret would pass the foot. */
function Editor({
  text,
  origin,
  colours,
  caret,
  marked,
  blink,
  said,
}: {
  text: string
  origin: number[] | undefined
  colours: CodeColours | null
  caret: { line: number; column: number }
  marked: Set<number> | undefined
  blink: boolean
  said: Said
}) {
  const lines = React.useMemo(
    () => runsOf(text, colours, origin),
    [text, colours, origin],
  )
  const box = React.useRef<HTMLDivElement>(null)
  // How many lines the pane shows: the pane's own height, read from it, the fact
  // the scroll is decided by.
  const [rows, setRows] = React.useState(Number.POSITIVE_INFINITY)
  React.useLayoutEffect(() => {
    const el = box.current
    if (!el) return
    const read = () => setRows(Math.floor(el.clientHeight / LINE_PX))
    read()
    const ro = new ResizeObserver(read)
    ro.observe(el)
    return () => ro.disconnect()
  }, [])
  const top = Math.max(0, caret.line - rows + 2)
  const digits = String(lines.length).length
  const ranges: { from: number; to: number; mark: Mark }[] = [
    ...said.diagnostics.map((d) => ({
      from: d.from,
      to: d.to,
      mark: d.severity,
    })),
    ...(said.selection
      ? [{ ...said.selection, mark: "selection" as const }]
      : []),
    ...said.flash.map((f) => ({ ...f, mark: "lit" as const })),
  ]
  let start = 0
  return (
    <div
      ref={box}
      data-slot="ide-editor"
      className="relative min-h-0 flex-1 overflow-hidden text-[12px] leading-(--ag-ide-line)"
      style={
        {
          fontFamily: MONO,
          "--ag-ide-line": `${LINE_PX}px`,
          "--ag-ide-gutter": `calc(${Math.max(digits, 2)}ch + 46px)`,
        } as React.CSSProperties
      }
    >
      <div
        className="relative"
        style={{ transform: `translateY(${-top * LINE_PX}px)` }}
      >
        {lines.map((runs, i) => {
          const n = i + 1
          const here = n === caret.line
          const length = runs.reduce((k, r) => k + r.text.length, 0)
          // A range over the whole line (a definition gone to) lights the line
          // edge to edge, as VS Code's range highlight; a part of one, its text.
          const lit =
            length > 0 &&
            said.flash.some((f) => f.from <= start && f.to >= start + length)
          const painted = paintRuns(
            runs,
            start,
            lit ? ranges.filter((r) => r.mark !== "lit") : ranges,
          )
          start += length + 1
          return (
            <div
              // biome-ignore lint/suspicious/noArrayIndexKey: a line is its number
              key={i}
              data-slot="ide-line"
              data-highlighted={marked?.has(n) || undefined}
              className={cn(
                "flex h-(--ag-ide-line)",
                marked?.has(n) && MARKED,
                lit && RANGE_LIT,
              )}
            >
              <span
                data-slot="ide-line-number"
                className={cn(
                  "w-(--ag-ide-gutter) shrink-0 pr-[26px] text-right",
                  here
                    ? "text-[#171184] scheme-dark:text-[#cccccc]"
                    : "text-[#6e7681]",
                )}
              >
                {n}
              </span>
              <span
                className={cn(
                  "relative min-w-0 flex-1 whitespace-pre",
                  here &&
                    "shadow-[inset_0_0_0_2px_#eeeeee] scheme-dark:shadow-[inset_0_0_0_2px_#282828]",
                )}
              >
                {painted.map((r, k) => (
                  <span
                    // biome-ignore lint/suspicious/noArrayIndexKey: runs are positional
                    key={k}
                    data-slot={
                      r.marks.some((m) => m in SEVERITY)
                        ? "ide-squiggle"
                        : undefined
                    }
                    className={cn(
                      r.ink &&
                        "text-(--ag-ide-ink) scheme-dark:text-(--ag-ide-ink-dark)",
                      r.marks.includes("selection") && SELECTION,
                      r.marks.includes("lit") && RANGE_LIT,
                      WORST.map((s) =>
                        r.marks.includes(s) ? SEVERITY[s].squiggle : null,
                      ).find(Boolean),
                    )}
                    style={
                      r.ink
                        ? ({
                            "--ag-ide-ink": r.ink.light,
                            "--ag-ide-ink-dark": r.ink.dark,
                            fontStyle: r.ink.italic ? "italic" : undefined,
                            fontWeight: r.ink.bold ? 700 : undefined,
                          } as React.CSSProperties)
                        : undefined
                    }
                  >
                    {r.text}
                  </span>
                ))}
                {here && (
                  <span
                    data-slot="ide-caret"
                    className={cn(
                      "absolute top-0 h-full w-[2px] bg-black scheme-dark:bg-[#aeafad]",
                      blink &&
                        "animate-[ag-ide-blink_1.06s_infinite] motion-reduce:animate-none",
                    )}
                    style={{ left: `${caret.column - 1}ch` }}
                  />
                )}
              </span>
            </div>
          )
        })}
        {said.popup && (
          <Widget
            popup={said.popup}
            place={placeOf(text, said.popup.at)}
            prefix={text.slice(said.popup.at, placeAt(text, caret))}
            above={caret.line - top > 7}
          />
        )}
        {said.prompt && (
          <RenameBox
            text={said.prompt.text}
            place={placeOf(text, said.prompt.at)}
          />
        )}
      </div>
    </div>
  )
}

/** A place in `text` as an offset. */
function placeAt(text: string, place: { line: number; column: number }) {
  const lines = text.split("\n")
  return (
    lines.slice(0, place.line - 1).reduce((n, l) => n + l.length + 1, 0) +
    place.column -
    1
  )
}

/** Where a widget stands: at a place of the code, its line's top or foot. */
function at(place: { line: number; column: number }, above: boolean) {
  return {
    left: `calc(var(--ag-ide-gutter) + ${place.column - 1}ch)`,
    ...(above
      ? { bottom: `calc(100% - ${(place.line - 1) * LINE_PX}px)` }
      : { top: place.line * LINE_PX }),
  }
}

/** The widget a popup is: the hover card, the suggest widget, signature help. */
function Widget({
  popup,
  place,
  prefix,
  above,
}: {
  popup: CodePopup
  place: { line: number; column: number }
  prefix: string
  above: boolean
}) {
  if (popup.kind === "completion") {
    const first = Math.max(0, popup.selected - SUGGEST_ROWS + 1)
    return (
      <div
        data-slot="ide-suggest"
        className={cn(
          "absolute z-10 w-[min(26rem,80%)] overflow-hidden py-px",
          WIDGET,
        )}
        style={{ ...at(place, false), fontFamily: MONO }}
      >
        {popup.items.slice(first, first + SUGGEST_ROWS).map((item, k) => {
          const i = first + k
          const kind = KINDS[item.kind ?? "text"]
          const chosen = i === popup.selected
          const match = item.label
            .toLowerCase()
            .startsWith(prefix.toLowerCase())
            ? prefix.length
            : 0
          return (
            <div
              key={item.label}
              data-slot="ide-suggest-row"
              data-selected={chosen || undefined}
              className={cn(
                "flex h-[22px] items-center gap-1.5 px-1.5",
                chosen &&
                  "bg-[#e8e8e8] outline outline-1 outline-[#005fb8] -outline-offset-1 scheme-dark:bg-[#04395e] scheme-dark:outline-[#0078d4]",
              )}
            >
              <kind.Icon
                aria-hidden
                className={cn("size-3.5 shrink-0", kind.ink)}
                strokeWidth={1.75}
              />
              <span className="min-w-0 flex-1 truncate">
                <span className="font-bold text-[#0066bf] scheme-dark:text-[#2aaaff]">
                  {item.label.slice(0, match)}
                </span>
                {item.label.slice(match)}
              </span>
              {chosen && item.detail && (
                <span className="truncate pl-4 text-[#616161] scheme-dark:text-[#9d9d9d]">
                  {item.detail}
                </span>
              )}
            </div>
          )
        })}
      </div>
    )
  }
  if (popup.kind === "signature")
    return (
      <div
        data-slot="ide-signature"
        className={cn("absolute z-10 max-w-[90%] px-2 py-1", WIDGET)}
        style={{ ...at(place, true), fontFamily: MONO }}
      >
        {popup.active ? (
          <>
            {popup.label.slice(0, popup.active.from)}
            <span className="font-bold underline">
              {popup.label.slice(popup.active.from, popup.active.to)}
            </span>
            {popup.label.slice(popup.active.to)}
          </>
        ) : (
          popup.label
        )}
      </div>
    )
  return (
    <div
      data-slot="ide-hover"
      className={cn(
        "absolute z-10 w-max max-w-[min(32rem,90%)] whitespace-normal",
        WIDGET,
      )}
      style={{ ...at(place, above), fontFamily: SYSTEM }}
    >
      {popup.diagnostics.map((d) => (
        <div
          key={`${d.from}:${d.message}`}
          className={cn("border-b px-2 py-1.5", BORDER)}
        >
          {d.message}
          {d.source && (
            <span className="pl-1.5 text-[#616161] scheme-dark:text-[#9d9d9d]">
              {d.source}
            </span>
          )}
        </div>
      ))}
      <div className="px-2 py-1.5" style={{ fontFamily: MONO }}>
        {popup.text}
      </div>
    </div>
  )
}

/** VS Code's rename box, under the name it renames: the new name being typed. */
function RenameBox({
  text,
  place,
}: {
  text: string
  place: { line: number; column: number }
}) {
  return (
    <div
      data-slot="ide-rename"
      className={cn("absolute z-10 w-56 p-1", WIDGET)}
      style={at(place, false)}
    >
      <div className="flex h-[22px] items-center border border-[#005fb8] bg-white px-1 scheme-dark:border-[#0078d4] scheme-dark:bg-[#313131]">
        {text}
        <span className="ml-px h-[14px] w-px bg-current" />
      </div>
      <div
        className="px-0.5 pt-1 text-[11px] text-[#616161] scheme-dark:text-[#9d9d9d]"
        style={{ fontFamily: SYSTEM }}
      >
        Enter to Rename, ⇧Enter to Preview
      </div>
    </div>
  )
}

/** The Problems panel: every file's diagnostics under its name, worst first. */
function Problems({ said }: { said: Said }) {
  return (
    <div
      data-slot="ide-problems"
      className={cn(
        "flex h-[38%] shrink-0 flex-col overflow-hidden border-t text-[12px]",
        BORDER,
      )}
    >
      <div className="flex h-[35px] shrink-0 items-center gap-5 px-5 text-[11px] tracking-[0.02em]">
        {["PROBLEMS", "OUTPUT", "DEBUG CONSOLE", "TERMINAL"].map((t, i) => (
          <span
            key={t}
            className={cn(
              "flex h-full items-center",
              i === 0
                ? "border-[#005fb8] border-b scheme-dark:border-[#0078d4]"
                : ICON_OFF,
            )}
          >
            {t}
          </span>
        ))}
      </div>
      <div className="min-h-0 flex-1 overflow-hidden">
        {said.problems.length === 0 && (
          <div className="px-5 text-[#616161] scheme-dark:text-[#9d9d9d]">
            No problems have been detected in the workspace.
          </div>
        )}
        {said.problems.map((p) => (
          <React.Fragment key={p.path}>
            <div className="flex h-[22px] items-center gap-1.5 px-2">
              <ChevronDown aria-hidden className="size-4 shrink-0" />
              <FileGlyph path={p.path} />
              <span>{nameOf(p.path)}</span>
              <span className="rounded-full bg-[#c4c4c4] px-1.5 text-[11px] leading-4 scheme-dark:bg-[#616161]">
                {p.diagnostics.length}
              </span>
            </div>
            {[...p.diagnostics]
              .sort(
                (a, b) => WORST.indexOf(a.severity) - WORST.indexOf(b.severity),
              )
              .map((d) => (
                <ProblemRow key={`${d.from}:${d.message}`} d={d} />
              ))}
          </React.Fragment>
        ))}
      </div>
    </div>
  )
}

function ProblemRow({ d }: { d: CodeDiagnostic }) {
  const s = SEVERITY[d.severity]
  return (
    <div
      data-slot="ide-problem"
      className="flex h-[22px] items-center gap-1.5 pr-2 pl-9 whitespace-nowrap"
    >
      <s.Icon aria-hidden className={cn("size-3.5 shrink-0", s.ink)} />
      <span className="truncate">{d.message}</span>
      {d.source && (
        <span className="shrink-0 text-[#616161] scheme-dark:text-[#9d9d9d]">
          {d.source}
        </span>
      )}
    </div>
  )
}

/** No file open: VS Code's empty editor, its shortcuts. */
function Empty() {
  return (
    <div
      data-slot="ide-empty"
      className="flex flex-1 flex-col items-center justify-center gap-2 text-[12px] text-[#868686]"
    >
      {[
        ["Show All Commands", "⇧ ⌘ P"],
        ["Go to File", "⌘ P"],
        ["Find in Files", "⇧ ⌘ F"],
      ].map(([what, keys]) => (
        <div key={what} className="grid w-56 grid-cols-2 gap-4">
          <span className="text-right">{what}</span>
          <span className="tracking-widest">{keys}</span>
        </div>
      ))}
    </div>
  )
}

function StatusBar({
  place,
  lang,
  errors,
  warnings,
}: {
  place: { line: number; column: number } | null
  lang: string
  errors: number
  warnings: number
}) {
  return (
    <div
      data-slot="ide-status-bar"
      className={cn(
        "flex h-[22px] shrink-0 items-center gap-3 border-t pr-3 text-[12px] [&_svg]:size-3.5",
        CHROME,
      )}
    >
      <span
        data-slot="ide-remote"
        className={cn(
          "flex h-full w-9 items-center justify-center text-white",
          ACCENT,
        )}
      >
        <ChevronRight aria-hidden className="-mr-1" strokeWidth={2.5} />
        <ChevronLeft aria-hidden className="-ml-1" strokeWidth={2.5} />
      </span>
      <span className="flex items-center gap-1">
        <GitBranch aria-hidden />
        main
      </span>
      <span data-slot="ide-counts" className="flex items-center gap-1">
        <CircleX aria-hidden /> {errors} <TriangleAlert aria-hidden />{" "}
        {warnings}
      </span>
      <span className="flex-1" />
      {place && (
        <>
          <span>
            Ln {place.line}, Col {place.column}
          </span>
          <span>Spaces: 2</span>
          <span>UTF-8</span>
          <span>LF</span>
          <span>{lang}</span>
        </>
      )}
    </div>
  )
}
ide.css
/* What no utility can express: the caret's blink, a keyframe. */
@layer properties, theme, base, components, utilities;

@layer components {
  /* VS Code's caret blinks on and off with no fade: half a period each. */
  @keyframes ag-ide-blink {
    0%,
    49.9% {
      opacity: 1;
    }
    50%,
    100% {
      opacity: 0;
    }
  }
}