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,268 @@
1
+ import { createEffect, createMemo, createSignal, For, on, Show } from "solid-js"
2
+ import type { ScrollBoxRenderable } from "@opentui/core"
3
+ import type { FileHistory } from "../core/types"
4
+ import { externalID, fileID, fileTree, sortFiles, sortModes, visibleTree, type Folder, type Row, type SortMode } from "./file-tree"
5
+ import type { TreeMetrics } from "./layout"
6
+ import {
7
+ Counts, countColumns, countsWidth, createHover, hoverColor, inline, keepScrollPosition, leftClick, middleEllipsis,
8
+ type PaneProps,
9
+ } from "./presentation"
10
+
11
+ const countFormat = { hideZero: true, showUnknown: true } as const
12
+
13
+ export function createExplorer(files: () => readonly FileHistory[], directory: () => string) {
14
+ const [mode, setMode] = createSignal<"Tree" | "List">("Tree")
15
+ const [sort, setSort] = createSignal<SortMode>("Recent")
16
+ const [selection, select] = createSignal<string>()
17
+ const [collapsed, setCollapsed] = createSignal(new Set([externalID]))
18
+ const sorted = createMemo(() => sortFiles(files(), sort(), directory()))
19
+ const hierarchy = createMemo(() => fileTree(sorted(), directory()))
20
+ const columns = createMemo(() => countColumns(sorted(), countFormat))
21
+ const metrics = createMemo<TreeMetrics>(() => {
22
+ const names: number[] = []
23
+ let depth = 0
24
+ function visit(children: ReadonlyMap<string, Row>, level: number) {
25
+ for (const row of children.values()) {
26
+ names.push(Bun.stringWidth(row.name))
27
+ depth = Math.max(depth, level)
28
+ if (row.kind === "folder") visit(row.children, level + 1)
29
+ }
30
+ }
31
+ visit(hierarchy().roots, 0)
32
+ return { names, depth }
33
+ })
34
+ const defaultPath = () => {
35
+ const leaves = [...hierarchy().leaves.values()]
36
+ return (leaves.find((file) => !file.external) ?? leaves[0])?.file.path
37
+ }
38
+ const rows = createMemo(() => {
39
+ const reduced = collapsed()
40
+ const { roots, leaves, external } = hierarchy()
41
+ if (mode() === "List") {
42
+ const files = [...leaves.values()]
43
+ const visible: Row[] = files.filter((file) => !file.external)
44
+ if (external.children.size) {
45
+ visible.push(external)
46
+ if (!reduced.has(externalID)) visible.push(...files.filter((file) => file.external))
47
+ }
48
+ return visible
49
+ }
50
+ return visibleTree(roots, (folder) => reduced.has(folder.id))
51
+ })
52
+ const entries = createMemo(() => new Map(rows().map((row) => [row.id, row])))
53
+ const selected = (): Row | undefined => entries().get(selection() ?? "") ?? rows()[0]
54
+ createEffect(() => {
55
+ if (selection() === undefined && rows()[0]) select(rows()[0].id)
56
+ })
57
+
58
+ function toggleFolder(folder: Folder) {
59
+ setCollapsed((current) => {
60
+ const next = new Set(current)
61
+ if (!next.delete(folder.id)) next.add(folder.id)
62
+ return next
63
+ })
64
+ }
65
+
66
+ function reveal(path: string, expandExternal = true) {
67
+ const id = fileID(path)
68
+ if (hierarchy().leaves.get(id)?.external && !expandExternal && collapsed().has(externalID)) {
69
+ select(externalID)
70
+ return
71
+ }
72
+ select(id)
73
+ const next = new Set(collapsed())
74
+ let changed = false
75
+ const leaf = hierarchy().leaves.get(id)
76
+ for (let folder = leaf?.parent; folder; folder = folder.parent) {
77
+ if (next.delete(folder.id)) changed = true
78
+ }
79
+ if (changed) setCollapsed(next)
80
+ }
81
+
82
+ function toggleMode() {
83
+ const row = selected()
84
+ if (mode() === "Tree") {
85
+ let item = row
86
+ while (item?.kind === "folder" && item.id !== externalID) item = item.children.values().next().value
87
+ if (item?.kind === "file" && item.external && collapsed().has(externalID)) select(externalID)
88
+ else select(item?.id)
89
+ setMode("List")
90
+ return
91
+ }
92
+ if (row?.kind === "file") reveal(row.file.path)
93
+ setMode("Tree")
94
+ }
95
+
96
+ return {
97
+ mode, sort, sorted, entries, rows, selected, select, reveal, defaultPath, collapsed, toggleFolder, toggleMode,
98
+ columns, metrics,
99
+ cycleSort: () => setSort((current) => sortModes[(sortModes.indexOf(current) + 1) % sortModes.length]),
100
+ }
101
+ }
102
+
103
+ export function Explorer(props: PaneProps & {
104
+ model: ReturnType<typeof createExplorer>
105
+ activePath?: string
106
+ preview: (path: string) => void
107
+ open: (path: string) => void
108
+ }) {
109
+ const model = props.model
110
+ const theme = () => props.context.theme
111
+ const modeHover = createHover()
112
+ const sortHover = createHover()
113
+ const [width, setWidth] = createSignal(0)
114
+ const shortcut = (key: string) => width() >= 22 ? `${key} ` : ""
115
+ const statsWidth = createMemo(() => countsWidth(model.columns()))
116
+ const ids = createMemo(() => [...model.entries().keys()])
117
+ const activeID = createMemo(() => props.activePath === undefined ? undefined : fileID(props.activePath))
118
+ let scroll: ScrollBoxRenderable | undefined
119
+ keepScrollPosition(ids, () => scroll)
120
+ createEffect(on(activeID, (id) => {
121
+ if (id) scroll?.scrollChildIntoView(id)
122
+ }))
123
+
124
+ function revealSelection() {
125
+ const row = model.selected()
126
+ if (row) scroll?.scrollChildIntoView(row.id)
127
+ }
128
+
129
+ function select(row?: Row) {
130
+ if (!row) return
131
+ model.select(row.id)
132
+ revealSelection()
133
+ if (row.kind === "file") props.preview(row.file.path)
134
+ }
135
+
136
+ function move(delta: number) {
137
+ const rows = model.rows()
138
+ const index = rows.findIndex((row) => row.id === model.selected()?.id)
139
+ select(rows[Math.max(0, Math.min(rows.length - 1, index + delta))])
140
+ }
141
+
142
+ function activate(row = model.selected()) {
143
+ if (!row) return
144
+ select(row)
145
+ if (row.kind === "folder") model.toggleFolder(row)
146
+ else props.open(row.file.path)
147
+ }
148
+
149
+ function left() {
150
+ const row = model.selected()
151
+ if (!row) return
152
+ if (row.kind === "folder" && !model.collapsed().has(row.id)) model.toggleFolder(row)
153
+ else if (model.mode() === "Tree") select(row.parent)
154
+ else if (row.kind === "file" && row.external) select(model.entries().get(externalID))
155
+ }
156
+
157
+ function right() {
158
+ const row = model.selected()
159
+ if (row?.kind !== "folder") return
160
+ if (model.collapsed().has(row.id)) model.toggleFolder(row)
161
+ else move(1)
162
+ }
163
+
164
+ function changeView(action: () => void) {
165
+ props.focus()
166
+ action()
167
+ revealSelection()
168
+ const row = model.selected()
169
+ if (row?.kind === "file") props.preview(row.file.path)
170
+ }
171
+
172
+ props.context.keymap.layer(() => ({
173
+ mode: "modal",
174
+ enabled: () => props.focused,
175
+ priority: 10,
176
+ commands: [
177
+ { bind: "up", run: () => move(-1) },
178
+ { bind: "down", run: () => move(1) },
179
+ { bind: "enter", run: () => activate() },
180
+ { bind: "left", run: left },
181
+ { bind: "right", run: right },
182
+ { bind: "pageup", run: () => scroll?.scrollBy(-1, "viewport") },
183
+ { bind: "pagedown", run: () => scroll?.scrollBy(1, "viewport") },
184
+ { bind: "v", run: () => changeView(model.toggleMode) },
185
+ { bind: "s", run: () => changeView(model.cycleSort) },
186
+ ],
187
+ }))
188
+
189
+ return (
190
+ <box flexGrow={1} minHeight={0} onMouseDown={leftClick(props.focus)}>
191
+ <box flexDirection="row" justifyContent="space-between" height={1} flexShrink={0} overflow="hidden">
192
+ <text wrapMode="none" flexShrink={0}
193
+ fg={props.focused ? theme().text.feedback.info.base : theme().text.muted}><b>Files</b></text>
194
+ <Show when={model.rows().length}>
195
+ <box flexDirection="row" gap={1} overflow="hidden">
196
+ <text wrapMode="none" selectable={false}
197
+ fg={modeHover.hovered() ? hoverColor(theme()) : theme().text.muted}
198
+ onMouseOver={modeHover.onMouseOver} onMouseOut={modeHover.onMouseOut}
199
+ onMouseUp={leftClick(() => changeView(model.toggleMode))}>{`${shortcut("v")}${model.mode()}`}</text>
200
+ <text wrapMode="none" selectable={false}
201
+ fg={sortHover.hovered() ? hoverColor(theme()) : theme().text.muted}
202
+ onMouseOver={sortHover.onMouseOver} onMouseOut={sortHover.onMouseOut}
203
+ onMouseUp={leftClick(() => changeView(model.cycleSort))}>
204
+ {`${shortcut("s")}${width() < 25 && model.sort() === "Known lines" ? "Lines" : model.sort()}`}
205
+ </text>
206
+ </box>
207
+ </Show>
208
+ </box>
209
+ <scrollbox flexGrow={1} minHeight={0} scrollX={false} focusable={false}
210
+ horizontalScrollbarOptions={{ visible: false }}
211
+ verticalScrollbarOptions={{ trackOptions: { foregroundColor: theme().scrollbar.base } }}
212
+ ref={(node) => {
213
+ scroll = node
214
+ node.viewport.onSizeChange = () => setWidth(node.viewport.width)
215
+ }}>
216
+ <For each={ids()}>
217
+ {(id) => {
218
+ const initial = model.entries().get(id)!
219
+ const row = () => model.entries().get(id) ?? initial
220
+ const selected = () => model.selected()?.id === id
221
+ const active = () => id === activeID()
222
+ const [hover, setHover] = createSignal(false)
223
+ const indent = () => {
224
+ const current = row()
225
+ const depth = model.mode() === "Tree" ? current.depth : Number(current.kind === "file" && current.external)
226
+ return Math.min(depth * 2, Math.floor(width() / 5),
227
+ Math.max(0, Math.floor((width() - statsWidth() - 8) / 2)))
228
+ }
229
+ const name = () => {
230
+ const current = row()
231
+ return inline(current.kind === "file" && model.mode() === "List" ? current.label : current.name)
232
+ }
233
+ const file = () => {
234
+ const current = row()
235
+ return current.kind === "file" ? current.file : undefined
236
+ }
237
+ const labelWidth = () => Math.max(0, width() - indent() - 2 - 1 -
238
+ (file() && statsWidth() ? statsWidth() + 1 : 0))
239
+ return (
240
+ <box id={id} height={1} flexShrink={0} flexDirection="row" gap={1} paddingRight={1} overflow="hidden"
241
+ onMouseOver={() => setHover(true)} onMouseOut={() => setHover(false)}
242
+ backgroundColor={selected() && props.focused ? theme().background.raised.high
243
+ : active() || hover() ? theme().background.raised.base : undefined}
244
+ onMouseUp={leftClick(() => {
245
+ props.focus()
246
+ activate(row())
247
+ })}>
248
+ <box flexGrow={1} minWidth={0} flexDirection="row" paddingLeft={indent()}>
249
+ <text width={2} flexShrink={0} selectable={false}
250
+ fg={selected() && props.focused ? theme().text.feedback.info.base : theme().text.muted}>
251
+ {row().kind === "folder" ? (model.collapsed().has(id) ? "▸" : "▾") : " "}
252
+ </text>
253
+ <text flexShrink={1} minWidth={0} wrapMode="none" selectable={false}
254
+ fg={row().kind === "file" ? theme().text.base : theme().text.muted}>
255
+ {middleEllipsis(name(), labelWidth())}
256
+ </text>
257
+ </box>
258
+ <Show when={statsWidth() ? file() : undefined}>
259
+ {(item) => <Counts context={props.context} stats={item()} columns={model.columns()} format={countFormat} />}
260
+ </Show>
261
+ </box>
262
+ )
263
+ }}
264
+ </For>
265
+ </scrollbox>
266
+ </box>
267
+ )
268
+ }
@@ -0,0 +1,113 @@
1
+ import { relativeLabel } from "../core/paths"
2
+ import type { FileHistory } from "../core/types"
3
+
4
+ export const sortModes = ["Recent", "Path", "Known lines"] as const
5
+ export type SortMode = (typeof sortModes)[number]
6
+
7
+ export function sortFiles(files: readonly FileHistory[], mode: SortMode, directory: string) {
8
+ const pathOrder = (a: FileHistory, b: FileHistory) =>
9
+ relativeLabel(a.path, directory).localeCompare(relativeLabel(b.path, directory))
10
+ if (mode === "Recent") return files.toSorted((a, b) => b.lastModified - a.lastModified || pathOrder(a, b))
11
+ if (mode === "Known lines") {
12
+ // A partial count is a lower bound; files with no known counts have no comparable volume.
13
+ const unknown = (file: FileHistory) =>
14
+ Number(file.unknownAdditions === file.operations && file.unknownDeletions === file.operations)
15
+ return files.toSorted((a, b) => unknown(a) - unknown(b) ||
16
+ (b.additions + b.deletions) - (a.additions + a.deletions) || pathOrder(a, b))
17
+ }
18
+ return files.toSorted(pathOrder)
19
+ }
20
+
21
+ type Entry = {
22
+ id: string
23
+ name: string
24
+ depth: number
25
+ last: boolean
26
+ parent?: Folder
27
+ }
28
+ export type Folder = Entry & { kind: "folder"; children: Map<string, Row>; chain: string[] }
29
+ type File = Entry & { kind: "file"; label: string; file: FileHistory; external: boolean }
30
+ export type Row = Folder | File
31
+
32
+ export const fileID = (path: string) => `file:${path}`
33
+ export const externalID = "external"
34
+
35
+ export function fileTree(files: readonly FileHistory[], directory: string, { foldersFirst = false } = {}) {
36
+ const roots = new Map<string, Row>()
37
+ const leaves = new Map<string, File>()
38
+ const external: Folder = {
39
+ id: externalID, kind: "folder", name: "External files", depth: 0, last: false,
40
+ children: new Map(), chain: [externalID],
41
+ }
42
+ for (const file of files) {
43
+ const label = relativeLabel(file.path, directory)
44
+ const outside = label === file.path && /^(?:\/|[A-Za-z]:|[^/\\:]+:(?:\/|~)|\.\.(?:\/|$))/.test(label)
45
+ const segments = label.split("/")
46
+ const name = segments.pop() || label
47
+ // Keep absolute and UNC roots distinct from relative paths in the same session.
48
+ const root = /^\/+/.exec(label)?.[0]
49
+ const folders = root ? [root, ...segments.filter(Boolean)] : segments
50
+ let parent = outside ? external : undefined
51
+ let children = parent?.children ?? roots
52
+ for (const segment of folders) {
53
+ const id: string = `${parent?.id ?? "dir:"}${segment.length}:${segment}`
54
+ const existing = children.get(id)
55
+ const folder: Folder = existing?.kind === "folder" ? existing : {
56
+ id, kind: "folder", name: segment, depth: 0, last: false, children: new Map(), chain: [id],
57
+ }
58
+ children.set(id, folder)
59
+ children = folder.children
60
+ parent = folder
61
+ }
62
+ const node: File = {
63
+ id: fileID(file.path), kind: "file", name, label, file, depth: 0, last: false, external: outside,
64
+ }
65
+ children.set(node.id, node)
66
+ leaves.set(node.id, node)
67
+ }
68
+
69
+ function compact(children: Map<string, Row>, parent?: Folder) {
70
+ if (foldersFirst) {
71
+ // Preserve the incoming path order among folders and among files.
72
+ for (const row of [...children.values()]) {
73
+ if (row.kind !== "file") continue
74
+ children.delete(row.id)
75
+ children.set(row.id, row)
76
+ }
77
+ }
78
+ let index = 0
79
+ for (const row of children.values()) {
80
+ row.parent = parent
81
+ row.depth = (parent?.depth ?? -1) + 1
82
+ row.last = ++index === children.size
83
+ if (row.kind === "file") continue
84
+ while (row.children.size === 1) {
85
+ const child = row.children.values().next().value
86
+ if (child?.kind !== "folder") break
87
+ row.name += (row.name.endsWith("/") ? "" : "/") + child.name
88
+ row.chain.push(child.id)
89
+ row.children = child.children
90
+ }
91
+ compact(row.children, row)
92
+ }
93
+ }
94
+ compact(roots)
95
+ if (external.children.size) {
96
+ external.last = true
97
+ compact(external.children, external)
98
+ roots.set(external.id, external)
99
+ }
100
+ return { roots, leaves, external }
101
+ }
102
+
103
+ export function visibleTree(roots: ReadonlyMap<string, Row>, collapsed: (folder: Folder) => boolean) {
104
+ const rows: Row[] = []
105
+ function append(children: ReadonlyMap<string, Row>) {
106
+ for (const row of children.values()) {
107
+ rows.push(row)
108
+ if (row.kind === "folder" && !collapsed(row)) append(row.children)
109
+ }
110
+ }
111
+ append(roots)
112
+ return rows
113
+ }
@@ -0,0 +1,216 @@
1
+ import { createMemo, createSignal, For, Show } from "solid-js"
2
+ import type { RecordedChange } from "../core/types"
3
+ import { Counts, createHover, hasHunks, hoverBackground, leftClick, tint, type PaneProps } from "./presentation"
4
+
5
+ const minTabWidth = 12
6
+ const maxTabWidth = 20
7
+ const tabGap = 1
8
+ const arrowWidth = 2
9
+ const clock = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" })
10
+ const shortClock = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" })
11
+ const kinds: Partial<Record<RecordedChange["kind"], string>> = { added: "Created", deleted: "Deleted", moved: "Moved" }
12
+
13
+ function recordMetadata(change: RecordedChange) {
14
+ const time = clock.format(change.time)
15
+ const minutes = `${change.timeSource === "start" ? "~" : ""}${shortClock.format(change.time)}`
16
+ const turn = `T${change.turn ?? "?"}`
17
+ const started = change.timeSource === "start"
18
+ const kind = kinds[change.kind]
19
+ const unknown = Number(change.additions === undefined) + Number(change.deletions === undefined)
20
+ const estimated = change.estimatedAdditions !== undefined
21
+ const counts = estimated
22
+ ? (unknown > 1 ? "Estimated additions · Some counts unknown" : "Estimated additions")
23
+ : unknown === 2 ? "Counts unknown" : unknown ? "Some counts unknown" : ""
24
+ let diff = ""
25
+ if (change.diffQuality === "partial") diff = "Partial preview"
26
+ else if (change.diffQuality === "missing") diff = change.diff ? "Incomplete Diff" : "No Diff"
27
+ else if (!hasHunks(change)) diff = "No textual Diff"
28
+ else if (change.incomplete) diff = "Partial"
29
+ return {
30
+ stamps: [
31
+ `${started ? "Started " : ""}${time} · Turn ${change.turn ?? "?"}`,
32
+ `${started ? "~" : ""}${time} ${turn}`, `${minutes} ${turn}`, minutes, turn,
33
+ ],
34
+ status: [kind, diff, counts].filter(Boolean).join(" · "),
35
+ shortStatus: [change.incomplete ? "Partial" : kind || (diff === "No textual Diff" ? "No hunks" : diff),
36
+ unknown ? (estimated ? "Estimated" : "Unknown") : ""].filter(Boolean).join(" · "),
37
+ }
38
+ }
39
+
40
+ function editStats(change: RecordedChange) {
41
+ return {
42
+ operations: 1,
43
+ additions: change.additions ?? 0,
44
+ deletions: change.deletions ?? 0,
45
+ estimatedAdditions: change.estimatedAdditions ?? 0,
46
+ unknownAdditions: Number(change.additions === undefined),
47
+ unknownDeletions: Number(change.deletions === undefined),
48
+ }
49
+ }
50
+
51
+ export function HistoryNav(props: PaneProps & {
52
+ changes: readonly RecordedChange[]
53
+ selected: number
54
+ width: number
55
+ select: (index: number) => void
56
+ page: (delta: number) => void
57
+ }) {
58
+ const theme = () => props.context.theme.surface("dialog")
59
+ const count = () => props.changes.length
60
+ const arrowCells = () => props.width >= 6 ? arrowWidth : 1
61
+ const available = () => props.width - 2 * arrowCells()
62
+ const slots = () => Math.max(0, Math.min(count(), Math.floor((available() + tabGap) / (minTabWidth + tabGap))))
63
+ const tabWidth = () => slots() ? Math.min(maxTabWidth, Math.floor((available() + tabGap) / slots()) - tabGap) : 0
64
+ const first = createMemo<{ path: string; index: number }>((previous) => {
65
+ const path = props.changes[0].path
66
+ const size = slots()
67
+ const selected = props.selected
68
+ if (!size) return { path, index: selected }
69
+ // Keep the window still until selection crosses an edge; clamp again when it resizes.
70
+ const start = previous?.path === path ? previous.index : selected - Math.floor(size / 2)
71
+ const index = Math.max(0, selected - size + 1, Math.min(start, selected, count() - size))
72
+ return { path, index }
73
+ })
74
+ const indices = createMemo(() => Array.from({ length: slots() }, (_, offset) => first().index + offset))
75
+ const colors = createMemo(() => {
76
+ const { background, text } = theme()
77
+ const accent = text.feedback.info.base
78
+ const normal = tint(background.base, text.base, 0.055)
79
+ return {
80
+ normal,
81
+ hover: tint(background.base, text.base, 0.105),
82
+ selected: tint(background.base, accent, 0.22),
83
+ selectedHover: tint(background.base, accent, 0.30),
84
+ line: tint(normal, text.base, 0.13),
85
+ accent,
86
+ }
87
+ })
88
+
89
+ function select(index: number) {
90
+ if (index >= 0 && index < count()) props.select(index)
91
+ }
92
+
93
+ props.context.keymap.layer(() => ({
94
+ mode: "modal",
95
+ enabled: () => props.focused,
96
+ priority: 10,
97
+ commands: [
98
+ { bind: "left", run: () => select(props.selected - 1) },
99
+ { bind: "right", run: () => select(props.selected + 1) },
100
+ { bind: "home", run: () => select(0) },
101
+ { bind: "end", run: () => select(count() - 1) },
102
+ { bind: "pageup", run: () => props.page(-1) },
103
+ { bind: "pagedown", run: () => props.page(1) },
104
+ ],
105
+ }))
106
+
107
+ const arrow = (symbol: string, delta: number) => {
108
+ const enabled = () => props.selected + delta >= 0 && props.selected + delta < count()
109
+ const hover = createHover()
110
+ return (
111
+ <box width={arrowCells()} height="100%" flexShrink={0} justifyContent="center"
112
+ alignItems={delta < 0 ? "flex-start" : "flex-end"}
113
+ backgroundColor={hover.hovered() && enabled() ? hoverBackground(theme()) : undefined}
114
+ onMouseOver={hover.onMouseOver} onMouseOut={hover.onMouseOut}
115
+ onMouseUp={leftClick(() => {
116
+ if (!enabled()) return
117
+ props.focus()
118
+ select(props.selected + delta)
119
+ })}>
120
+ <text wrapMode="none" selectable={false}
121
+ fg={!enabled() ? theme().text.faint : props.focused ? colors().accent : theme().text.base}>{symbol}</text>
122
+ </box>
123
+ )
124
+ }
125
+ const metadata = createMemo(() => props.changes.map(recordMetadata))
126
+ const record = () => metadata()[props.selected]
127
+ const warning = () => props.changes[props.selected].incomplete ? theme().text.feedback.warning.base : theme().text.muted
128
+ const statusRow = createMemo(() => {
129
+ const fractionWidth = String(count()).length * 2 + 3
130
+ return metadata().some(({ stamps, status }) =>
131
+ status && Bun.stringWidth(stamps[0]) + status.length + fractionWidth + 2 > props.width)
132
+ })
133
+ const metadataLine = createMemo(() => {
134
+ const { stamps, status } = record()
135
+ const full = `${props.selected + 1} / ${count()}`
136
+ const short = `${props.selected + 1}/${count()}`
137
+ const available = props.width - (!statusRow() && status ? status.length + 1 : 0)
138
+ for (const stamp of stamps) {
139
+ const remaining = available - Bun.stringWidth(stamp) - 1
140
+ if (remaining >= full.length) return { stamp, fraction: full }
141
+ if (remaining >= short.length) return { stamp, fraction: short }
142
+ }
143
+ return { stamp: "", fraction: short }
144
+ })
145
+ const statusLabel = () => {
146
+ const { status, shortStatus } = record()
147
+ if (status.length <= props.width) return status
148
+ return shortStatus.length <= props.width ? shortStatus : shortStatus.replace(" · Unknown", " ?")
149
+ }
150
+ const compactLabel = () => `#${props.selected + 1}`
151
+ const compactCountsWidth = () => available() - compactLabel().length - 1
152
+
153
+ return (
154
+ <box flexShrink={0} overflow="hidden">
155
+ <box flexDirection="row" height={slots() ? 3 : 1} flexShrink={0} overflow="hidden">
156
+ {arrow("‹", -1)}
157
+ <box flexGrow={1} minWidth={0} flexDirection="row" justifyContent="center" alignItems="center"
158
+ gap={tabGap} overflow="hidden" onMouseDown={leftClick(props.focus)}>
159
+ <Show when={slots()} fallback={
160
+ <>
161
+ <text minWidth={0} flexShrink={1} wrapMode="none" truncate selectable={false} fg={colors().accent}>
162
+ {compactLabel()}
163
+ </text>
164
+ <Show when={compactCountsWidth() >= 5}>
165
+ <Counts context={props.context} stats={editStats(props.changes[props.selected])} selectable={false}
166
+ format={{ showUnknown: true, width: compactCountsWidth() }} />
167
+ </Show>
168
+ </>
169
+ }>
170
+ <For each={indices()}>
171
+ {(index) => {
172
+ const [hover, setHover] = createSignal(false)
173
+ const active = () => index === props.selected
174
+ return (
175
+ <box width={tabWidth()} height={3} flexShrink={0} alignItems="center" overflow="hidden"
176
+ backgroundColor={active() ? (hover() ? colors().selectedHover : colors().selected)
177
+ : (hover() ? colors().hover : colors().normal)}
178
+ onMouseOver={() => setHover(true)} onMouseOut={() => setHover(false)}
179
+ onMouseUp={leftClick(() => {
180
+ props.focus()
181
+ select(index)
182
+ })}>
183
+ <text height={1} wrapMode="none" selectable={false} fg={active() ? colors().accent : theme().text.muted}>
184
+ {`#${index + 1}`}
185
+ </text>
186
+ <Counts context={props.context} stats={editStats(props.changes[index])} selectable={false}
187
+ format={{ showUnknown: true, width: tabWidth() }} />
188
+ <text height={1} wrapMode="none" selectable={false} fg={active() ? colors().accent : colors().line}>
189
+ {(active() ? "━" : "─").repeat(tabWidth())}
190
+ </text>
191
+ </box>
192
+ )
193
+ }}
194
+ </For>
195
+ </Show>
196
+ </box>
197
+ {arrow("›", 1)}
198
+ </box>
199
+ <box flexDirection="row" height={1} flexShrink={0} gap={1} justifyContent="space-between"
200
+ overflow="hidden" onMouseDown={leftClick(props.focus)}>
201
+ <box flexDirection="row" minWidth={0} flexShrink={1} gap={1}>
202
+ <text minWidth={0} flexShrink={1} wrapMode="none" fg={theme().text.muted}>{metadataLine().stamp}</text>
203
+ <Show when={!statusRow() && record().status}>
204
+ <text wrapMode="none" flexShrink={0} fg={warning()}>{record().status}</text>
205
+ </Show>
206
+ </box>
207
+ <text wrapMode="none" flexShrink={0} fg={theme().text.muted}>{metadataLine().fraction}</text>
208
+ </box>
209
+ <Show when={statusRow()}>
210
+ <text height={1} wrapMode="none" truncate fg={warning()} onMouseDown={leftClick(props.focus)}>
211
+ {statusLabel()}
212
+ </text>
213
+ </Show>
214
+ </box>
215
+ )
216
+ }
@@ -0,0 +1,90 @@
1
+ import type { CountColumns } from "./presentation"
2
+
3
+ /** The tree never gets narrower than this when the dialog has room. */
4
+ export const treeMinWidth = 18
5
+ /** The Diff pane never gets narrower than this when the dialog has room. */
6
+ export const detailMinWidth = 28
7
+ /** Cells taken by the vertical divider between both panes. */
8
+ export const splitterWidth = 1
9
+ /** Representative filename width used by the automatic layout. */
10
+ export const nameSampleWidth = 0.8
11
+ const minimumNameWidth = 6
12
+
13
+ export type TreeMetrics = {
14
+ /** Display cell widths of every row name in the full, uncollapsed tree. */
15
+ names: readonly number[]
16
+ /** Nesting depth in levels; one level costs two indent cells. */
17
+ depth: number
18
+ }
19
+
20
+ export type CountColumnsLike = Pick<CountColumns, "added" | "removed">
21
+
22
+ export function columnsWidth(columns: CountColumnsLike) {
23
+ return columns.added + columns.removed + Number(columns.added > 0 && columns.removed > 0)
24
+ }
25
+
26
+ function sample(values: readonly number[], percentile: number) {
27
+ if (!values.length) return 0
28
+ const sorted = values.toSorted((a, b) => a - b)
29
+ return sorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * percentile))]!
30
+ }
31
+
32
+ function indentWidth(depth: number, content: number) {
33
+ // Explorer caps indentation too; it must not crowd out the counts.
34
+ return Math.min(Math.max(0, depth) * 2, Math.floor(content / 5))
35
+ }
36
+
37
+ export function splitBounds(width: number) {
38
+ const content = Math.max(0, Math.floor(width))
39
+ const available = Math.max(0, content - splitterWidth)
40
+ if (!available) return { min: 0, max: 0 }
41
+ const min = Math.min(treeMinWidth, available)
42
+ const max = Math.max(min, Math.min(available, available - detailMinWidth))
43
+ return { min, max }
44
+ }
45
+
46
+ export function clampTreeWidth(width: number, content: number, columns?: CountColumnsLike) {
47
+ const bounds = splitBounds(content)
48
+ const stats = columns ? columnsWidth(columns) : 0
49
+ const min = Math.min(bounds.max, Math.max(bounds.min, stats ? stats + 4 : 0))
50
+ if (!Number.isFinite(width)) return min
51
+ return Math.max(min, Math.min(bounds.max, Math.floor(width)))
52
+ }
53
+
54
+ export function autoTreeWidth(input: {
55
+ width: number
56
+ columns: CountColumnsLike
57
+ metrics: TreeMetrics
58
+ }) {
59
+ const content = Math.max(0, Math.floor(input.width))
60
+ const bounds = splitBounds(content)
61
+ if (!content) return 0
62
+ const stats = columnsWidth(input.columns)
63
+ const indent = indentWidth(input.metrics.depth, content)
64
+ const structural = indent + 3 + (stats ? stats + 1 : 0) + minimumNameWidth
65
+ const desired = structural - minimumNameWidth +
66
+ Math.max(minimumNameWidth, sample(input.metrics.names, nameSampleWidth))
67
+ // Keep the suggested 25%-40% range, but never squeeze out the indentation,
68
+ // the fixed count columns or a readable filename.
69
+ const low = Math.min(bounds.max, Math.max(bounds.min, Math.ceil(content * 0.25), structural))
70
+ const high = Math.max(low, Math.min(bounds.max, Math.max(Math.floor(content * 0.4), structural)))
71
+ return Math.max(low, Math.min(high, desired))
72
+ }
73
+
74
+ export function splitLayout(input: {
75
+ width: number
76
+ columns: CountColumnsLike
77
+ metrics: TreeMetrics
78
+ preferred?: number
79
+ }) {
80
+ const content = Math.max(0, Math.floor(input.width))
81
+ if (!content) return { tree: 0, detail: 0, splitter: 0 }
82
+ const tree = input.preferred && input.preferred > 0
83
+ ? clampTreeWidth(input.preferred, content, input.columns)
84
+ : autoTreeWidth(input)
85
+ return {
86
+ tree,
87
+ splitter: splitterWidth,
88
+ detail: Math.max(0, content - tree - splitterWidth),
89
+ }
90
+ }