@tooee/diff 0.7.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.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @tooee/diff
2
+
3
+ Unified and split diff rendering for Tooee, drawn by [Hunk](https://github.com/modem-dev/hunk)'s
4
+ public OpenTUI primitives (`hunkdiff/opentui`).
5
+
6
+ Part of the [Tooee](https://github.com/gingerhendrix/tooee) monorepo. See the main repo for
7
+ documentation.
8
+
9
+ ## What it provides
10
+
11
+ - `buildDiffModel(patch)` — parses unified patch text into navigation rows: one row per file
12
+ header and one per `@@` hunk, each carrying its own patch text and its span in the original
13
+ patch.
14
+ - `DiffView` — a `row-document` whose rows are those diff rows. The row document stays the only
15
+ scroll owner, so the cursor, search decorations, marks, scroll-follow and mouse routing all keep
16
+ working.
17
+ - `diffCodeBlockRenderer` / `DIFF_CODE_BLOCK_RENDERERS` — a Markdown code-block renderer that
18
+ draws ` ```diff ` and ` ```patch ` fences as Hunk blocks. `@tooee/view` registers it by default.
19
+ - `resolveHunkDiffTheme` — maps a Tooee theme onto the closest bundled Hunk theme.
20
+ - `isDiffPatch` — content sniffing for patch text.
21
+
22
+ `@tooee/diff` is the only package that imports `hunkdiff`. `@tooee/renderers` stays free of it.
23
+
24
+ ## Row model
25
+
26
+ Hunk renders a whole file at a time, but a diff is only pleasant to navigate hunk by hunk. A hunk
27
+ row therefore carries a copy of its file whose `metadata.hunks` is narrowed to a single hunk while
28
+ the whole-file line arrays stay intact — so line numbers and the `··· N unchanged lines ···`
29
+ counts still resolve against the complete file.
30
+
31
+ Files Hunk renders without hunks (binary, too large, untracked) contribute one `body` row instead,
32
+ so the notice Hunk draws for them is still shown.
33
+
34
+ ## Fence options
35
+
36
+ Words after the fence type are read as options; unknown words are ignored.
37
+
38
+ ```diff split nolines wrap
39
+
40
+ | Word | Effect |
41
+ | --------- | ------------------------------------------------------------ |
42
+ | `split` | Side-by-side layout (falls back to stacked below 80 columns) |
43
+ | `nolines` | Hides Hunk's line-number columns |
44
+ | `wrap` | Wraps long lines instead of clipping them |
45
+
46
+ A fence whose body is not a real unified diff — prose-style `+`/`-` bullets, for instance —
47
+ returns `null` and falls back to the default syntax-highlighted code block.
48
+
49
+ ## Known limits
50
+
51
+ - **Line-number column width is per hunk.** Hunk sizes its line-number columns from the hunks it
52
+ is given, and each hunk row is given one hunk, so two hunks of the same file can differ by a
53
+ column when their line numbers differ in digit count. Everything else — collapsed-gap counts,
54
+ content, word-level highlights — matches a whole-file render.
55
+ - **Themes are approximated.** Hunk resolves one of its own bundled palettes by name and accepts
56
+ no custom colour table, so each Tooee theme is mapped to the closest bundled Hunk theme rather
57
+ than reproduced exactly. Unmapped (user) themes fall back to GitHub's palette on the matching
58
+ light/dark side.
59
+ - **Marks are not painted inside hunks.** Row-level decorations (cursor, search, selection, marks)
60
+ paint under the row, but Hunk draws its own backgrounds over most of it, so a mark on a diff row
61
+ reads mainly from the gutter sign.
62
+ - **Diff content is replace-only when streaming.** `ContentChunk`'s `append` does not accept
63
+ `diff`; send the full patch through a `replace` chunk instead.
64
+ - **Peer range.** `hunkdiff@0.18.0` declares `@opentui/core`/`@opentui/react` `^0.4.3`. It runs and
65
+ type-checks against Tooee's `0.5.1`, and Bun resolves it without a warning inside this workspace,
66
+ but a standalone install of `@tooee/diff` may print a peer-dependency warning until Hunk widens
67
+ the range. The version is pinned exactly because Hunk is pre-1.0.
68
+ - **Install weight.** `hunkdiff` declares the `bun` npm package as a runtime dependency and ships a
69
+ prebuilt CLI binary as an optional one, neither of which `hunkdiff/opentui` imports. Adding this
70
+ package grew the local Bun store by roughly 580 MB, of which about 400 MB is the Bun binary and
71
+ its platform variants and 134 MB is `hunkdiff-linux-x64`. Only the ~18 MB `hunkdiff/opentui`
72
+ bundle is actually used. Fixing this needs an upstream packaging change; `bun patch` cannot drop
73
+ a declared dependency from the resolution graph.
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@tooee/diff",
3
+ "version": "0.7.0",
4
+ "description": "Hunk-backed unified/split diff rendering for Tooee",
5
+ "keywords": [
6
+ "cli",
7
+ "diff",
8
+ "opentui",
9
+ "patch",
10
+ "terminal",
11
+ "tui"
12
+ ],
13
+ "homepage": "https://github.com/gingerhendrix/tooee",
14
+ "bugs": "https://github.com/gingerhendrix/tooee/issues",
15
+ "license": "MIT",
16
+ "author": "Gareth Andrew",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/gingerhendrix/tooee.git",
20
+ "directory": "packages/diff"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "src"
25
+ ],
26
+ "type": "module",
27
+ "exports": {
28
+ ".": {
29
+ "import": {
30
+ "@tooee/source": "./src/index.ts",
31
+ "default": "./dist/index.js"
32
+ }
33
+ }
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "scripts": {
39
+ "typecheck": "tsc --noEmit"
40
+ },
41
+ "dependencies": {
42
+ "@tooee/renderers": "0.7.0",
43
+ "@tooee/themes": "0.7.0",
44
+ "hunkdiff": "0.18.0"
45
+ },
46
+ "devDependencies": {
47
+ "@opentui/core": "^0.5.1",
48
+ "@opentui/react": "^0.5.1",
49
+ "@types/bun": "^1.3.10",
50
+ "@types/react": "^19.2.14",
51
+ "typescript": "^5.9.3"
52
+ },
53
+ "peerDependencies": {
54
+ "@opentui/core": "^0.5.1",
55
+ "@opentui/react": "^0.5.1",
56
+ "react": "^18.0.0 || ^19.0.0"
57
+ }
58
+ }
package/src/detect.ts ADDED
@@ -0,0 +1,18 @@
1
+ /** Lines that only appear at the start of a unified diff. */
2
+ const GIT_HEADER = /^diff --git /mu;
3
+ const UNIFIED_HEADERS = /^--- .*\n\+\+\+ /mu;
4
+ const HUNK_HEADER = /^@@ -\d/mu;
5
+
6
+ /**
7
+ * Whether text looks like a unified patch.
8
+ *
9
+ * Used to route extension-less input (stdin, files without a `.patch`/`.diff`
10
+ * suffix) to the diff viewer. A hunk header is required as well as a file
11
+ * header so prose containing a stray `--- ` rule is not mistaken for a diff.
12
+ */
13
+ export const isDiffPatch = function isDiffPatch(text: string): boolean {
14
+ if (!HUNK_HEADER.test(text)) {
15
+ return false;
16
+ }
17
+ return GIT_HEADER.test(text) || UNIFIED_HEADERS.test(text);
18
+ };
@@ -0,0 +1,102 @@
1
+ import { useMemo } from "react";
2
+ import type { ReactNode } from "react";
3
+ import type { HunkDiffLayout } from "hunkdiff/opentui";
4
+ import { CodeBlockChrome } from "@tooee/renderers";
5
+ import type { CodeBlockRenderer, CodeBlockRendererProps } from "@tooee/renderers";
6
+ import { useTheme } from "@tooee/themes";
7
+ import { buildDiffModel } from "./model.js";
8
+ import { DiffRowView, effectiveLayout } from "./diff-view.js";
9
+ import { resolveHunkDiffTheme } from "./theme-map.js";
10
+
11
+ /** Options a fence info string can carry after the fence type. */
12
+ export interface DiffFenceOptions {
13
+ layout: HunkDiffLayout;
14
+ showLineNumbers: boolean;
15
+ wrapLines: boolean;
16
+ }
17
+
18
+ /**
19
+ * Read fence options from the info string, e.g. ```` ```diff split nolines ````.
20
+ *
21
+ * Unknown words are ignored so ordinary info strings (a filename, say) still
22
+ * render.
23
+ */
24
+ export const parseDiffFenceOptions = function parseDiffFenceOptions(
25
+ info: string,
26
+ ): DiffFenceOptions {
27
+ const words = new Set(
28
+ info
29
+ .trim()
30
+ .split(/\s+/u)
31
+ .slice(1)
32
+ .map((word) => word.toLowerCase()),
33
+ );
34
+ return {
35
+ layout: words.has("split") ? "split" : "stack",
36
+ showLineNumbers: !words.has("nolines"),
37
+ wrapLines: words.has("wrap"),
38
+ };
39
+ };
40
+
41
+ /**
42
+ * Renders ```` ```diff ```` and ```` ```patch ```` fences as Hunk diff blocks.
43
+ *
44
+ * The fence stays one Markdown block, so the document cursor, search and copy
45
+ * still treat it as a unit over the raw fence text; only its drawing changes.
46
+ * Fence bodies that are not parseable unified diffs return `null`, which falls
47
+ * back to the default syntax-highlighted code block — today's behaviour.
48
+ */
49
+ const DiffCodeBlock = function DiffCodeBlock({
50
+ text,
51
+ info,
52
+ width,
53
+ indent,
54
+ }: CodeBlockRendererProps): ReactNode {
55
+ const { theme, name: themeName } = useTheme();
56
+ const model = useMemo(() => {
57
+ try {
58
+ return buildDiffModel(text);
59
+ } catch {
60
+ return null;
61
+ }
62
+ }, [text]);
63
+ const options = useMemo(() => parseDiffFenceOptions(info), [info]);
64
+
65
+ // A ```diff fence is often prose-style +/- lines with no hunk headers. Only
66
+ // real unified diffs render as Hunk blocks; the rest fall back.
67
+ if (!model || !model.rows.some((row) => row.kind === "hunk")) {
68
+ return null;
69
+ }
70
+
71
+ const hunkTheme = resolveHunkDiffTheme(themeName, theme);
72
+ const blockWidth = Math.max(1, width);
73
+ // A single-file fence needs no file header: the fence is the file.
74
+ const rows =
75
+ model.files.length > 1 ? model.rows : model.rows.filter((row) => row.kind !== "file");
76
+
77
+ return (
78
+ <CodeBlockChrome theme={theme} indent={indent}>
79
+ {rows.map(
80
+ (row): ReactNode => (
81
+ <DiffRowView
82
+ key={row.key}
83
+ row={row}
84
+ width={blockWidth}
85
+ theme={hunkTheme}
86
+ layout={effectiveLayout(options.layout, blockWidth)}
87
+ showHunkLineNumbers={options.showLineNumbers}
88
+ wrapLines={options.wrapLines}
89
+ />
90
+ ),
91
+ )}
92
+ </CodeBlockChrome>
93
+ );
94
+ };
95
+
96
+ export const diffCodeBlockRenderer: CodeBlockRenderer = DiffCodeBlock;
97
+
98
+ /** Fence types `diffCodeBlockRenderer` is registered for. */
99
+ export const DIFF_CODE_BLOCK_RENDERERS: Record<string, CodeBlockRenderer> = {
100
+ diff: diffCodeBlockRenderer,
101
+ patch: diffCodeBlockRenderer,
102
+ };
@@ -0,0 +1,166 @@
1
+ import { useMemo } from "react";
2
+ import type { ReactNode } from "react";
3
+ import { useTerminalDimensions } from "@opentui/react";
4
+ import { HunkDiffBody, HunkDiffFileHeader } from "hunkdiff/opentui";
5
+ import type { HunkDiffLayout, HunkDiffThemeName } from "hunkdiff/opentui";
6
+ import { useTheme } from "@tooee/themes";
7
+ import {
8
+ DEFAULT_SIGN_COLUMN_WIDTH,
9
+ computeRowDocumentGutterWidth,
10
+ useGutterPalette,
11
+ } from "@tooee/renderers";
12
+ import type { DocumentBindings } from "@tooee/renderers";
13
+ import "@tooee/renderers/row-document";
14
+ import type { DiffRow } from "./model.js";
15
+ import { resolveHunkDiffTheme } from "./theme-map.js";
16
+
17
+ /**
18
+ * Narrowest content width a split layout stays readable at. Below it, split
19
+ * falls back to stack so a narrow terminal shows whole lines instead of two
20
+ * unusable columns.
21
+ */
22
+ export const MIN_SPLIT_WIDTH = 80;
23
+
24
+ /** Columns held back from the measured width for the scrollbar and right edge. */
25
+ const SCROLLBAR_RESERVE = 2;
26
+
27
+ export interface DiffRenderOptions {
28
+ layout?: HunkDiffLayout;
29
+ /** Line-number columns inside each hunk (Hunk's own gutter). */
30
+ showHunkLineNumbers?: boolean;
31
+ showHunkHeaders?: boolean;
32
+ wrapLines?: boolean;
33
+ horizontalOffset?: number;
34
+ /** Word-level intra-line highlighting. */
35
+ highlight?: boolean;
36
+ tabWidth?: number;
37
+ /** Overrides the theme derived from the active Tooee theme. */
38
+ theme?: HunkDiffThemeName;
39
+ }
40
+
41
+ export interface DiffRowViewProps extends DiffRenderOptions {
42
+ row: DiffRow;
43
+ width: number;
44
+ theme: HunkDiffThemeName;
45
+ /** Draws Hunk's selected-hunk styling under the document cursor. */
46
+ active?: boolean;
47
+ }
48
+
49
+ /** Split falls back to stack when the content area is too narrow for two columns. */
50
+ export const effectiveLayout = function effectiveLayout(
51
+ layout: HunkDiffLayout | undefined,
52
+ width: number,
53
+ ): HunkDiffLayout {
54
+ return layout === "split" && width < MIN_SPLIT_WIDTH ? "stack" : (layout ?? "stack");
55
+ };
56
+
57
+ /**
58
+ * One diff row. File rows render Hunk's compact header; hunk and body rows
59
+ * render a Hunk body — for hunk rows the file model is already narrowed to a
60
+ * single hunk, so exactly one hunk is drawn.
61
+ */
62
+ export const DiffRowView = function DiffRowView({
63
+ row,
64
+ width,
65
+ theme,
66
+ active = false,
67
+ layout,
68
+ showHunkLineNumbers = true,
69
+ showHunkHeaders = true,
70
+ wrapLines = false,
71
+ horizontalOffset = 0,
72
+ highlight = true,
73
+ tabWidth,
74
+ }: DiffRowViewProps): ReactNode {
75
+ if (row.kind === "file") {
76
+ return <HunkDiffFileHeader file={row.file} width={width} theme={theme} />;
77
+ }
78
+
79
+ return (
80
+ <HunkDiffBody
81
+ file={row.file}
82
+ width={width}
83
+ theme={theme}
84
+ layout={effectiveLayout(layout, width)}
85
+ showLineNumbers={showHunkLineNumbers}
86
+ showHunkHeaders={showHunkHeaders}
87
+ wrapLines={wrapLines}
88
+ horizontalOffset={horizontalOffset}
89
+ highlight={highlight}
90
+ tabWidth={tabWidth}
91
+ selectedHunkIndex={active && row.kind === "hunk" ? 0 : undefined}
92
+ />
93
+ );
94
+ };
95
+
96
+ export interface DiffViewProps extends DiffRenderOptions {
97
+ rows: readonly DiffRow[];
98
+ /** Controller bindings: scroll follow, decorations and row mouse handling. */
99
+ document?: DocumentBindings;
100
+ /** Row-document gutter (Tooee's row numbers), not Hunk's line numbers. */
101
+ showLineNumbers?: boolean;
102
+ /** Row index under the cursor, so the active hunk can be styled. */
103
+ activeIndex?: number | null;
104
+ /** Overrides the measured content width; mainly for tests. */
105
+ width?: number;
106
+ }
107
+
108
+ /**
109
+ * The scrolling diff document: one `row-document` row per file header and per
110
+ * hunk, each drawn by Hunk.
111
+ *
112
+ * The row document is the single scroll owner — Hunk's public primitives bring
113
+ * no scrolling of their own — so the cursor, search decorations, marks and
114
+ * scroll-follow all keep working over diff rows.
115
+ */
116
+ export const DiffView = function DiffView({
117
+ rows,
118
+ document,
119
+ showLineNumbers = true,
120
+ activeIndex = null,
121
+ width,
122
+ ...render
123
+ }: DiffViewProps): ReactNode {
124
+ const { theme, name: themeName } = useTheme();
125
+ const palette = useGutterPalette();
126
+ const { width: terminalWidth } = useTerminalDimensions();
127
+
128
+ const gutterWidth = useMemo(
129
+ () =>
130
+ computeRowDocumentGutterWidth({
131
+ rowCount: rows.length,
132
+ showLineNumbers,
133
+ signColumnWidth: DEFAULT_SIGN_COLUMN_WIDTH,
134
+ }),
135
+ [rows.length, showLineNumbers],
136
+ );
137
+ const contentWidth = Math.max(1, width ?? terminalWidth - gutterWidth - SCROLLBAR_RESERVE);
138
+
139
+ const hunkTheme = render.theme ?? resolveHunkDiffTheme(themeName, theme);
140
+
141
+ return (
142
+ <row-document
143
+ ref={document?.ref}
144
+ showLineNumbers={showLineNumbers}
145
+ palette={palette}
146
+ decorations={document?.decorations}
147
+ signColumnWidth={DEFAULT_SIGN_COLUMN_WIDTH}
148
+ style={{ flexGrow: 1 }}
149
+ onMouseDown={document?.onMouseDown}
150
+ >
151
+ {rows.map(
152
+ (row, index): ReactNode => (
153
+ <box key={row.key}>
154
+ <DiffRowView
155
+ {...render}
156
+ row={row}
157
+ width={contentWidth}
158
+ theme={hunkTheme}
159
+ active={index === activeIndex}
160
+ />
161
+ </box>
162
+ ),
163
+ )}
164
+ </row-document>
165
+ );
166
+ };
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ export { buildDiffModel, diffRowAdapter, scanPatchSections, countHunkDiffStats } from "./model.js";
2
+ export type { DiffModel, DiffRow, DiffRowKind } from "./model.js";
3
+ export { DiffView, DiffRowView, effectiveLayout, MIN_SPLIT_WIDTH } from "./diff-view.js";
4
+ export type { DiffViewProps, DiffRowViewProps, DiffRenderOptions } from "./diff-view.js";
5
+ export {
6
+ diffCodeBlockRenderer,
7
+ parseDiffFenceOptions,
8
+ DIFF_CODE_BLOCK_RENDERERS,
9
+ } from "./diff-code-block.js";
10
+ export type { DiffFenceOptions } from "./diff-code-block.js";
11
+ export { resolveHunkDiffTheme, isLightBackground, HUNK_THEME_MAP } from "./theme-map.js";
12
+ export type { HunkThemePair } from "./theme-map.js";
13
+ export { isDiffPatch } from "./detect.js";
14
+ export type {
15
+ HunkDiffFile,
16
+ HunkDiffLayout,
17
+ HunkDiffStats,
18
+ HunkDiffThemeName,
19
+ } from "hunkdiff/opentui";
package/src/model.ts ADDED
@@ -0,0 +1,247 @@
1
+ import { createHunkDiffFilesFromPatch } from "hunkdiff/opentui";
2
+ import type { HunkDiffFile, HunkDiffFileInput, HunkDiffStats } from "hunkdiff/opentui";
3
+ import { SourceIndex } from "@tooee/renderers";
4
+ import type { DocumentRowSource } from "@tooee/renderers";
5
+
6
+ /**
7
+ * What a navigation row stands for.
8
+ *
9
+ * - `file` — the file's header line (path, rename arrow, stats).
10
+ * - `hunk` — one `@@` hunk of a file.
11
+ * - `body` — a file Hunk renders without hunks (binary, too large, untracked);
12
+ * the whole file model is handed to the body renderer so it can draw its
13
+ * own notice.
14
+ */
15
+ export type DiffRowKind = "file" | "hunk" | "body";
16
+
17
+ export interface DiffRow {
18
+ kind: DiffRowKind;
19
+ /** Stable identity across re-parses of the same patch. */
20
+ key: string;
21
+ /** Id of the owning file in the parsed model. */
22
+ fileId: string;
23
+ fileIndex: number;
24
+ /** Hunk position within the file; `-1` for `file` and `body` rows. */
25
+ hunkIndex: number;
26
+ /**
27
+ * The model handed to Hunk for this row. `hunk` rows carry a copy of the
28
+ * owning file whose metadata is narrowed to a single hunk, so Hunk renders
29
+ * exactly one hunk while still resolving line content and collapsed-gap
30
+ * counts against the complete file.
31
+ */
32
+ file: HunkDiffFileInput;
33
+ /** The owning file, unnarrowed. */
34
+ parent: HunkDiffFile;
35
+ /** Patch text for this row — the unit search and copy work in. */
36
+ text: string;
37
+ /** Provenance in the original patch text, or `null` when it cannot be resolved. */
38
+ source: DocumentRowSource | null;
39
+ }
40
+
41
+ export interface DiffModel {
42
+ /** Files as parsed by Hunk, in patch order. */
43
+ files: HunkDiffFile[];
44
+ rows: DiffRow[];
45
+ /** Total additions/deletions across every file. */
46
+ stats: HunkDiffStats;
47
+ /** The patch text the model was built from. */
48
+ patch: string;
49
+ }
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // Patch scanning
53
+ // ---------------------------------------------------------------------------
54
+
55
+ interface PatchSection {
56
+ start: number;
57
+ end: number;
58
+ /** End of the file's header lines: the offset of its first hunk, or `end`. */
59
+ headerEnd: number;
60
+ hunks: { start: number; end: number }[];
61
+ }
62
+
63
+ const GIT_HEADER = "diff --git ";
64
+ const OLD_FILE_HEADER = "--- ";
65
+ const HUNK_HEADER = "@@";
66
+
67
+ /**
68
+ * Split patch text into per-file sections and per-hunk ranges, in offsets over
69
+ * the original string.
70
+ *
71
+ * Hunk's parser does not expose source positions, so provenance is recovered by
72
+ * scanning the same text. Both `diff --git` patches and bare unified diffs are
73
+ * handled: a `--- ` line opens a new section only when it cannot belong to the
74
+ * section already being read.
75
+ */
76
+ export const scanPatchSections = function scanPatchSections(patch: string): PatchSection[] {
77
+ const sections: PatchSection[] = [];
78
+
79
+ const openSection = (start: number): PatchSection => {
80
+ const section: PatchSection = { end: start, headerEnd: start, hunks: [], start };
81
+ sections.push(section);
82
+ return section;
83
+ };
84
+
85
+ let offset = 0;
86
+ for (const line of patch.split("\n")) {
87
+ const lineStart = offset;
88
+ const lineEnd = offset + line.length + 1;
89
+ offset = lineEnd;
90
+
91
+ let current = sections.at(-1);
92
+ if (
93
+ line.startsWith(GIT_HEADER) ||
94
+ (line.startsWith(OLD_FILE_HEADER) && (current === undefined || current.hunks.length > 0))
95
+ ) {
96
+ current = openSection(lineStart);
97
+ } else if (line.startsWith(HUNK_HEADER)) {
98
+ current ??= openSection(lineStart);
99
+ if (current.hunks.length === 0) {
100
+ current.headerEnd = lineStart;
101
+ }
102
+ current.hunks.push({ end: lineEnd, start: lineStart });
103
+ }
104
+
105
+ if (current === undefined) {
106
+ continue;
107
+ }
108
+ current.end = lineEnd;
109
+ const lastHunk = current.hunks.at(-1);
110
+ if (lastHunk) {
111
+ lastHunk.end = lineEnd;
112
+ } else {
113
+ current.headerEnd = lineEnd;
114
+ }
115
+ }
116
+
117
+ // The trailing split entry after a final newline contributes no content.
118
+ for (const section of sections) {
119
+ section.end = Math.min(section.end, patch.length);
120
+ section.headerEnd = Math.min(section.headerEnd, section.end);
121
+ for (const hunk of section.hunks) {
122
+ hunk.end = Math.min(hunk.end, section.end);
123
+ }
124
+ }
125
+
126
+ return sections;
127
+ };
128
+
129
+ // ---------------------------------------------------------------------------
130
+ // Model construction
131
+ // ---------------------------------------------------------------------------
132
+
133
+ /** Narrow a file to a single hunk while keeping its whole-file line arrays. */
134
+ const narrowToHunk = function narrowToHunk(
135
+ file: HunkDiffFile,
136
+ hunkIndex: number,
137
+ ): HunkDiffFileInput {
138
+ const hunk = file.metadata.hunks[hunkIndex];
139
+ return {
140
+ ...file,
141
+ id: `${file.id}#${hunkIndex}`,
142
+ metadata: { ...file.metadata, hunks: [hunk] },
143
+ };
144
+ };
145
+
146
+ const fallbackHunkTexts = function fallbackHunkTexts(patch: string): {
147
+ header: string;
148
+ hunks: string[];
149
+ } {
150
+ const header: string[] = [];
151
+ const hunks: string[][] = [];
152
+ let currentHunk: string[] | null = null;
153
+ for (const line of patch.split("\n")) {
154
+ if (line.startsWith(HUNK_HEADER)) {
155
+ currentHunk = [line];
156
+ hunks.push(currentHunk);
157
+ } else if (currentHunk) {
158
+ currentHunk.push(line);
159
+ } else {
160
+ header.push(line);
161
+ }
162
+ }
163
+ return { header: header.join("\n"), hunks: hunks.map((lines) => lines.join("\n")) };
164
+ };
165
+
166
+ /**
167
+ * Parse unified patch text into the navigation rows the diff subview and the
168
+ * Markdown fence renderer share.
169
+ *
170
+ * Rows are `file` headers and `hunk` bodies so navigation, marks and the
171
+ * cursor land on a hunk rather than on a whole file. Files Hunk renders without
172
+ * hunks contribute a single `body` row instead.
173
+ */
174
+ export const buildDiffModel = function buildDiffModel(patch: string, sourceId?: string): DiffModel {
175
+ const files = createHunkDiffFilesFromPatch(patch, sourceId);
176
+ const sections = scanPatchSections(patch);
177
+ const aligned = sections.length === files.length ? sections : null;
178
+ const index = new SourceIndex(patch, sourceId);
179
+
180
+ const rows: DiffRow[] = [];
181
+ for (const [fileIndex, file] of files.entries()) {
182
+ const section = aligned?.[fileIndex];
183
+ const fallback = fallbackHunkTexts(file.patch ?? "");
184
+ const { hunks } = file.metadata;
185
+ const hunkSpansAligned = section !== undefined && section.hunks.length === hunks.length;
186
+
187
+ rows.push({
188
+ file,
189
+ fileId: file.id,
190
+ fileIndex,
191
+ hunkIndex: -1,
192
+ key: `${file.id}:file`,
193
+ kind: "file",
194
+ parent: file,
195
+ source: section ? { primary: index.span(section.start, section.headerEnd) } : null,
196
+ text: section ? patch.slice(section.start, section.headerEnd) : fallback.header,
197
+ });
198
+
199
+ if (hunks.length === 0) {
200
+ rows.push({
201
+ file,
202
+ fileId: file.id,
203
+ fileIndex,
204
+ hunkIndex: -1,
205
+ key: `${file.id}:body`,
206
+ kind: "body",
207
+ parent: file,
208
+ source: section ? { primary: index.span(section.start, section.end) } : null,
209
+ text: section ? patch.slice(section.start, section.end) : (file.patch ?? ""),
210
+ });
211
+ continue;
212
+ }
213
+
214
+ for (const [hunkIndex] of hunks.entries()) {
215
+ const span = hunkSpansAligned ? section.hunks[hunkIndex] : undefined;
216
+ rows.push({
217
+ file: narrowToHunk(file, hunkIndex),
218
+ fileId: file.id,
219
+ fileIndex,
220
+ hunkIndex,
221
+ key: `${file.id}:hunk:${hunkIndex}`,
222
+ kind: "hunk",
223
+ parent: file,
224
+ source: span ? { primary: index.span(span.start, span.end) } : null,
225
+ text: span ? patch.slice(span.start, span.end) : (fallback.hunks[hunkIndex] ?? ""),
226
+ });
227
+ }
228
+ }
229
+
230
+ let additions = 0;
231
+ let deletions = 0;
232
+ for (const file of files) {
233
+ additions += file.stats.additions;
234
+ deletions += file.stats.deletions;
235
+ }
236
+
237
+ return { files, patch, rows, stats: { additions, deletions } };
238
+ };
239
+
240
+ /** Row identity, text and provenance for a `DocumentController` over `DiffRow`s. */
241
+ export const diffRowAdapter = {
242
+ getKey: (row: DiffRow): string => row.key,
243
+ getSource: (row: DiffRow): DocumentRowSource | null => row.source,
244
+ getText: (row: DiffRow): string => row.text,
245
+ };
246
+
247
+ export { countHunkDiffStats } from "hunkdiff/opentui";
@@ -0,0 +1,88 @@
1
+ import type { HunkDiffThemeName } from "hunkdiff/opentui";
2
+ import type { ResolvedTheme } from "@tooee/themes";
3
+
4
+ /**
5
+ * Hunk resolves one of its own bundled palettes by name; it accepts no custom
6
+ * colour table, so a Tooee theme is matched to the closest bundled Hunk theme
7
+ * rather than reproduced exactly.
8
+ *
9
+ * Every Tooee theme ships both a light and a dark variant, and which one is
10
+ * active depends on the terminal, so each entry names a Hunk theme per variant
11
+ * and the resolved background decides between them.
12
+ */
13
+ export interface HunkThemePair {
14
+ dark: HunkDiffThemeName;
15
+ light: HunkDiffThemeName;
16
+ }
17
+
18
+ const GITHUB: HunkThemePair = { dark: "github-dark", light: "github-light" };
19
+
20
+ /** Closest bundled Hunk theme for each theme shipped with `@tooee/themes`. */
21
+ export const HUNK_THEME_MAP: Record<string, HunkThemePair> = {
22
+ aura: { dark: "laserwave", light: "min-light" },
23
+ ayu: { dark: "ayu-dark", light: "ayu-light" },
24
+ catppuccin: { dark: "catppuccin-mocha", light: "catppuccin-latte" },
25
+ "catppuccin-frappe": { dark: "catppuccin-frappe", light: "catppuccin-latte" },
26
+ "catppuccin-macchiato": { dark: "catppuccin-macchiato", light: "catppuccin-latte" },
27
+ cobalt2: { dark: "dark-plus", light: "light-plus" },
28
+ cursor: { dark: "vitesse-dark", light: "vitesse-light" },
29
+ dracula: { dark: "dracula", light: "min-light" },
30
+ everforest: { dark: "everforest-dark", light: "everforest-light" },
31
+ flexoki: { dark: "vitesse-dark", light: "vitesse-light" },
32
+ github: GITHUB,
33
+ "github-light": { dark: "github-dark", light: "github-light" },
34
+ gruvbox: { dark: "gruvbox-dark-medium", light: "gruvbox-light-medium" },
35
+ kanagawa: { dark: "kanagawa-wave", light: "kanagawa-lotus" },
36
+ "lucent-orng": { dark: "vesper", light: "min-light" },
37
+ material: { dark: "material-theme", light: "material-theme-lighter" },
38
+ matrix: { dark: "vitesse-black", light: "min-light" },
39
+ mercury: { dark: "min-dark", light: "min-light" },
40
+ monokai: { dark: "monokai", light: "min-light" },
41
+ nightowl: { dark: "night-owl", light: "night-owl-light" },
42
+ nord: { dark: "nord", light: "min-light" },
43
+ "one-dark": { dark: "one-dark-pro", light: "one-light" },
44
+ opencode: { dark: "vitesse-dark", light: "vitesse-light" },
45
+ "opencode-light": { dark: "vitesse-dark", light: "vitesse-light" },
46
+ orng: { dark: "vesper", light: "min-light" },
47
+ "osaka-jade": { dark: "everforest-dark", light: "everforest-light" },
48
+ palenight: { dark: "material-theme-palenight", light: "material-theme-lighter" },
49
+ rosepine: { dark: "rose-pine", light: "rose-pine-dawn" },
50
+ solarized: { dark: "solarized-dark", light: "solarized-light" },
51
+ synthwave84: { dark: "synthwave-84", light: "min-light" },
52
+ tokyonight: { dark: "tokyo-night", light: "min-light" },
53
+ vercel: { dark: "vitesse-black", light: "vitesse-light" },
54
+ vesper: { dark: "vesper", light: "min-light" },
55
+ zenburn: { dark: "gruvbox-dark-soft", light: "gruvbox-light-soft" },
56
+ };
57
+
58
+ const HEX_COLOR = /^#(?<digits>[0-9a-f]{3}|[0-9a-f]{6})$/iu;
59
+ /** Rec. 601 luma above this counts as a light background. */
60
+ const LIGHT_LUMA = 128;
61
+
62
+ /** `true` when `color` is a hex colour bright enough to read as a light background. */
63
+ export const isLightBackground = function isLightBackground(color: string): boolean {
64
+ const digits = HEX_COLOR.exec(color.trim())?.groups?.digits;
65
+ if (digits === undefined) {
66
+ // Named or transparent backgrounds carry no brightness: assume dark.
67
+ return false;
68
+ }
69
+ // #abc expands to #aabbcc; the pattern only ever matches ASCII hex digits.
70
+ const full = digits.length === 3 ? digits.replaceAll(/[0-9a-f]/giu, "$&$&") : digits;
71
+ const r = Number.parseInt(full.slice(0, 2), 16);
72
+ const g = Number.parseInt(full.slice(2, 4), 16);
73
+ const b = Number.parseInt(full.slice(4, 6), 16);
74
+ return 0.299 * r + 0.587 * g + 0.114 * b > LIGHT_LUMA;
75
+ };
76
+
77
+ /**
78
+ * The bundled Hunk theme to render a diff with. Unmapped themes (user themes
79
+ * from `~/.config/tooee/themes`) fall back to GitHub's palette on the same
80
+ * light/dark side as the active theme's background.
81
+ */
82
+ export const resolveHunkDiffTheme = function resolveHunkDiffTheme(
83
+ themeName: string,
84
+ theme: ResolvedTheme,
85
+ ): HunkDiffThemeName {
86
+ const pair = HUNK_THEME_MAP[themeName] ?? GITHUB;
87
+ return isLightBackground(theme.background) ? pair.light : pair.dark;
88
+ };