opencode-change-history 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,177 @@
1
+ import { createMemo, createSignal, For, Show } from "solid-js"
2
+ import { sumStatistics } from "../core/history"
3
+ import type { History, Statistics } from "../core/types"
4
+ import { externalID, fileTree, sortFiles, visibleTree, type Folder, type Row } from "./file-tree"
5
+ import {
6
+ Counts, countColumns, countsWidth, createHover, HistoryStatus, hoverBackground, hoverColor, inline, leftClick, pathTail,
7
+ plural, Totals, useHistory,
8
+ type Context, type CountColumns, type HistoryProps,
9
+ } from "./presentation"
10
+
11
+ const countFormat = { hideZero: true, showUnknown: true }
12
+
13
+ function Ratio(props: { context: Context; history: History; width: number }) {
14
+ const theme = () => props.context.theme
15
+ // Include submitted-write estimates so the ratio follows the displayed counts.
16
+ const added = () => props.history.additions + props.history.estimatedAdditions
17
+ const known = () => added() + props.history.deletions
18
+ const addedCells = () => {
19
+ const additions = added()
20
+ const { deletions } = props.history
21
+ if (!additions) return 0
22
+ if (!deletions) return props.width
23
+ const rounded = Math.round(props.width * additions / known())
24
+ return props.width < 2 ? rounded : Math.max(1, Math.min(props.width - 1, rounded))
25
+ }
26
+ return (
27
+ <text height={1} wrapMode="none" selectable={false} fg={theme().border.base}>
28
+ <Show when={known()} fallback={"─".repeat(props.width)}>
29
+ <span style={{ fg: theme().diff.highlight.added }}>{"━".repeat(addedCells())}</span>
30
+ <span style={{ fg: theme().diff.highlight.removed }}>{"━".repeat(props.width - addedCells())}</span>
31
+ </Show>
32
+ </text>
33
+ )
34
+ }
35
+
36
+ function treeLabel(row: Row, collapsed: boolean, width: number) {
37
+ const path = row.kind === "folder" && !row.name.endsWith("/") ? `${row.name}/` : row.name
38
+ const name = inline(row.id === externalID ? "Other files" : path)
39
+ const marker = row.kind === "folder" && width > 0 ? `${collapsed ? "›" : "⌄"}${width > 2 ? " " : ""}` : ""
40
+ const budget = width - Bun.stringWidth(marker)
41
+ const branches: string[] = []
42
+ for (let item = row; item.parent; item = item.parent) {
43
+ branches.push(item === row ? (item.last ? "└─ " : "├─ ") : (item.last ? " " : "│ "))
44
+ }
45
+ // Prefer room for the name over indentation when the terminal is narrow.
46
+ const indent = budget - Math.min(Bun.stringWidth(name), Math.ceil(budget / 2))
47
+ const prefix = branches.slice(0, Math.floor(indent / 3)).reverse().join("")
48
+ return { prefix, marker, name: pathTail(name, budget - Bun.stringWidth(prefix)) }
49
+ }
50
+
51
+ function SidebarRow(props: {
52
+ context: Context
53
+ row: Row
54
+ stats?: Statistics
55
+ columns: CountColumns
56
+ width: number
57
+ collapsed: boolean
58
+ activate: () => void
59
+ }) {
60
+ const theme = () => props.context.theme
61
+ const [hover, setHover] = createSignal(false)
62
+ const countWidth = () => props.stats ? countsWidth(props.columns) : 0
63
+ const stacked = () => countWidth() > 0 && props.width <= countWidth()
64
+ const label = createMemo(() => {
65
+ const available = props.width - countWidth()
66
+ const width = stacked() ? props.width : available - Number(countWidth() > 0 && available > 1)
67
+ return treeLabel(props.row, props.collapsed, width)
68
+ })
69
+ return (
70
+ <box flexDirection={stacked() ? "column" : "row"} justifyContent="space-between" flexShrink={0}
71
+ height={stacked() ? 2 : 1} overflow="hidden"
72
+ backgroundColor={hover() ? hoverBackground(theme()) : undefined}
73
+ onMouseOver={() => setHover(true)} onMouseOut={() => setHover(false)} onMouseUp={leftClick(props.activate)}>
74
+ <text height={1} flexShrink={1} minWidth={0} wrapMode="none" selectable={false}
75
+ fg={props.row.kind === "file" ? theme().text.base : theme().text.muted}>
76
+ <span style={{ fg: theme().border.base }}>{label().prefix}</span>{label().marker}{label().name}
77
+ </text>
78
+ <Show when={countWidth() ? props.stats : undefined}>
79
+ {(stats) => <Counts context={props.context} stats={stats()} columns={props.columns} format={countFormat} />}
80
+ </Show>
81
+ </box>
82
+ )
83
+ }
84
+
85
+ export function ChangesSidebar(props: HistoryProps & { open: (path?: string) => void }) {
86
+ const theme = () => props.context.theme
87
+ const header = createHover()
88
+ const details = createHover()
89
+ const ready = useHistory(() => props.state)
90
+ const history = () => ready()?.history
91
+ const [width, setWidth] = createSignal(0)
92
+ const [collapsed, setCollapsed] = createSignal(new Set<string>())
93
+ const hierarchy = createMemo(() => {
94
+ const value = ready()
95
+ const directory = value?.directory ?? ""
96
+ return fileTree(sortFiles(value?.history.files ?? [], "Path", directory), directory, { foldersFirst: true })
97
+ })
98
+ const statistics = createMemo(() => {
99
+ const stats = new Map<string, Statistics>()
100
+ function collect(row: Row): Statistics {
101
+ const total = row.kind === "file" ? row.file : sumStatistics(Array.from(row.children.values(), collect))
102
+ stats.set(row.id, total)
103
+ return total
104
+ }
105
+ for (const row of hierarchy().roots.values()) collect(row)
106
+ return stats
107
+ })
108
+ // Size both columns before blanking known zeroes, even in a one-sided session.
109
+ const columns = createMemo(() => countColumns(statistics().values(), { showUnknown: true }))
110
+ const isCollapsed = (folder: Folder) => folder.chain.some((id) => collapsed().has(id))
111
+ const rows = createMemo(() => visibleTree(hierarchy().roots, isCollapsed))
112
+ const entries = createMemo(() => new Map(rows().map((row) => [row.id, row])))
113
+ const ids = createMemo(() => [...entries().keys()])
114
+
115
+ function toggle(folder: Folder) {
116
+ const next = new Set(collapsed())
117
+ // Use the full compacted path; if a refresh splits the chain, leave new siblings visible.
118
+ if (isCollapsed(folder)) {
119
+ for (const id of folder.chain) next.delete(id)
120
+ } else {
121
+ next.add(folder.chain.at(-1)!)
122
+ }
123
+ setCollapsed(next)
124
+ }
125
+
126
+ return (
127
+ // The host scrolls sidebar.content; this section contributes its full height.
128
+ <box width="100%" flexShrink={0} onSizeChange={function () { setWidth(this.width) }}>
129
+ <box flexDirection="row" justifyContent="space-between" columnGap={1}
130
+ backgroundColor={header.hovered() ? hoverBackground(theme()) : undefined}
131
+ onMouseOver={header.onMouseOver} onMouseOut={header.onMouseOut}
132
+ onMouseUp={leftClick(() => props.open())}>
133
+ <text wrapMode="none" truncate minWidth={0} selectable={false} fg={theme().text.base}><b>Changes</b></text>
134
+ <Show when={history()}>
135
+ {(summary) => <text wrapMode="none" truncate minWidth={0} selectable={false} fg={theme().text.muted}>
136
+ {plural(summary().files.length, "file")}
137
+ </text>}
138
+ </Show>
139
+ </box>
140
+ <Show when={history()?.files.length ? history() : undefined}>
141
+ {(summary) => (
142
+ <>
143
+ <Totals context={props.context} stats={summary()} />
144
+ <Ratio context={props.context} history={summary()} width={width()} />
145
+ </>
146
+ )}
147
+ </Show>
148
+ <HistoryStatus context={props.context} state={props.state} history={history()} />
149
+ <For each={ids()}>
150
+ {(id) => {
151
+ const initial = entries().get(id)!
152
+ const row = () => entries().get(id) ?? initial
153
+ const closed = () => {
154
+ const item = row()
155
+ return item.kind === "folder" && isCollapsed(item)
156
+ }
157
+ return (
158
+ <SidebarRow context={props.context} row={row()} collapsed={closed()} width={width()} columns={columns()}
159
+ stats={row().kind === "file" || closed() ? statistics().get(id) : undefined}
160
+ activate={() => {
161
+ const item = row()
162
+ if (item.kind === "folder") toggle(item)
163
+ else props.open(item.file.path)
164
+ }} />
165
+ )
166
+ }}
167
+ </For>
168
+ <box height={1} marginTop={1} flexShrink={0}
169
+ backgroundColor={details.hovered() ? hoverBackground(theme()) : undefined}
170
+ onMouseOver={details.onMouseOver} onMouseOut={details.onMouseOut}
171
+ onMouseUp={leftClick(() => props.open())}>
172
+ <text height={1} wrapMode="none" truncate selectable={false}
173
+ fg={details.hovered() ? hoverColor(theme()) : theme().text.muted}>View details ›</text>
174
+ </box>
175
+ </box>
176
+ )
177
+ }
@@ -0,0 +1,300 @@
1
+ import { useTerminalDimensions } from "@opentui/solid"
2
+ import { MouseButton, type MouseEvent, type ScrollBoxRenderable } from "@opentui/core"
3
+ import { batch, createEffect, createMemo, createSignal, on, Show } from "solid-js"
4
+ import type { FileHistory } from "../core/types"
5
+ import { createExplorer, Explorer } from "./explorer"
6
+ import { DiffView } from "./diff-view"
7
+ import { HistoryNav } from "./history-nav"
8
+ import { clampTreeWidth, splitLayout } from "./layout"
9
+ import {
10
+ Counts, countLabels, countsWidth, createHover, HistoryStatus, hoverColor, KeyHints, leftClick, middleEllipsis,
11
+ pathLabel, plural, Summary, tint, useHistory, type Context, type Hint, type HistoryProps,
12
+ } from "./presentation"
13
+
14
+ const noFiles: readonly FileHistory[] = []
15
+ const panes = ["files", "history", "diff"] as const
16
+ type Pane = (typeof panes)[number]
17
+
18
+ const splitMemory = new WeakMap<object, number>()
19
+
20
+ function splitPreference(context: Context) {
21
+ const memory = {
22
+ get: () => splitMemory.get(context),
23
+ set: (width: number) => { splitMemory.set(context, width) },
24
+ }
25
+ if (typeof context.storage?.store !== "function") return memory
26
+ try {
27
+ const [state, update] = context.storage.store<{ width: number }>("change-history.split", {
28
+ initial: { width: 0 },
29
+ })
30
+ return {
31
+ get: () => typeof state.width === "number" && state.width > 0 ? state.width : splitMemory.get(context),
32
+ set: (width: number) => {
33
+ splitMemory.set(context, width)
34
+ void update((draft) => { draft.width = width }).catch(() => {})
35
+ },
36
+ }
37
+ } catch {
38
+ return memory
39
+ }
40
+ }
41
+
42
+ function FileHeader(props: {
43
+ context: Context; file: FileHistory; path: string; width: number; spaced: boolean; back?: () => void
44
+ }) {
45
+ const theme = () => props.context.theme
46
+ const backHover = createHover()
47
+ const countsFormat = { hideZero: true, showUnknown: true } as const
48
+ const layout = createMemo(() => {
49
+ const { file, width } = props
50
+ const label = plural(file.operations, "edit")
51
+ const short = `${file.operations}e`
52
+ const counts = countsWidth(countLabels(file, countsFormat))
53
+ const partial = file.incomplete ? "Partial" : ""
54
+ const status = partial && width < short.length + partial.length + 7 ? "!" : partial
55
+ const reserved = 1 + (status ? status.length + 1 : 0)
56
+ const statsWidth = label.length + counts + reserved
57
+ const back = props.back ? (width >= 14 ? "‹ Files" : "‹") : ""
58
+ const backWidth = back ? back.length + 1 : 0
59
+ const inline = Bun.stringWidth(props.path) + backWidth + statsWidth + 2 <= width
60
+ const caption = inline || statsWidth <= width ? label : short
61
+ return {
62
+ inline, caption, status, back,
63
+ pathWidth: width - backWidth - (inline ? statsWidth + 2 : 0),
64
+ countWidth: Math.max(0, width - caption.length - reserved),
65
+ }
66
+ })
67
+
68
+ return (
69
+ <box flexShrink={0} flexDirection={layout().inline ? "row" : "column"} justifyContent="space-between"
70
+ gap={layout().inline ? 2 : 0} marginBottom={props.spaced ? 1 : 0} overflow="hidden">
71
+ <box flexDirection="row" justifyContent="space-between" height={1} minWidth={0} gap={1}>
72
+ <text flexGrow={1} minWidth={0} wrapMode="none" fg={theme().text.base}>
73
+ <b>{middleEllipsis(props.path, layout().pathWidth)}</b>
74
+ </text>
75
+ <Show when={props.back}>
76
+ {(back) => <text flexShrink={0} wrapMode="none" selectable={false}
77
+ fg={backHover.hovered() ? hoverColor(theme()) : theme().text.feedback.info.base}
78
+ onMouseOver={backHover.onMouseOver} onMouseOut={backHover.onMouseOut}
79
+ onMouseUp={leftClick(back())}>{layout().back}</text>}
80
+ </Show>
81
+ </box>
82
+ <box flexDirection="row" height={1} gap={1} flexShrink={0} overflow="hidden">
83
+ <text minWidth={0} wrapMode="none" truncate fg={theme().text.muted}>{layout().caption}</text>
84
+ <Show when={layout().countWidth > 0}>
85
+ <Counts context={props.context} stats={props.file} format={{ ...countsFormat, width: layout().countWidth }} />
86
+ </Show>
87
+ <Show when={layout().status}>
88
+ <text flexShrink={0} wrapMode="none" fg={theme().text.feedback.warning.base}>{layout().status}</text>
89
+ </Show>
90
+ </box>
91
+ </box>
92
+ )
93
+ }
94
+
95
+ export function ChangesDialog(props: HistoryProps & { request?: { path: string }; close: () => void; refresh: () => void }) {
96
+ const theme = () => props.context.theme
97
+ const escHover = createHover()
98
+ const divider = createMemo(() => {
99
+ const { background, text } = theme().surface("dialog")
100
+ return tint(background.base, text.base, 0.16)
101
+ })
102
+ const dimensions = useTerminalDimensions()
103
+ const height = () => Math.max(1, dimensions().height - Math.max(2, Math.floor(dimensions().height / 6)))
104
+ const [width, setWidth] = createSignal(0)
105
+ const wide = () => width() >= 74
106
+ const [detailWidth, setDetailWidth] = createSignal(0)
107
+ const ready = useHistory(() => props.state, true)
108
+ const history = () => ready()?.history
109
+ const files = () => history()?.files ?? noFiles
110
+ const directory = () => ready()?.directory ?? ""
111
+ const model = createExplorer(files, directory)
112
+ const preference = splitPreference(props.context)
113
+ const [manualWidth, setManualWidth] = createSignal<number>()
114
+ const [draggingSplit, setDraggingSplit] = createSignal(false)
115
+ const [hoveringSplit, setHoveringSplit] = createSignal(false)
116
+ const split = createMemo(() => splitLayout({
117
+ width: width(),
118
+ columns: model.columns(),
119
+ metrics: model.metrics(),
120
+ preferred: manualWidth() ?? preference.get(),
121
+ }))
122
+ const splitColor = () => draggingSplit() || hoveringSplit() ? theme().text.feedback.info.base : divider()
123
+ let splitDrag: { x: number; width: number } | undefined
124
+ const [path, setPath] = createSignal<string>()
125
+ const [pane, setPane] = createSignal<Pane>()
126
+ const [reveal, setReveal] = createSignal<{ path: string }>()
127
+ const [selection, setSelection] = createSignal<{ path: string; id: string }>()
128
+ const file = createMemo(() => files().find((item) => item.path === path()))
129
+ const selected = createMemo(() => {
130
+ const current = file()
131
+ if (!current) return -1
132
+ const saved = selection()
133
+ const index = saved?.path === current.path ? current.changes.findIndex((change) => change.id === saved.id) : -1
134
+ return index >= 0 ? index : current.changes.length - 1
135
+ })
136
+ const change = () => file()?.changes[selected()]
137
+ const focused = () => file() ? pane() ?? (wide() ? "files" : "history") : "files"
138
+ const focusFiles = () => setPane("files")
139
+ const focusHistory = () => setPane("history")
140
+ const focusDiff = () => setPane("diff")
141
+ let diffScroll: ScrollBoxRenderable | undefined
142
+
143
+ function startSplit(event: MouseEvent) {
144
+ if (event.button !== MouseButton.LEFT) return
145
+ event.preventDefault()
146
+ event.stopPropagation()
147
+ splitDrag = { x: event.x, width: split().tree }
148
+ setDraggingSplit(true)
149
+ }
150
+
151
+ function moveSplit(event: MouseEvent) {
152
+ if (!splitDrag) return
153
+ event.preventDefault()
154
+ event.stopPropagation()
155
+ setManualWidth(clampTreeWidth(splitDrag.width + event.x - splitDrag.x, width(), model.columns()))
156
+ }
157
+
158
+ function endSplit() {
159
+ if (!splitDrag) return
160
+ splitDrag = undefined
161
+ setDraggingSplit(false)
162
+ const current = manualWidth()
163
+ if (current !== undefined) preference.set(clampTreeWidth(current, width(), model.columns()))
164
+ }
165
+
166
+ function preview(next: string | undefined) {
167
+ if (next === path()) return
168
+ batch(() => {
169
+ setPath(next)
170
+ setSelection(undefined)
171
+ })
172
+ }
173
+
174
+ function open(next: string) {
175
+ preview(next)
176
+ if (!wide()) focusHistory()
177
+ }
178
+
179
+ createEffect(on(files, (current) => {
180
+ if (current.some((file) => file.path === path())) return
181
+ const next = model.defaultPath()
182
+ batch(() => {
183
+ if (next) model.reveal(next, false)
184
+ preview(next)
185
+ })
186
+ }))
187
+
188
+ createEffect(on([() => props.request, files], ([request, current]) => {
189
+ if (!request || reveal() === request || !current.some((file) => file.path === request.path)) return
190
+ batch(() => {
191
+ model.reveal(request.path)
192
+ setReveal(request)
193
+ preview(request.path)
194
+ focusHistory()
195
+ })
196
+ }))
197
+
198
+ function switchPane(step: number) {
199
+ if (!file()) return
200
+ setPane(panes[(panes.indexOf(focused()) + step + panes.length) % panes.length])
201
+ }
202
+
203
+ function selectEdit(index: number) {
204
+ const current = file()
205
+ const next = current?.changes[index]
206
+ if (current && next) setSelection({ path: current.path, id: next.id })
207
+ }
208
+
209
+ // Remember even the implicit latest choice so a refresh can preserve that record.
210
+ createEffect(() => {
211
+ const current = change()
212
+ if (current && selection()?.id !== current.id) setSelection({ path: current.path, id: current.id })
213
+ })
214
+
215
+ props.context.keymap.layer(() => ({
216
+ mode: "modal",
217
+ priority: 10,
218
+ commands: [
219
+ { bind: "tab", run: () => switchPane(1) },
220
+ { bind: "shift+tab", run: () => switchPane(-1) },
221
+ { bind: "r", run: () => props.refresh() },
222
+ ],
223
+ }))
224
+
225
+ const hints = (): Hint[] => {
226
+ const label = props.state.status === "loading" && history() ? "Refreshing…" : "Refresh"
227
+ const compact = width() < 48
228
+ const items: Hint[] = [["r", compact ? "" : label, props.refresh]]
229
+ if (!file()) return items
230
+ items.unshift(["Tab", compact ? "" : "Focus", () => switchPane(1)])
231
+ if (focused() === "diff") items.unshift(["↑↓/←→", compact ? "" : "Pan", focusDiff])
232
+ else {
233
+ if (wide() || focused() === "history") items.unshift(["←→", "History"])
234
+ if (wide() || focused() === "files") items.unshift(["↑↓", "Files"])
235
+ if (!wide() && focused() === "files" && width() >= 30) items.splice(1, 0, ["Enter", "Open"])
236
+ }
237
+ if (width() >= 62) items.push(["PgUp/PgDn", "Scroll"])
238
+ return items
239
+ }
240
+
241
+ return (
242
+ <box width="100%" height={height()} paddingX={dimensions().width >= 60 ? 3 : 1}
243
+ paddingBottom={height() >= 16 ? 1 : 0} gap={height() >= 16 ? 1 : 0} overflow="hidden">
244
+ <box flexShrink={0}>
245
+ <box flexDirection="row" justifyContent="space-between">
246
+ <text minWidth={0} flexShrink={1} wrapMode="none" truncate fg={theme().text.base}><b>Change history</b></text>
247
+ <text flexShrink={0} fg={escHover.hovered() ? hoverColor(theme()) : theme().text.muted} selectable={false}
248
+ onMouseOver={escHover.onMouseOver} onMouseOut={escHover.onMouseOut}
249
+ onMouseUp={leftClick(props.close)}>esc</text>
250
+ </box>
251
+ <Show when={history()}>
252
+ {(summary) => <Summary context={props.context} stats={summary()} files={summary().files.length} width={width()} />}
253
+ </Show>
254
+ <HistoryStatus context={props.context} state={props.state} history={history()} compact />
255
+ </box>
256
+ <box flexGrow={1} minHeight={0} flexDirection="row" overflow="hidden"
257
+ onSizeChange={function () { setWidth(this.width) }}>
258
+ {/* Keep both scrollboxes mounted when navigating the single-column view. */}
259
+ <box position={wide() ? "relative" : "absolute"} left={0} top={0} overflow="hidden"
260
+ width={wide() ? split().tree : "100%"} height="100%" flexShrink={0}
261
+ visible={wide() || focused() === "files"}>
262
+ <Explorer context={props.context} model={model} activePath={file()?.path}
263
+ focused={focused() === "files"} focus={focusFiles} open={open} preview={preview} />
264
+ </box>
265
+ <Show when={wide()}>
266
+ <box width={split().splitter} height="100%" flexShrink={0}
267
+ border={["left"]} borderColor={splitColor()}
268
+ onMouseOver={() => setHoveringSplit(true)} onMouseOut={() => setHoveringSplit(false)}
269
+ onMouseDown={startSplit} onMouseDrag={moveSplit}
270
+ onMouseUp={endSplit} onMouseDragEnd={endSplit} />
271
+ </Show>
272
+ <box position={wide() ? "relative" : "absolute"} left={0} top={0} width={wide() ? undefined : "100%"}
273
+ height="100%" flexGrow={1} minWidth={0} overflow="hidden" visible={wide() || focused() !== "files"}
274
+ onSizeChange={function () { setDetailWidth(this.width) }}>
275
+ <Show when={file()}>
276
+ {(current) => <FileHeader context={props.context} file={current()} path={pathLabel(current().path, directory())}
277
+ width={detailWidth()} spaced={height() >= 16} back={wide() ? undefined : focusFiles} />}
278
+ </Show>
279
+ <Show when={change()}>
280
+ {(record) => (
281
+ <>
282
+ <HistoryNav context={props.context} changes={file()!.changes} selected={selected()} width={detailWidth()}
283
+ select={selectEdit} page={(delta) => diffScroll?.scrollBy(delta, "viewport")}
284
+ focused={focused() === "history"} focus={focusHistory} />
285
+ <box flexGrow={1} minHeight={0} overflow="hidden" border={["top"]}
286
+ borderColor={focused() === "diff" ? theme().text.feedback.info.base : theme().border.base}>
287
+ <DiffView context={props.context} change={record()} directory={directory()}
288
+ focused={focused() === "diff"} focus={focusDiff} scrollRef={(node) => { diffScroll = node }} />
289
+ </box>
290
+ </>
291
+ )}
292
+ </Show>
293
+ </box>
294
+ </box>
295
+ <Show when={height() >= 9}>
296
+ <KeyHints context={props.context} items={hints()} singleLine />
297
+ </Show>
298
+ </box>
299
+ )
300
+ }
@@ -0,0 +1,141 @@
1
+ import { generateSyntax } from "@opencode/theme/tui"
2
+ import type { ScrollBoxRenderable } from "@opentui/core"
3
+ import { createEffect, createMemo, createSignal, For, Match, on, onCleanup, Show, Switch } from "solid-js"
4
+ import type { RecordedChange } from "../core/types"
5
+ import { hasHunks, leftClick, pathLabel, tint, visible, type PaneProps } from "./presentation"
6
+
7
+ // OpenTUI's built-in parsers; unsupported types still get the native Diff colors.
8
+ const filetypes = new Map([
9
+ ["js", "javascript"], ["jsx", "javascriptreact"], ["mjs", "javascript"], ["cjs", "javascript"],
10
+ ["ts", "typescript"], ["tsx", "typescriptreact"], ["mts", "typescript"], ["cts", "typescript"],
11
+ ["md", "markdown"], ["markdown", "markdown"], ["zig", "zig"],
12
+ ])
13
+
14
+ const cellWidth = (line: string) => Bun.stringWidth(line.replaceAll("\t", " "))
15
+ const longestLine = (text: string) => text.split("\n").reduce((width, line) => Math.max(width, cellWidth(line)), 0)
16
+
17
+ function patchWidth(patch: string, numbered: boolean) {
18
+ let code = 0
19
+ let digits = 1
20
+ let inHunk = false
21
+ for (const line of patch.split("\n")) {
22
+ const hunk = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line)
23
+ if (hunk) {
24
+ inHunk = true
25
+ const [, oldStart, oldLength = "1", newStart, newLength = "1"] = hunk
26
+ digits = Math.max(digits, String(Math.max(Number(oldStart) + Number(oldLength) - 1,
27
+ Number(newStart) + Number(newLength) - 1)).length)
28
+ } else if (inHunk && /^[ +\-]/.test(line)) {
29
+ code = Math.max(code, cellWidth(line.slice(1)))
30
+ }
31
+ }
32
+ // OpenTUI's default gutter has two padding cells and two sign cells.
33
+ return code + 4 + (numbered ? digits : 0)
34
+ }
35
+
36
+ export function DiffView(props: PaneProps & {
37
+ change: RecordedChange
38
+ directory: string
39
+ scrollRef: (scroll: ScrollBoxRenderable) => void
40
+ }) {
41
+ const theme = () => props.context.theme
42
+ const horizontalThumb = createMemo(() => {
43
+ const dialog = theme().surface("dialog")
44
+ return tint(dialog.background.base, dialog.scrollbar.base, props.focused ? 0.8 : 0.55)
45
+ })
46
+ const [width, setWidth] = createSignal(0)
47
+ const syntax = createMemo(() => {
48
+ const style = generateSyntax(theme(), props.context.renderer.nativeScene)
49
+ onCleanup(() => { void props.context.renderer.idle().then(() => style.destroy()) })
50
+ return style
51
+ })
52
+ const filetype = createMemo(() => filetypes.get(props.change.path.split(".").at(-1)?.toLowerCase() ?? ""))
53
+ let scroll: ScrollBoxRenderable | undefined
54
+
55
+ const changeID = createMemo(() => props.change.id)
56
+ createEffect(on(changeID, () => scroll?.scrollTo({ x: 0, y: 0 }), { defer: true }))
57
+ const page = (step: number) => scroll?.scrollBy(step, "viewport")
58
+ props.context.keymap.layer(() => ({
59
+ mode: "modal",
60
+ enabled: () => props.focused,
61
+ priority: 10,
62
+ commands: [
63
+ { bind: "up", run: () => scroll?.scrollBy({ x: 0, y: -1 }) },
64
+ { bind: "down", run: () => scroll?.scrollBy({ x: 0, y: 1 }) },
65
+ { bind: "left", run: () => scroll?.scrollBy({ x: -4, y: 0 }) },
66
+ { bind: "right", run: () => scroll?.scrollBy({ x: 4, y: 0 }) },
67
+ { bind: "pageup", run: () => page(-1) },
68
+ { bind: "pagedown", run: () => page(1) },
69
+ { bind: "home", run: () => { if (scroll) scroll.scrollTop = 0 } },
70
+ { bind: "end", run: () => { if (scroll) scroll.scrollTop = scroll.scrollHeight } },
71
+ ],
72
+ }))
73
+
74
+ const notice = (message: () => string) => (
75
+ <text width={width()} flexShrink={0} fg={theme().text.muted}>{message()}</text>
76
+ )
77
+ function Patch(patch: { text: string; partial?: boolean }) {
78
+ const diff = createMemo(() => visible(patch.text))
79
+ const cells = createMemo(() => patchWidth(diff(), !patch.partial))
80
+ return (
81
+ <diff diff={diff()} view="unified" showLineNumbers={!patch.partial} wrapMode="none"
82
+ flexShrink={0} width={Math.max(width(), cells())}
83
+ fg={theme().text.base} filetype={filetype()} syntaxStyle={syntax()}
84
+ addedBg={theme().diff.background.added}
85
+ removedBg={theme().diff.background.removed}
86
+ contextBg={theme().diff.background.context}
87
+ addedSignColor={theme().diff.highlight.added}
88
+ removedSignColor={theme().diff.highlight.removed}
89
+ lineNumberFg={theme().diff.lineNumber.text}
90
+ lineNumberBg={theme().diff.background.context}
91
+ addedLineNumberBg={theme().diff.lineNumber.background.added}
92
+ removedLineNumberBg={theme().diff.lineNumber.background.removed}
93
+ />
94
+ )
95
+ }
96
+
97
+ return (
98
+ <scrollbox flexGrow={1} minHeight={0} minWidth={0} scrollX scrollY focusable={false}
99
+ onMouseDown={leftClick(props.focus)}
100
+ scrollbarOptions={{ trackOptions: { foregroundColor: theme().scrollbar.base } }}
101
+ horizontalScrollbarOptions={{ trackOptions: { foregroundColor: horizontalThumb() } }}
102
+ ref={(node) => {
103
+ scroll = node
104
+ props.scrollRef(node)
105
+ node.viewport.onSizeChange = () => setWidth(node.viewport.width)
106
+ }}>
107
+ <Show when={props.change.previousPath}>
108
+ {(path) => notice(() => `Moved from ${pathLabel(path(), props.directory)}`)}
109
+ </Show>
110
+ <Show when={props.change.note}>
111
+ {(note) => notice(() => visible(note()))}
112
+ </Show>
113
+ <Switch>
114
+ <Match when={hasHunks(props.change) && props.change.diff}>
115
+ {(patch) => <Patch text={patch()} />}
116
+ </Match>
117
+ <Match when={props.change.diffQuality === "recorded"}>
118
+ {notice(() => "The recorded Diff has no textual hunks.")}
119
+ </Match>
120
+ <Match when={props.change.fragments?.length}>
121
+ {notice(() => "Preview from tool input · positions and changes are unverified.")}
122
+ <For each={props.change.fragments}>
123
+ {(fragment) => <Patch text={fragment} partial />}
124
+ </For>
125
+ </Match>
126
+ <Match when={props.change.diff}>
127
+ {(raw) => (
128
+ <>
129
+ {notice(() => "The recorded Diff is incomplete.")}
130
+ <text wrapMode="none" flexShrink={0} fg={theme().text.base}
131
+ width={Math.max(width(), longestLine(visible(raw())))}>{visible(raw())}</text>
132
+ </>
133
+ )}
134
+ </Match>
135
+ <Match when={true}>
136
+ {notice(() => "No Diff was recorded for this edit.")}
137
+ </Match>
138
+ </Switch>
139
+ </scrollbox>
140
+ )
141
+ }