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:
1 parent
56ee5364fa
commit
9e4558d7d1
8 files changed
+929
-308
No files matched your search
+168
-73
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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,
|
||||
|
||||
@@ -70,11 +70,11 @@ describe("links and paths in replies", () => {
|
||||
const app = await open({ width: 200, session: fakeSession({ snapshot, projection: withReply("I changed `src/a.ts:3` and left src/missing.ts alone.", false) }) });
|
||||
const missing = app.find("missing.ts");
|
||||
await app.click(missing.x, missing.y);
|
||||
expect(app.frame()).not.toContain("Editing");
|
||||
expect(app.frame()).not.toContain("Details ");
|
||||
const path = app.find("a.ts:3");
|
||||
await app.click(path.x, path.y);
|
||||
expect(app.frame()).toContain("Details Editor");
|
||||
expect(app.frame()).toContain("Editing src/a.ts ");
|
||||
expect(app.frame()).toContain("Details src/a.ts ✕");
|
||||
expect(app.hints()).toStartWith("keys: a.ts");
|
||||
});
|
||||
|
||||
test("a drag over a link selects it rather than opening it", async () => {
|
||||
|
||||
+394
-117
@@ -1,33 +1,96 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { RGBA } from "@opentui/core";
|
||||
|
||||
import { loadLayout } from "../../src/layout.ts";
|
||||
import { DEFAULT_LAYOUT, loadLayout } from "../../src/layout.ts";
|
||||
import { colors } from "../../src/ui/theme.ts";
|
||||
import { withReply } from "./fixtures.ts";
|
||||
import { fakeSession, renderApp, v2ShellSnapshot, v2ThreadId } from "./harness.tsx";
|
||||
|
||||
let app: Awaited<ReturnType<typeof renderApp>> | null = null;
|
||||
const open = async (...args: Parameters<typeof renderApp>) => (app = await renderApp(...args));
|
||||
const saved = { visual: process.env.VISUAL, editor: process.env.EDITOR };
|
||||
afterEach(() => {
|
||||
app?.destroy();
|
||||
app = null;
|
||||
for (const [key, value] of [["VISUAL", saved.visual], ["EDITOR", saved.editor]] as const) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
});
|
||||
/** Runs as `$EDITOR "$1"`. */
|
||||
const setEditor = (command: string) => {
|
||||
delete process.env.VISUAL;
|
||||
process.env.EDITOR = command;
|
||||
};
|
||||
|
||||
const terminal = { threadId: v2ThreadId, terminalId: "term-1", cwd: "/workspace/project", worktreePath: null, status: "running", pid: 42, exitCode: null, exitSignal: null, hasRunningSubprocess: false, label: "", updatedAt: "2026-06-20T00:00:00.000Z" };
|
||||
const second = { ...terminal, terminalId: "term-2" };
|
||||
const snapshot = { type: "snapshot", threadId: v2ThreadId, terminalId: "term-1", createdAt: "2026-06-20T00:00:00.000Z", snapshot: { history: "earlier output\r\nuser@host:~$ " } };
|
||||
const withTerminal = (events: readonly unknown[] = [snapshot]) => fakeSession({ terminals: [terminal], terminalEvents: events, projection: withReply("The reply above the drawer.", false) });
|
||||
const withTerminals = () => fakeSession({ terminals: [terminal, second], terminalEvents: [snapshot], projection: withReply("The reply above the drawer.", false) });
|
||||
|
||||
const PREFIX_HINT = "ctrl+\\ … · tab next · j drawer · l column · 1-9 tab · x close · z zoom · n new · esc cancel";
|
||||
const keysOn = (name: string) => `keys: ${name} · ctrl+\\ ctrl+\\ leave · ctrl+\\ panes`;
|
||||
type App = Awaited<ReturnType<typeof renderApp>>;
|
||||
/** ctrl+\, then a key. */
|
||||
const prefix = async (app: App, key: string, modifiers?: Parameters<App["press"]>[1]) => {
|
||||
await app.press("\\", { ctrl: true });
|
||||
await app.press(key, modifiers);
|
||||
};
|
||||
const attached = (app: App) => app.calls("attachTerminal").map((call) => (call.args[0] as { terminalId: string }).terminalId);
|
||||
/** The colours of the cell at a point. */
|
||||
const cellAt = (app: App, x: number, y: number) => {
|
||||
const line = app.renderer.currentRenderBuffer.getSpanLines()[y] as unknown as { spans: { text: string; fg: RGBA; bg: RGBA }[] };
|
||||
let left = 0;
|
||||
for (const span of line.spans) {
|
||||
left += Bun.stringWidth(span.text);
|
||||
if (left > x) return { fg: span.fg.toString(), bg: span.bg.toString() };
|
||||
}
|
||||
throw new Error(`nothing at ${x},${y}`);
|
||||
};
|
||||
const color = (hex: string) => RGBA.fromHex(hex).toString();
|
||||
const waitFor = async (check: () => boolean) => {
|
||||
for (let tries = 0; tries < 60 && !check(); tries++) await app?.settle(25);
|
||||
};
|
||||
|
||||
/** A workspace on this machine holding README.md and src/ui/deep/TerminalPane.tsx, as the project's folder. */
|
||||
function workspace() {
|
||||
const root = mkdtempSync(join(tmpdir(), "t3tui-edit-"));
|
||||
writeFileSync(join(root, "README.md"), "hello\n");
|
||||
mkdirSync(join(root, "src/ui/deep"), { recursive: true });
|
||||
writeFileSync(join(root, "src/ui/deep/TerminalPane.tsx"), "export {};\n");
|
||||
const project = { ...v2ShellSnapshot.projects[0]!, workspaceRoot: root };
|
||||
return { root, snapshot: { ...v2ShellSnapshot, projects: [project] } };
|
||||
}
|
||||
/** A stand-in Neovim: it writes down how it was run; the instance waits, the remote calls answer at once (1 buffer modified). */
|
||||
function fakeNvim() {
|
||||
const bin = mkdtempSync(join(tmpdir(), "t3tui-nvim-bin-"));
|
||||
const log = join(bin, "log");
|
||||
writeFileSync(join(bin, "nvim"), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${log}'\nif [ "$1" = --server ]; then case "$4" in len*) echo 1;; esac; exit 0; fi\nsleep 5\n`);
|
||||
chmodSync(join(bin, "nvim"), 0o755);
|
||||
setEditor(join(bin, "nvim"));
|
||||
return () => {
|
||||
try {
|
||||
return readFileSync(log, "utf8").trim().split("\n");
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe("terminal drawer", () => {
|
||||
test("ctrl+j opens the thread's terminal in a drawer below the composer, with its scrollback, and it takes every key", async () => {
|
||||
const app = await open({ session: withTerminal() });
|
||||
await app.press("j", { ctrl: true });
|
||||
expect(app.frame()).toContain("Terminal 1 +");
|
||||
expect(app.frame()).toContain("Terminal 1 ✕ + new");
|
||||
expect(app.frame()).toContain("user@host:~$");
|
||||
expect(app.calls("attachTerminal")).toHaveLength(1);
|
||||
expect(app.hints()).toBe("ctrl+\\ leave pane");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
// Under the composer, the conversation's full width.
|
||||
const tab = app.find("Terminal 1 +");
|
||||
const tab = app.find("Terminal 1 ✕");
|
||||
expect(tab.y).toBeGreaterThan(app.find("Press i to type").y);
|
||||
expect(tab.x).toBeLessThan(app.find("Press i to type").x);
|
||||
await app.press("q");
|
||||
@@ -37,19 +100,49 @@ describe("terminal drawer", () => {
|
||||
expect(app.frame()).toContain("user@host:~$");
|
||||
});
|
||||
|
||||
test("ctrl+\\ leaves the drawer and comes back to it; a click focuses it too", async () => {
|
||||
test("ctrl+\\ is a prefix: twice leaves the drawer and comes back; any other key only cancels it and reaches no program", async () => {
|
||||
const app = await open({ session: withTerminal() });
|
||||
await app.press("j", { ctrl: true });
|
||||
await app.press("\\", { ctrl: true });
|
||||
expect(app.hints()).toStartWith("ctrl+\\ pane · j/k threads");
|
||||
expect(app.hints()).toBe(PREFIX_HINT);
|
||||
await app.press("q");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
await prefix(app, "escape");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
expect(app.calls("writeTerminal")).toHaveLength(0);
|
||||
await prefix(app, "\\", { ctrl: true });
|
||||
expect(app.hints()).toStartWith("ctrl+\\ panes · j/k threads");
|
||||
await app.press("j");
|
||||
expect(app.calls("writeTerminal")).toHaveLength(0);
|
||||
await prefix(app, "\\", { ctrl: true });
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
await prefix(app, "k");
|
||||
expect(app.hints()).toStartWith("ctrl+\\ panes");
|
||||
});
|
||||
|
||||
test("the prefix gives up after about two seconds", async () => {
|
||||
const app = await open({ session: withTerminal() });
|
||||
await app.press("j", { ctrl: true });
|
||||
await app.press("\\", { ctrl: true });
|
||||
expect(app.hints()).toBe("ctrl+\\ leave pane");
|
||||
await app.press("\\", { ctrl: true });
|
||||
expect(app.hints()).toBe(PREFIX_HINT);
|
||||
await app.settle(2100);
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
await app.press("q");
|
||||
expect(app.calls("writeTerminal").map((call) => call.args[2])).toEqual(["q"]);
|
||||
});
|
||||
|
||||
test("a click on the drawer focuses it; a click on the conversation or the message box takes the keys back", async () => {
|
||||
const app = await open({ session: withTerminal() });
|
||||
await app.press("j", { ctrl: true });
|
||||
const reply = app.find("The reply above");
|
||||
await app.click(reply.x, reply.y);
|
||||
expect(app.hints()).toStartWith("ctrl+\\ panes · j/k threads");
|
||||
const shell = app.find("user@host");
|
||||
await app.click(shell.x, shell.y);
|
||||
expect(app.hints()).toBe("ctrl+\\ leave pane");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
const composer = app.find("Press i to type");
|
||||
await app.click(composer.x, composer.y);
|
||||
expect(app.hints()).toStartWith("enter send");
|
||||
});
|
||||
|
||||
test("ctrl+j hides the drawer again, from it or from the conversation, and brings back the same terminal", async () => {
|
||||
@@ -60,51 +153,132 @@ describe("terminal drawer", () => {
|
||||
expect(app.hints()).toStartWith("j/k threads");
|
||||
await app.press("j", { ctrl: true });
|
||||
expect(app.frame()).toContain("user@host");
|
||||
await app.press("\\", { ctrl: true });
|
||||
await prefix(app, "\\", { ctrl: true });
|
||||
await app.press("j", { ctrl: true });
|
||||
expect(app.frame()).not.toContain("user@host");
|
||||
expect(app.calls("writeTerminal")).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("each terminal is a tab: a click, alt+1…9, or the T picker switches; + opens another", async () => {
|
||||
const second = { ...terminal, terminalId: "term-2" };
|
||||
const app = await open({ session: fakeSession({ terminals: [terminal, second], terminalEvents: [snapshot] }) });
|
||||
test("each terminal is a tab: a click, the prefix's 1…9, or the T picker switches; + new opens another", async () => {
|
||||
const app = await open({ session: withTerminals() });
|
||||
await app.press("j", { ctrl: true });
|
||||
expect(app.frame()).toContain("Terminal 1 Terminal 2 +");
|
||||
const attached = () => app.calls("attachTerminal").map((call) => (call.args[0] as { terminalId: string }).terminalId);
|
||||
expect(attached()).toEqual(["term-1"]);
|
||||
expect(app.frame()).toContain("Terminal 1 ✕ Terminal 2 + new");
|
||||
expect(attached(app)).toEqual(["term-1"]);
|
||||
await prefix(app, "2");
|
||||
expect(attached(app)).toEqual(["term-1", "term-2"]);
|
||||
expect(app.hints()).toBe(keysOn("Terminal 2"));
|
||||
// From the conversation too, the drawer's tabs.
|
||||
await prefix(app, "\\", { ctrl: true });
|
||||
await prefix(app, "1");
|
||||
expect(attached(app)).toEqual(["term-1", "term-2", "term-1"]);
|
||||
// alt+1…9 is gone.
|
||||
await app.press("2", { meta: true });
|
||||
expect(attached()).toEqual(["term-1", "term-2"]);
|
||||
// From the conversation too, while the drawer shows.
|
||||
await app.press("\\", { ctrl: true });
|
||||
await app.press("1", { meta: true });
|
||||
expect(attached()).toEqual(["term-1", "term-2", "term-1"]);
|
||||
expect(attached(app)).toEqual(["term-1", "term-2", "term-1"]);
|
||||
const tab = app.find("Terminal 2");
|
||||
await app.click(tab.x, tab.y);
|
||||
expect(attached()).toEqual(["term-1", "term-2", "term-1", "term-2"]);
|
||||
expect(attached(app)).toEqual(["term-1", "term-2", "term-1", "term-2"]);
|
||||
expect(app.hints()).toBe(keysOn("Terminal 2"));
|
||||
await prefix(app, "k");
|
||||
await app.press("T");
|
||||
await app.press("return");
|
||||
expect(attached().at(-1)).toBe("term-1");
|
||||
const plus = app.find("Terminal 2 +");
|
||||
await app.click(plus.x + "Terminal 2 ".length, plus.y);
|
||||
expect(attached(app).at(-1)).toBe("term-1");
|
||||
const plus = app.find("+ new");
|
||||
await app.click(plus.x, plus.y);
|
||||
expect(app.calls("openTerminal")).toHaveLength(1);
|
||||
expect(app.frame()).toContain("Terminal 1 Terminal 2 Terminal 3 +");
|
||||
expect(attached().at(-1)).toBe("term-3");
|
||||
expect(app.frame()).toContain("Terminal 1 Terminal 2 Terminal 3 ✕ + new");
|
||||
expect(attached(app).at(-1)).toBe("term-3");
|
||||
// So does the prefix's n.
|
||||
await prefix(app, "n");
|
||||
expect(app.calls("openTerminal")).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("the prefix's x, the active tab's ✕ and a middle click close a terminal, after asking", async () => {
|
||||
const app = await open({ session: withTerminals() });
|
||||
await app.press("j", { ctrl: true });
|
||||
await prefix(app, "x");
|
||||
expect(app.frame()).toContain("Close Terminal 1?");
|
||||
await app.press("escape");
|
||||
expect(app.calls("closeTerminal")).toHaveLength(0);
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
const close = app.find("Terminal 1 ✕");
|
||||
await app.click(close.x + "Terminal 1 ".length, close.y);
|
||||
expect(app.frame()).toContain("Close Terminal 1?");
|
||||
await app.press("return");
|
||||
expect(app.calls("closeTerminal").map((call) => call.args[1])).toEqual(["term-1"]);
|
||||
const other = app.find("Terminal 2");
|
||||
await app.mockMouse.click(other.x, other.y, 1);
|
||||
await app.settle();
|
||||
expect(app.frame()).toContain("Close Terminal 2?");
|
||||
});
|
||||
|
||||
test("the prefix's z zooms the drawer over the conversation and the message box, until z again", async () => {
|
||||
const app = await open({ session: withTerminal() });
|
||||
await app.press("j", { ctrl: true });
|
||||
const tabs = app.find("Terminal 1 ✕").y;
|
||||
await prefix(app, "z");
|
||||
expect(app.frame()).not.toContain("The reply above");
|
||||
expect(app.frame()).not.toContain("Press i to type");
|
||||
expect(app.find("Terminal 1 ✕").y).toBeLessThan(tabs);
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
await prefix(app, "z");
|
||||
expect(app.frame()).toContain("The reply above");
|
||||
expect(app.find("Terminal 1 ✕").y).toBe(tabs);
|
||||
// From the conversation, z zooms the pane that last had the keys.
|
||||
await prefix(app, "k");
|
||||
await prefix(app, "z");
|
||||
expect(app.frame()).not.toContain("The reply above");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
});
|
||||
|
||||
test("the focused pane's strip and edge light up; the message box's bar steps back", async () => {
|
||||
const app = await open({ session: withTerminal() });
|
||||
await app.press("j", { ctrl: true });
|
||||
const tab = app.find("Terminal 1 ✕");
|
||||
const shell = app.find("user@host");
|
||||
const bar = app.find("Press i to type");
|
||||
expect(cellAt(app, tab.x, tab.y).fg).toBe(color(colors.accent));
|
||||
expect(cellAt(app, tab.x - 2, tab.y).bg).toBe(color(colors.element));
|
||||
expect(cellAt(app, shell.x - 1, shell.y).fg).toBe(color(colors.accent));
|
||||
expect(cellAt(app, bar.x - 3, bar.y).fg).toBe(color(colors.faint));
|
||||
await prefix(app, "k");
|
||||
expect(cellAt(app, tab.x, tab.y).fg).toBe(color(colors.muted));
|
||||
expect(cellAt(app, tab.x - 2, tab.y).bg).toBe(color(colors.panel));
|
||||
expect(cellAt(app, shell.x - 1, shell.y).fg).toBe(color(colors.faint));
|
||||
expect(cellAt(app, bar.x - 3, bar.y).fg).toBe(color(colors.border));
|
||||
});
|
||||
|
||||
test("while the drawer is hidden, a strip under the message box names the terminals this run opened; a click brings one back", async () => {
|
||||
const app = await open({ session: withTerminals() });
|
||||
expect(app.frame()).not.toContain("▸ Terminal");
|
||||
await app.press("j", { ctrl: true });
|
||||
await app.press("j", { ctrl: true });
|
||||
// Terminal 2 wasn't opened here.
|
||||
expect(app.frame()).toContain("▸ Terminal 1 ctrl+j");
|
||||
expect(app.find("▸ Terminal 1").y).toBeGreaterThan(app.find("Press i to type").y);
|
||||
await prefix(app, "j");
|
||||
await prefix(app, "2");
|
||||
await app.press("j", { ctrl: true });
|
||||
expect(app.frame()).toContain("▸ Terminal 1 · Terminal 2 ctrl+j");
|
||||
const name = app.find("Terminal 1 · ");
|
||||
await app.click(name.x, name.y);
|
||||
expect(attached(app).at(-1)).toBe("term-1");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
expect(app.frame()).not.toContain("▸ Terminal");
|
||||
});
|
||||
|
||||
test("a terminal that closes takes its tab away, and the last one the drawer", async () => {
|
||||
const closed = { type: "closed", threadId: v2ThreadId, terminalId: "term-1", createdAt: "2026-06-20T00:00:00.000Z" };
|
||||
const app = await open({ session: withTerminal([snapshot, closed]) });
|
||||
await app.press("j", { ctrl: true });
|
||||
expect(app.frame()).not.toContain("Terminal 1 +");
|
||||
expect(app.frame()).not.toContain("Terminal 1 ✕");
|
||||
expect(app.hints()).toBe("Terminal closed");
|
||||
});
|
||||
|
||||
test("dragging the drawer's edge resizes it and keeps the height; right-click resets it", async () => {
|
||||
const app = await open({ session: withTerminal() });
|
||||
await app.press("j", { ctrl: true });
|
||||
await app.press("\\", { ctrl: true });
|
||||
const tabs = () => app.find("Terminal 1 +").y;
|
||||
await prefix(app, "k");
|
||||
const tabs = () => app.find("Terminal 1 ✕").y;
|
||||
const before = tabs();
|
||||
const edge = app.find("━");
|
||||
await app.mockMouse.drag(edge.x + 5, edge.y, edge.x + 5, edge.y - 4);
|
||||
@@ -125,24 +299,29 @@ describe("terminal drawer", () => {
|
||||
expect(app.frame()).toContain("Press i to type");
|
||||
});
|
||||
|
||||
test("Move terminal to the side puts terminals in the right column's Terminal tab, and stays", async () => {
|
||||
const app = await open({ width: 200, session: withTerminal() });
|
||||
test("Pane: move terminal to the side puts each terminal in the right column's one strip of tabs, and stays", async () => {
|
||||
const app = await open({ width: 200, layout: { ...DEFAULT_LAYOUT, detailsWidth: 46 }, session: withTerminals() });
|
||||
await app.press("k", { ctrl: true });
|
||||
await app.type("move terminal to the side");
|
||||
await app.press("return");
|
||||
expect((await loadLayout()).terminalPlacement).toBe("side");
|
||||
await app.press("j", { ctrl: true });
|
||||
expect(app.frame()).toContain("Details Terminal");
|
||||
const tab = app.find("Terminal 1 +");
|
||||
expect(tab.x).toBeGreaterThan(200 - 38 - 1);
|
||||
expect(app.hints()).toBe("ctrl+\\ leave pane");
|
||||
// { and } step through the column's tabs from the conversation.
|
||||
await app.press("\\", { ctrl: true });
|
||||
await app.press("{");
|
||||
expect(app.frame()).toContain("Details Terminal 1 ✕ Terminal 2 + new");
|
||||
expect(app.frame().match(/Terminal 2/g)).toHaveLength(1);
|
||||
expect(app.find("Details Terminal 1").x).toBeGreaterThan(200 - 46 - 1);
|
||||
expect(app.frame()).toContain("user@host");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
// The prefix's 1…9 count the column's tabs; Details gives the keys back.
|
||||
await prefix(app, "1");
|
||||
expect(app.frame()).not.toContain("user@host");
|
||||
expect(app.frame()).toContain("/workspace/project");
|
||||
await app.press("}");
|
||||
expect(app.hints()).toStartWith("ctrl+\\ panes");
|
||||
await prefix(app, "l");
|
||||
expect(app.frame()).toContain("user@host");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
await prefix(app, "3");
|
||||
expect(attached(app).at(-1)).toBe("term-2");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 2"));
|
||||
await app.press("j", { ctrl: true });
|
||||
expect(app.frame()).not.toContain("Details Terminal");
|
||||
});
|
||||
@@ -154,35 +333,86 @@ describe("terminal drawer", () => {
|
||||
});
|
||||
|
||||
test("ctrl+g writes the message in $EDITOR in the composer's place, and what's saved comes back", async () => {
|
||||
const previous = { visual: process.env.VISUAL, editor: process.env.EDITOR };
|
||||
delete process.env.VISUAL;
|
||||
// Run as `$EDITOR "$1"`: this one waits a moment, overwrites the file and exits.
|
||||
process.env.EDITOR = "sleep 0.5; printf 'from the editor' >";
|
||||
try {
|
||||
const app = await open();
|
||||
await app.press("i");
|
||||
await app.type("draft");
|
||||
const composer = app.find("draft");
|
||||
await app.press("g", { ctrl: true });
|
||||
expect(app.frame()).toContain("Message · save and quit");
|
||||
expect(app.frame()).not.toContain("draft");
|
||||
expect(app.find("Message · save and quit").x).toBeLessThan(composer.x);
|
||||
expect(app.hints()).toBe("ctrl+\\ leave pane");
|
||||
for (let tries = 0; tries < 40 && app.frame().includes("Message · save and quit"); tries++) await app.settle(50);
|
||||
expect(app.frame()).not.toContain("Message · save and quit");
|
||||
expect(app.frame()).toContain("from the editor");
|
||||
expect(app.hints()).toStartWith("enter send");
|
||||
} finally {
|
||||
restoreEditor(previous);
|
||||
}
|
||||
// This one waits a moment, overwrites the file and exits.
|
||||
setEditor("sleep 0.5; printf 'from the editor' >");
|
||||
const app = await open();
|
||||
await app.press("i");
|
||||
await app.type("draft");
|
||||
const composer = app.find("draft");
|
||||
await app.press("g", { ctrl: true });
|
||||
expect(app.frame()).toContain("Message · save and quit");
|
||||
expect(app.frame()).not.toContain("draft");
|
||||
expect(app.find("Message · save and quit").x).toBeLessThan(composer.x);
|
||||
expect(app.hints()).toBe(keysOn("message"));
|
||||
await waitFor(() => !app.frame().includes("Message · save and quit"));
|
||||
expect(app.frame()).not.toContain("Message · save and quit");
|
||||
expect(app.frame()).toContain("from the editor");
|
||||
expect(app.hints()).toStartWith("enter send");
|
||||
});
|
||||
});
|
||||
|
||||
const restoreEditor = (previous: { visual: string | undefined; editor: string | undefined }) => {
|
||||
if (previous.visual !== undefined) process.env.VISUAL = previous.visual;
|
||||
if (previous.editor === undefined) delete process.env.EDITOR;
|
||||
else process.env.EDITOR = previous.editor;
|
||||
};
|
||||
describe("the panes together", () => {
|
||||
test("tab after ctrl+\\ moves through the message editor, the drawer and the column in turn, and back; shift+tab goes the other way", async () => {
|
||||
const { snapshot } = workspace();
|
||||
setEditor("sleep 5; true");
|
||||
const vcs = { status: "live", local: { isRepo: true, hasPrimaryRemote: true, isDefaultRef: true, refName: "main", hasWorkingTreeChanges: true, workingTree: { files: [{ path: "README.md", insertions: 1, deletions: 0 }], insertions: 1, deletions: 0 } }, remote: { hasUpstream: true, aheadCount: 0, behindCount: 0, pr: null } };
|
||||
const app = await open({ width: 200, height: 50, session: fakeSession({ snapshot, vcs, terminals: [terminal], terminalEvents: [snapshot] }) });
|
||||
await app.press("l");
|
||||
await app.press("o");
|
||||
expect(app.hints()).toBe(keysOn("README.md"));
|
||||
await prefix(app, "k");
|
||||
await app.press("j", { ctrl: true });
|
||||
await prefix(app, "k");
|
||||
await app.press("g", { ctrl: true });
|
||||
expect(app.hints()).toBe(keysOn("message"));
|
||||
const order = [];
|
||||
for (let step = 0; step < 4; step++) {
|
||||
await prefix(app, "tab");
|
||||
order.push(app.hints());
|
||||
}
|
||||
expect(order).toEqual([keysOn("Terminal 1"), keysOn("README.md"), expect.stringMatching(/^ctrl\+\\ panes/), keysOn("message")]);
|
||||
await prefix(app, "tab", { shift: true });
|
||||
expect(app.hints()).toStartWith("ctrl+\\ panes");
|
||||
await prefix(app, "tab", { shift: true });
|
||||
expect(app.hints()).toBe(keysOn("README.md"));
|
||||
await prefix(app, "j");
|
||||
expect(app.hints()).toBe(keysOn("Terminal 1"));
|
||||
await prefix(app, "l");
|
||||
expect(app.hints()).toBe(keysOn("README.md"));
|
||||
await prefix(app, "h");
|
||||
expect(app.hints()).toStartWith("ctrl+\\ panes");
|
||||
});
|
||||
|
||||
test("the palette lists terminal and pane commands under one prefix each, closing and clearing only the active terminal", async () => {
|
||||
const app = await open({ session: withTerminals() });
|
||||
await app.press("j", { ctrl: true });
|
||||
await prefix(app, "k");
|
||||
await app.press("k", { ctrl: true });
|
||||
await app.type("terminal:");
|
||||
const frame = app.frame();
|
||||
for (const title of ["Terminal: hide", "Terminal: new", "Terminal: attach full screen", "Terminal: pick…", "Terminal: close Terminal 1", "Terminal: clear Terminal 1"]) expect(frame).toContain(title);
|
||||
expect(frame).not.toContain("Terminal 2");
|
||||
await app.press("escape");
|
||||
await app.press("k", { ctrl: true });
|
||||
await app.type("pane:");
|
||||
for (const title of ["Pane: next", "Pane: zoom", "Pane: move terminal to the side"]) expect(app.frame()).toContain(title);
|
||||
});
|
||||
|
||||
test("the palette sits on a solid backdrop over the whole conversation area, so no conversation shows beside it", async () => {
|
||||
const app = await open({ session: fakeSession({ projection: withReply("Decision: fix the bleed at the palette's edges.", false) }) });
|
||||
const reply = app.find("Decision:");
|
||||
await app.press("k", { ctrl: true });
|
||||
const lines = app.frame().split("\n");
|
||||
expect(lines.some((line) => line.includes("Decision"))).toBe(false);
|
||||
// The backdrop runs from the list's edge to the right edge, below the header to above the hints.
|
||||
expect(cellAt(app, reply.x, reply.y).bg).toBe(color(colors.panel));
|
||||
expect(cellAt(app, 139, 1).bg).toBe(color(colors.panel));
|
||||
expect(cellAt(app, reply.x, 38).bg).toBe(color(colors.panel));
|
||||
const search = app.find("Search commands");
|
||||
const left = search.x - reply.x;
|
||||
expect(left).toBeGreaterThan(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("editing a changed file", () => {
|
||||
const vcs = {
|
||||
@@ -190,6 +420,17 @@ describe("editing a changed file", () => {
|
||||
local: { isRepo: true, hasPrimaryRemote: true, isDefaultRef: true, refName: "main", hasWorkingTreeChanges: true, workingTree: { files: [{ path: "README.md", insertions: 2, deletions: 1 }], insertions: 2, deletions: 1 } },
|
||||
remote: { hasUpstream: true, aheadCount: 0, behindCount: 0, pr: null },
|
||||
};
|
||||
const twoFiles = { ...vcs, local: { ...vcs.local, workingTree: { ...vcs.local.workingTree, files: [{ path: "README.md", insertions: 2, deletions: 1 }, { path: "src/ui/deep/TerminalPane.tsx", insertions: 1, deletions: 0 }] } } };
|
||||
/** o on each changed file in turn, from the details panel. */
|
||||
const editBoth = async (app: App) => {
|
||||
await app.press("l");
|
||||
await app.press("o");
|
||||
await prefix(app, "k");
|
||||
await app.press("l");
|
||||
for (let tries = 0; tries < 8 && !app.hints().includes("o edit file"); tries++) await app.press("j");
|
||||
await app.press("j");
|
||||
await app.press("o");
|
||||
};
|
||||
|
||||
test("o on a file in Changes, or its ▸ Edit, opens it in the pane when it's on this machine", async () => {
|
||||
const app = await open({ width: 200, session: fakeSession({ vcs }) });
|
||||
@@ -201,58 +442,94 @@ describe("editing a changed file", () => {
|
||||
expect(app.hints()).toBe("README.md isn't on this machine.");
|
||||
});
|
||||
|
||||
test("a file on this machine opens in the column's Editor tab, which closes when the editor does", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "t3tui-edit-"));
|
||||
writeFileSync(join(root, "README.md"), "hello\n");
|
||||
const project = { ...v2ShellSnapshot.projects[0]!, workspaceRoot: root };
|
||||
const previous = { visual: process.env.VISUAL, editor: process.env.EDITOR };
|
||||
delete process.env.VISUAL;
|
||||
process.env.EDITOR = "sleep 0.6; true";
|
||||
try {
|
||||
const app = await open({ width: 200, session: fakeSession({ vcs, snapshot: { ...v2ShellSnapshot, projects: [project] } }) });
|
||||
await app.press("l");
|
||||
await app.press("o");
|
||||
expect(app.frame()).toContain("Details Editor");
|
||||
expect(app.frame()).toContain("Editing README.md");
|
||||
expect(app.find("Details Editor").x).toBeGreaterThan(200 - 38 - 1);
|
||||
expect(app.hints()).toBe("ctrl+\\ leave pane");
|
||||
// Back to Details and to the editor again, with it still running.
|
||||
await app.press("\\", { ctrl: true });
|
||||
await app.press("}");
|
||||
expect(app.frame()).not.toContain("Editing README.md");
|
||||
await app.click(app.find("Editor").x, app.find("Editor").y);
|
||||
expect(app.frame()).toContain("Editing README.md");
|
||||
for (let tries = 0; tries < 40 && app.frame().includes("Details Editor"); tries++) await app.settle(50);
|
||||
expect(app.frame()).not.toContain("Details Editor");
|
||||
expect(app.frame()).toContain("Changes");
|
||||
} finally {
|
||||
restoreEditor(previous);
|
||||
}
|
||||
test("a file on this machine opens in a tab of the column named by its path, which closes when the editor does", async () => {
|
||||
const { snapshot } = workspace();
|
||||
setEditor("sleep 0.6; true");
|
||||
const app = await open({ width: 200, session: fakeSession({ vcs, snapshot }) });
|
||||
await app.press("l");
|
||||
await app.press("o");
|
||||
expect(app.frame()).toContain("Details README.md ✕");
|
||||
expect(app.find("Details README.md").x).toBeGreaterThan(200 - 38 - 1);
|
||||
expect(app.hints()).toBe(keysOn("README.md"));
|
||||
// Back to Details and to the editor again, with it still running.
|
||||
await prefix(app, "1");
|
||||
expect(app.frame()).toContain("Changes");
|
||||
const tab = app.find("Details README.md");
|
||||
await app.click(tab.x + "Details ".length, tab.y);
|
||||
expect(app.hints()).toBe(keysOn("README.md"));
|
||||
await waitFor(() => !app.frame().includes("Details README.md"));
|
||||
expect(app.frame()).not.toContain("Details README.md");
|
||||
expect(app.frame()).toContain("Changes");
|
||||
});
|
||||
|
||||
test("each file gets a tab of its own, named from the workspace and shortened from the middle", async () => {
|
||||
const { snapshot } = workspace();
|
||||
setEditor("sleep 5; true");
|
||||
const app = await open({ width: 200, session: fakeSession({ vcs: twoFiles, snapshot }) });
|
||||
await editBoth(app);
|
||||
// The column's default width cuts them; wider, they fit.
|
||||
expect(app.frame()).toContain("Details README.md …nalPane.tsx ✕");
|
||||
await app.mockMouse.drag(200 - 39, 10, 200 - 60, 10);
|
||||
await app.settle(100);
|
||||
expect(app.frame()).toContain("Details README.md src/ui/deep/TerminalPane.tsx ✕");
|
||||
expect(app.frame()).toContain("src/ui/deep/TerminalPane.tsx");
|
||||
expect(app.hints()).toBe(keysOn("TerminalPane.tsx"));
|
||||
await prefix(app, "2");
|
||||
expect(app.hints()).toBe(keysOn("README.md"));
|
||||
// An editor that can't be asked to quit isn't closed under you.
|
||||
await prefix(app, "x");
|
||||
expect(app.hints()).toStartWith("Quit README.md from inside it");
|
||||
expect(app.frame()).toContain("Details README.md ✕");
|
||||
});
|
||||
|
||||
test("Neovim takes further files in the instance already running, through its socket, and the prefix's x asks it to quit", async () => {
|
||||
const { root, snapshot } = workspace();
|
||||
const log = fakeNvim();
|
||||
const app = await open({ width: 200, session: fakeSession({ vcs: twoFiles, snapshot }) });
|
||||
await editBoth(app);
|
||||
await waitFor(() => log().some((line) => line.includes("--remote-expr")));
|
||||
expect(app.frame()).toContain("Details src/…/TerminalPane.tsx ✕");
|
||||
expect(app.frame()).not.toContain("README.md ✕");
|
||||
expect(app.hints()).toBe(keysOn("TerminalPane.tsx"));
|
||||
const [listen, remote] = log();
|
||||
const socket = /^--listen (\S+) /.exec(listen ?? "")?.[1];
|
||||
expect(listen).toBe(`--listen ${socket} ${join(root, "README.md")}`);
|
||||
expect(remote).toBe(`--server ${socket} --remote-expr execute('drop ' .. fnameescape('${join(root, "src/ui/deep/TerminalPane.tsx")}'))`);
|
||||
await prefix(app, "x");
|
||||
await waitFor(() => log().length > 2);
|
||||
expect(log()[2]).toBe(`--server ${socket} --remote-send <C-\\><C-N>:confirm qa<CR>`);
|
||||
});
|
||||
|
||||
test("with the column hidden, the header names the editor still running in it, with ● for unsaved changes", async () => {
|
||||
const { snapshot } = workspace();
|
||||
fakeNvim();
|
||||
const app = await open({ width: 200, session: fakeSession({ vcs, snapshot }) });
|
||||
await app.press("l");
|
||||
await app.press("o");
|
||||
await prefix(app, "k");
|
||||
await app.press("d");
|
||||
await waitFor(() => app.frame().includes("●"));
|
||||
expect(app.frame().split("\n")[0]).toContain("Editor: README.md ● · d");
|
||||
const note = app.find("Editor: README.md");
|
||||
await app.click(note.x, note.y);
|
||||
expect(app.frame()).toContain("Details README.md ✕");
|
||||
});
|
||||
|
||||
test("on a narrow window the column, editor and all, takes the conversation's place", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "t3tui-edit-"));
|
||||
writeFileSync(join(root, "README.md"), "hello\n");
|
||||
const project = { ...v2ShellSnapshot.projects[0]!, workspaceRoot: root };
|
||||
const previous = { visual: process.env.VISUAL, editor: process.env.EDITOR };
|
||||
delete process.env.VISUAL;
|
||||
process.env.EDITOR = "sleep 3; true";
|
||||
try {
|
||||
const app = await open({ width: 100, session: fakeSession({ vcs, snapshot: { ...v2ShellSnapshot, projects: [project] }, projection: withReply("The reply under the column.", false) }) });
|
||||
await app.press("d");
|
||||
await app.press("l");
|
||||
await app.press("o");
|
||||
expect(app.find("Editing README.md").x).toBeLessThan(50);
|
||||
expect(app.frame()).not.toContain("The reply under");
|
||||
expect(app.frame()).toContain("Press i to type");
|
||||
// d hides the column, editor and all, and brings it back with the editor still running.
|
||||
await app.press("\\", { ctrl: true });
|
||||
await app.press("d");
|
||||
expect(app.frame()).toContain("The reply under");
|
||||
await app.press("d");
|
||||
expect(app.frame()).toContain("Editing README.md");
|
||||
} finally {
|
||||
restoreEditor(previous);
|
||||
}
|
||||
const { snapshot } = workspace();
|
||||
setEditor("sleep 3; true");
|
||||
const app = await open({ width: 100, session: fakeSession({ vcs, snapshot, projection: withReply("The reply under the column.", false) }) });
|
||||
await app.press("d");
|
||||
await app.press("l");
|
||||
await app.press("o");
|
||||
expect(app.find("README.md ✕").x).toBeLessThan(50);
|
||||
expect(app.frame()).not.toContain("The reply under");
|
||||
expect(app.frame()).toContain("Press i to type");
|
||||
// d hides the column, editor and all, and brings it back with the editor still running.
|
||||
await prefix(app, "k");
|
||||
await app.press("d");
|
||||
expect(app.frame()).toContain("The reply under");
|
||||
await app.press("d");
|
||||
expect(app.frame()).toContain("README.md ✕");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user