Make the panes one interaction model, with ctrl+\ as their prefix

Focus moves through what's open in one order: conversation, message editor,
drawer, column. ctrl+\ is a prefix wherever the keys are: ctrl+\ again
toggles, tab and shift+tab step, j/l/k focus the drawer, column or
conversation, 1-9 pick a tab in the focused strip, x closes (a terminal
after asking, Neovim by asking it to quit), z zooms the focused pane over
the conversation, n opens a terminal. alt+1-9 and { } are gone.

The focused pane's strip and edge light up and the rest go quiet; the hint
bar names where the keys are. In side placement the column has one strip of
tabs, Details, each editor and each terminal. Each file gets its own editor
tab, or goes to the running Neovim. Tabs close with their ✕ or a middle
click. A strip under the message box names terminals running out of sight,
and the editors in a hidden column. Terminal and pane commands in the
palette share a prefix, and the palette covers the conversation area.
This commit is contained in:
Callum Alpass committed 2026-11-03 20:53:31 +11:00
1 parent 56ee5364fa
commit 9e4558d7d1
8 files changed
+929 -308

No files matched your search

+168 -73
View File
@@ -36,7 +36,7 @@ import { useDraft } from "./useDraft.ts";
import { useModelPicker } from "./useModelPicker.ts";
import { useQuestion } from "./useQuestion.ts";
import { useThreadMenu } from "./useThreadMenu.ts";
import { editorCommand, scratchFile } from "./editor.ts";
import { editorCommand, editorIsNvim, nvimOpen, nvimSocket, scratchFile } from "./editor.ts";
import { TerminalPane } from "./TerminalPane.tsx";
import { usePanes, type Placement } from "./usePanes.ts";
import { Palette } from "./Palette.tsx";
@@ -58,10 +58,10 @@ import { BAR, NO_BORDER } from "./edges.ts";
import { ThreadList } from "./ThreadList.tsx";
import { useTurns } from "./useTurns.ts";
import { ThreadView, type ConversationMouse, type ConversationTarget } from "./ThreadView.tsx";
import { Button, ResizeHandle, Tab, Tabs } from "./Button.tsx";
import { Button, isLeftClick, ResizeHandle, Tab, Tabs, useHover } from "./Button.tsx";
import { HintBar } from "./HintBar.tsx";
import { bindingFor, commandsFor, fromCommand, hinted, hintsFor, keys, type Binding } from "../model/keymap.ts";
import { firstLine, truncate } from "./text.ts";
import { firstLine, truncate, truncatePath, truncateNumbered } from "./text.ts";
import { useEvent } from "./useEvent.ts";
import { useQueue } from "./useQueue.ts";
import { useSecretRequest } from "./useSecretRequest.ts";
@@ -78,7 +78,7 @@ import { useUsageSummary } from "./useUsage.ts";
/**
* "input": typing goes to the composer. "nav": single keys move, scroll, approve.
* "details": j/k move through the details panel. "settings": j/k move through settings.
* "pane": every key but ctrl+\ goes to the program in the terminal pane.
* "pane": every key but ctrl+\ (the panes' prefix) goes to the program in the focused pane.
* The rest are overlays with their own input.
*/
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings" | "find" | "pull-request" | "pane";
@@ -100,6 +100,8 @@ const MIN_DRAWER_ROWS = 6;
const MIN_CONVERSATION_ROWS = 10;
/** The drawer's default share of the conversation's height, and the message editor's of the window's. */
const DRAWER_SHARE = 0.4;
/** The `+ new` after a strip of terminal tabs. */
const NEW_TAB_WIDTH = 7;
/** The conversation this wide or wider shows diffs side by side. */
const SPLIT_DIFF_WIDTH = 140;
@@ -570,7 +572,11 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
columnPref: detailsPref,
setColumnPref: setDetailsPrefState,
focused: mode === "pane",
focus: (focused) => setMode((current) => (focused ? "pane" : current === "pane" ? "nav" : current)),
focus: (focused) => setMode((current) => (focused ? "pane" : current === "pane" || current === "details" ? "nav" : current)),
detailsFocused: mode === "details",
openTerminal: workspace.openTerminal,
newTerminal: workspace.newTerminal,
closeTerminal: workspace.closeTerminal,
say,
});
const movePlacement = () => {
@@ -579,7 +585,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
saveLayoutNow({ terminalPlacement: next });
};
useEffect(() => {
if (mode === "details") panes.setColumnTab("details");
if (mode === "details") panes.showColumnTab("details");
}, [mode]);
/** The composer's text in $EDITOR, in the composer's place; what's saved comes back when it exits. */
@@ -589,25 +595,48 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
if (panes.message) return panes.enter("message");
const key = composerKey;
const file = scratchFile(composerText(composer));
const socket = editorIsNvim() ? nvimSocket() : null;
panes.openMessage({
kind: "local",
id: `message:${file.path}`,
title: "Message · save and quit to bring it back",
command: editorCommand(file.path),
onExit: (code) => {
const edited = code === 0 ? file.read() : null;
file.remove();
if (edited === null) return say("The editor exited with an error; the message is unchanged.", true);
putMessage(key, edited);
setMode((current) => (current === "pane" ? "input" : current));
socket: socket?.path ?? null,
program: {
kind: "local",
id: `message:${file.path}`,
title: "Message · save and quit to bring it back",
command: editorCommand(file.path, socket?.path),
onExit: (code) => {
socket?.remove();
const edited = code === 0 ? file.read() : null;
file.remove();
if (edited === null) return say("The editor exited with an error; the message is unchanged.", true);
putMessage(key, edited);
setMode((current) => (current === "pane" ? "input" : current));
},
},
});
};
/** A workspace file in $EDITOR, in the column's Editor tab, when the workspace is on this machine. */
/**
* A workspace file in $EDITOR, in a tab of the column, when the workspace is on this machine.
* Neovim takes further files in the instance already running, through its socket.
*/
const editFile = (path: string, cwd: string | null) => {
const file = cwd ? resolvePathLinkTarget(path, cwd) : path;
if (!existsSync(file)) return say(`${path} isn't on this machine.`, true);
panes.openEditor({ kind: "local", id: `edit:${file}`, title: `Editing ${path}`, command: editorCommand(file), cwd: cwd ?? undefined, onExit: () => {} });
const open = panes.editors.find((editor) => editor.program.id === `edit:${file}`);
if (open) return panes.editorOpened(open.program.id, open.path);
const server = panes.editors.find((editor) => editor.socket);
if (server?.socket) {
void nvimOpen(server.socket, file).then((output) => (output === null ? startEditor(file, path, cwd) : panes.editorOpened(server.program.id, path)));
return;
}
startEditor(file, path, cwd);
};
const startEditor = (file: string, path: string, cwd: string | null) => {
const socket = editorIsNvim() ? nvimSocket() : null;
panes.openEditor({
path,
socket: socket?.path ?? null,
program: { kind: "local", id: `edit:${file}`, title: path, command: editorCommand(file, socket?.path), cwd: cwd ?? undefined, onExit: () => socket?.remove() },
});
};
/** A click on a link opens it in the browser; on a path to a workspace file, in the column's editor. A drag doesn't. */
@@ -831,20 +860,23 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
// Keys that work wherever there's no line input to type into.
const quitKey: Binding = { keys: ["ctrl+c"], run: quit };
const paletteKey: Binding = { keys: ["ctrl+k"], run: openPalette };
const terminalKey: Binding = { keys: ["ctrl+j"], run: () => panes.toggleTerminal(workspace.openTerminal) };
const paneKey = panes.keys.pane;
const terminalKey: Binding = {
keys: ["ctrl+j"],
run: panes.toggleTerminal,
...(threadId && !draft ? { command: { id: "terminal", title: panes.terminal ? "Terminal: hide" : "Terminal: open", keywords: ["shell", "console", "drawer"] } } : {}),
};
const prefixKey = panes.keys.prefix;
const editorKey: Binding | null = hasComposer ? { keys: ["ctrl+g"], run: openEditor, command: { id: "editor", title: "Write the message in $EDITOR", keywords: ["vim", "editor", "compose"] } } : null;
const nextThreadKey: Binding = { keys: ["ctrl+n", "alt+↓"], label: "ctrl+n/p", run: () => move(1) };
const previousThreadKey: Binding = { keys: ["ctrl+p", "alt+↑"], run: () => move(-1) };
// Anywhere with a text field, ctrl+u and ctrl+d edit (delete to line start, delete forward); page up/down still scroll.
const lineInput = mode === "filter" || mode === "input" || mode === "find" || mode === "palette" || mode === "picker" || mode === "confirm";
const globalKeys = keys(
paneKey,
prefixKey,
quitKey,
paletteKey,
terminalKey,
editorKey,
panes.keys.tabs,
{ keys: lineInput ? ["pagedown"] : ["pagedown", "ctrl+d"], run: () => scrollPage(1) },
{ keys: lineInput ? ["pageup"] : ["pageup", "ctrl+u"], run: () => scrollPage(-1) },
!attached && nextThreadKey,
@@ -896,10 +928,6 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
hinted(paletteKey, "commands"),
{ keys: ["q"], run: quit, hint: "quit", command: { id: "quit", title: "Quit t3tui", keywords: ["exit"] } },
panel.keys.toggle,
panes.keys.column.map((binding) => ({ ...binding, run: () => {
if (mode === "details") panel.leave();
binding.run?.();
} })),
{ keys: ["e"], run: () => setExpandAll((value) => !value), command: { id: "expand", title: expandAll ? "Collapse work" : "Expand all work", keywords: ["fold", "tool calls"] } },
thread?.history.hasMore && { keys: ["o"], run: loadEarlier, command: { id: "earlier", title: "Load earlier turns", keywords: ["history", "older"] } },
!attached && { keys: ["z"], run: () => setShowFolded((value) => !value), command: { id: "settled", title: showFolded ? "Hide settled threads" : "Show settled threads", keywords: ["snoozed", "archive"] } },
@@ -911,7 +939,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
);
// A diff and a draft name their own few keys; everything else names the lot.
const navHints = keys(
paneKey,
panes.any && prefixKey,
diff
? [scrollDiffDown, closeDiff, detailsKey]
: draft
@@ -922,8 +950,12 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
// Commands only the palette runs.
const paletteOnly = keys(
editorKey,
panes.terminal && { keys: [], run: panes.hideTerminal, command: { id: "pane-close", title: "Hide the terminal", keywords: ["detach", "drawer", "close"] } },
threadId && !draft && { keys: [], run: movePlacement, command: { id: "terminal-placement", title: placement === "bottom" ? "Move terminal to the side" : "Move terminal below", keywords: ["drawer", "column", "right", "bottom", "layout"] } },
panes.keys.commands,
threadId && !draft && { keys: [], run: movePlacement, command: { id: "terminal-placement", title: placement === "bottom" ? "Pane: move terminal to the side" : "Pane: move terminal below", keywords: ["drawer", "column", "right", "bottom", "layout"] } },
threadId && !draft && panes.activeTerminal && [
{ keys: [], run: () => workspace.closeTerminal(panes.activeTerminal!), command: { id: "terminal-close", title: `Terminal: close ${panes.activeTerminal.label}`, keywords: ["shell", "end", "kill"] } },
{ keys: [], run: () => workspace.clearTerminal(panes.activeTerminal!), command: { id: "terminal-clear", title: `Terminal: clear ${panes.activeTerminal.label}`, keywords: ["shell", "scrollback"] } },
],
{ keys: [], run: () => setSplitDiffPref(!splitDiff), command: { id: "split-diff", title: "Toggle split diff", keywords: ["side by side", "unified", "diff view"] } },
queue.keys.input,
queue.keys.palette,
@@ -935,7 +967,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
pullRequests.commands.map((command): Binding => ({ ...fromCommand(command), keys: [], ...(command.shortcut ? { label: command.shortcut } : {}) })),
{ keys: [], run: openSettings, command: { id: "settings", title: "Settings", keywords: ["preferences", "config", "options", "notifications", "alerts"] } },
);
const commands = commandsFor(keys(paneKey, navKeys, paletteOnly));
const commands = commandsFor(keys(navKeys, paletteOnly));
// The composer. Enter and newlines are the textarea's own; their hints only explain.
const sendKey = config.sendShortcut === "enter" ? "enter" : "ctrl+enter";
@@ -1010,10 +1042,12 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
return { layers: [confirmKeys], hints: confirmKeys };
}
}
// In the drawer, ctrl+j hides it again, as it leaves a terminal attached full screen.
if (mode === "pane" && paneKey) return { layers: [keys(panes.keys.focused, panes.focusedPane === "terminal" && terminalKey)], hints: [paneKey] };
// After ctrl+\, the next key is the prefix's; handleKey takes it.
if (panes.prefix) return { layers: [], hints: panes.keys.afterPrefix };
// In a terminal, ctrl+j hides it again, as it leaves a terminal attached full screen.
if (mode === "pane") return { layers: [keys(prefixKey, panes.terminalFocused && terminalKey)], hints: panes.keys.focused };
// The secret field takes every key while it's focused.
if (secret.focused) return { layers: [secret.bindings, [quitKey]], hints: secret.bindings };
if (secret.focused) return { layers: [secret.bindings, [prefixKey, quitKey]], hints: secret.bindings };
switch (mode) {
case "input":
if (menu) return { layers: [menuKeys, inputKeys, globalKeys], hints: menuKeys };
@@ -1038,6 +1072,12 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const handleKey = (key: KeyEvent) => {
// A key ends a mouse selection; it was copied when the drag ended.
if (renderer.hasSelection) renderer.clearSelection();
// Any key ends the prefix: its own keys run, the rest only cancel it, and none reach a program.
if (panes.prefix) {
panes.endPrefix();
bindingFor(panes.keys.afterPrefix, key)?.run?.();
return key.preventDefault();
}
for (const layer of keymap.layers) {
const binding = bindingFor(layer, key);
if (binding?.run) {
@@ -1127,18 +1167,21 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
// The right-hand column, with its tabs, goes beside the conversation, or in its place when there's no room.
// It stays in the tree while it holds a program, hidden or not, so the program keeps running.
const columnInPlace = detailsWidth > detailsRoom;
const columnMounted = panel.show || panes.editor !== null || (placement === "side" && panes.terminal !== null);
const columnMounted = panel.show || panes.editors.length > 0 || (placement === "side" && panes.terminal !== null);
// A zoomed pane fills the conversation's area: the column over it, the drawer or message editor in its place.
const zoom = panes.zoomed;
const columnFills = columnInPlace || zoom === "column";
// In the conversation's place, Details gives way to a diff, settings and the like, as the conversation does.
const detailsGivesWay = settingsIndex !== null || (mode === "pull-request" && pullRequests.view !== null) || diff !== null || draft !== null || mode === "find" || !threadId;
const columnVisible = panel.show && !(columnInPlace && panes.columnTab === "details" && detailsGivesWay);
const rightColumn = columnVisible && !columnInPlace;
const rightColumn = columnVisible && !columnFills;
// The drawer leaves the conversation some rows, or takes its place when it can't.
const drawer = placement === "bottom" ? panes.terminal : null;
// The edge above it takes a row too.
const drawerRoom = areaHeight - MIN_CONVERSATION_ROWS - 1;
const drawerInPlace = drawer !== null && drawerRoom < MIN_DRAWER_ROWS;
const drawerInPlace = drawer !== null && (drawerRoom < MIN_DRAWER_ROWS || zoom === "drawer");
const drawerHeight = Math.max(MIN_DRAWER_ROWS, Math.min(drawerRoom, drawerHeightPref ?? Math.round(areaHeight * DRAWER_SHARE)));
const conversationHidden = (columnVisible && columnInPlace) || drawerInPlace;
const conversationHidden = (columnVisible && columnFills) || drawerInPlace || zoom === "message";
const conversationWidth = width - (showList ? listWidth + 1 : 0) - (rightColumn ? detailsWidth + 1 : 0);
const splitDiff = splitDiffPref ?? conversationWidth >= SPLIT_DIFF_WIDTH;
// The block's height: a row of padding on top, the text, then the model line inside it.
@@ -1172,24 +1215,41 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
const mode = runtimeMode === "full-access" ? "" : (RUNTIME_MODE_LABELS[runtimeMode] ?? runtimeMode);
return { name, rest: [...options, mode].filter(Boolean).join(" · ") };
})();
const composerBarColor = mode === "input" ? colors.accent : colors.border;
// The thread's terminal, in the drawer or the column, with a tab for each of its terminals.
// While a pane has the keys, the message box's bar steps back with the rest of the conversation.
const composerBarColor = mode === "input" ? colors.accent : mode === "pane" ? colors.faint : colors.border;
// The thread's terminal: in the drawer, with a tab for each of its terminals, or under the column's own tabs.
const terminalTarget = panes.terminal;
const terminalPane = terminalTarget ? (
<TerminalPane
key={`${terminalTarget.threadId}:${terminalTarget.terminalId}`}
program={{ kind: "server", id: terminalTarget.terminalId, target: terminalTarget }}
session={session}
focused={panes.focusedPane === "terminal"}
header={
<Tabs tabs={panes.tabs.map((tab) => ({ id: tab.terminalId, label: tab.label }))} active={terminalTarget.terminalId} onPick={(id) => panes.selectTab(panes.tabs.findIndex((tab) => tab.terminalId === id))}>
<Tab label="+" onPress={workspace.newTerminal} />
</Tabs>
}
onFocus={() => panes.enter("terminal")}
focused={panes.focusedPane === (placement === "side" ? "column" : "drawer")}
{...(placement === "side"
? {}
: {
header: (
<Tabs tabs={panes.tabs.map((tab) => ({ id: tab.terminalId, label: tab.label, shorten: (room: number) => truncateNumbered(tab.label, room) }))} active={terminalTarget.terminalId} focused={panes.focusedPane === "drawer"} width={conversationWidth - 3 - NEW_TAB_WIDTH} onPick={(id) => panes.openTerminal(panes.tabs.find((tab) => tab.terminalId === id)!)} onClose={panes.closeTab}>
<Tab label="+ new" onPress={workspace.newTerminal} />
</Tabs>
),
})}
onFocus={() => panes.enter(placement === "side" ? "column" : "drawer")}
onClose={(note) => panes.terminalEnded(terminalTarget, note)}
/>
) : null;
const columnWidth = columnFills ? width - listWidth : detailsWidth;
// While the column is hidden, the editors in it are named under the message box, or in the header.
const awayEditor = !panel.show && panes.editors.length > 0 ? (panes.editors.find((editor) => editor.program.id === panes.columnTab) ?? panes.editors.at(-1)!) : null;
const awayNote = awayEditor ? (
<StripLink
label={`Editor: ${truncatePath(awayEditor.path, 32)}${panes.editors.length > 1 ? ` +${panes.editors.length - 1}` : ""}${panes.editors.some((editor) => panes.modified.has(editor.program.id)) ? " ●" : ""} · d`}
onPress={() => panel.setPref(true)}
/>
) : null;
const runningStrip = threadId && !draft && panes.running.length > 0;
/** The palette and pickers cover the conversation's area, between the list and the column. */
const paletteArea = { left: showList ? listWidth + 1 : 0, width: conversationWidth, height: height - 2 };
const detailsPanel = (inPlace: boolean) => (
<DetailsPanel
details={panel.details}
@@ -1245,6 +1305,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
{shell.status.type !== "live" ? <text fg={colors.warn} wrapMode="none" onMouseDown={() => session.retryNow()}>{` ${status}`}</text> : null}
{usageInfo.note ? <text fg={colors.warn} wrapMode="none">{` ${usageInfo.note}`}</text> : null}
<box flexGrow={1} />
{runningStrip ? null : awayNote}
{awayNote && !runningStrip ? <text fg={colors.faint}>{" "}</text> : null}
<Button label="ctrl+k" shortcut="commands" plain onPress={openPalette} />
</box>
<box flexDirection="row" flexGrow={1} flexShrink={1} minHeight={0} overflow="hidden">
@@ -1280,8 +1342,8 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
saveLayoutNow({ listWidth: null });
}} />}
<box flexDirection="column" flexGrow={1} minHeight={0} onSizeChange={function (this: { height: number }) { setColumnHeight(this.height); }}>
<box flexDirection="column" flexGrow={1} minHeight={0} visible={!drawerInPlace}>
<box flexDirection="column" flexGrow={1} minHeight={0} visible={!drawerInPlace} onMouseDown={focusConversation} onSizeChange={function (this: { height: number }) { setContentHeight(this.height); }}>
<box flexDirection="column" flexGrow={1} minHeight={0} visible={!drawerInPlace && zoom !== "message"}>
<box flexDirection="column" flexGrow={1} minHeight={0} visible={!drawerInPlace && zoom !== "message"} onMouseDown={focusConversation} onSizeChange={function (this: { height: number }) { setContentHeight(this.height); }}>
{conversationHidden ? null : settingsIndex !== null ? (
<SettingsView
rows={settingsRows}
@@ -1328,7 +1390,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
)}
</box>
</box>
<box flexDirection="column" flexShrink={0} onSizeChange={function (this: { height: number }) { setBelowHeight(this.height); }}>
<box flexDirection="column" visible={zoom !== "drawer"} {...(zoom === "message" ? { flexGrow: 1, minHeight: 0 } : { flexShrink: 0 })} onSizeChange={function (this: { height: number }) { setBelowHeight(this.height); }}>
{workspace.note ? <text fg={workspace.setupFailed ? colors.bad : colors.muted}>{workspace.note}</text> : null}
{find.open ? <ThreadFindBar query={find.query} focused={mode === "find"} data={find.data} pending={find.pending} error={find.error} onQuery={find.onQuery} onStep={find.step} onClose={() => setMode("nav")} /> : null}
{mode !== "confirm" && secret.request ? <SecretPanel request={secret.request} value={secret.value} error={secret.error} busy={secret.busy} actions={secret.actions} /> : null}
@@ -1365,13 +1427,13 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
) : null}
{working && threadId && !draft && !pendingApproval ? <LiveStatus label={liveLabel} tool={liveTool} /> : null}
{panes.message ? (
<box flexDirection="column" flexShrink={0} marginTop={1} height={Math.max(MIN_DRAWER_ROWS, Math.round((height - 2) * DRAWER_SHARE))}>
<box flexDirection="column" marginTop={1} {...(zoom === "message" ? { flexGrow: 1, minHeight: 0 } : { flexShrink: 0, height: Math.max(MIN_DRAWER_ROWS, Math.round((height - 2) * DRAWER_SHARE)) })}>
<TerminalPane
key={panes.message.id}
program={panes.message}
key={panes.message.program.id}
program={panes.message.program}
session={session}
focused={panes.focusedPane === "message"}
header={<text fg={panes.focusedPane === "message" ? colors.text : colors.muted} wrapMode="none" flexGrow={1}>{panes.message.title}</text>}
header={<text fg={panes.focusedPane === "message" ? colors.text : colors.muted} wrapMode="none" flexGrow={1}>{panes.message.program.title}</text>}
onFocus={() => panes.enter("message")}
onClose={panes.messageClosed}
/>
@@ -1459,6 +1521,21 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
</box>
</box>
) : null}
{runningStrip ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={1} backgroundColor={colors.panel}>
<text fg={colors.faint} flexShrink={0} selectable={false}>{"▸ "}</text>
{panes.running.map((target, index) => (
<box key={target.terminalId} flexDirection="row" flexShrink={0}>
{index > 0 ? <text fg={colors.faint} selectable={false}>{" · "}</text> : null}
<StripLink label={target.label} onPress={() => panes.openTerminal(target)} />
</box>
))}
<text fg={colors.faint} flexShrink={0} selectable={false}>{" "}</text>
<StripLink label="ctrl+j" color={colors.faint} onPress={panes.toggleTerminal} />
<box flexGrow={1} />
{awayNote}
</box>
) : null}
</box>
{drawer ? (
<>
@@ -1496,30 +1573,37 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
minHeight={0}
overflow="hidden"
backgroundColor={columnInPlace ? colors.bg : colors.panel}
{...(columnInPlace ? { position: "absolute", left: showList ? listWidth + 1 : 0, right: 0, top: 0, height: contentHeight } : { width: detailsWidth, flexShrink: 0 })}
{...(columnFills ? { position: "absolute", left: showList ? listWidth + 1 : 0, right: 0, top: 0, height: zoom === "column" ? columnHeight : contentHeight } : { width: detailsWidth, flexShrink: 0 })}
>
{panes.columnTabs.length > 1 ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1} backgroundColor={colors.panel}>
<Tabs tabs={panes.columnTabs} active={panes.columnTab} onPick={(id) => panes.setColumnTab(id as typeof panes.columnTab)} />
<text fg={colors.faint} wrapMode="none" flexShrink={0}>{"{ }"}</text>
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1} backgroundColor={panes.focusedPane === "column" ? colors.element : colors.panel}>
<Tabs
tabs={panes.columnTabs.map((tab) => ({ id: tab.id, label: tab.label, closable: tab.kind !== "details", shorten: (room: number) => (tab.kind === "editor" ? truncatePath(tab.label, room) : truncateNumbered(tab.label, room)) }))}
active={panes.columnTab}
focused={panes.focusedPane === "column"}
width={columnWidth - 2 - (placement === "side" && panes.terminal ? NEW_TAB_WIDTH : 0)}
onPick={(id) => (id === "details" ? panes.showColumnTab(id) : panes.enter("column", id))}
onClose={panes.closeTab}
>
{placement === "side" && panes.terminal ? <Tab label="+ new" onPress={workspace.newTerminal} /> : null}
</Tabs>
</box>
) : null}
{panes.columnTab === "details" ? detailsPanel(columnInPlace) : null}
{panes.editor ? (
<box flexDirection="column" flexGrow={1} minHeight={0} visible={panes.columnTab === "editor"}>
{panes.columnTab === "details" ? detailsPanel(columnFills) : null}
{panes.editors.map((editor) => (
<box key={editor.program.id} flexDirection="column" flexGrow={1} minHeight={0} visible={panes.columnTab === editor.program.id}>
<TerminalPane
key={panes.editor.id}
program={panes.editor}
program={editor.program}
session={session}
focused={panes.focusedPane === "editor"}
header={<text fg={panes.focusedPane === "editor" ? colors.text : colors.muted} wrapMode="none" flexGrow={1}>{truncate(panes.editor.title, Math.max(8, (columnInPlace ? width - listWidth : detailsWidth) - 17))}</text>}
onFocus={() => panes.enter("editor")}
onClose={panes.editorClosed}
focused={panes.focusedPane === "column" && panes.columnTab === editor.program.id}
header={<text fg={panes.focusedPane === "column" ? colors.text : colors.muted} wrapMode="none" flexGrow={1}>{truncatePath(editor.path, Math.max(8, columnWidth - 6))}</text>}
onFocus={() => panes.enter("column", editor.program.id)}
onClose={(note) => panes.editorClosed(editor.program.id, note)}
/>
</box>
) : null}
))}
{placement === "side" && panes.terminal ? (
<box flexDirection="column" flexGrow={1} minHeight={0} visible={panes.columnTab === "terminal"}>
<box flexDirection="column" flexGrow={1} minHeight={0} visible={panes.columnTab.startsWith("terminal:")}>
{terminalPane}
</box>
) : null}
@@ -1527,16 +1611,15 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
) : null}
</box>
<box flexDirection="row" paddingLeft={2} height={1} flexShrink={0}>
{flash ? <text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text> : <HintBar hints={hintsFor(keymap.hints)} width={width - 2} />}
{flash && !panes.prefix ? <text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text> : <HintBar hints={hintsFor(keymap.hints)} width={width - 2} />}
</box>
{mode === "palette" ? (
<Palette
{...paletteArea}
query={paletteQuery}
status={paletteSearch.error ?? (paletteSearch.pending ? "Searching messages…" : null)}
groups={groups}
selected={Math.min(paletteIndex, Math.max(0, entries.length - 1))}
width={width}
height={height}
onQuery={(value) => {
setPaletteQuery(value);
setPaletteIndex(0);
@@ -1548,12 +1631,11 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
) : null}
{mode === "picker" && picker ? (
<Palette
{...paletteArea}
query={pickerQuery}
placeholder={picker.placeholder}
groups={pickerView}
selected={Math.min(pickerIndex, Math.max(0, pickerEntries.length - 1))}
width={width}
height={height}
onQuery={(value) => {
setPickerQuery(value);
setPickerIndex(0);
@@ -1597,3 +1679,16 @@ function connectionLabel(shell: ShellState, now: number): string {
const wait = status.retryAt === null ? 0 : Math.max(0, Math.ceil((status.retryAt - now) / 1000));
return `couldn't connect, ${wait > 0 ? `retrying in ${wait}s` : "retrying…"} · ${truncate(firstLine(status.message), 60)}`;
}
/** A name in the strip under the message box; a click does what it names. */
function StripLink(props: { readonly label: string; readonly color?: string; readonly onPress: () => void }) {
const [hover, hoverProps] = useHover();
return (
<box flexShrink={0} {...hoverProps} onMouseDown={(event: MouseEvent) => {
event.stopPropagation();
if (isLeftClick(event)) props.onPress();
}}>
<text fg={hover ? colors.text : (props.color ?? colors.muted)} wrapMode="none" selectable={false}>{props.label}</text>
</box>
);
}
+65 -8
View File
@@ -3,6 +3,7 @@ import type { BoxProps as OpenTuiBoxProps } from "@opentui/react";
import { useState, type ReactNode } from "react";
import { BAR, NO_BORDER } from "./edges.ts";
import { truncate } from "./text.ts";
import { colors } from "./theme.ts";
/** Hover state for a clickable box. Moving between a box and its own text sends out then over, so it settles on the right value. */
@@ -100,36 +101,92 @@ export function ResizeHandle(props: { readonly active: boolean; readonly horizon
);
}
type TabItem = {
readonly id: string;
readonly label: string;
readonly closable?: boolean;
/** The label cut to a width, when cutting its end isn't the way (a path keeps its file name). */
readonly shorten?: (width: number) => string;
};
/** The fewest columns a label is cut to. */
const MIN_TAB_LABEL = 4;
/**
* A one-line strip of tabs: the active one in the accent on a raised block, the rest muted.
* A click switches; anything after the tabs (a `+`, a key hint) goes in `children`.
* A one-line strip of tabs. In a focused pane the active one is in the accent; otherwise the
* strip goes quiet. A click switches; with `onClose`, the active tab has a ✕ and a middle-click
* closes any tab. Long labels are cut to fit `width`. Anything after the tabs
* (a `+ new`) goes in `children`, outside `width`.
*/
export function Tabs(props: { readonly tabs: readonly { readonly id: string; readonly label: string }[]; readonly active: string | null; readonly onPick: (id: string) => void; readonly children?: ReactNode }) {
export function Tabs(props: {
readonly tabs: readonly TabItem[];
readonly active: string | null;
readonly focused: boolean;
readonly width: number;
readonly onPick: (id: string) => void;
readonly onClose?: (id: string) => void;
readonly children?: ReactNode;
}) {
const { onClose } = props;
const closable = (tab: TabItem) => onClose !== undefined && tab.closable !== false;
const labels = fitLabels(props.tabs, props.width - props.tabs.reduce((sum, tab) => sum + 2 + (tab.id === props.active && closable(tab) ? 2 : 0), 0));
return (
<box flexDirection="row" height={1} flexShrink={0} flexGrow={1} overflow="hidden">
{props.tabs.map((tab) => (
<Tab key={tab.id} label={tab.label} active={tab.id === props.active} onPress={() => props.onPick(tab.id)} />
{props.tabs.map((tab, index) => (
<Tab
key={tab.id}
label={labels[index]!}
active={tab.id === props.active}
focused={props.focused}
onPress={() => props.onPick(tab.id)}
{...(onClose && closable(tab) ? { onClose: () => onClose(tab.id) } : {})}
/>
))}
{props.children}
</box>
);
}
export function Tab(props: { readonly label: string; readonly active?: boolean; readonly onPress: () => void }) {
/** The tabs' labels cut to fit `room` in all: each to the same widest width that fits, but no narrower than a few columns. */
function fitLabels(tabs: readonly TabItem[], room: number): string[] {
const widths = tabs.map((tab) => Bun.stringWidth(tab.label));
let cap = Math.max(0, ...widths);
while (cap > MIN_TAB_LABEL && widths.reduce((sum, width) => sum + Math.min(width, cap), 0) > room) cap--;
return tabs.map((tab, index) => (widths[index]! <= cap ? tab.label : (tab.shorten?.(cap) ?? truncate(tab.label, cap))));
}
export function Tab(props: { readonly label: string; readonly active?: boolean; readonly focused?: boolean; readonly onPress: () => void; readonly onClose?: (() => void) | undefined }) {
const [hover, hoverProps] = useHover();
const { active, focused, onClose } = props;
const color = hover ? colors.text : active ? (focused ? colors.accent : colors.muted) : focused ? colors.muted : colors.faint;
return (
<box
flexDirection="row"
flexShrink={0}
paddingLeft={1}
paddingRight={1}
backgroundColor={props.active ? colors.element : hover ? colors.hoverBg : "transparent"}
backgroundColor={active ? colors.element : hover ? colors.hoverBg : "transparent"}
{...hoverProps}
onMouseDown={(event: MouseEvent) => {
event.stopPropagation();
if (isLeftClick(event)) props.onPress();
else if (event.button === 1) onClose?.();
}}
>
<text fg={props.active ? colors.accent : hover ? colors.text : colors.muted} wrapMode="none" selectable={false}>{props.label}</text>
<text fg={color} wrapMode="none" selectable={false}>{props.label}</text>
{active && onClose ? (
<text
fg={focused ? colors.muted : colors.faint}
wrapMode="none"
selectable={false}
onMouseDown={(event: MouseEvent) => {
event.stopPropagation();
if (isLeftClick(event)) onClose();
}}
>
{" ✕"}
</text>
) : null}
</box>
);
}
+22 -18
View File
@@ -8,7 +8,8 @@ import { colors } from "./theme.ts";
/**
* The web's command palette (mod+K) as an overlay: a search box over grouped commands and
* threads. Arrows or ctrl+n/p move, enter runs, a click runs, esc closes.
* threads. Arrows or ctrl+n/p move, enter runs, a click runs, esc closes. It sits on a solid
* backdrop over the whole conversation area (`left`, `width`, `height`), centred in it.
*/
export function Palette(props: {
readonly query: string;
@@ -16,6 +17,7 @@ export function Palette(props: {
readonly placeholder?: string;
readonly groups: readonly PaletteGroup[];
readonly selected: number;
readonly left: number;
readonly width: number;
readonly height: number;
readonly onQuery: (query: string) => void;
@@ -25,7 +27,7 @@ export function Palette(props: {
readonly onMove: (step: -1 | 1) => void;
}) {
const width = Math.min(80, props.width - 4);
const listHeight = Math.max(4, Math.min(props.height - 8, 22));
const listHeight = Math.max(4, Math.min(props.height - 6, 22));
// Rows are entries plus a header per group; keep the selection in view.
const rows: ({ kind: "header"; label: string; key: string } | { kind: "entry"; entry: PaletteEntry; index: number })[] = [];
let index = 0;
@@ -38,22 +40,24 @@ export function Palette(props: {
const start = Math.max(0, Math.min(selectedRow - Math.floor(listHeight / 2), rows.length - listHeight));
const inner = width - 3;
return (
<box position="absolute" top={2} left={Math.floor((props.width - width) / 2)} width={width} zIndex={10} flexDirection="column" paddingLeft={1} paddingRight={1} paddingTop={1} paddingBottom={1} backgroundColor={colors.panel}>
<box border={["left"]} customBorderChars={BAR} borderColor={colors.accent} backgroundColor={colors.element} height={1} flexDirection="row" flexShrink={0}>
<input focused flexGrow={1} placeholder={props.placeholder ?? "Search commands and threads (> for commands only)"} value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.element} focusedBackgroundColor={colors.element} />
</box>
{props.status ? <text fg={colors.muted}>{props.status}</text> : null}
<box flexDirection="column" height={listHeight} marginTop={1} onMouseScroll={(event: MouseEvent) => { const step = wheelStep(event); if (step) props.onMove(step); }}>
{rows.length === 0 ? <text fg={colors.muted}>No matches</text> : null}
{rows.slice(start, start + listHeight).map((row) =>
row.kind === "header" ? (
<text key={row.key} fg={colors.faint}>
<strong>{row.label}</strong>
</text>
) : (
<Row key={entryKey(row.entry)} entry={row.entry} selected={row.index === props.selected} inner={inner} onPick={() => props.onPick(row.index)} />
),
)}
<box position="absolute" top={1} left={props.left} width={props.width} height={props.height} zIndex={10} flexDirection="column" alignItems="center" paddingTop={1} backgroundColor={colors.panel}>
<box width={width} flexDirection="column" paddingLeft={1} paddingRight={1}>
<box border={["left"]} customBorderChars={BAR} borderColor={colors.accent} backgroundColor={colors.element} height={1} flexDirection="row" flexShrink={0}>
<input focused flexGrow={1} placeholder={props.placeholder ?? "Search commands and threads (> for commands only)"} value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.element} focusedBackgroundColor={colors.element} />
</box>
{props.status ? <text fg={colors.muted}>{props.status}</text> : null}
<box flexDirection="column" height={listHeight} marginTop={1} onMouseScroll={(event: MouseEvent) => { const step = wheelStep(event); if (step) props.onMove(step); }}>
{rows.length === 0 ? <text fg={colors.muted}>No matches</text> : null}
{rows.slice(start, start + listHeight).map((row) =>
row.kind === "header" ? (
<text key={row.key} fg={colors.faint}>
<strong>{row.label}</strong>
</text>
) : (
<Row key={entryKey(row.entry)} entry={row.entry} selected={row.index === props.selected} inner={inner} onPick={() => props.onPick(row.index)} />
),
)}
</box>
</box>
</box>
);
+10 -8
View File
@@ -31,14 +31,15 @@ interface Link {
/**
* A terminal filling its box: the drawer, a tab of the right-hand column or the composer's
* place. Keys go to its program while it has focus, its size follows the box, and it closes
* when the program exits. Key it by the program's id.
* when the program exits. Its left edge and header light up while it has the keys. Key it by
* the program's id.
*/
export function TerminalPane(props: {
readonly program: PaneProgram;
readonly session: T3Session;
readonly focused: boolean;
/** The row above the terminal: its title, or the drawer's tabs. */
readonly header: ReactNode;
/** The row above the terminal: its title, or the drawer's tabs; none under the column's own tabs. */
readonly header?: ReactNode;
readonly onFocus: () => void;
readonly onClose: (message?: string) => void;
}) {
@@ -76,13 +77,14 @@ export function TerminalPane(props: {
backgroundColor={colors.panel}
border={["left"]}
customBorderChars={BAR}
borderColor={focused ? colors.accent : colors.panel}
borderColor={focused ? colors.accent : colors.faint}
onMouseDown={onFocus}
>
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1}>
{props.header}
<text fg={colors.faint} wrapMode="none" flexShrink={0}>{focused ? "ctrl+\\ leave" : "ctrl+\\ focus"}</text>
</box>
{props.header ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={1} paddingRight={1} backgroundColor={focused ? colors.element : colors.panel}>
{props.header}
</box>
) : null}
<embeddedTerminal
ref={terminal}
flexGrow={1}
+250 -69
View File
@@ -1,22 +1,43 @@
import type { ThreadId } from "@t3tools/contracts";
import { basename } from "node:path";
import { useEffect, useRef, useState } from "react";
import { keys, type Binding } from "../model/keymap.ts";
import { nvimModified, nvimQuit } from "./editor.ts";
import type { PaneProgram } from "./TerminalPane.tsx";
import type { TerminalTarget } from "./terminalAttach.ts";
export type Placement = "bottom" | "side";
export type ColumnTab = "details" | "editor" | "terminal";
/** The pane that takes the keys in "pane" mode. */
export type PaneFocus = "terminal" | "editor" | "message";
/** The panes that take the keys, in the order focus moves through them after the conversation. */
export type PaneFocus = "message" | "drawer" | "column";
const PANE_ORDER: readonly PaneFocus[] = ["message", "drawer", "column"];
/** How long ctrl+\ waits for the key after it. */
const PREFIX_MS = 2000;
const DETAILS = "details";
/** The column's tab for the shown terminal, in side placement. */
const TERMINAL = "terminal";
type LocalProgram = Extract<PaneProgram, { kind: "local" }>;
const COLUMN_TAB_LABELS: Record<ColumnTab, string> = { details: "Details", editor: "Editor", terminal: "Terminal" };
/** A program run here in $EDITOR, with Neovim's socket when it serves one. */
export interface EditorProgram {
readonly program: LocalProgram;
readonly socket: string | null;
}
/** A file in $EDITOR, in a tab of the column: the path its tab shows, relative to the workspace. */
export interface EditorTab extends EditorProgram {
readonly path: string;
}
export interface ColumnTab {
readonly id: string;
readonly label: string;
readonly kind: "details" | "editor" | "terminal";
}
/**
* The panes around the conversation: each thread's terminals (in the drawer below it, or the
* right-hand column's Terminal tab), a file in $EDITOR in the column's Editor tab, and the
* message in $EDITOR in the composer's place. Which one has the keys, and the keys between them.
* The panes around the conversation: each thread's terminals (in the drawer below it, or as
* tabs of the right-hand column), files in $EDITOR in the column's tabs, and the message in
* $EDITOR in the composer's place. Which one has the keys, and the ctrl+\ prefix that moves
* them, picks tabs, closes and zooms.
*/
export function usePanes(deps: {
readonly threadId: ThreadId | undefined;
@@ -30,6 +51,12 @@ export function usePanes(deps: {
/** Whether a pane has the keys, and giving them to one or back to the conversation. */
readonly focused: boolean;
readonly focus: (focused: boolean) => void;
/** Whether the details panel has the keys: the column counts as focused for tabs and zoom. */
readonly detailsFocused: boolean;
/** Finds or starts a terminal for the thread, a new one, and closing one (after asking). */
readonly openTerminal: () => void;
readonly newTerminal: () => void;
readonly closeTerminal: (target: TerminalTarget) => void;
readonly say: (text: string, bad?: boolean) => void;
}) {
const { threadId, placement, column, focused, say } = deps;
@@ -37,40 +64,89 @@ export function usePanes(deps: {
const [drawers, setDrawers] = useState<ReadonlyMap<ThreadId, { readonly target: TerminalTarget; readonly open: boolean }>>(new Map());
/** Terminals that closed or exited here, until the server's list catches up. */
const [ended, setEnded] = useState<ReadonlySet<string>>(new Set());
const [editor, setEditor] = useState<LocalProgram | null>(null);
const [message, setMessage] = useState<LocalProgram | null>(null);
const [tab, setTab] = useState<ColumnTab>("details");
const [target, setTarget] = useState<PaneFocus>("terminal");
/** Terminals this run has shown, which the strip under the message box names while the drawer is hidden. */
const [seen, setSeen] = useState<ReadonlySet<string>>(new Set());
const [editors, setEditors] = useState<readonly EditorTab[]>([]);
const [message, setMessage] = useState<EditorProgram | null>(null);
const [tab, setTab] = useState<string>(DETAILS);
const [target, setTarget] = useState<PaneFocus>("drawer");
const [prefix, setPrefix] = useState(false);
const [zoomed, setZoomed] = useState<PaneFocus | null>(null);
/** Editors with unsaved changes, checked as the column hides (they can't change while it's hidden). */
const [modified, setModified] = useState<ReadonlySet<string>>(new Set());
const prefixTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
/** The column's setting before a tab opened it, to go back to once that tab closes. */
const restore = useRef<{ readonly pref: boolean | null } | null>(null);
/** The program tab the column showed last, for focusing the column from Details. */
const lastProgramTab = useRef<string | null>(null);
const endedKey = (terminal: TerminalTarget) => `${terminal.threadId}:${terminal.terminalId}`;
const key = (terminal: TerminalTarget) => `${terminal.threadId}:${terminal.terminalId}`;
const drawer = threadId ? drawers.get(threadId) : undefined;
const listed = deps.terminals.filter((terminal) => !ended.has(endedKey(terminal)));
const listed = deps.terminals.filter((terminal) => !ended.has(key(terminal)));
// A terminal just opened shows before the server lists it.
const tabs = drawer && !ended.has(endedKey(drawer.target)) && !listed.some((terminal) => terminal.terminalId === drawer.target.terminalId) ? [...listed, drawer.target] : listed;
const tabs = drawer && !ended.has(key(drawer.target)) && !listed.some((terminal) => terminal.terminalId === drawer.target.terminalId) ? [...listed, drawer.target] : listed;
const terminal = drawer?.open ? drawer.target : null;
/** The terminal ctrl+j shows, and the palette's close and clear act on. */
const activeTerminal = (drawer && tabs.some((candidate) => candidate.terminalId === drawer.target.terminalId) ? drawer.target : tabs[0]) ?? null;
const side = placement === "side";
const columnTabs: ColumnTab[] = ["details", ...(editor ? ["editor" as const] : []), ...(side && terminal ? ["terminal" as const] : [])];
const columnTab = columnTabs.includes(tab) ? tab : "details";
const terminalTabId = (terminalId: string) => `${TERMINAL}:${terminalId}`;
const columnTabs: ColumnTab[] = [
{ id: DETAILS, label: "Details", kind: "details" },
...editors.map((editor): ColumnTab => ({ id: editor.program.id, label: editor.path, kind: "editor" })),
...(side && terminal ? tabs.map((candidate): ColumnTab => ({ id: terminalTabId(candidate.terminalId), label: candidate.label, kind: "terminal" })) : []),
];
const columnTab = tab === TERMINAL && side && terminal ? terminalTabId(terminal.terminalId) : editors.some((editor) => editor.program.id === tab) ? tab : DETAILS;
const activeColumnTab = columnTabs.find((candidate) => candidate.id === columnTab)!;
const programTabs = columnTabs.filter((candidate) => candidate.kind !== "details");
const shown: Record<PaneFocus, boolean> = {
terminal: terminal !== null && (!side || (column && columnTab === "terminal")),
editor: column && columnTab === "editor",
message: message !== null,
drawer: terminal !== null && !side,
column: column && columnTab !== DETAILS,
};
/** What focus can move to: open panes, and the column while it holds a program, even hidden. */
const open: Record<PaneFocus, boolean> = { ...shown, column: programTabs.length > 0 };
const available = PANE_ORDER.filter((pane) => open[pane]);
const focusedPane = focused && shown[target] ? target : null;
// A pane that went away, or out of sight, gives the keys back.
const zoomShown = zoomed !== null && (zoomed === "column" ? column : shown[zoomed]);
// A pane that went away, or out of sight, gives the keys back, and its zoom.
useEffect(() => {
if (focused && !shown[target]) deps.focus(false);
if (zoomed && !zoomShown) setZoomed(null);
});
useEffect(() => () => void (prefixTimer.current && clearTimeout(prefixTimer.current)), []);
// The ● for unsaved changes while the column is hidden: Neovim says; other editors can't.
const sockets = editors.flatMap((editor) => (editor.socket ? [`${editor.program.id}\n${editor.socket}`] : [])).join("\n");
useEffect(() => {
if (column || !sockets) {
setModified(new Set());
return;
}
let current = true;
const checks = editors.flatMap((editor) => (editor.socket ? [nvimModified(editor.socket).then((changed) => (changed ? [editor.program.id] : []))] : []));
void Promise.all(checks).then((ids) => current && setModified(new Set(ids.flat())));
return () => {
current = false;
};
}, [column, sockets]);
const enter = (pane: PaneFocus) => {
/** Gives a pane the keys; the column on `tab`, or the program tab it showed last. */
const enter = (pane: PaneFocus, tab?: string) => {
if (pane === "column" && tab) showColumnTab(tab);
else if (pane === "column" && columnTab === DETAILS) {
const next = programTabs.find((candidate) => candidate.id === lastProgramTab.current || (lastProgramTab.current === TERMINAL && candidate.kind === "terminal")) ?? programTabs[0];
if (next) showColumnTab(next.id);
} else if (pane === "column") showColumnTab(columnTab);
setTarget(pane);
deps.focus(true);
};
const showTab = (next: ColumnTab) => {
/** Shows a column tab, showing the column for it if it was hidden. */
const showColumnTab = (id: string) => {
const terminalTab = tabs.find((candidate) => terminalTabId(candidate.terminalId) === id);
if (terminalTab) setDrawer(terminalTab.threadId, { target: terminalTab, open: true });
const next = terminalTab ? TERMINAL : id;
setTab(next);
if (next !== DETAILS) lastProgramTab.current = next;
if (column) return;
restore.current ??= { pref: deps.columnPref };
deps.setColumnPref(true);
@@ -83,35 +159,40 @@ export function usePanes(deps: {
};
const setDrawer = (id: ThreadId, value: { readonly target: TerminalTarget; readonly open: boolean }) => setDrawers((previous) => new Map(previous).set(id, value));
/** Shows a terminal, as a tab of the drawer or of the column, and gives it the keys. */
const openTerminal = (next: TerminalTarget) => {
/** Shows a terminal, as a tab of the drawer or of the column; `focus` gives it the keys. */
const showTerminal = (next: TerminalTarget, focus: boolean) => {
setEnded((previous) => {
const rest = new Set(previous);
rest.delete(endedKey(next));
rest.delete(key(next));
return rest;
});
setSeen((previous) => (previous.has(key(next)) ? previous : new Set(previous).add(key(next))));
setDrawer(next.threadId, { target: next, open: true });
if (side) showTab("terminal");
enter("terminal");
if (side) showColumnTab(TERMINAL);
if (!focus) return;
setTarget(side ? "column" : "drawer");
deps.focus(true);
};
const openTerminal = (next: TerminalTarget) => showTerminal(next, true);
const hideTerminal = () => {
if (!threadId || !drawer) return;
setDrawer(threadId, { ...drawer, open: false });
if (side) tabGone(editor !== null);
if (side) tabGone(editors.length > 0);
};
/** ctrl+j: hides the terminal when it shows, or shows the last one, or `open` finds one. */
const toggleTerminal = (open: () => void) => {
if (shown.terminal) return hideTerminal();
if (drawer && tabs.some((candidate) => candidate.terminalId === drawer.target.terminalId)) return openTerminal(drawer.target);
open();
const terminalShown = terminal !== null && (!side || (column && activeColumnTab.kind === "terminal"));
/** ctrl+j: hides the terminal when it shows, or shows the last one, or finds one. */
const toggleTerminal = () => {
if (terminalShown) return hideTerminal();
if (activeTerminal) return openTerminal(activeTerminal);
deps.openTerminal();
};
const selectTab = (index: number) => {
const next = tabs[index];
if (next) setDrawer(next.threadId, { target: next, open: true });
if (next) showTerminal(next, false);
};
/** A terminal closed or exited: its tab goes, the next one shows, and the last takes the drawer with it. */
const terminalEnded = (gone: TerminalTarget, note?: string) => {
setEnded((previous) => new Set(previous).add(endedKey(gone)));
setEnded((previous) => new Set(previous).add(key(gone)));
const next = tabs.find((candidate) => candidate.terminalId !== gone.terminalId);
if (next) setDrawer(gone.threadId, { target: next, open: drawers.get(gone.threadId)?.open ?? true });
else {
@@ -120,67 +201,167 @@ export function usePanes(deps: {
rest.delete(gone.threadId);
return rest;
});
if (side && gone.threadId === threadId) tabGone(editor !== null);
if (side && gone.threadId === threadId) tabGone(editors.length > 0);
}
if (note) say(note);
};
/** A file in $EDITOR, in the column's Editor tab. An editor may hold unsaved work, so it isn't replaced. */
const openEditor = (program: LocalProgram) => {
if (editor && editor.id !== program.id) return say("The editor is still open; ctrl+\\ there and quit it first.", true);
setEditor(program);
showTab("editor");
enter("editor");
/** A file in $EDITOR, in a tab of its own in the column, with the keys. */
const openEditor = (editor: EditorTab) => {
setEditors((previous) => (previous.some((candidate) => candidate.program.id === editor.program.id) ? previous : [...previous, editor]));
showColumnTab(editor.program.id);
setTarget("column");
deps.focus(true);
};
const editorClosed = (note?: string) => {
setEditor(null);
tabGone(side && terminal !== null);
/** Another file went to an editor already running (Neovim's socket): its tab names it and takes the keys. */
const editorOpened = (id: string, path: string) => {
setEditors((previous) => previous.map((editor) => (editor.program.id === id ? { ...editor, path } : editor)));
showColumnTab(id);
setTarget("column");
deps.focus(true);
};
const editorClosed = (id: string, note?: string) => {
setEditors((previous) => previous.filter((editor) => editor.program.id !== id));
tabGone(editors.length > 1 || (side && terminal !== null));
if (note) say(note);
};
/** The message in $EDITOR, in the composer's place. */
const openMessage = (program: LocalProgram) => {
setMessage(program);
enter("message");
const openMessage = (next: EditorProgram) => {
setMessage(next);
setTarget("message");
deps.focus(true);
};
// ctrl+\ goes back to the pane that last had the keys, or the first that shows.
const next = ([target, "message", "editor", "terminal"] as const).find((pane) => shown[pane]);
const paneKey: Binding | null = next
? { keys: ["ctrl+\\"], run: () => (focused ? deps.focus(false) : enter(next)), hint: focused ? "leave pane" : "pane", command: { id: "pane-focus", title: focused ? "Leave the pane" : "Focus the pane", keywords: ["terminal", "editor"] } }
: null;
/** alt+1…9 pick the terminal tab, while the terminal shows. */
const tabKeys: Binding[] = shown.terminal ? tabs.slice(0, 9).map((_, index) => ({ keys: [`alt+${index + 1}`], run: () => selectTab(index) })) : [];
const cycle = (step: 1 | -1) => setTab(columnTabs[(columnTabs.indexOf(columnTab) + step + columnTabs.length) % columnTabs.length]!);
/** { and } step through the column's tabs; [ and ] step through turns. */
const columnKeys: Binding[] =
column && columnTabs.length > 1
? [
{ keys: ["}"], run: () => cycle(1), command: { id: "column-next", title: "Next tab in the right column", keywords: ["details", "editor", "terminal"] } },
{ keys: ["{"], run: () => cycle(-1), command: { id: "column-previous", title: "Previous tab in the right column", keywords: ["details", "editor", "terminal"] } },
]
: [];
/** While a pane has the keys, all it keeps are these. */
const focusedKeys = keys(paneKey, focusedPane === "terminal" && tabKeys);
/** Asks an editor to quit: Neovim through its socket, where it asks about unsaved changes itself. Others would lose them, so no. */
const quitEditor = (editor: EditorProgram, name: string, pane: PaneFocus) => {
if (!editor.socket) return say(`Quit ${name} from inside it; closing it here could lose unsaved changes.`, true);
enter(pane);
void nvimQuit(editor.socket).then((sent) => sent === null && say(`Could not reach the editor for ${name}.`, true));
};
/** Closes a tab: a terminal after asking, an editor by asking it to quit. Details stays. */
const closeTab = (id: string) => {
const terminalTab = tabs.find((candidate) => candidate.terminalId === id || terminalTabId(candidate.terminalId) === id);
if (terminalTab) return deps.closeTerminal(terminalTab);
const editor = editors.find((candidate) => candidate.program.id === id);
if (editor) quitEditor(editor, basename(editor.path), "column");
};
const closeFocused = () => {
if (focusedPane === "drawer" && terminal) return closeTab(terminal.terminalId);
if (focusedPane === "column") return closeTab(columnTab);
if (focusedPane === "message" && message) return quitEditor(message, "the message", "message");
say(deps.detailsFocused ? "Details stays; d hides the column." : "No pane has the keys; ctrl+\\ tab moves them to one.", true);
};
/** The pane ctrl+\ ctrl+\ goes back to: the one that last had the keys, or the first that's open. */
const last = ([target, ...PANE_ORDER] as const).find((pane) => open[pane]) ?? null;
const toggle = () => {
if (focused) return deps.focus(false);
if (last) return enter(last);
say("No pane is open; ctrl+j opens a terminal.");
};
/** Steps focus through the conversation and the open panes, in order. */
const step = (by: 1 | -1) => {
const ring: (PaneFocus | null)[] = [null, ...available];
const next = ring[(ring.indexOf(focusedPane) + by + ring.length) % ring.length] ?? null;
if (next) enter(next);
else deps.focus(false);
};
const focusDrawer = () => {
if (terminal) return side ? enter("column") : enter("drawer");
toggleTerminal();
};
const focusColumn = () => (open.column ? enter("column") : say("Nothing runs in the column; o on a changed file opens one.", true));
/** 1…9: a tab of the focused strip, the column's or else the drawer's. */
const pickTab = (index: number) => {
if (focusedPane !== "column" && !deps.detailsFocused) return selectTab(index);
const next = columnTabs[index];
if (next?.kind === "details") showColumnTab(next.id);
else if (next) enter("column", next.id);
};
const toggleZoom = () => {
if (zoomed) return setZoomed(null);
const pane = focusedPane ?? (deps.detailsFocused ? "column" : last);
if (!pane) return say("No pane is open to zoom.", true);
if (!focusedPane && !deps.detailsFocused) enter(pane);
setZoomed(pane);
};
const startPrefix = () => {
if (prefixTimer.current) clearTimeout(prefixTimer.current);
prefixTimer.current = setTimeout(() => setPrefix(false), PREFIX_MS);
setPrefix(true);
};
const endPrefix = () => {
if (prefixTimer.current) clearTimeout(prefixTimer.current);
prefixTimer.current = null;
setPrefix(false);
};
/** ctrl+\ takes the next key, wherever the keys are. */
const prefixKey: Binding = { keys: ["ctrl+\\"], run: startPrefix, hint: "panes" };
/** The keys after ctrl+\: any other key just cancels it. */
const prefixKeys: Binding[] = keys(
{ keys: [], label: "ctrl+\\", hint: "…" },
{ keys: ["ctrl+\\"], run: toggle },
{ keys: ["tab"], run: () => step(1), hint: "next" },
{ keys: ["shift+tab"], run: () => step(-1) },
{ keys: ["j"], run: focusDrawer, hint: "drawer" },
{ keys: ["l"], run: focusColumn, hint: "column" },
{ keys: ["k", "h"], run: () => deps.focus(false) },
{ keys: [], label: "1-9", hint: "tab" },
Array.from({ length: 9 }, (_, index): Binding => ({ keys: [`${index + 1}`], run: () => pickTab(index) })),
{ keys: ["x"], run: closeFocused, hint: "close" },
{ keys: ["z"], run: toggleZoom, hint: zoomed ? "unzoom" : "zoom" },
{ keys: ["n"], run: deps.newTerminal, hint: "new" },
{ keys: ["esc"], run: () => {}, hint: "cancel" },
);
/** Where the keys are, by name. */
const focusedName = focusedPane === "message" ? "message" : focusedPane === "drawer" ? terminal?.label : focusedPane === "column" ? (activeColumnTab.kind === "editor" ? basename(activeColumnTab.label) : activeColumnTab.label) : undefined;
/** The hint bar while a pane has the keys. */
const focusedKeys: Binding[] = focusedName
? [
{ keys: [], label: "keys:", hint: focusedName },
{ keys: [], label: "ctrl+\\ ctrl+\\", run: toggle, hint: "leave" },
{ keys: [], label: "ctrl+\\", run: startPrefix, hint: "panes" },
]
: [];
/** Palette commands for what the prefix does. */
const commands: Binding[] = keys(
available.length > 0 && { keys: [], label: "ctrl+\\ tab", run: () => step(1), command: { id: "pane-next", title: "Pane: next", keywords: ["focus", "terminal", "editor", "switch"] } },
(available.length > 0 || deps.detailsFocused) && { keys: [], label: "ctrl+\\ z", run: toggleZoom, command: { id: "pane-zoom", title: zoomed ? "Pane: unzoom" : "Pane: zoom", keywords: ["maximize", "fullscreen", "fill"] } },
);
return {
terminal,
tabs,
editor,
activeTerminal,
/** Terminals this run showed that still run, while the terminal is hidden. */
running: terminal ? [] : tabs.filter((candidate) => seen.has(key(candidate))),
editors,
modified,
message,
columnTabs: columnTabs.map((id) => ({ id, label: COLUMN_TAB_LABELS[id] })),
columnTabs,
columnTab,
setColumnTab: setTab,
showColumnTab,
focusedPane,
/** Whether a terminal has the keys, in the drawer or the column. */
terminalFocused: focusedPane === "drawer" || (focusedPane === "column" && activeColumnTab.kind === "terminal"),
zoomed: zoomShown ? zoomed : null,
prefix,
endPrefix,
enter,
openTerminal,
hideTerminal,
toggleTerminal,
selectTab,
terminalEnded,
closeTab,
openEditor,
editorOpened,
editorClosed,
openMessage,
messageClosed: () => setMessage(null),
keys: { pane: paneKey, tabs: tabKeys, column: columnKeys, focused: focusedKeys },
keys: { prefix: prefixKey, afterPrefix: prefixKeys, focused: focusedKeys, commands },
/** Whether ctrl+\ has a pane to go to, for the hint. */
any: available.length > 0,
};
}
+17 -12
View File
@@ -114,13 +114,18 @@ export function useWorkspace(input: {
groups: [{ label: "Terminals", items: threadTerminals.map((terminal) => ({ id: `terminal:full:${terminal.terminalId}`, title: label(terminal), run: () => enterTerminal(terminal, true) })) }],
});
};
const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => {
/** Closing ends the shell and deletes its history, so it asks first. */
const closeTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "label">) => {
if (!thread) return;
if (action === "close") {
run("Terminal closed", () => session.closeTerminal(thread.id, terminal.terminalId));
return;
}
run("Terminal cleared", () => session.clearTerminal(thread.id, terminal.terminalId));
confirm({
title: `Close ${resolveTerminalSessionLabel(terminal.terminalId, terminal)}?`,
detail: "Ends its shell and deletes its history.",
confirmLabel: "close",
run: () => run("Terminal closed", () => session.closeTerminal(thread.id, terminal.terminalId)),
});
};
const clearTerminal = (terminal: Pick<TerminalSummary, "terminalId">) => {
if (thread) run("Terminal cleared", () => session.clearTerminal(thread.id, terminal.terminalId));
};
const terminalItems = (action: "close" | "clear"): PickerItem[] => {
@@ -128,7 +133,7 @@ export function useWorkspace(input: {
return threadTerminals.map((terminal) => ({
id: `terminal:${action}:${terminal.terminalId}`,
title: `${verb} › ${label(terminal)}`,
run: () => terminalMutation(terminal, action),
run: () => (action === "close" ? closeTerminal(terminal) : clearTerminal(terminal)),
}));
};
// Close/clear appear as one sub-picker each, plus search-only rows so typing finds them.
@@ -290,11 +295,9 @@ export function useWorkspace(input: {
});
};
const commands: Command[] = thread && !input.draft ? [
{ id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal },
{ id: "terminal-picker", title: "Terminals…", shortcut: "T", keywords: ["shell", "close", "clear", "attach"], run: terminalPicker },
{ id: "terminal-new", title: "New terminal", keywords: ["shell", "open"], run: () => newTerminal() },
{ id: "terminal-full-screen", title: "Attach terminal full screen", keywords: ["shell", "console", "attach"], run: attachFullScreen },
...terminalItems("close"), ...terminalItems("clear"),
{ id: "terminal-picker", title: "Terminal: pick…", shortcut: "T", keywords: ["shell", "close", "clear", "attach"], run: terminalPicker },
{ id: "terminal-new", title: "Terminal: new", keywords: ["shell", "open"], run: () => newTerminal() },
{ id: "terminal-full-screen", title: "Terminal: attach full screen", keywords: ["shell", "console", "attach"], run: attachFullScreen },
{ id: "branches", title: "Branches and worktrees…", shortcut: "b", keywords: ["git", "switch", "ref", "create", "remove", "pull"], run: branchPicker },
{ id: "workspace-editor", title: input.diff ? "Open diff file in editor" : "Open workspace in editor", shortcut: "E", keywords: ["folder", "code", "vscode", "cursor"], run: openInEditor },
...(setup?.threadId === thread.id && setup.phase === "running" ? [{ id: "setup-cancel", title: "Cancel worktree setup…", keywords: ["preparation", "stop"], run: cancelSetup }] : []),
@@ -325,6 +328,8 @@ export function useWorkspace(input: {
key,
openTerminal,
newTerminal: () => newTerminal(),
closeTerminal,
clearTerminal,
tabs,
note,
setupFailed: setup?.phase === "failed" || setupError !== null,