feat: word-level diff

This commit is contained in:
Nate 2025-07-30 10:54:51 -07:00
parent 8e44284927
commit 191b5ea63b
2 changed files with 311 additions and 36 deletions

199
src/ui/ColoredDiff.test.ts Normal file
View file

@ -0,0 +1,199 @@
import { render } from "ink-testing-library";
import React from "react";
import { ColoredDiff } from "./ColoredDiff.js";
describe("ColoredDiff", () => {
it("renders simple line additions", () => {
const diffContent = `@@ -1,3 +1,4 @@
function hello() {
+ console.log("added line");
return "world";
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
expect(frame).toContain("console.log(\"added line\")");
expect(frame).toContain("+");
});
it("renders simple line deletions", () => {
const diffContent = `@@ -1,4 +1,3 @@
function hello() {
- console.log("removed line");
return "world";
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
expect(frame).toContain("console.log(\"removed line\")");
expect(frame).toContain("-");
});
it("renders context lines", () => {
const diffContent = `@@ -1,4 +1,4 @@
function hello() {
- console.log("old");
+ console.log("new");
return "world";
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
expect(frame).toContain("function hello()");
expect(frame).toContain("return \"world\"");
});
it("renders word-level diffs for modified lines", () => {
const diffContent = `@@ -1,3 +1,3 @@
function hello() {
- return "old text";
+ return "new text";
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
expect(frame).toContain("return \"");
expect(frame).toContain("text\"");
// Should show both old and new versions for word-level diff
expect(frame).toContain("-");
expect(frame).toContain("+");
});
it("handles empty diff content", () => {
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent: "" }));
const frame = lastFrame();
expect(frame).toContain("No changes detected");
});
it("truncates long diffs", () => {
// Create a diff with more than 16 lines
const lines = Array.from({ length: 20 }, (_, i) => `+ line ${i + 1}`).join('\n');
const diffContent = `@@ -1,1 +1,20 @@
function hello() {
${lines}
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
expect(frame).toContain("more lines");
});
it("handles mixed add/delete groups for word-level diffing", () => {
const diffContent = `@@ -1,4 +1,4 @@
function hello() {
- const x = "old value";
- const y = "another old";
+ const x = "new value";
+ const y = "another new";
return x + y;
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
// Should render word-level diffs
expect(frame).toContain("const x = \"");
expect(frame).toContain("value\"");
expect(frame).toContain("const y = \"another");
});
it("handles single-type changes without word-level diffing", () => {
const diffContent = `@@ -1,3 +1,4 @@
function hello() {
+ console.log("new line 1");
+ console.log("new line 2");
return "world";
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
// Should render as normal line additions, not word-level
expect(frame).toContain("console.log(\"new line 1\")");
expect(frame).toContain("console.log(\"new line 2\")");
expect(frame).toContain("+");
});
it("text content matches expected diff output ignoring styling", () => {
const diffContent = `@@ -1,4 +1,4 @@
function hello() {
- return "old text";
+ return "new text";
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
// Extract just the line numbers and content, ignoring colors/styling
// The output should contain these essential elements:
expect(frame).toContain("function hello()");
expect(frame).toContain("- ");
expect(frame).toContain("+ ");
expect(frame).toContain("return \"");
expect(frame).toContain("text\"");
// Verify we have both old and new text content
expect(frame).toContain("old text");
expect(frame).toContain("new text");
// Verify we don't have corrupted or missing content
const lineMatches = frame?.match(/return "/g) || [];
expect(lineMatches.length).toBeGreaterThanOrEqual(2); // Should appear in both - and + lines
});
it("word-level diff preserves all original content", () => {
const diffContent = `@@ -1,3 +1,3 @@
const x = 1;
-const y = "hello world";
+const y = "hello universe";
const z = 3;`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
// All original text should be preserved
expect(frame).toContain("const x = 1");
expect(frame).toContain("const z = 3");
// Both old and new versions should be shown
expect(frame).toContain("hello world");
expect(frame).toContain("hello universe");
expect(frame).toContain("const y = \"hello");
// Should have proper line prefixes
expect(frame).toContain("- ");
expect(frame).toContain("+ ");
});
it("complex word-level diff maintains content integrity", () => {
const diffContent = `@@ -1,5 +1,5 @@
function calculate() {
- const result = oldFunction(a, b);
- return result.value;
+ const result = newFunction(a, b, c);
+ return result.data;
}`;
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
const frame = lastFrame();
// Check that all unique content appears
expect(frame).toContain("function calculate()");
expect(frame).toContain("const result =");
expect(frame).toContain("oldFunction(a, b)");
expect(frame).toContain("newFunction(a, b, c)");
expect(frame).toContain("return result.");
expect(frame).toContain("value");
expect(frame).toContain("data");
// Verify structure is maintained
expect(frame).toContain("- ");
expect(frame).toContain("+ ");
});
});

View file

@ -1,5 +1,6 @@
import { Box, Text } from "ink";
import React from "react";
import { diffWordsWithSpace } from "diff";
interface DiffLine {
type: 'add' | 'del' | 'context' | 'hunk' | 'other';
@ -67,6 +68,25 @@ function parseDiffWithLineNumbers(diffContent: string): DiffLine[] {
return result;
}
function getWordLevelContent(oldContent: string, newContent: string, showType: 'removed' | 'added'): string {
const changes = diffWordsWithSpace(oldContent, newContent);
let result = '';
changes.forEach((change) => {
if (showType === 'removed') {
if (change.removed || !change.added) {
result += change.value;
}
} else {
if (change.added || !change.removed) {
result += change.value;
}
}
});
return result;
}
export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) => {
const parsedLines = parseDiffWithLineNumbers(diffContent);
@ -81,46 +101,102 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent })
const truncatedLines = displayableLines.slice(0, 16);
const isTruncated = displayableLines.length > 16;
// Group consecutive add/delete lines for word-level diffing
const groupedLines: Array<{ type: 'group' | 'single', lines: DiffLine[] }> = [];
let currentGroup: DiffLine[] = [];
for (let i = 0; i < truncatedLines.length; i++) {
const line = truncatedLines[i];
const nextLine = truncatedLines[i + 1];
if (line.type === 'add' || line.type === 'del') {
currentGroup.push(line);
// If next line is different type or end of array, finalize the group
if (!nextLine || (nextLine.type !== 'add' && nextLine.type !== 'del')) {
if (currentGroup.length > 1) {
const delLines = currentGroup.filter(l => l.type === 'del');
const addLines = currentGroup.filter(l => l.type === 'add');
// Only do word-level diff if we have both deletions and additions
if (delLines.length > 0 && addLines.length > 0) {
groupedLines.push({ type: 'group', lines: currentGroup });
} else {
// Single type, treat as individual lines
currentGroup.forEach(l => groupedLines.push({ type: 'single', lines: [l] }));
}
} else {
groupedLines.push({ type: 'single', lines: currentGroup });
}
currentGroup = [];
}
} else {
groupedLines.push({ type: 'single', lines: [line] });
}
}
return (
<Box flexDirection="column">
{truncatedLines.map((line, index) => {
const lineKey = `diff-line-${index}`;
let gutterNumStr = '';
let prefixSymbol = ' ';
let dim = false;
let backgroundColor: string | undefined = undefined;
{groupedLines.map((group, groupIndex) => {
if (group.type === 'single') {
const line = group.lines[0];
const lineKey = `diff-line-${groupIndex}`;
let gutterNumStr = '';
let prefixSymbol = ' ';
let dim = false;
let backgroundColor: string | undefined = undefined;
switch (line.type) {
case 'add':
gutterNumStr = (line.newLine ?? '').toString();
backgroundColor = '#1a4a1a';
prefixSymbol = '+';
break;
case 'del':
gutterNumStr = (line.oldLine ?? '').toString();
backgroundColor = '#4a1a1a';
prefixSymbol = '-';
break;
case 'context':
gutterNumStr = (line.newLine ?? '').toString();
dim = true;
prefixSymbol = ' ';
break;
default:
return null;
switch (line.type) {
case 'add':
gutterNumStr = (line.newLine ?? '').toString();
backgroundColor = '#1a4a1a';
prefixSymbol = '+';
break;
case 'del':
gutterNumStr = (line.oldLine ?? '').toString();
backgroundColor = '#4a1a1a';
prefixSymbol = '-';
break;
case 'context':
gutterNumStr = (line.newLine ?? '').toString();
dim = true;
prefixSymbol = ' ';
break;
default:
return null;
}
return (
<Box key={lineKey} flexDirection="row">
<Text color="gray">{gutterNumStr.padEnd(4)} </Text>
<Text backgroundColor={backgroundColor} dimColor={dim}>
{prefixSymbol}{' '}
</Text>
<Text backgroundColor={backgroundColor} dimColor={dim}>
{line.content}
</Text>
</Box>
);
} else {
// Word-level diff group
const delLines = group.lines.filter(l => l.type === 'del');
const addLines = group.lines.filter(l => l.type === 'add');
const oldContent = delLines.map(l => l.content).join('\n');
const newContent = addLines.map(l => l.content).join('\n');
return (
<Box key={`group-${groupIndex}`} flexDirection="column">
<Box flexDirection="row">
<Text color="gray">{(delLines[0]?.oldLine ?? '').toString().padEnd(4)} </Text>
<Text backgroundColor="#4a1a1a">- {getWordLevelContent(oldContent, newContent, 'removed')}</Text>
</Box>
<Box flexDirection="row">
<Text color="gray">{(addLines[0]?.newLine ?? '').toString().padEnd(4)} </Text>
<Text backgroundColor="#1a4a1a">+ {getWordLevelContent(oldContent, newContent, 'added')}</Text>
</Box>
</Box>
);
}
return (
<Box key={lineKey} flexDirection="row">
<Text color="gray">{gutterNumStr.padEnd(4)} </Text>
<Text backgroundColor={backgroundColor} dimColor={dim}>
{prefixSymbol}{' '}
</Text>
<Text backgroundColor={backgroundColor} dimColor={dim}>
{line.content}
</Text>
</Box>
);
})}
{isTruncated && (
<Text color="gray" dimColor>