Repository navigation
Expand file tree
/
Copy pathpatch-diff.tsx
More file actions
211 lines (202 loc) · 7.73 KB
/
Copy pathpatch-diff.tsx
File metadata and controls
211 lines (202 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/** @jsxImportSource @opentui/solid */
import {
BoxRenderable,
CodeRenderable,
DiffRenderable,
getTreeSitterClient,
type ColorInput,
type DiffGutterOptions,
type OnHighlightCallback,
type Renderable,
type ScrollBoxRenderable,
type SimpleHighlight,
} from "@opentui/core"
import type { JSX } from "@opentui/solid"
import { useRenderer } from "@opentui/solid"
import { batch, createMemo, createSignal, For, onCleanup, Show, splitProps } from "solid-js"
import { splitAddedPatch, splitPatchHunks, type AddedPatchChunk } from "../util/diff"
export interface PatchDiffRef {
readonly hunks: () => readonly (DiffRenderable | BoxRenderable)[]
}
// Smaller patches render fine as a single DiffRenderable; only split files large enough to stall the TUI.
const VIRTUAL_MIN_LINES = 3000
const VIRTUAL_CHUNK_LINES = 128
type Props = Omit<JSX.IntrinsicElements["diff"], "diff" | "lineNumberBg" | "ref"> & {
diff: string
hunkFg: ColorInput
lineNumberBg: ColorInput
ref?: (value: PatchDiffRef) => void
scroll?: () => ScrollBoxRenderable | undefined
/** Extra gutter columns before the line numbers, painted in each row's color. */
gutterPadding?: number
}
export function PatchDiff(props: Props) {
const [local, diffProps] = splitProps(props, ["diff", "hunkFg", "lineNumberBg", "ref", "scroll", "gutterPadding"])
const hunks = createMemo(() => splitPatchHunks(local.diff))
const chunks = createMemo(() => {
if (!local.scroll) return
const result = splitAddedPatch(local.diff, VIRTUAL_CHUNK_LINES)
return result && lineCount(result) > VIRTUAL_MIN_LINES ? result : undefined
})
// Hunks, virtual chunks and split sides each have their own gutter; give them all one width so the code lines up.
const gutter = createMemo((): DiffGutterOptions => {
const items = chunks()
const paddingLeft = 1 + (local.gutterPadding ?? 0)
if (items) return { paddingLeft, minDigits: String(lineCount(items)).length }
const last = [...local.diff.matchAll(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm)].flatMap((match) => [
Number(match[1]) + Number(match[2] ?? 1) - 1,
Number(match[3]) + Number(match[4] ?? 1) - 1,
])
return { paddingLeft, minDigits: String(Math.max(1, ...last)).length }
})
const nodes = new Map<number, DiffRenderable>()
let virtualRoot: BoxRenderable | undefined
local.ref?.({
hunks: () => {
if (chunks()) return virtualRoot && !virtualRoot.isDestroyed ? [virtualRoot] : []
return [...nodes.entries()]
.sort(([left], [right]) => left - right)
.map(([, node]) => node)
.filter((node) => !node.isDestroyed)
},
})
const register = (index: number, node: DiffRenderable) => {
nodes.set(index, node)
onCleanup(() => nodes.delete(index))
}
return (
<Show
when={chunks()}
fallback={
<For each={hunks()}>
{(hunk, index) => (
<>
<Show when={index() > 0}>
<box width="100%" height={1} backgroundColor={local.lineNumberBg}>
<text fg={local.hunkFg} bg={local.lineNumberBg}>
{` ${hunk.header ?? ""}`}
</text>
</box>
</Show>
<diff
{...diffProps}
ref={(node: DiffRenderable) => register(index(), node)}
diff={hunk.patch}
minHeight={hunk.rows}
lineNumberBg={local.lineNumberBg}
gutter={gutter()}
/>
</>
)}
</For>
}
>
{(items) => (
<VirtualAddedPatch
chunks={items()}
scroll={local.scroll!}
diffProps={diffProps}
lineNumberBg={local.lineNumberBg}
gutter={gutter()}
register={register}
registerRoot={(root) => (virtualRoot = root)}
/>
)}
</Show>
)
}
// Chunks render without wrapping so each one is exactly `rows` tall. Offscreen chunks become fixed-height
// placeholders, and the chunks overlapping the viewport (plus one on each side) follow from the scroll offset.
function VirtualAddedPatch(props: {
chunks: readonly AddedPatchChunk[]
scroll: () => ScrollBoxRenderable | undefined
diffProps: Omit<JSX.IntrinsicElements["diff"], "diff" | "lineNumberBg" | "ref">
lineNumberBg: ColorInput
gutter: DiffGutterOptions
register: (index: number, node: DiffRenderable) => void
registerRoot: (root: BoxRenderable) => void
}) {
const renderer = useRenderer()
const [first, setFirst] = createSignal(0)
const [last, setLast] = createSignal(0)
// A chunk is not valid source on its own (a slice of a JSON object parses as an error), so highlight
// the whole file once and give each chunk its slice of the result.
const contents = createMemo(() => props.chunks.map((chunk) => chunk.lines.map((line) => line.slice(1)).join("\n")))
const offsets = createMemo(() =>
contents().map((_, index, all) => all.slice(0, index).reduce((sum, content) => sum + content.length + 1, 0)),
)
const fileHighlights = createMemo(() => {
const filetype = props.diffProps.filetype
if (!filetype) return
return (
getTreeSitterClient()
.highlightOnce(contents().join("\n"), filetype)
.then((result) => result.highlights)
// Rejects when the renderer tears down the client mid-parse; chunks then keep their own highlights.
.catch(() => undefined)
)
})
const chunkHighlights =
(index: number): OnHighlightCallback =>
async () => {
const all = await fileHighlights()
if (!all) return
const start = offsets()[index]
const end = start + contents()[index].length
return all.flatMap((highlight): SimpleHighlight[] =>
highlight[0] < end && highlight[1] > start
? [[Math.max(highlight[0], start) - start, Math.min(highlight[1], end) - start, highlight[2], highlight[3]]]
: [],
)
}
return (
<box
width="100%"
ref={(root: BoxRenderable) => {
props.registerRoot(root)
root.onLifecyclePass = () => {
const scroll = props.scroll()
if (!scroll) return
// ScrollBox's scroll position is not a Solid signal; observe it during the render pass.
const top = scroll.scrollTop - (root.y - scroll.content.y)
batch(() => {
setFirst(Math.floor(top / VIRTUAL_CHUNK_LINES))
setLast(Math.floor((top + scroll.viewport.height) / VIRTUAL_CHUNK_LINES))
})
}
renderer.registerLifecyclePass(root)
onCleanup(() => renderer.unregisterLifecyclePass(root))
}}
>
<For each={props.chunks}>
{(chunk, index) => (
<Show when={index() >= first() - 1 && index() <= last() + 1} fallback={<box height={chunk.rows} />}>
<diff
{...props.diffProps}
ref={(node: DiffRenderable) => {
props.register(index(), node)
// DiffRenderable creates its CodeRenderable after ref runs; setting onHighlight re-highlights.
queueMicrotask(() => {
const code = findCode(node)
if (code) code.onHighlight = chunkHighlights(index())
})
}}
diff={chunk.patch}
wrapMode="none"
height={chunk.rows}
lineNumberBg={props.lineNumberBg}
gutter={props.gutter}
/>
</Show>
)}
</For>
</box>
)
}
function findCode(node: Renderable): CodeRenderable | undefined {
if (node instanceof CodeRenderable) return node
return node.getChildren().reduce<CodeRenderable | undefined>((found, child) => found ?? findCode(child), undefined)
}
function lineCount(chunks: readonly AddedPatchChunk[]) {
return chunks.reduce((count, chunk) => count + chunk.rows, 0)
}