diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 7e594c4..e835aff 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -5,7 +5,7 @@ import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContex import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts"; import { existsSync, statSync } from "node:fs"; import { homedir } from "node:os"; -import { isAbsolute, relative } from "node:path"; +import { isAbsolute, join, relative } from "node:path"; import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -29,9 +29,12 @@ import { ComposerMenu } from "./ComposerMenu.tsx"; import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx"; import { DetailsPanel } from "./DetailsPanel.tsx"; import { DiffView, type DiffState } from "./DiffView.tsx"; +import { FilePreview } from "./FilePreview.tsx"; +import { FilesPanel } from "./FilesPanel.tsx"; import { DraftView } from "./DraftView.tsx"; import { useComposerMenu } from "./useComposerMenu.ts"; import { useDetails } from "./useDetails.ts"; +import { useFiles } from "./useFiles.ts"; import { useDraft } from "./useDraft.ts"; import { useModelPicker } from "./useModelPicker.ts"; import { useQuestion } from "./useQuestion.ts"; @@ -587,6 +590,25 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui useEffect(() => { if (mode === "details") panes.showColumnTab("details"); }, [mode]); + const files = useFiles({ + session, + live, + cwd: draft ? null : panel.cwd, + visible: panel.show && panes.columnKind === "files", + changes: panel.details?.changes?.files ?? [], + working, + ignoredListing: providerConfig?.environment.capabilities.ignoredFileListing === true, + open: (path) => openFile(path), + preview: (path) => panel.cwd && panes.openPreview(path, panel.cwd), + mention: (path, kind) => { + if (composerMenu.mention({ path, kind })) say(`Added @${path}${kind === "directory" ? "/" : ""}`); + else say("There's no message box to mention it in.", true); + }, + copy: (path) => copy(path, path), + leave: () => setMode("nav"), + say, + }); + const previewScrollRef = useRef(null); /** The composer's text in $EDITOR, in the composer's place; what's saved comes back when it exits. */ const openEditor = () => { @@ -639,6 +661,14 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui }); }; + /** A file from the Files tab: in $EDITOR when it's on this machine, else read-only in a preview tab. */ + const openFile = (path: string) => { + const cwd = panel.cwd; + if (!cwd) return; + if (existsSync(join(cwd, path))) editFile(path, cwd); + else panes.openPreview(path, cwd); + }; + /** 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. */ const openAt = (x: number, y: number) => { if (renderer.getSelection()?.getSelectedText()) return; @@ -909,6 +939,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui library.commands(threadId).map((command) => fromCommand(command)), workspace.commands.map((command) => fromCommand(command)), threadId && !draft && { keys: ["f"], run: openFind, command: { id: "find", title: "Find in thread", keywords: ["search", "messages", "plans"] } }, + threadId && !draft && { keys: ["F"], run: panes.showFiles, command: { id: "files", title: "Files: show", keywords: ["explorer", "tree", "browse", "project", "workspace"] } }, // Only P is a navigation key; the rest are the PR view's own (below). pullRequests.commands.filter((command) => command.id === "pull-requests").map((command) => fromCommand(command)), { keys: ["j", "↓"], label: "j/k", run: () => (attached ? scrollBy(1) : move(1)), hint: attached ? "scroll" : "threads" }, @@ -1007,6 +1038,16 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui { keys: ["G"], run: () => scrollToEnd(scrollRef.current) }, pullRequests.viewKeys, ); + const previewKeys = keys( + { keys: ["j", "↓"], label: "j/k", run: () => previewScrollRef.current?.scrollBy(1), hint: "scroll" }, + { keys: ["k", "↑"], run: () => previewScrollRef.current?.scrollBy(-1) }, + { keys: ["space", "pagedown"], run: () => previewScrollRef.current?.scrollBy(Math.max(1, height - 10)) }, + { keys: ["pageup"], run: () => previewScrollRef.current?.scrollBy(-Math.max(1, height - 10)) }, + { keys: ["g"], run: () => previewScrollRef.current?.scrollTo(0) }, + { keys: ["G"], run: () => scrollToEnd(previewScrollRef.current) }, + { keys: [], label: "ctrl+\\ x", run: () => panes.closeTab(panes.columnTab), hint: "close" }, + { keys: ["esc"], run: () => setMode("nav"), hint: "back" }, + ); const findKeys = keys( find.bindings, { keys: ["esc"], run: () => setMode("nav"), hint: "close find" }, @@ -1044,7 +1085,9 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui } // 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. + // Files and previews take their own keys; a terminal takes all but ctrl+\, and ctrl+j hides it again. + if (mode === "pane" && panes.focusedPane === "column" && panes.columnKind === "files") return { layers: [files.keys, globalKeys], hints: [...files.keys, prefixKey] }; + if (mode === "pane" && panes.focusedPane === "column" && panes.columnKind === "preview") return { layers: [previewKeys, globalKeys], hints: [...previewKeys, prefixKey] }; 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, [prefixKey, quitKey]], hints: secret.bindings }; @@ -1578,7 +1621,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui {panes.columnTabs.length > 1 ? ( ({ id: tab.id, label: tab.label, closable: tab.kind !== "details", shorten: (room: number) => (tab.kind === "editor" ? truncatePath(tab.label, room) : truncateNumbered(tab.label, room)) }))} + tabs={panes.columnTabs.map((tab) => ({ id: tab.id, label: tab.label, closable: tab.kind !== "details" && tab.kind !== "files", shorten: (room: number) => (tab.kind === "editor" || tab.kind === "preview" ? 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)} @@ -1590,6 +1633,31 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui ) : null} {panes.columnTab === "details" ? detailsPanel(columnFills) : null} + {panes.columnKind === "files" ? ( + { + panes.showFiles(); + files.click(path); + }} + onQuery={files.onQuery} + onSubmit={files.submit} + onClickResult={(index) => { + panes.showFiles(); + files.clickResult(index); + }} + /> + ) : null} + {panes.previews.filter((preview) => preview.id === panes.columnTab).map((preview) => ( + + ))} {panes.editors.map((editor) => ( }) { + const { session, threadId, cwd, path } = props; + const codeStyle = useCodeStyle(); + const markdownStyle = useMarkdownStyle(); + const [loaded, setLoaded] = useState(null); + const kind = previewKind(path); + useEffect(() => { + let cancelled = false; + const done = (next: Loaded) => !cancelled && setLoaded(next); + const failed = (error: unknown) => done({ kind: "error", message: error instanceof Error ? error.message : String(error) }); + const local = join(cwd, path); + const here = existsSync(local); + if (kind === "image") { + if (here) done({ kind: "image", bytes: readFileSync(local) }); + else if (threadId) session.fetchWorkspaceFile(threadId, local).then((response) => response.arrayBuffer()).then((buffer) => done({ kind: "image", bytes: new Uint8Array(buffer) }), failed); + else failed(new Error("No thread to fetch the image through.")); + } else { + session.readFile(cwd, path).then( + (file) => done({ kind: "text", text: file.contents, truncated: file.truncated, bytes: file.byteLength }), + (error: unknown) => { + if ((error as { failure?: string }).failure !== "binary_file") return failed(error); + if (here) return done({ kind: "binary", bytes: statSync(local).size }); + if (!threadId) return done({ kind: "binary", bytes: null }); + // Only the size, from the headers; the bytes aren't wanted. + session.fetchWorkspaceFile(threadId, local).then((response) => { + void response.body?.cancel(); + const length = Number(response.headers.get("content-length")); + done({ kind: "binary", bytes: Number.isFinite(length) && length > 0 ? length : null }); + }, () => done({ kind: "binary", bytes: null })); + }, + ); + } + return () => { + cancelled = true; + }; + }, [session, threadId, cwd, path, kind]); + + const inner = Math.max(10, props.width - 3); + return ( + + + {truncatePath(path, Math.max(8, inner - 10))} + + read-only + + + {!loaded ? ( + Loading… + ) : loaded.kind === "error" ? ( + {`Could not read the file: ${loaded.message}`} + ) : loaded.kind === "binary" ? ( + {loaded.bytes === null ? "Binary file" : `Binary file, ${sizeLabel(loaded.bytes)}`} + ) : loaded.kind === "image" ? ( + + ) : ( + + {loaded.truncated ? {`Showing the start of a ${sizeLabel(loaded.bytes)} file.`} : null} + {kind === "markdown" ? ( + + ) : ( + + )} + + )} + + + ); +} + +/** An image fitted to the column, in the terminal's best image protocol; a note if it can't be drawn. */ +function PreviewImage(props: { readonly bytes: Uint8Array; readonly width: number }) { + const image = useRef(null); + const [size, setSize] = useState({ width: props.width, height: IMAGE_ROWS }); + const [failed, setFailed] = useState(false); + if (failed) return {`Image, ${sizeLabel(props.bytes.length)}; it can't be drawn here.`}; + return ( + image.current && setSize(image.current.getFittedSize(props.width, IMAGE_ROWS))} + onError={() => setFailed(true)} + /> + ); +} diff --git a/src/ui/FilesPanel.tsx b/src/ui/FilesPanel.tsx new file mode 100644 index 0000000..fd4158d --- /dev/null +++ b/src/ui/FilesPanel.tsx @@ -0,0 +1,114 @@ +import type { MouseEvent } from "@opentui/core"; +import { useEffect, useState } from "react"; + +import { rootLabel, type FileRow } from "../model/files.ts"; +import { ClickRow, wheelStep } from "./Button.tsx"; +import { BAR } from "./edges.ts"; +import { truncate, truncatePath } from "./text.ts"; +import { colors } from "./theme.ts"; +import type { FileSearch } from "./useFiles.ts"; + +/** + * The Files tab: the root on top, then the tree, or the `/` search's results in its place. + * Folders open with ▸/▾; git's M and ? sit on the right, a faint • on folders with changes + * inside, and what git ignores is faint. + */ +export function FilesPanel(props: { + readonly root: string | null; + readonly rows: readonly FileRow[]; + readonly selected: string | null; + readonly search: FileSearch | null; + readonly width: number; + readonly focused: boolean; + readonly loading: boolean; + readonly error: string | null; + readonly onClick: (path: string) => void; + readonly onQuery: (value: string) => void; + readonly onSubmit: () => void; + readonly onClickResult: (index: number) => void; +}) { + const { rows, search, focused } = props; + const [height, setHeight] = useState(0); + const [top, setTop] = useState(0); + const count = search ? (search.results?.length ?? 0) : rows.length; + const at = search ? search.selected : Math.max(0, rows.findIndex((row) => row.kind !== "loading" && row.path === props.selected)); + // The selection stays in view; the wheel scrolls past it until it moves again. + useEffect(() => { + setTop((current) => (at < current ? at : height > 0 && at >= current + height ? at - height + 1 : current)); + }, [at, height]); + const start = Math.max(0, Math.min(top, count - height)); + // The selection bar and a column of padding either side of the text. + const inner = Math.max(8, props.width - 3); + const selectedBg = focused ? colors.selectedBg : colors.element; + return ( + + {props.root ? rootLabel(props.root, inner) : "No workspace"} + {search?.editing ? ( + + + + ) : search ? ( + {` /${search.query}`} + ) : null} + { + const step = wheelStep(event); + if (step) setTop(Math.max(0, Math.min(count - height, start + step * 3))); + }} + > + {search ? ( + search.results === null ? ( + Searching… + ) : search.results.length === 0 ? ( + {search.query.trim() ? "No matching files or folders." : "Type to search the workspace."} + ) : ( + search.results.slice(start, start + height).map((entry, offset) => { + const index = start + offset; + const active = index === search.selected; + const label = `${entry.path}${entry.kind === "directory" ? "/" : ""}`; + return ( + props.onClickResult(index)}> + {active ? "▌" : " "} + {truncatePath(label, inner)} + + ); + }) + ) + ) : props.error ? ( + {`Could not list the folder: ${props.error}`} + ) : props.loading ? ( + Loading… + ) : rows.length === 0 ? ( + No files. + ) : ( + rows.slice(start, start + height).map((row) => ) + )} + + + ); +} + +function Row(props: { readonly row: FileRow; readonly inner: number; readonly selected: boolean; readonly selectedBg: string; readonly onClick: (path: string) => void }) { + const { row, inner, selected } = props; + const indent = " ".repeat(row.depth); + if (row.kind === "loading") return {` ${indent} …`}; + const glyph = row.kind === "directory" ? (row.expanded ? "▾ " : "▸ ") : " "; + const mark = row.marker ?? (row.changedInside ? "•" : ""); + const name = truncate(row.name, Math.max(4, inner - indent.length - glyph.length - (mark ? mark.length + 1 : 0))); + return ( + props.onClick(row.path)}> + {selected ? "▌" : " "} + {`${indent}${glyph}`} + {name} + + {mark ? {mark} : null} + + ); +} diff --git a/src/ui/theme.ts b/src/ui/theme.ts index 88fbd38..88246f4 100644 --- a/src/ui/theme.ts +++ b/src/ui/theme.ts @@ -83,6 +83,7 @@ export const colors: Palette = { ...DARK }; export function applyTheme(theme: ThemeMode | Palette): void { Object.assign(colors, theme === "light" ? LIGHT : theme === "dark" ? DARK : theme); markdownStyles = new WeakMap(); + codeStyles = new WeakMap(); } /** Dark or light, by the background's luminance; null if the terminal didn't say. */ @@ -192,3 +193,30 @@ export function useMarkdownStyle(): SyntaxStyle { markdownStyles.set(owner, style); return style; } + +let codeStyles = new WeakMap(); + +/** Source files in the preview tab: the palette's few hues on the tree-sitter scopes that matter. */ +export function useCodeStyle(): SyntaxStyle { + const owner = useRenderer().nativeScene; + let style = codeStyles.get(owner); + if (style) return style; + style = SyntaxStyle.fromStyles({ + default: { fg: colors.text }, + keyword: { fg: colors.input }, + string: { fg: colors.good }, + comment: { fg: colors.faint, italic: true }, + number: { fg: colors.plan }, + boolean: { fg: colors.plan }, + constant: { fg: colors.plan }, + function: { fg: colors.accent }, + type: { fg: colors.info }, + constructor: { fg: colors.info }, + operator: { fg: colors.muted }, + punctuation: { fg: colors.muted }, + "markup.heading": { fg: colors.text, bold: true }, + "markup.raw": { fg: colors.plan }, + }, owner); + codeStyles.set(owner, style); + return style; +} diff --git a/src/ui/useComposerChips.ts b/src/ui/useComposerChips.ts index 5b694e9..a2ee57d 100644 --- a/src/ui/useComposerChips.ts +++ b/src/ui/useComposerChips.ts @@ -20,7 +20,7 @@ export function markChip(composer: TextareaRenderable, start: number, end: numbe } /** Inserts `label` at the cursor as a chip, apart from the words either side. */ -function insertChip(composer: TextareaRenderable, label: string, data: ChipData): void { +export function insertChip(composer: TextareaRenderable, label: string, data: ChipData): void { const before = composer.plainText[indexAtOffset(composer.plainText, composer.cursorOffset) - 1]; if (before && !/\s/.test(before)) composer.insertText(" "); const start = composer.cursorOffset; diff --git a/src/ui/useComposerMenu.ts b/src/ui/useComposerMenu.ts index 8105f10..364142a 100644 --- a/src/ui/useComposerMenu.ts +++ b/src/ui/useComposerMenu.ts @@ -5,7 +5,7 @@ import { useEffect, useRef, useState, type RefObject } from "react"; import type { T3Session } from "../client/session.ts"; import { composerItemEnd, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts"; import { keys, type Binding } from "../model/keymap.ts"; -import { markChip } from "./useComposerChips.ts"; +import { insertChip, markChip } from "./useComposerChips.ts"; import { useComposerPullRequests } from "./usePullRequests.ts"; /** @@ -117,6 +117,15 @@ export function useComposerMenu(deps: { deps.onChosen(item); }; + /** A file or folder mentioned from outside the menu (the Files tab): its chip at the cursor, as choosing it here puts it. */ + const mention = (entry: ProjectEntry): boolean => { + const composer = composerRef.current; + const [item] = pathItems([entry]); + if (!composer || !item?.chip) return false; + insertChip(composer, item.chip, { sent: (item.replacement ?? "").trimEnd() }); + sync(); + return true; + }; /** The mentions still in this text, as the message's context. */ const context = (text: string): OrchestrationMessageContext | undefined => messageContext(text, mentions.current.get(composerKey) ?? new Map()); /** The message went: its mentions go with it. */ @@ -143,5 +152,5 @@ export function useComposerMenu(deps: { ) : []; - return { menu, selected, sync, pick: (at: number) => menu && choose(menu.items[at]), context, forget, remember, bindings }; + return { menu, selected, sync, mention, pick: (at: number) => menu && choose(menu.items[at]), context, forget, remember, bindings }; } diff --git a/src/ui/useFiles.ts b/src/ui/useFiles.ts new file mode 100644 index 0000000..cb5726f --- /dev/null +++ b/src/ui/useFiles.ts @@ -0,0 +1,284 @@ +import type { ProjectEntry } from "@t3tools/contracts"; +import { useEffect, useMemo, useRef, useState } from "react"; + +import type { T3Session } from "../client/session.ts"; +import type { ChangedFile } from "../model/details.ts"; +import { fileRows, parentOf } from "../model/files.ts"; +import { keys } from "../model/keymap.ts"; + +/** As many results as the web's file search shows. */ +const SEARCH_LIMIT = 200; +/** Re-lists after a burst of changes settle. */ +const REFRESH_DELAY_MS = 300; + +/** A workspace's tree as this run has seen it: the folders listed, which are open, and the selection. */ +interface Workspace { + readonly directories: ReadonlyMap; + readonly expanded: ReadonlySet; + readonly ignored: ReadonlySet; + readonly selected: string | null; +} +const EMPTY: Workspace = { directories: new Map(), expanded: new Set(), ignored: new Set(), selected: null }; + +export interface FileSearch { + readonly query: string; + /** The query line has the keys. */ + readonly editing: boolean; + /** null while the search runs. */ + readonly results: readonly ProjectEntry[] | null; + readonly selected: number; +} + +/** + * The Files tab: the workspace's folders listed lazily as they open, with git's marks and + * ignored entries, a `/` search over the workspace, and the keys that open, preview, mention + * and copy what's selected. Each workspace keeps its tree for the run. + */ +export function useFiles(deps: { + readonly session: T3Session; + readonly live: boolean; + /** The thread's worktree, else its project's root. */ + readonly cwd: string | null; + /** The tab is on screen: the root lists the first time it is. */ + readonly visible: boolean; + /** The working tree's changes, as the Changes list has them. */ + readonly changes: readonly ChangedFile[]; + /** A turn runs; one finishing re-lists the open folders. */ + readonly working: boolean; + /** The server answers listIgnoredFiles. */ + readonly ignoredListing: boolean; + readonly open: (path: string) => void; + readonly preview: (path: string) => void; + readonly mention: (path: string, kind: ProjectEntry["kind"]) => void; + readonly copy: (path: string) => void; + /** Gives the keys back. */ + readonly leave: () => void; + readonly say: (text: string, bad?: boolean) => void; +}) { + const { session, cwd, visible, live, say } = deps; + const [workspaces, setWorkspaces] = useState>(new Map()); + /** Folders being listed, as `cwd\0path`. */ + const [loading, setLoading] = useState>(new Set()); + const [rootError, setRootError] = useState<{ readonly cwd: string; readonly message: string } | null>(null); + const [search, setSearch] = useState(null); + const workspace = (cwd ? workspaces.get(cwd) : undefined) ?? EMPTY; + const update = (at: string, change: (previous: Workspace) => Workspace) => setWorkspaces((previous) => new Map(previous).set(at, change(previous.get(at) ?? EMPTY))); + const inFlight = useRef(new Set()); + + const list = (at: string, path: string) => { + const key = `${at}\0${path}`; + if (inFlight.current.has(key)) return; + inFlight.current.add(key); + setLoading((previous) => new Set(previous).add(key)); + session.listEntries(at, path).then( + (entries) => { + // A folder's listing can include deeper paths; this one shows its own children. + update(at, (previous) => ({ ...previous, directories: new Map(previous.directories).set(path, entries.filter((entry) => parentOf(entry.path) === path)) })); + if (path === "") setRootError(null); + }, + (error) => (path === "" ? setRootError({ cwd: at, message: messageOf(error) }) : say(`Could not list ${path}: ${messageOf(error)}`, true)), + ).finally(() => { + inFlight.current.delete(key); + setLoading((previous) => { + const next = new Set(previous); + next.delete(key); + return next; + }); + }); + }; + const listIgnored = (at: string) => { + if (!deps.ignoredListing) return; + session.listIgnoredFiles(at).then( + (files) => update(at, (previous) => ({ ...previous, ignored: new Set(files.map((file) => file.path)) })), + () => {}, + ); + }; + /** Lists again the root and every open folder that's listed, and what git ignores. */ + const refresh = () => { + if (!cwd) return; + for (const path of ["", ...workspace.expanded]) if (path === "" || workspace.directories.has(path)) list(cwd, path); + listIgnored(cwd); + if (search?.query.trim()) runSearch(search.query); + }; + + // The root lists the first time the tab shows for a workspace; after that, showing it re-lists. + const listed = cwd !== null && workspace.directories.has(""); + useEffect(() => { + if (!visible || !cwd || !live) return; + if (!listed) { + list(cwd, ""); + listIgnored(cwd); + } else refresh(); + // eslint-disable-next-line react-hooks/exhaustive-deps -- runs as the tab shows, or the workspace changes. + }, [visible, cwd, live]); + // A turn finishing, or git's changes moving, re-lists the open folders while the tab shows. + const changesKey = deps.changes.map((file) => `${file.status}${file.path}`).join("\n"); + const settled = useRef({ changesKey, working: deps.working }); + useEffect(() => { + const previous = settled.current; + settled.current = { changesKey, working: deps.working }; + if (!visible || !listed || (previous.changesKey === changesKey && !(previous.working && !deps.working))) return; + const timer = setTimeout(refresh, REFRESH_DELAY_MS); + return () => clearTimeout(timer); + // eslint-disable-next-line react-hooks/exhaustive-deps -- runs when the changes or the turn do. + }, [changesKey, deps.working]); + + const rows = useMemo( + () => + fileRows({ + directories: workspace.directories, + expanded: workspace.expanded, + loading: new Set([...loading].flatMap((key) => (cwd && key.startsWith(`${cwd}\0`) ? [key.slice(cwd.length + 1)] : []))), + ignored: workspace.ignored, + changes: deps.changes, + }), + [workspace, loading, cwd, deps.changes], + ); + const entries = rows.filter((row) => row.kind !== "loading"); + const selectedIndex = Math.max(0, entries.findIndex((row) => row.path === workspace.selected)); + const selected = entries[selectedIndex]; + + const select = (path: string) => cwd && update(cwd, (previous) => ({ ...previous, selected: path })); + const setExpanded = (path: string, open: boolean) => { + if (!cwd) return; + update(cwd, (previous) => { + const expanded = new Set(previous.expanded); + if (open) expanded.add(path); + else expanded.delete(path); + return { ...previous, expanded }; + }); + if (open && !workspace.directories.has(path)) list(cwd, path); + }; + const move = (delta: number) => { + const next = entries[Math.max(0, Math.min(entries.length - 1, selectedIndex + delta))]; + if (next) select(next.path); + }; + /** l: opens a folder, or steps into one already open; opens a file. */ + const forward = () => { + if (!selected) return; + if (selected.kind === "file") return deps.open(selected.path); + if (!selected.expanded) return setExpanded(selected.path, true); + const child = entries[selectedIndex + 1]; + if (child && parentOf(child.path) === selected.path) select(child.path); + }; + /** h: closes a folder, or goes to the folder it's in. */ + const back = () => { + if (!selected) return; + if (selected.kind === "directory" && selected.expanded) return setExpanded(selected.path, false); + const parent = parentOf(selected.path); + if (parent) select(parent); + }; + /** A click: selects, opens or closes a folder, and opens a file already selected. */ + const click = (path: string) => { + const row = entries.find((candidate) => candidate.path === path); + if (!row) return; + const wasSelected = selected?.path === path; + select(path); + if (row.kind === "directory") setExpanded(path, !row.expanded); + else if (wasSelected) deps.open(path); + }; + + // Search: debounced as the composer's @ search is. + const runSearch = (query: string) => { + const at = cwd; + if (!at) return; + session.searchEntries(at, query.trim(), SEARCH_LIMIT).then( + (results) => setSearch((previous) => (previous?.query === query ? { ...previous, results: results.filter((entry) => !entry.path.split("/").includes(".git")) } : previous)), + (error) => { + setSearch((previous) => (previous?.query === query ? { ...previous, results: [] } : previous)); + say(`Search failed: ${messageOf(error)}`, true); + }, + ); + }; + useEffect(() => setSearch(null), [cwd]); + const query = search?.query ?? ""; + useEffect(() => { + if (!query.trim()) return; + const timer = setTimeout(() => runSearch(query), 120); + return () => clearTimeout(timer); + // eslint-disable-next-line react-hooks/exhaustive-deps -- runs as the query changes. + }, [query, cwd]); + const onQuery = (value: string) => setSearch((previous) => ({ query: value, editing: previous?.editing ?? true, results: value.trim() ? null : [], selected: 0 })); + const results = search?.results ?? []; + const result = results[Math.min(search?.selected ?? 0, results.length - 1)]; + const moveResult = (delta: number) => setSearch((previous) => previous && { ...previous, selected: Math.max(0, Math.min(results.length - 1, previous.selected + delta)) }); + const clearSearch = () => setSearch(null); + /** A folder found by search shows in the tree, open, its parents open above it. */ + const reveal = (path: string) => { + if (!cwd) return; + const parts = path.split("/"); + const folders = parts.map((_, index) => parts.slice(0, index + 1).join("/")); + update(cwd, (previous) => ({ ...previous, expanded: new Set([...previous.expanded, ...folders]), selected: path })); + for (const folder of folders) if (!workspace.directories.has(folder)) list(cwd, folder); + clearSearch(); + }; + const openResult = (entry: ProjectEntry | undefined) => { + if (!entry) return; + if (entry.kind === "directory") return reveal(entry.path); + setSearch((previous) => previous && { ...previous, editing: false }); + deps.open(entry.path); + }; + + const target = search ? result : selected; + const mention = () => target && deps.mention(target.path, target.kind); + const copy = () => target && deps.copy(target.path); + const preview = () => target?.kind === "file" && deps.preview(target.path); + const startSearch = () => setSearch((previous) => ({ query: previous?.query ?? "", editing: true, results: previous?.results ?? [], selected: previous?.selected ?? 0 })); + + /** While the query line has the keys: what it doesn't type. */ + const searchKeys = keys( + { keys: ["↓", "ctrl+n"], label: "↑/↓", run: () => moveResult(1), hint: "move" }, + { keys: ["↑", "ctrl+p"], run: () => moveResult(-1) }, + // The query line's own submit opens it. + { keys: [], label: "enter", hint: "open" }, + { keys: ["tab"], run: () => setSearch((previous) => previous && { ...previous, editing: false }), hint: "results" }, + { keys: ["esc"], run: clearSearch, hint: "clear" }, + ); + /** While the results have the keys. */ + const resultKeys = keys( + { keys: ["j", "↓"], label: "j/k", run: () => moveResult(1), hint: "move" }, + { keys: ["k", "↑"], run: () => moveResult(-1) }, + { keys: ["enter", "l", "→"], run: () => openResult(result), hint: "open" }, + { keys: ["m"], run: mention, hint: "mention" }, + { keys: ["y"], run: copy, hint: "copy path" }, + { keys: ["p"], run: preview, hint: "preview" }, + { keys: ["/"], run: startSearch, hint: "search" }, + { keys: ["g"], run: () => moveResult(-results.length) }, + { keys: ["G"], run: () => moveResult(results.length) }, + { keys: ["esc"], run: clearSearch, hint: "clear" }, + ); + const treeKeys = keys( + { keys: ["j", "↓"], label: "j/k", run: () => move(1), hint: "move" }, + { keys: ["k", "↑"], run: () => move(-1) }, + { keys: ["l", "enter", "→"], run: forward, hint: "open" }, + { keys: ["h", "←"], run: back }, + { keys: ["/"], run: startSearch, hint: "search" }, + { keys: ["m"], run: mention, hint: "mention" }, + { keys: ["y"], run: copy, hint: "copy path" }, + { keys: ["p"], run: preview, hint: "preview" }, + { keys: ["r"], run: refresh, hint: "refresh" }, + { keys: ["g"], run: () => move(-entries.length) }, + { keys: ["G"], run: () => move(entries.length) }, + { keys: ["esc"], run: deps.leave, hint: "back" }, + ); + + return { + rows, + selected: selected?.path ?? null, + search, + loadingRoot: !listed && cwd !== null && (loading.has(`${cwd}\0`) || !rootError), + error: rootError?.cwd === cwd ? rootError.message : null, + click, + onQuery, + /** Enter in the query line: opens the highlighted result. */ + submit: () => openResult(result), + /** A click on a search result: selects it, or opens it once selected. */ + clickResult: (index: number) => { + if (index === search?.selected && !search.editing) return openResult(results[index]); + setSearch((previous) => previous && { ...previous, editing: false, selected: index }); + }, + keys: search?.editing ? searchKeys : search ? resultKeys : treeKeys, + }; +} + +const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error)); diff --git a/src/ui/usePanes.ts b/src/ui/usePanes.ts index 0737e98..acc758f 100644 --- a/src/ui/usePanes.ts +++ b/src/ui/usePanes.ts @@ -14,6 +14,7 @@ const PANE_ORDER: readonly PaneFocus[] = ["message", "drawer", "column"]; /** How long ctrl+\ waits for the key after it. */ const PREFIX_MS = 2000; const DETAILS = "details"; +const FILES = "files"; /** The column's tab for the shown terminal, in side placement. */ const TERMINAL = "terminal"; type LocalProgram = Extract; @@ -27,16 +28,22 @@ export interface EditorProgram { export interface EditorTab extends EditorProgram { readonly path: string; } +/** A workspace file shown read-only in a tab of the column: its path relative to `cwd`. */ +export interface PreviewTab { + readonly id: string; + readonly path: string; + readonly cwd: string; +} export interface ColumnTab { readonly id: string; readonly label: string; - readonly kind: "details" | "editor" | "terminal"; + readonly kind: "details" | "files" | "editor" | "preview" | "terminal"; } /** * 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 + * tabs of the right-hand column), the Files tab, files in $EDITOR or previewed 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: { @@ -67,6 +74,7 @@ export function usePanes(deps: { /** Terminals this run has shown, which the strip under the message box names while the drawer is hidden. */ const [seen, setSeen] = useState>(new Set()); const [editors, setEditors] = useState([]); + const [previews, setPreviews] = useState([]); const [message, setMessage] = useState(null); const [tab, setTab] = useState(DETAILS); const [target, setTarget] = useState("drawer"); @@ -93,19 +101,22 @@ export function usePanes(deps: { const terminalTabId = (terminalId: string) => `${TERMINAL}:${terminalId}`; const columnTabs: ColumnTab[] = [ { id: DETAILS, label: "Details", kind: "details" }, + { id: FILES, label: "Files", kind: "files" }, ...editors.map((editor): ColumnTab => ({ id: editor.program.id, label: editor.path, kind: "editor" })), + ...previews.map((preview): ColumnTab => ({ id: preview.id, label: preview.path, kind: "preview" })), ...(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 columnTab = tab === TERMINAL && side && terminal ? terminalTabId(terminal.terminalId) : tab === FILES || editors.some((editor) => editor.program.id === tab) || previews.some((preview) => preview.id === tab) ? tab : DETAILS; const activeColumnTab = columnTabs.find((candidate) => candidate.id === columnTab)!; - const programTabs = columnTabs.filter((candidate) => candidate.kind !== "details"); + /** The tabs that hold something of their own: programs and previews. */ + const programTabs = columnTabs.filter((candidate) => candidate.kind !== "details" && candidate.kind !== "files"); const shown: Record = { 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 = { ...shown, column: programTabs.length > 0 }; + /** What focus can move to: open panes, and the column while it shows Files or holds a program, even hidden. */ + const open: Record = { ...shown, column: shown.column || programTabs.length > 0 }; const available = PANE_ORDER.filter((pane) => open[pane]); const focusedPane = focused && shown[target] ? target : null; const zoomShown = zoomed !== null && (zoomed === "column" ? column : shown[zoomed]); @@ -130,12 +141,12 @@ export function usePanes(deps: { }; }, [column, sockets]); - /** Gives a pane the keys; the column on `tab`, or the program tab it showed last. */ + /** Gives a pane the keys; the column on `tab`, or the tab it showed last, or Files. */ 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); + const next = columnTabs.find((candidate) => candidate.id === lastProgramTab.current || (lastProgramTab.current === TERMINAL && candidate.kind === "terminal")) ?? programTabs[0]; + showColumnTab(next?.id ?? FILES); } else if (pane === "column") showColumnTab(columnTab); setTarget(pane); deps.focus(true); @@ -177,7 +188,7 @@ export function usePanes(deps: { const hideTerminal = () => { if (!threadId || !drawer) return; setDrawer(threadId, { ...drawer, open: false }); - if (side) tabGone(editors.length > 0); + if (side) tabGone(editors.length + previews.length > 0); }; 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. */ @@ -201,7 +212,7 @@ export function usePanes(deps: { rest.delete(gone.threadId); return rest; }); - if (side && gone.threadId === threadId) tabGone(editors.length > 0); + if (side && gone.threadId === threadId) tabGone(editors.length + previews.length > 0); } if (note) say(note); }; @@ -222,9 +233,20 @@ export function usePanes(deps: { }; const editorClosed = (id: string, note?: string) => { setEditors((previous) => previous.filter((editor) => editor.program.id !== id)); - tabGone(editors.length > 1 || (side && terminal !== null)); + tabGone(editors.length > 1 || previews.length > 0 || (side && terminal !== null)); if (note) say(note); }; + /** A file read-only in a tab of its own in the column, with the keys. */ + const openPreview = (path: string, cwd: string) => { + const id = `preview:${cwd}:${path}`; + setPreviews((previous) => (previous.some((preview) => preview.id === id) ? previous : [...previous, { id, path, cwd }])); + enter("column", id); + }; + /** A preview closes back to Files, which it was opened from. */ + const closePreview = (id: string) => { + setPreviews((previous) => previous.filter((preview) => preview.id !== id)); + if (columnTab === id) setTab(FILES); + }; /** The message in $EDITOR, in the composer's place. */ const openMessage = (next: EditorProgram) => { setMessage(next); @@ -243,10 +265,12 @@ export function usePanes(deps: { 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"); + if (editor) return quitEditor(editor, basename(editor.path), "column"); + if (previews.some((preview) => preview.id === id)) closePreview(id); }; const closeFocused = () => { if (focusedPane === "drawer" && terminal) return closeTab(terminal.terminalId); + if (focusedPane === "column" && columnTab === FILES) return say("Files stays; d hides the column.", true); 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); @@ -270,7 +294,7 @@ export function usePanes(deps: { 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)); + const focusColumn = () => enter("column"); /** 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); @@ -315,7 +339,7 @@ export function usePanes(deps: { { 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; + const focusedName = focusedPane === "message" ? "message" : focusedPane === "drawer" ? terminal?.label : focusedPane === "column" ? (activeColumnTab.kind === "editor" || activeColumnTab.kind === "preview" ? basename(activeColumnTab.label) : activeColumnTab.label) : undefined; /** The hint bar while a pane has the keys. */ const focusedKeys: Binding[] = focusedName ? [ @@ -337,10 +361,13 @@ export function usePanes(deps: { /** Terminals this run showed that still run, while the terminal is hidden. */ running: terminal ? [] : tabs.filter((candidate) => seen.has(key(candidate))), editors, + previews, modified, message, columnTabs, columnTab, + /** What the column's shown tab is. */ + columnKind: activeColumnTab.kind, showColumnTab, focusedPane, /** Whether a terminal has the keys, in the drawer or the column. */ @@ -358,6 +385,9 @@ export function usePanes(deps: { openEditor, editorOpened, editorClosed, + openPreview, + /** Shows Files and gives it the keys. */ + showFiles: () => enter("column", FILES), openMessage, messageClosed: () => setMessage(null), keys: { prefix: prefixKey, afterPrefix: prefixKeys, focused: focusedKeys, commands }, diff --git a/test/app/links.test.tsx b/test/app/links.test.tsx index 39643c9..d0165bd 100644 --- a/test/app/links.test.tsx +++ b/test/app/links.test.tsx @@ -70,10 +70,10 @@ 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("Details "); + expect(app.frame()).not.toContain("missing.ts ✕"); const path = app.find("a.ts:3"); await app.click(path.x, path.y); - expect(app.frame()).toContain("Details src/a.ts ✕"); + expect(app.frame()).toContain("Details Files src/a.ts ✕"); expect(app.hints()).toStartWith("keys: a.ts"); }); diff --git a/test/app/pane.test.tsx b/test/app/pane.test.tsx index cb2e538..f221342 100644 --- a/test/app/pane.test.tsx +++ b/test/app/pane.test.tsx @@ -300,18 +300,18 @@ describe("terminal drawer", () => { }); 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() }); + const app = await open({ width: 200, layout: { ...DEFAULT_LAYOUT, detailsWidth: 54 }, 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 1 ✕ Terminal 2 + new"); + expect(app.frame()).toContain("Details Files 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.find("Details Files Terminal 1").x).toBeGreaterThan(200 - 54 - 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. + // The prefix's 1…9 count the column's tabs (Details, Files, then the rest); Details gives the keys back. await prefix(app, "1"); expect(app.frame()).not.toContain("user@host"); expect(app.frame()).toContain("/workspace/project"); @@ -319,7 +319,7 @@ describe("terminal drawer", () => { await prefix(app, "l"); expect(app.frame()).toContain("user@host"); expect(app.hints()).toBe(keysOn("Terminal 1")); - await prefix(app, "3"); + await prefix(app, "4"); expect(attached(app).at(-1)).toBe("term-2"); expect(app.hints()).toBe(keysOn("Terminal 2")); await app.press("j", { ctrl: true }); @@ -453,17 +453,17 @@ describe("editing a changed file", () => { 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.frame()).toContain("Details Files README.md ✕"); + expect(app.find("Details Files 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); + const tab = app.find("Details Files README.md"); + await app.click(tab.x + "Details Files ".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"); + await waitFor(() => !app.frame().includes("Details Files README.md")); + expect(app.frame()).not.toContain("Details Files README.md"); expect(app.frame()).toContain("Changes"); }); @@ -473,27 +473,27 @@ describe("editing a changed file", () => { 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); + expect(app.frame()).toContain("Details Files …DME.md …ne.tsx ✕"); + await app.mockMouse.drag(200 - 39, 10, 200 - 68, 10); await app.settle(100); - expect(app.frame()).toContain("Details README.md src/ui/deep/TerminalPane.tsx ✕"); + expect(app.frame()).toContain("Details Files 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"); + await prefix(app, "3"); 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 ✕"); + expect(app.frame()).toContain("Details Files 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 }) }); + const app = await open({ width: 200, layout: { ...DEFAULT_LAYOUT, detailsWidth: 46 }, 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()).toContain("Details Files src/…/TerminalPane.tsx ✕"); expect(app.frame()).not.toContain("README.md ✕"); expect(app.hints()).toBe(keysOn("TerminalPane.tsx")); const [listen, remote] = log(); @@ -517,7 +517,7 @@ describe("editing a changed file", () => { 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 ✕"); + expect(app.frame()).toContain("Details Files README.md ✕"); }); test("on a narrow window the column, editor and all, takes the conversation's place", async () => {