a modal editor in the terminal, helix's look, typing and saving on the playhead
npx shadcn add @ag/terminal-editorAlready installed? Preview an update
npx shadcn add @ag/terminal-editor --dry-runYour installed source stays unchanged until you update it. How updates work
- Changed: drawn from
terminal-editor-screen's model, so a still at the sameprogressis the same screen. Its markup is unchanged. Migration:shadcn add @ag/terminal-editor, which brings@ag/terminal-editor-screen. - Changed: the bufferline and the status line run to the window's edges through its inset (
--terminal-inset, set byterminal), what they hold on the text's grid, live and in a still alike. - Added: taking typing (
onEdit), it selects as an editor does: a drag selects from the press to the release, drawn as the editor's selection and handed toonEditas oneselectstep when the button lets go; ⌘A selects all, ⌘C copies, ⌘X cuts; a key typed, Backspace or Delete over a selection replaces it, an arrow lands on the end it points to. The page's own selection stays out of the box.
also called helix, vim, neovim
shelf devices & demos
comes with terminal-editor-screen
uses terminal, terminal-session, code-session, code, playback
the demo above, verbatim
"use client"
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 { Macos } from "@/registry/base-nova/ui/macos"
import { usePlayhead } from "@/registry/base-nova/ui/playback"
import { Player } from "@/registry/base-nova/ui/player"
import { Terminal } from "@/registry/base-nova/ui/terminal"
import { TerminalEditor } from "@/registry/base-nova/ui/terminal-editor"
// #region edit
// The file before, and what is done to it: the same steps `ide` plays as VS Code.
// Here each `type` is insert mode (INS) and the save is `:w`.
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>
`,
},
]
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 PLAYABLE = codeTimeline(FILES, EDIT).playable
// #endregion
// #region buffers
// Two files open: helix's bufferline across the top, the front one lit, `[+]` on
// the one with unsaved keys; `open` switches between them.
const SITE: CodeFile[] = [
FILES[0] as CodeFile,
{
path: "style.css",
text: `body {
font-family: system-ui;
}
`,
},
]
const SWITCH: CodeStep[] = [
{ kind: "open", path: "index.html" },
{ kind: "open", path: "style.css", delay: 500 },
{ kind: "type", line: 2, text: "\n margin: 2rem;", delay: 300 },
{ kind: "open", path: "index.html", delay: 500 },
{ kind: "type", line: 8, text: "\n <p>styled</p>", delay: 300 },
{ kind: "save", delay: 400 },
]
const SWITCH_PLAYABLE = codeTimeline(SITE, SWITCH).playable
// #endregion
// #region wrap
// A line longer than the screen, drawn on as many rows as it needs: the file keeps
// it one line.
const NOTES: CodeFile[] = [
{
path: "notes.csv",
text: `date,place,people,what happened,what it cost,who paid,how it was paid,what is left to do
2026-08-14,the coast,4,fuel and tolls on the way down,84.20,ana,card,nothing
`,
},
]
const WRAP_EDIT: CodeStep[] = [
{ kind: "open", path: "notes.csv" },
{
kind: "type",
line: 2,
text: "\n2026-08-15,the market,2,groceries for the week,96.75,luis,cash,split it",
delay: 500,
},
]
const WRAP_PLAYABLE = codeTimeline(NOTES, WRAP_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 undercurl 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[]'",
source: "typescript",
},
])
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" },
{ label: "length", kind: "property" },
{ 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: "open", path: "accounts.cells", delay: 2200 },
{ kind: "type", line: 3, text: "\nexpenses:food,expenses", delay: 400 },
{ kind: "save", delay: 300 },
{ kind: "open", path: "money.cells", delay: 500 },
]
const FIX_PLAYABLE = codeTimeline(BOOKS, FIX, { diagnose: CELLS }).playable
// #endregion
// #region desktop
// The browser reloads once `:w` has landed; 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: [
...PLAYABLE.chapters,
{ start: VISIT_TIMELINE.starts[0] as number, title: "reload" },
],
}
/** The page as the browser draws unstyled HTML, the card once the file has it. */
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 && (
<div className="max-w-[22rem] rounded-2xl border border-zinc-200 p-4 font-sans">
<p className="font-semibold text-[15px]">Adrian Galilea</p>
<p className="text-[13px] text-zinc-500">e-id.to/adriangalilea</p>
</div>
)}
</div>
)
}
const PAGES = {
"example.com": (serving: number) => <Served card={serving > 0} />,
}
const DESKTOP: Timeline = { app: "Terminal", chord: "", steps: [] }
const NO_ART: Art = { icon: "", glyphs: {} }
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" : "Terminal"}
device="macbook"
captions={false}
alt="A Mac with a terminal and Safari side by side: the embed's script and card typed into index.html in helix, :w, and Safari reloading example.com to show the card"
>
<Terminal
alt=""
accent="#e7a13c"
size="11px"
className="absolute top-[40px] left-[16px] w-[590px]"
>
<TerminalEditor files={FILES} steps={EDIT} duration={CLOCK} rows={25} />
</Terminal>
<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 TerminalEditorDemo() {
return (
<div className="space-y-16">
<Sample
name="helix"
glance="large"
title="helix, played"
description="insert mode while keys land, [+] while unsaved, :w answered"
with="edit"
>
<Player playable={PLAYABLE} label="an edit of index.html in helix">
<Terminal
alt="helix in a terminal: the embed's script typed into index.html's head, the card into its body, then :w"
accent="#e7a13c"
>
<TerminalEditor files={FILES} steps={EDIT} />
</Terminal>
</Player>
</Sample>
<Sample
name="phosphor"
title="still, on the default phosphor"
description="a fixed progress: mid-word, in insert mode"
with="edit"
>
<Terminal alt="helix mid-edit, in insert mode">
<TerminalEditor
files={FILES}
steps={EDIT}
progress={0.55}
rows={12}
/>
</Terminal>
</Sample>
<Sample
name="language"
title="the language server"
description="a typo undercurled with its message at the line's end, space d's picker, a hover, the completion menu fixing it, signature help, goto definition, a rename across two files"
with="language"
>
<Player
playable={SERVER_TIMELINE.playable}
label="helix's language server, step by step"
>
<Terminal
alt="helix: a typo typed and diagnosed, the diagnostics picker, a hover, completion picking length, signature help, goto definition, a rename to welcome"
accent="#e7a13c"
>
<TerminalEditor files={SOURCES} steps={SERVER} diagnose={TS} />
</Terminal>
</Player>
</Sample>
<Sample
name="problem"
title="a still: the problem said"
description="a fixed progress: the gutter's mark, the undercurl, the message, the counts"
with="language"
>
<Terminal alt="helix with a diagnosed typo">
<TerminalEditor
files={SOURCES}
steps={SERVER}
diagnose={TS}
rows={8}
progress={
(SERVER_TIMELINE.ends[1] as number) / SERVER_TIMELINE.total
}
/>
</Terminal>
</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"
>
<Terminal
alt="helix: money.cells undercurls expenses:food, no key of accounts; accounts.cells gets the account typed in, and money.cells's problem is gone"
accent="#e7a13c"
>
<TerminalEditor
files={BOOKS}
steps={FIX}
diagnose={CELLS}
rows={9}
/>
</Terminal>
</Player>
</Sample>
<Sample
name="buffers"
title="two files, the bufferline"
description="helix's bufferline while more than one file is open: the front one lit, [+] on unsaved keys"
with="edit buffers"
>
<Player
playable={SWITCH_PLAYABLE}
label="an edit across two files in helix"
>
<Terminal
alt="helix with two buffers: a margin typed into style.css, a paragraph into index.html, then :w"
accent="#e7a13c"
>
<TerminalEditor files={SITE} steps={SWITCH} />
</Terminal>
</Player>
</Sample>
<Sample
name="wrap"
title="soft-wrap"
description="lines longer than the screen drawn on several rows behind ↪, numbered once; the file keeps each one line"
with="wrap"
>
<Player
playable={WRAP_PLAYABLE}
label="a long csv line, soft-wrapped in helix"
>
<Terminal
alt="helix soft-wrapping a csv whose header is longer than the screen"
accent="#e7a13c"
className="mx-auto max-w-[36rem]"
>
<TerminalEditor
files={NOTES}
steps={WRAP_EDIT}
rows={10}
softWrap
/>
</Terminal>
</Player>
</Sample>
<Sample
name="mac"
title="on a mac, with the result"
description="the edit and the reload on one playhead: the browser waits for :w"
with="edit desktop"
>
<Player
playable={BOTH}
label="an edit in helix, then the page reloaded"
>
<Desktop />
</Player>
</Sample>
</div>
)
}the source, every file an install writes
"use client"
// A MODAL EDITOR IN THE TERMINAL, helix's look: the bufferline of open files across
// the top, the diagnostics gutter and line numbers, the code highlighted, the caret a
// block in normal mode and a bar in insert, what the language server says (the range
// undercurled, the message at the line's end as helix's end-of-line diagnostics, the
// hover and the completion menu as helix's bordered popups, signature help, `space d`'s
// diagnostics picker), the status line with the mode (NOR, INS), the file, whether it
// is unsaved and the error and warning counts, and the command line where `:w` and
// `rename-to:` are typed and answered. It plays an edit on the playhead
// (lib/code-session, the same steps `ide` plays as VS Code), and draws inside
// `terminal`'s window as the full-screen program it is:
//
// <Terminal alt="…"><TerminalEditor files={…} steps={…} /></Terminal>
//
// What is on the screen is decided by lib/terminal-editor-screen (`editorScreen`), the
// same model its SVG still draws (`renderEditorSvg`), so a still and this view cannot
// disagree; this file places the model's cells in `ch` and `em` and adds what only a
// page has: the caret's blink, the presses and the keys.
//
// It wears the terminal's phosphor (`useTerminalPalette`) for everything but the
// code, which takes code's dark theme (lib/code-tokens), and the severities, which
// take the terminal's own red, yellow, blue and grey: a terminal is dark whatever
// the page is. Display-only, like the terminal around it, but for the bufferline's
// files when `onOpen` makes them pressable, and the text when `onEdit` makes it a text
// box: each press and key handed to the page as the step it makes, the frame still the
// edit's.
import * as React from "react"
import {
type CodeDiagnose,
type CodeFile,
type CodePopup,
type CodeStep,
codeFrameAt,
codeTimeline,
keyStep,
offsetAt,
placeOf,
} from "@/registry/base-nova/lib/code-session"
import { langOf } from "@/registry/base-nova/lib/code-tokens"
import {
type EditorRow,
type EditorScreen,
EOL_GAP,
EOL_OPACITY,
editorScreen,
MENU_ROWS,
SELECTION_ALPHA,
SEVERITY,
TEXT_TOP,
WRAP_INDICATOR,
} from "@/registry/base-nova/lib/terminal-editor-screen"
import { LINE_HEIGHT } from "@/registry/base-nova/lib/terminal-session"
import { usePlayhead } from "@/registry/base-nova/ui/playback"
import { useTerminalPalette } from "@/registry/base-nova/ui/terminal"
import { useCodeColoursOf } from "@/registry/base-nova/ui/use-code-colours"
export interface TerminalEditorProps {
/** The files the editor can open (`/` between folders). */
files: CodeFile[]
steps: CodeStep[]
/** The instant drawn, 0..1 of the edit, for a still. Inside a driver (a Player)
* omit it: the driver provides it. The same instant as an SVG still:
* lib/terminal-editor-screen `editorStill` and `renderEditorSvg`. */
progress?: number
/** The clock's length when the edit shares it with something longer, ms: the
* last frame holds to it (lib/code-session `codeTimeline`). */
duration?: number
/** The language server's diagnostics, run on each file with every file's text at
* the instant (lib/code-session `CodeDiagnose`): a problem one file causes in
* another shows, and goes when it is fixed there. */
diagnose?: CodeDiagnose
/** Rows of the screen above the status and command lines: the text's, and the
* bufferline's when it shows. The view follows the caret, a few rows short of
* the foot, as helix scrolls. */
rows?: number
/** Helix's `bufferline`: the open files across the top `always`, only while
* more than one is open (`multiple`, helix's choice when set), or `never`. */
bufferline?: "always" | "multiple" | "never"
/** Helix's `soft-wrap`: a line longer than the screen is drawn on as many rows as
* it needs, each row after the first behind helix's `↪ `, numbered once. The file
* is never changed: a line that must stay one line (a header) stays one. */
softWrap?: boolean
/** The bufferline's files pressable: a press asks for that file in front, and the
* page answers with the edit's next step (`{ kind: "open", path }` appended to
* `steps`), so what is drawn stays the edit's frame. Absent, display-only. */
onOpen?: (path: string) => void
/** The editor takes typing as a text box does, with no modes: focused, it is in
* insert, a click places the caret, a key types at it, the arrows, Home and End
* move it, Backspace and Delete take a character. Each is handed over as the
* step it makes (`keyStep`), and the page answers by appending it to `steps`,
* as `onOpen`. Inside `<Terminal interactive>`, so the box is not hidden in one
* picture. Absent, display-only. */
onEdit?: (step: CodeStep) => void
}
/** How long the caret has been still, ms, before it blinks, and a blink's whole
* period: a terminal's. */
const STILL_MS = 500
const BLINK_MS = 1060
/** The caret: solid while keys land, blinking once it has been still (`still`), on the
* page's clock, as a terminal's does; solid always under reduced motion. */
function Caret({
still,
style,
}: {
still: boolean
style: React.CSSProperties
}) {
const ref = React.useRef<HTMLSpanElement>(null)
React.useEffect(() => {
const el = ref.current
if (!still || !el || matchMedia("(prefers-reduced-motion: reduce)").matches)
return
const blink = el.animate([{ opacity: 1 }, { opacity: 0 }], {
duration: BLINK_MS,
iterations: Number.POSITIVE_INFINITY,
easing: "steps(2, jump-none)",
})
return () => blink.cancel()
}, [still])
return (
<span
ref={ref}
data-slot="terminal-editor-caret"
className="absolute top-0 h-full"
style={style}
/>
)
}
/** The screen's whole width in columns (the gutter's included, as the model counts
* them) over one character's width, as the page draws them. Unbounded until it is
* read. */
function useColumns(): [React.RefObject<HTMLSpanElement | null>, number] {
const probe = React.useRef<HTMLSpanElement>(null)
const [columns, setColumns] = React.useState(Number.POSITIVE_INFINITY)
React.useLayoutEffect(() => {
const el = probe.current
const room = el?.closest<HTMLElement>('[data-slot="terminal-editor"]')
if (!el || !room) return
const read = () => {
// Not laid out (inside `display: none`, a layout kept for a narrow window): no
// width to count yet. The observer reads again once it is.
if (el.getClientRects().length === 0) return
const ch = el.getBoundingClientRect().width / 10
if (!(ch > 0))
throw new Error("terminal-editor: a character with no width")
setColumns(Math.floor(room.clientWidth / ch))
}
read()
const sizes = new ResizeObserver(read)
sizes.observe(room)
return () => sizes.disconnect()
}, [])
return [probe, columns]
}
const nameOf = (path: string) => path.split("/").at(-1) as string
/** A bar (the bufferline, the status line) through the window's inset to its edges, as
* a terminal extends a row's ground into its padding; what it holds stays on the grid. */
const EDGE_TO_EDGE: React.CSSProperties = {
marginInline: "calc(-1 * var(--terminal-inset, 0px))",
paddingInline: "var(--terminal-inset, 0px)",
}
/** An edit played in the terminal: the frame at the instant drawn as helix. Its
* playable, for the driver: `codeTimeline(files, steps).playable`. */
export function TerminalEditor({
files,
steps,
progress,
duration,
diagnose,
rows = 14,
bufferline = "multiple",
softWrap = false,
onOpen,
onEdit,
}: TerminalEditorProps) {
const palette = useTerminalPalette()
const [focused, setFocused] = React.useState(false)
const timeline = React.useMemo(
() => codeTimeline(files, steps, { duration, diagnose }),
[files, steps, duration, diagnose],
)
const ms = usePlayhead(progress).at * timeline.total
const played = codeFrameAt(timeline, ms)
// A selection being dragged, the editor's own until the button lets go: drawn as the
// frame's, and handed to `onEdit` as one `select` step when the drag ends.
const [drag, setDrag] = React.useState<{
anchor: number
head: number
} | null>(null)
const dragging = React.useRef(drag)
dragging.current = drag
const f = drag
? {
...played,
caret: drag.head,
selection:
drag.head === drag.anchor
? null
: {
from: Math.min(drag.anchor, drag.head),
to: Math.max(drag.anchor, drag.head),
},
mode: drag.head === drag.anchor ? played.mode : ("select" as const),
}
: played
const path = f.active ?? "[scratch]"
const texts = React.useMemo(
() => timeline.states.map((s) => ({ text: s.text, lang: langOf(s.path) })),
[timeline],
)
const colours = useCodeColoursOf(texts)[f.state] ?? null
const [probe, columns] = useColumns()
// A text box has no modes: taking typing, the editor is in insert.
const screen = editorScreen(f, {
palette,
colours,
rows,
columns,
bufferline,
softWrap,
insert: onEdit !== undefined && focused,
})
const { status, caret } = screen
/** What the selection holds, the file's own text. */
const selected = () =>
f.selection ? f.text.slice(f.selection.from, f.selection.to) : ""
/** A key, as the step it makes. Select all, copy and cut are the box's, never the
* page's: the box keeps its own selection. */
const key = (e: React.KeyboardEvent) => {
if (!onEdit) return
if (e.metaKey || e.ctrlKey) {
const k = e.key.toLowerCase()
if (k === "a") {
e.preventDefault()
onEdit({
kind: "select",
line: 1,
column: 1,
to: placeOf(f.text, f.text.length),
})
} else if ((k === "c" || k === "x") && f.selection) {
e.preventDefault()
void navigator.clipboard.writeText(selected())
if (k === "x") {
const cut = keyStep("Delete", f.text, f.caret, f.selection)
if (cut) onEdit(cut)
}
}
return
}
if (e.altKey) return
const step = keyStep(e.key, f.text, f.caret, f.selection)
if (!step) return
e.preventDefault()
onEdit(step)
}
/** Where a pointer stands on a screen row, as an offset of the file's text. */
const offsetOn = (row: EditorRow, e: React.PointerEvent<HTMLElement>) => {
const ch = (probe.current?.getBoundingClientRect().width ?? 0) / 10
if (!(ch > 0)) return null
const x = e.clientX - e.currentTarget.getBoundingClientRect().left
const indent = row.first ? 0 : WRAP_INDICATOR.length
const at = Math.round(x / ch) - indent + row.from
return offsetAt(f.text, {
line: row.line + 1,
column: Math.min(Math.max(at, row.from), row.length) + 1,
})
}
/** A press on a screen row: the caret placed where it landed, and a drag begun from
* there, which ends wherever the button lets go, on the editor or off it. */
const press = (row: EditorRow, e: React.PointerEvent<HTMLElement>) => {
const at = onEdit ? offsetOn(row, e) : null
if (!onEdit || at === null) return
onEdit({ kind: "place", ...placeOf(f.text, at) })
setDrag({ anchor: at, head: at })
const text = f.text
const release = () => {
window.removeEventListener("pointerup", release)
const d = dragging.current
setDrag(null)
if (d && d.head !== d.anchor)
onEdit({
kind: "select",
...placeOf(text, d.anchor),
to: placeOf(text, d.head),
})
}
window.addEventListener("pointerup", release)
}
/** The pointer over a row with the button down, the drag's head where it is. */
const extend = (row: EditorRow, e: React.PointerEvent<HTMLElement>) => {
if (!dragging.current || (e.buttons & 1) === 0) return
const at = offsetOn(row, e)
if (at !== null && at !== dragging.current.head)
setDrag({ anchor: dragging.current.anchor, head: at })
}
return (
<div
data-slot="terminal-editor"
// Taking typing, a press places the caret and never starts the page's selection.
className={`whitespace-pre outline-none${onEdit ? " select-none" : ""}`}
style={{ color: palette.command }}
{...(onEdit && {
role: "textbox",
"aria-multiline": true,
"aria-label": `${nameOf(path)}, editable`,
tabIndex: 0,
onKeyDown: key,
onFocus: () => setFocused(true),
onBlur: () => setFocused(false),
})}
>
{screen.buffers && (
<div
data-slot="terminal-editor-bufferline"
className="flex overflow-hidden"
style={{
background: palette.bar,
height: `${LINE_HEIGHT}em`,
...EDGE_TO_EDGE,
}}
>
{screen.buffers.map((b) => {
const look = {
className: "shrink-0 px-[1ch]",
style: b.front
? { background: palette.dot, color: palette.command }
: { color: palette.muted },
}
return onOpen ? (
<button
key={b.path}
type="button"
data-slot="terminal-editor-buffer"
data-active={b.front || undefined}
// The terminal is one picture to assistive tech (role img, its
// screen hidden): a tab is for the pointer, never a focus stop.
tabIndex={-1}
onClick={() => b.front || onOpen(b.path)}
{...look}
className={`${look.className} cursor-pointer whitespace-pre transition-colors hover:brightness-150`}
>
{b.label}
</button>
) : (
<span
key={b.path}
data-slot="terminal-editor-buffer"
data-active={b.front || undefined}
{...look}
>
{b.label}
</span>
)
})}
</div>
)}
<div
data-slot="terminal-editor-text"
className="relative"
style={{ paddingTop: `${TEXT_TOP}em` }}
>
{screen.rows.map((row, r) => {
const worst = row?.worst ?? null
return (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: a screen row
key={r}
data-slot="terminal-editor-line"
className="flex overflow-hidden"
style={{ height: `${LINE_HEIGHT}em` }}
>
<span
data-slot="terminal-editor-gutter"
className="w-[1ch] shrink-0"
style={{
color: worst ? SEVERITY[worst.severity].ink : undefined,
}}
>
{row?.first && worst ? "●" : ""}
</span>
<span
data-slot="terminal-editor-number"
className="shrink-0 pr-[1ch] text-right"
style={{
width: `${screen.digits + 2}ch`,
color: row?.current ? palette.accent : palette.prompt,
}}
>
{row?.first ? row.line + 1 : ""}
</span>
<span
className={`relative min-w-0 flex-1${onEdit ? " cursor-text" : ""}`}
onPointerDown={onEdit && row ? (e) => press(row, e) : undefined}
onPointerMove={
onEdit && row ? (e) => extend(row, e) : undefined
}
>
{r === 0 && (
// One character's width ten times over: what the screen's columns
// are counted in.
<span ref={probe} aria-hidden className="invisible absolute">
0000000000
</span>
)}
{row && !row.first && (
<span
data-slot="terminal-editor-wrap"
style={{ color: palette.prompt }}
>
{WRAP_INDICATOR}
</span>
)}
{row?.runs.map((run, k) => (
<span
// biome-ignore lint/suspicious/noArrayIndexKey: runs are positional
key={k}
data-slot={
run.undercurl ? "terminal-editor-undercurl" : undefined
}
style={{
color: run.color ?? undefined,
fontStyle: run.italic ? "italic" : undefined,
fontWeight: run.bold ? 700 : undefined,
background: run.selected
? `color-mix(in oklab, ${palette.accent} ${Math.round(SELECTION_ALPHA * 100)}%, transparent)`
: undefined,
textDecoration: run.undercurl
? `underline wavy ${SEVERITY[run.undercurl].ink}`
: undefined,
}}
>
{run.text}
</span>
))}
{row?.last && worst && (
// Helix's end-of-line diagnostic: the worst one's message, after
// the line, in its severity's colour.
<span
data-slot="terminal-editor-eol"
style={{
color: SEVERITY[worst.severity].ink,
opacity: EOL_OPACITY,
}}
>
{EOL_GAP}
{worst.message}
</span>
)}
{caret?.row === r && (
<Caret
still={f.keyed < 0 || ms - f.keyed >= STILL_MS}
style={{
left: `${caret.column}ch`,
width: caret.insert ? "2px" : "1ch",
background: palette.accent,
mixBlendMode: caret.insert ? undefined : "difference",
}}
/>
)}
</span>
</div>
)
})}
{screen.popup && (
<Popup
popup={screen.popup.popup}
at={screen.popup}
gutter={screen.gutter}
rows={screen.rows.length}
/>
)}
{screen.picker && <Picker picker={screen.picker} />}
</div>
<div
data-slot="terminal-editor-status"
className="flex gap-[1ch]"
style={{ background: palette.bar, ...EDGE_TO_EDGE }}
>
<span
data-slot="terminal-editor-mode"
className="px-[1ch] font-bold"
style={{
background: status.insert ? palette.command : palette.accent,
color: palette.bg,
}}
>
{status.mode}
</span>
<span className="min-w-0 flex-1 truncate">{status.file}</span>
{status.counts.map(({ severity, n }) => (
<span
key={severity}
data-slot="terminal-editor-count"
style={{ color: SEVERITY[severity].ink }}
>
● {n}
</span>
))}
<span className="pr-[1ch]" style={{ color: palette.muted }}>
{status.place}
</span>
</div>
<div
data-slot="terminal-editor-command"
className="px-[1ch]"
style={{ color: palette.muted }}
>
{screen.command.text || " "}
{screen.command.prompt && (
<span style={{ background: palette.accent, color: palette.bg }}>
{" "}
</span>
)}
</div>
</div>
)
}
/** A helix popup at a place of the screen, drawn in a box-drawing border: the
* hover's docs and signature help above the caret's row when they fit there, the
* completion menu below it. */
function Popup({
popup,
at,
gutter,
rows,
}: {
popup: CodePopup
at: { row: number; column: number; below: boolean }
gutter: number
rows: number
}) {
const palette = useTerminalPalette()
const box: React.CSSProperties = {
position: "absolute",
zIndex: 10,
left: `${gutter + at.column}ch`,
border: `1px solid ${palette.prompt}`,
background: palette.bar,
color: palette.command,
maxWidth: `calc(100% - ${gutter + at.column}ch)`,
...(at.below
? { top: `calc(${TEXT_TOP}em + ${(at.row + 1) * LINE_HEIGHT}em)` }
: { bottom: `calc(100% - ${TEXT_TOP}em - ${at.row * LINE_HEIGHT}em)` }),
}
if (popup.kind === "completion") {
const first = Math.max(0, popup.selected - MENU_ROWS + 1)
const shown = popup.items.slice(first, first + Math.min(MENU_ROWS, rows))
const width = Math.max(...shown.map((i) => i.label.length))
return (
<div data-slot="terminal-editor-completion" style={box}>
{shown.map((item, k) => {
const chosen = first + k === popup.selected
return (
<div
key={item.label}
data-selected={chosen || undefined}
className="px-[1ch]"
style={
chosen
? { background: palette.accent, color: palette.bg }
: undefined
}
>
{item.label.padEnd(width + 2)}
<span style={{ color: chosen ? palette.bg : palette.muted }}>
{item.kind ?? "text"}
</span>
</div>
)
})}
</div>
)
}
if (popup.kind === "signature")
return (
<div
data-slot="terminal-editor-signature"
className="px-[1ch]"
style={box}
>
{popup.active ? (
<>
{popup.label.slice(0, popup.active.from)}
<span style={{ color: palette.accent, fontWeight: 700 }}>
{popup.label.slice(popup.active.from, popup.active.to)}
</span>
{popup.label.slice(popup.active.to)}
</>
) : (
popup.label
)}
</div>
)
return (
<div
data-slot="terminal-editor-hover"
className="whitespace-pre-wrap px-[1ch]"
style={box}
>
{popup.text}
</div>
)
}
/** `space d`: helix's diagnostics picker over the editor, its prompt, the count,
* and one row per diagnostic of the file (its severity, source, message, place),
* the first selected. */
function Picker({ picker }: { picker: NonNullable<EditorScreen["picker"]> }) {
const palette = useTerminalPalette()
const list = picker.diagnostics
return (
<div
data-slot="terminal-editor-picker"
className="absolute inset-x-[4ch] top-[1em] z-20 overflow-hidden"
style={{
border: `1px solid ${palette.prompt}`,
background: palette.bg,
color: palette.command,
}}
>
<div className="flex px-[1ch]">
<span style={{ color: palette.accent }}>{"> "}</span>
<span
style={{ background: palette.accent, width: "1ch" }}
aria-hidden
/>
<span className="flex-1" />
<span style={{ color: palette.muted }}>
{list.length}/{list.length}
</span>
</div>
<div style={{ borderTop: `1px solid ${palette.prompt}` }}>
{list.length === 0 && (
<div className="px-[1ch]" style={{ color: palette.muted }}>
no diagnostics in {picker.name}
</div>
)}
{list.slice(0, MENU_ROWS).map((d, i) => {
const p = placeOf(picker.text, d.from)
return (
<div
key={`${d.from}:${d.message}`}
data-slot="terminal-editor-picker-row"
className="flex gap-[2ch] overflow-hidden px-[1ch]"
style={i === 0 ? { background: palette.dot } : undefined}
>
<span
className="w-[5ch] shrink-0"
style={{ color: SEVERITY[d.severity].ink }}
>
{SEVERITY[d.severity].name}
</span>
<span className="shrink-0" style={{ color: palette.muted }}>
{d.source ?? ""}
</span>
<span className="min-w-0 flex-1 truncate">{d.message}</span>
<span className="shrink-0" style={{ color: palette.muted }}>
{picker.name}:{p.line}:{p.column}
</span>
</div>
)
})}
</div>
</div>
)
}