@carlosstenzel/opencode-git-sidebar 0.1.1 → 0.1.3
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.
- package/README-pt-br.md +120 -0
- package/README.md +19 -5
- package/dist/gui-experimental.cjs +129 -7
- package/docs/images/git-sidebar-diff.svg +58 -0
- package/docs/images/git-sidebar-files.svg +99 -0
- package/docs/images/git-sidebar-overview.svg +79 -0
- package/package.json +8 -2
- package/src/commit-selected.ts +165 -0
- package/src/git-exec.ts +105 -0
- package/src/git-parse.ts +121 -0
- package/src/git-read.ts +225 -0
- package/src/graph-canvas.tsx +174 -0
- package/src/graph-theme.ts +27 -0
- package/src/graph.ts +191 -0
- package/src/gui-load.ts +151 -0
- package/src/gui.tsx +436 -149
- package/src/index.ts +38 -342
- package/src/rpc.ts +4 -1
- package/src/style.ts +125 -3
- package/src/ui-helpers.ts +43 -0
package/src/git-read.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { lstat, readFile } from "node:fs/promises"
|
|
2
|
+
import { basename, join } from "node:path"
|
|
3
|
+
import { diffBase, repoRoot, runOptional, runRaw } from "./git-exec.js"
|
|
4
|
+
import {
|
|
5
|
+
parseCommitLog,
|
|
6
|
+
parseDiffTreeNames,
|
|
7
|
+
parseNumstat,
|
|
8
|
+
parseStatus,
|
|
9
|
+
parseTrack,
|
|
10
|
+
type Change,
|
|
11
|
+
type CommitRecord,
|
|
12
|
+
type Stat,
|
|
13
|
+
} from "./git-parse.js"
|
|
14
|
+
|
|
15
|
+
export type Status = {
|
|
16
|
+
repo: string
|
|
17
|
+
branch: string
|
|
18
|
+
dirty: boolean
|
|
19
|
+
changes: number
|
|
20
|
+
ahead: number
|
|
21
|
+
behind: number
|
|
22
|
+
upstream: string
|
|
23
|
+
}
|
|
24
|
+
export type Branch = {
|
|
25
|
+
name: string
|
|
26
|
+
current: boolean
|
|
27
|
+
upstream: string
|
|
28
|
+
ahead: number
|
|
29
|
+
behind: number
|
|
30
|
+
hash: string
|
|
31
|
+
subject: string
|
|
32
|
+
date: string
|
|
33
|
+
}
|
|
34
|
+
export type Commit = CommitRecord & { files: string[] }
|
|
35
|
+
|
|
36
|
+
const DIFF_ARGS = ["-c", "core.quotePath=false", "diff", "--no-color", "--no-ext-diff"]
|
|
37
|
+
const UNTRACKED_STAT_FILES = 400
|
|
38
|
+
const UNTRACKED_STAT_BYTES = 512 * 1024
|
|
39
|
+
|
|
40
|
+
function emptyStatus(): Status {
|
|
41
|
+
return { repo: "", branch: "", dirty: false, changes: 0, ahead: 0, behind: 0, upstream: "" }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function counts(upstream: string, ref: string, directory: string, signal?: AbortSignal) {
|
|
45
|
+
const raw = await runOptional(
|
|
46
|
+
"git",
|
|
47
|
+
["rev-list", "--left-right", "--count", `${upstream}...${ref}`],
|
|
48
|
+
directory,
|
|
49
|
+
{ signal },
|
|
50
|
+
)
|
|
51
|
+
const [behind, ahead] = raw.split(/\s+/).map((value) => Number(value) || 0)
|
|
52
|
+
return { ahead, behind }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Lines an untracked file would add. Undefined when it is not a regular file or is too large to count cheaply.
|
|
56
|
+
async function untrackedStat(file: string): Promise<Stat | undefined> {
|
|
57
|
+
try {
|
|
58
|
+
const info = await lstat(file)
|
|
59
|
+
if (!info.isFile() || info.size > UNTRACKED_STAT_BYTES) return undefined
|
|
60
|
+
const bytes = await readFile(file)
|
|
61
|
+
if (bytes.subarray(0, 8000).includes(0)) return { additions: 0, deletions: 0, binary: true }
|
|
62
|
+
let lines = 0
|
|
63
|
+
for (const byte of bytes) if (byte === 10) lines++
|
|
64
|
+
if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) lines++
|
|
65
|
+
return { additions: lines, deletions: 0, binary: false }
|
|
66
|
+
} catch {
|
|
67
|
+
return undefined
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Stats of the untracked entries of `git status`: a file, or a directory git lists as one entry (`dir/`).
|
|
72
|
+
async function untrackedStats(entries: Change[], root: string, signal?: AbortSignal) {
|
|
73
|
+
const stats = new Map<string, Stat>()
|
|
74
|
+
if (!entries.length) return stats
|
|
75
|
+
const raw = await runRaw("git", ["ls-files", "--others", "--exclude-standard", "-z"], root, { signal })
|
|
76
|
+
const files = raw.split("\0").filter(Boolean)
|
|
77
|
+
if (files.length > UNTRACKED_STAT_FILES) return stats
|
|
78
|
+
const counted = new Map<string, Stat | undefined>()
|
|
79
|
+
for (let start = 0; start < files.length; start += 16) {
|
|
80
|
+
const batch = files.slice(start, start + 16)
|
|
81
|
+
const results = await Promise.all(batch.map((file) => untrackedStat(join(root, file))))
|
|
82
|
+
batch.forEach((file, index) => counted.set(file, results[index]))
|
|
83
|
+
}
|
|
84
|
+
for (const entry of entries) {
|
|
85
|
+
const inside = entry.path.endsWith("/") ? files.filter((file) => file.startsWith(entry.path)) : [entry.path]
|
|
86
|
+
const parts = inside.map((file) => counted.get(file))
|
|
87
|
+
if (!parts.length || parts.some((part) => !part)) continue
|
|
88
|
+
const known = parts as Stat[]
|
|
89
|
+
stats.set(entry.path, {
|
|
90
|
+
additions: known.reduce((sum, part) => sum + part.additions, 0),
|
|
91
|
+
deletions: 0,
|
|
92
|
+
binary: known.every((part) => part.binary),
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
return stats
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function readStatus(directory: string, signal?: AbortSignal): Promise<Status> {
|
|
99
|
+
const inside = await runOptional("git", ["rev-parse", "--is-inside-work-tree"], directory, { signal })
|
|
100
|
+
if (inside !== "true") return emptyStatus()
|
|
101
|
+
|
|
102
|
+
const root = await runOptional("git", ["rev-parse", "--show-toplevel"], directory, { signal })
|
|
103
|
+
const branch =
|
|
104
|
+
(await runOptional("git", ["symbolic-ref", "--short", "-q", "HEAD"], directory, { signal })) ||
|
|
105
|
+
"(desanexado)"
|
|
106
|
+
const porcelain = await runOptional("git", ["status", "--porcelain"], directory, { signal })
|
|
107
|
+
const changes = porcelain ? porcelain.split("\n").filter(Boolean).length : 0
|
|
108
|
+
const upstream = await runOptional(
|
|
109
|
+
"git",
|
|
110
|
+
["rev-parse", "--abbrev-ref", "@{upstream}"],
|
|
111
|
+
directory,
|
|
112
|
+
{ signal },
|
|
113
|
+
)
|
|
114
|
+
const { ahead, behind } = upstream
|
|
115
|
+
? await counts(upstream, "HEAD", directory, signal)
|
|
116
|
+
: { ahead: 0, behind: 0 }
|
|
117
|
+
return {
|
|
118
|
+
repo: root ? basename(root) : basename(directory),
|
|
119
|
+
branch,
|
|
120
|
+
dirty: changes > 0,
|
|
121
|
+
changes,
|
|
122
|
+
ahead,
|
|
123
|
+
behind,
|
|
124
|
+
upstream,
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function readChanges(directory: string, signal?: AbortSignal): Promise<Change[]> {
|
|
129
|
+
// `-z` keeps paths as they are (no quoting) and `runRaw` keeps the leading space of an unstaged ` M` entry.
|
|
130
|
+
const raw = await runRaw("git", ["status", "--porcelain", "-z"], directory, { signal })
|
|
131
|
+
const changes = parseStatus(raw)
|
|
132
|
+
if (!changes.length) return changes
|
|
133
|
+
const root = await repoRoot(directory, signal)
|
|
134
|
+
const base = await diffBase(root, signal)
|
|
135
|
+
const [tracked, untracked] = await Promise.all([
|
|
136
|
+
runRaw("git", [...DIFF_ARGS, "--numstat", "-z", "-M", base, "--"], root, { signal }).then(parseNumstat),
|
|
137
|
+
untrackedStats(
|
|
138
|
+
changes.filter((change) => change.status === "??"),
|
|
139
|
+
root,
|
|
140
|
+
signal,
|
|
141
|
+
),
|
|
142
|
+
])
|
|
143
|
+
return changes.map((change): Change => ({
|
|
144
|
+
...change,
|
|
145
|
+
...(change.status === "??" ? untracked.get(change.path) : tracked.get(change.path)),
|
|
146
|
+
}))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export async function readBranches(directory: string, limit?: number, signal?: AbortSignal): Promise<Branch[]> {
|
|
150
|
+
const current = await runOptional("git", ["rev-parse", "--abbrev-ref", "HEAD"], directory, { signal })
|
|
151
|
+
const format =
|
|
152
|
+
"%(refname:short)\t%(objectname:short)\t%(upstream:short)\t%(contents:subject)\t%(committerdate:iso-strict)\t%(upstream:track)"
|
|
153
|
+
const local = await runRaw(
|
|
154
|
+
"git",
|
|
155
|
+
["for-each-ref", `--format=${format}`, "refs/heads"],
|
|
156
|
+
directory,
|
|
157
|
+
{ signal, env: { LC_ALL: "C" } },
|
|
158
|
+
)
|
|
159
|
+
const remote = await runRaw(
|
|
160
|
+
"git",
|
|
161
|
+
["for-each-ref", `--format=${format}`, "refs/remotes"],
|
|
162
|
+
directory,
|
|
163
|
+
{ signal, env: { LC_ALL: "C" } },
|
|
164
|
+
)
|
|
165
|
+
const lines = [local, remote].filter(Boolean).join("\n").split("\n").filter(Boolean)
|
|
166
|
+
const result: Branch[] = []
|
|
167
|
+
for (const line of lines) {
|
|
168
|
+
const [name, hash, upstream, subject, date, track] = line.split("\t")
|
|
169
|
+
if (!name || name.endsWith("/HEAD")) continue
|
|
170
|
+
const { ahead, behind } = parseTrack(track ?? "")
|
|
171
|
+
result.push({
|
|
172
|
+
name,
|
|
173
|
+
current: name === current,
|
|
174
|
+
upstream: upstream || "",
|
|
175
|
+
ahead,
|
|
176
|
+
behind,
|
|
177
|
+
hash: hash || "",
|
|
178
|
+
subject: subject || "",
|
|
179
|
+
date: date || "",
|
|
180
|
+
})
|
|
181
|
+
if (result.length >= (limit || 60)) break
|
|
182
|
+
}
|
|
183
|
+
return result
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function readCommits(
|
|
187
|
+
directory: string,
|
|
188
|
+
limit?: number,
|
|
189
|
+
signal?: AbortSignal,
|
|
190
|
+
all = false,
|
|
191
|
+
): Promise<Commit[]> {
|
|
192
|
+
const maxCount = `--max-count=${limit || 20}`
|
|
193
|
+
// Topologia de branches: `--all` também arrastaria `refs/stash` e `refs/notes`.
|
|
194
|
+
const allArgs = all ? ["--branches", "--remotes", "--tags"] : []
|
|
195
|
+
const raw = await runOptional(
|
|
196
|
+
"git",
|
|
197
|
+
[
|
|
198
|
+
"log",
|
|
199
|
+
...allArgs,
|
|
200
|
+
maxCount,
|
|
201
|
+
// Parents must never be listed before their children, whatever the
|
|
202
|
+
// committer dates say; the lane layout relies on that order.
|
|
203
|
+
"--topo-order",
|
|
204
|
+
"--date=iso-strict",
|
|
205
|
+
// `--decorate=short` vence `log.decorate` do usuário (não neutraliza `log.excludeDecoration`).
|
|
206
|
+
"--decorate=short",
|
|
207
|
+
"--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%ad%x1f%P%x1f%D",
|
|
208
|
+
],
|
|
209
|
+
directory,
|
|
210
|
+
{ signal },
|
|
211
|
+
)
|
|
212
|
+
const commits = parseCommitLog(raw)
|
|
213
|
+
if (!commits.length) return []
|
|
214
|
+
const filesRaw = await runOptional(
|
|
215
|
+
"git",
|
|
216
|
+
["log", ...allArgs, maxCount, "--topo-order", "--name-only", "-z", "--pretty=format:%H%x00"],
|
|
217
|
+
directory,
|
|
218
|
+
{ signal },
|
|
219
|
+
)
|
|
220
|
+
const filesByCommit = parseDiffTreeNames(filesRaw)
|
|
221
|
+
return commits.map((commit) => ({
|
|
222
|
+
...commit,
|
|
223
|
+
files: filesByCommit.get(commit.hash) ?? [],
|
|
224
|
+
}))
|
|
225
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { createEffect, createMemo, createSignal, For, onCleanup, onMount, type JSX } from "solid-js"
|
|
2
|
+
import { buildEdges, FALLBACK_ROW_HEIGHT, type GraphCommit, type GraphRow } from "./graph.js"
|
|
3
|
+
import { laneColor, laneWidth, laneX } from "./graph-theme.js"
|
|
4
|
+
|
|
5
|
+
const NODE_RADIUS = 3.5
|
|
6
|
+
const STROKE = 2
|
|
7
|
+
|
|
8
|
+
type Measurement = {
|
|
9
|
+
centers: number[]
|
|
10
|
+
height: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function sameCenters(a: number[], b: number[]): boolean {
|
|
14
|
+
return a.length === b.length && a.every((value, index) => Math.abs(value - b[index]) < 0.5)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Draws the whole graph as one SVG layered over the commit list.
|
|
19
|
+
*
|
|
20
|
+
* Dots sit on the measured centre of each `[data-graph-row]`, and every edge
|
|
21
|
+
* links a commit's dot to its parent's dot, so lanes are continuous curves
|
|
22
|
+
* instead of per-row rails. The SVG is absolutely positioned and ignores pointer
|
|
23
|
+
* events: measuring it can never change a row's height, which would otherwise
|
|
24
|
+
* feed the ResizeObserver back into a layout loop.
|
|
25
|
+
*
|
|
26
|
+
* Rows are re-measured on mount, whenever the row/commit list changes, on row
|
|
27
|
+
* or container resize, and on DOM mutations such as expanding a commit's files.
|
|
28
|
+
* The measured signal only updates when a centre actually moved, so the loop
|
|
29
|
+
* settles after one pass.
|
|
30
|
+
*/
|
|
31
|
+
export function GraphCanvas(props: {
|
|
32
|
+
rows: () => GraphRow[]
|
|
33
|
+
commits: () => GraphCommit[]
|
|
34
|
+
lanes: () => number
|
|
35
|
+
target: () => HTMLElement | undefined
|
|
36
|
+
}): JSX.Element {
|
|
37
|
+
const width = () => laneWidth(props.lanes())
|
|
38
|
+
const fallback = (): Measurement => {
|
|
39
|
+
const count = props.rows().length
|
|
40
|
+
return {
|
|
41
|
+
centers: props.rows().map((_, index) => index * FALLBACK_ROW_HEIGHT + FALLBACK_ROW_HEIGHT / 2),
|
|
42
|
+
height: Math.max(count * FALLBACK_ROW_HEIGHT, FALLBACK_ROW_HEIGHT),
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const [measurement, setMeasurement] = createSignal<Measurement>(fallback())
|
|
46
|
+
const edgeList = createMemo(() =>
|
|
47
|
+
buildEdges(props.rows(), props.commits(), measurement().centers, measurement().height),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
let canvas: HTMLDivElement | undefined
|
|
51
|
+
let resize: ResizeObserver | undefined
|
|
52
|
+
let mutations: MutationObserver | undefined
|
|
53
|
+
let watched: HTMLElement[] = []
|
|
54
|
+
|
|
55
|
+
const centerAt = (index: number) =>
|
|
56
|
+
measurement().centers[index] ?? index * FALLBACK_ROW_HEIGHT + FALLBACK_ROW_HEIGHT / 2
|
|
57
|
+
|
|
58
|
+
const rowElements = (): HTMLElement[] => {
|
|
59
|
+
const target = props.target()
|
|
60
|
+
if (!target) return []
|
|
61
|
+
return Array.from(target.querySelectorAll<HTMLElement>("[data-graph-row]"))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const watch = (elements: HTMLElement[]) => {
|
|
65
|
+
if (!resize) return
|
|
66
|
+
if (watched.length === elements.length && watched.every((el, index) => el === elements[index])) return
|
|
67
|
+
for (const element of watched) resize.unobserve(element)
|
|
68
|
+
for (const element of elements) resize.observe(element)
|
|
69
|
+
watched = elements
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const measure = () => {
|
|
73
|
+
// Without ResizeObserver (tests, exotic hosts) keep the synthetic 42px rows.
|
|
74
|
+
if (typeof ResizeObserver === "undefined") return
|
|
75
|
+
const elements = rowElements()
|
|
76
|
+
if (elements.length === 0) return
|
|
77
|
+
|
|
78
|
+
const centers = elements.map((element) => element.offsetTop + element.offsetHeight / 2)
|
|
79
|
+
const last = elements[elements.length - 1]
|
|
80
|
+
const height = last.offsetTop + last.offsetHeight
|
|
81
|
+
const current = measurement()
|
|
82
|
+
if (!sameCenters(current.centers, centers) || Math.abs(current.height - height) >= 0.5) {
|
|
83
|
+
setMeasurement({ centers, height })
|
|
84
|
+
}
|
|
85
|
+
watch(elements)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
onMount(() => {
|
|
89
|
+
if (typeof ResizeObserver === "undefined") return
|
|
90
|
+
resize = new ResizeObserver(measure)
|
|
91
|
+
const target = props.target()
|
|
92
|
+
if (target) resize.observe(target)
|
|
93
|
+
measure()
|
|
94
|
+
|
|
95
|
+
// Expanding a commit inserts its file list as a sibling, which moves every
|
|
96
|
+
// row below without resizing any of them: only a mutation reveals it.
|
|
97
|
+
if (typeof MutationObserver !== "undefined" && target) {
|
|
98
|
+
mutations = new MutationObserver((records) => {
|
|
99
|
+
if (canvas && records.every((record) => canvas!.contains(record.target))) return
|
|
100
|
+
measure()
|
|
101
|
+
})
|
|
102
|
+
mutations.observe(target, { childList: true, subtree: true })
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
createEffect(() => {
|
|
107
|
+
// Track the list so new rows are measured once Solid has written the DOM.
|
|
108
|
+
props.rows()
|
|
109
|
+
props.commits()
|
|
110
|
+
props.lanes()
|
|
111
|
+
measure()
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
onCleanup(() => {
|
|
115
|
+
resize?.disconnect()
|
|
116
|
+
mutations?.disconnect()
|
|
117
|
+
watched = []
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
return (
|
|
121
|
+
<div
|
|
122
|
+
class="gs-graph"
|
|
123
|
+
ref={(element) => (canvas = element)}
|
|
124
|
+
style={{ width: `${width()}px`, height: `${measurement().height}px` }}
|
|
125
|
+
>
|
|
126
|
+
<svg
|
|
127
|
+
width={width()}
|
|
128
|
+
height={measurement().height}
|
|
129
|
+
viewBox={`0 0 ${width()} ${measurement().height}`}
|
|
130
|
+
aria-hidden="true"
|
|
131
|
+
fill="none"
|
|
132
|
+
stroke-linecap="round"
|
|
133
|
+
stroke-linejoin="round"
|
|
134
|
+
>
|
|
135
|
+
<defs>
|
|
136
|
+
<For each={edgeList()}>
|
|
137
|
+
{(edge) => (
|
|
138
|
+
<linearGradient
|
|
139
|
+
id={`gs-edge-${edge.hash}-${edge.parentLane}`}
|
|
140
|
+
gradientUnits="userSpaceOnUse"
|
|
141
|
+
x1={edge.from.x}
|
|
142
|
+
y1={edge.from.y}
|
|
143
|
+
x2={edge.to.x}
|
|
144
|
+
y2={edge.to.y}
|
|
145
|
+
>
|
|
146
|
+
<stop offset="0%" stop-color={laneColor(edge.lane)} />
|
|
147
|
+
<stop offset="100%" stop-color={laneColor(edge.parentLane)} />
|
|
148
|
+
</linearGradient>
|
|
149
|
+
)}
|
|
150
|
+
</For>
|
|
151
|
+
</defs>
|
|
152
|
+
<For each={edgeList()}>
|
|
153
|
+
{(edge) => (
|
|
154
|
+
<path
|
|
155
|
+
d={edge.d}
|
|
156
|
+
stroke={`url(#gs-edge-${edge.hash}-${edge.parentLane})`}
|
|
157
|
+
stroke-width={STROKE}
|
|
158
|
+
/>
|
|
159
|
+
)}
|
|
160
|
+
</For>
|
|
161
|
+
<For each={props.rows()}>
|
|
162
|
+
{(row, index) => (
|
|
163
|
+
<circle
|
|
164
|
+
cx={laneX(row.lane)}
|
|
165
|
+
cy={centerAt(index())}
|
|
166
|
+
r={NODE_RADIUS}
|
|
167
|
+
fill={laneColor(row.lane)}
|
|
168
|
+
/>
|
|
169
|
+
)}
|
|
170
|
+
</For>
|
|
171
|
+
</svg>
|
|
172
|
+
</div>
|
|
173
|
+
)
|
|
174
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// One hue per lane so crossing lines stay readable; each falls back to a colour
|
|
2
|
+
// that works on light and dark panels, and a theme can override the variables.
|
|
3
|
+
// Shared by the legacy per-row gutter and the single graph canvas so both draw
|
|
4
|
+
// the same palette.
|
|
5
|
+
export const LANE_COLORS = [
|
|
6
|
+
"var(--gs-lane-0, #2563eb)",
|
|
7
|
+
"var(--gs-lane-1, #0d9488)",
|
|
8
|
+
"var(--gs-lane-2, #8b5cf6)",
|
|
9
|
+
"var(--gs-lane-3, #c2410c)",
|
|
10
|
+
"var(--gs-lane-4, #db2777)",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
export const MAX_LANES = 5
|
|
14
|
+
export const PITCH = 10
|
|
15
|
+
|
|
16
|
+
export function laneX(lane: number, pitch: number = PITCH): number {
|
|
17
|
+
return Math.min(lane, MAX_LANES - 1) * pitch + pitch / 2
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function laneColor(lane: number): string {
|
|
21
|
+
return LANE_COLORS[lane % LANE_COLORS.length]
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Width reserved for the graph column, capped so a wild row cannot push the text away. */
|
|
25
|
+
export function laneWidth(lanes: number): number {
|
|
26
|
+
return Math.min(lanes, MAX_LANES) * PITCH
|
|
27
|
+
}
|
package/src/graph.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { laneX } from "./graph-theme.js"
|
|
2
|
+
|
|
3
|
+
export type GraphCommit = { hash: string; parents: string[] }
|
|
4
|
+
|
|
5
|
+
export type GraphRow = {
|
|
6
|
+
hash: string
|
|
7
|
+
lane: number
|
|
8
|
+
top: number[]
|
|
9
|
+
bottom: number[]
|
|
10
|
+
parents: number[]
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type Graph = { rows: GraphRow[]; lanes: number }
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Assigns one lane per commit and the geometry hints used by the gutter.
|
|
17
|
+
*
|
|
18
|
+
* `commits` is in `git log` order (newest first). `active` holds, per lane, the
|
|
19
|
+
* hash still waiting for its own row (`null` means the lane is free).
|
|
20
|
+
*
|
|
21
|
+
* A commit keeps the lane where its hash is already waiting, otherwise it takes
|
|
22
|
+
* the first free lane, otherwise it opens a new one. The first parent continues
|
|
23
|
+
* on the node's lane when it is not already waiting elsewhere; any parent that
|
|
24
|
+
* is already active keeps its lane (converging instead of drawing a second line
|
|
25
|
+
* to the same commit), while a new extra parent takes a free lane, else opens
|
|
26
|
+
* one. A lane is released as soon as its hash is consumed and no parent was
|
|
27
|
+
* placed back on it, so a stale hash never pins a lane.
|
|
28
|
+
*/
|
|
29
|
+
export function buildGraph(commits: GraphCommit[]): Graph {
|
|
30
|
+
const active: (string | null)[] = []
|
|
31
|
+
const rows: GraphRow[] = []
|
|
32
|
+
let lanes = 0
|
|
33
|
+
|
|
34
|
+
for (const commit of commits) {
|
|
35
|
+
// Snapshot the lanes that already carry a pending hash before touching the
|
|
36
|
+
// row. Only those lanes have a line entering from the top; a lane allocated
|
|
37
|
+
// for a new tip has nothing above its dot, so it must stay out of `top`.
|
|
38
|
+
const top: number[] = []
|
|
39
|
+
for (let index = 0; index < active.length; index += 1) {
|
|
40
|
+
if (active[index] !== null) top.push(index)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let lane = active.indexOf(commit.hash)
|
|
44
|
+
if (lane < 0) {
|
|
45
|
+
lane = active.indexOf(null)
|
|
46
|
+
if (lane < 0) {
|
|
47
|
+
lane = active.length
|
|
48
|
+
active.push(null)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// The node is consumed here: its lane is free unless a parent lands on it.
|
|
53
|
+
active[lane] = null
|
|
54
|
+
|
|
55
|
+
const parentLanes: number[] = []
|
|
56
|
+
for (let index = 0; index < commit.parents.length; index += 1) {
|
|
57
|
+
const parent = commit.parents[index]
|
|
58
|
+
const existing = active.indexOf(parent)
|
|
59
|
+
let parentLane: number
|
|
60
|
+
|
|
61
|
+
if (existing >= 0) {
|
|
62
|
+
// A lane already points at this parent: converge instead of opening a
|
|
63
|
+
// second line for the same commit.
|
|
64
|
+
parentLane = existing
|
|
65
|
+
} else if (index === 0 && active[lane] === null) {
|
|
66
|
+
// The first parent is a straight continuation of the node's lane.
|
|
67
|
+
parentLane = lane
|
|
68
|
+
active[lane] = parent
|
|
69
|
+
} else {
|
|
70
|
+
parentLane = active.indexOf(null)
|
|
71
|
+
if (parentLane < 0) {
|
|
72
|
+
parentLane = active.length
|
|
73
|
+
active.push(parent)
|
|
74
|
+
} else {
|
|
75
|
+
active[parentLane] = parent
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Repeated parents (never produced by git) must not duplicate a lane.
|
|
80
|
+
if (!parentLanes.includes(parentLane)) parentLanes.push(parentLane)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const bottom: number[] = []
|
|
84
|
+
for (let index = 0; index < active.length; index += 1) {
|
|
85
|
+
if (active[index] !== null) bottom.push(index)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
rows.push({
|
|
89
|
+
hash: commit.hash,
|
|
90
|
+
lane,
|
|
91
|
+
top,
|
|
92
|
+
bottom,
|
|
93
|
+
parents: parentLanes,
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
// Width is the widest column used so far, transient tip lanes included, so
|
|
97
|
+
// the gutter width stays stable while scrolling down the history.
|
|
98
|
+
lanes = Math.max(lanes, lane + 1, ...bottom.map((index) => index + 1))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return { rows, lanes }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export type GraphPoint = { x: number; y: number }
|
|
105
|
+
|
|
106
|
+
export type GraphEdge = {
|
|
107
|
+
hash: string
|
|
108
|
+
/** Lane of the commit, used as the start of the stroke gradient. */
|
|
109
|
+
lane: number
|
|
110
|
+
parentLane: number
|
|
111
|
+
from: GraphPoint
|
|
112
|
+
to: GraphPoint
|
|
113
|
+
/** SVG path data linking the commit dot to its parent dot. */
|
|
114
|
+
d: string
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const FALLBACK_ROW_HEIGHT = 42
|
|
118
|
+
|
|
119
|
+
function fmt(value: number): string {
|
|
120
|
+
return String(Number(value.toFixed(3)))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function edgePath(from: GraphPoint, to: GraphPoint): string {
|
|
124
|
+
const start = `${fmt(from.x)} ${fmt(from.y)}`
|
|
125
|
+
const end = `${fmt(to.x)} ${fmt(to.y)}`
|
|
126
|
+
if (from.x === to.x) return `M ${start} L ${end}`
|
|
127
|
+
// Vertical tangents at both dots: the curve leaves the commit downwards and
|
|
128
|
+
// meets the parent from above, so a chain of edges reads as one smooth lane
|
|
129
|
+
// instead of a hook. `bend` shrinks with short spans to avoid overshooting.
|
|
130
|
+
const dy = to.y - from.y
|
|
131
|
+
const bend = dy <= 0 ? 8 : dy * 0.45
|
|
132
|
+
return `M ${start} C ${fmt(from.x)} ${fmt(from.y + bend)} ${fmt(to.x)} ${fmt(to.y - bend)} ${end}`
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Builds the edges of the whole graph in one pass.
|
|
137
|
+
*
|
|
138
|
+
* Each edge runs from the centre of a commit's row to the centre of its parent's
|
|
139
|
+
* row, so a single canvas can draw long, continuous curves without per-row
|
|
140
|
+
* rails. A parent outside the loaded slice leaves through the bottom border on
|
|
141
|
+
* the lane `GraphRow.parents` reserved for it. `centers` is indexed like `rows`;
|
|
142
|
+
* with no measurements at all there is nothing to place, so it returns no edges
|
|
143
|
+
* rather than emitting NaN coordinates.
|
|
144
|
+
*/
|
|
145
|
+
export function buildEdges(
|
|
146
|
+
rows: { hash: string; lane: number; parents: number[] }[],
|
|
147
|
+
commits: { hash: string; parents: string[] }[],
|
|
148
|
+
centers: number[],
|
|
149
|
+
totalHeight: number,
|
|
150
|
+
): GraphEdge[] {
|
|
151
|
+
if (centers.length === 0) return []
|
|
152
|
+
|
|
153
|
+
const indexByHash = new Map<string, number>()
|
|
154
|
+
rows.forEach((row, index) => indexByHash.set(row.hash, index))
|
|
155
|
+
|
|
156
|
+
const edges: GraphEdge[] = []
|
|
157
|
+
rows.forEach((row, index) => {
|
|
158
|
+
const commit = commits[index]
|
|
159
|
+
if (!commit) return
|
|
160
|
+
|
|
161
|
+
const from: GraphPoint = {
|
|
162
|
+
x: laneX(row.lane),
|
|
163
|
+
y: centers[index] ?? centers[centers.length - 1],
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
commit.parents.forEach((parentHash, parentIndex) => {
|
|
167
|
+
const rowIndex = indexByHash.get(parentHash) ?? -1
|
|
168
|
+
const parentLane = rowIndex >= 0 ? rows[rowIndex].lane : (row.parents[parentIndex] ?? row.lane)
|
|
169
|
+
const to: GraphPoint =
|
|
170
|
+
rowIndex >= 0
|
|
171
|
+
? {
|
|
172
|
+
x: laneX(rows[rowIndex].lane),
|
|
173
|
+
y: centers[rowIndex] ?? totalHeight,
|
|
174
|
+
}
|
|
175
|
+
: { x: laneX(parentLane), y: totalHeight }
|
|
176
|
+
|
|
177
|
+
edges.push({
|
|
178
|
+
hash: row.hash,
|
|
179
|
+
lane: row.lane,
|
|
180
|
+
parentLane,
|
|
181
|
+
from,
|
|
182
|
+
to,
|
|
183
|
+
d: edgePath(from, to),
|
|
184
|
+
})
|
|
185
|
+
})
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
return edges
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export { FALLBACK_ROW_HEIGHT }
|