Merge pull request #121 from continuedev/word-level-diff
word level diff
This commit is contained in:
commit
48adb23ab0
2 changed files with 396 additions and 56 deletions
199
src/ui/ColoredDiff.test.ts
Normal file
199
src/ui/ColoredDiff.test.ts
Normal 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("+ ");
|
||||
});
|
||||
});
|
||||
|
|
@ -1,15 +1,25 @@
|
|||
import { diffWordsWithSpace, Change } from "diff";
|
||||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
import React, { useMemo } from "react";
|
||||
|
||||
// Color constants for diff display
|
||||
const COLORS = {
|
||||
ADDITION_BG: "#325b30",
|
||||
DELETION_BG: "#712f37",
|
||||
ADDITION_HIGHLIGHT: "#59a467",
|
||||
DELETION_HIGHLIGHT: "#a75e6d",
|
||||
LINE_NUMBER: "gray",
|
||||
} as const;
|
||||
|
||||
interface DiffLine {
|
||||
type: 'add' | 'del' | 'context' | 'hunk' | 'other';
|
||||
type: "add" | "del" | "context" | "hunk" | "other";
|
||||
oldLine?: number;
|
||||
newLine?: number;
|
||||
content: string;
|
||||
}
|
||||
|
||||
function parseDiffWithLineNumbers(diffContent: string): DiffLine[] {
|
||||
const lines = diffContent.split('\n');
|
||||
const lines = diffContent.split("\n");
|
||||
const result: DiffLine[] = [];
|
||||
let currentOldLine = 0;
|
||||
let currentNewLine = 0;
|
||||
|
|
@ -22,105 +32,236 @@ function parseDiffWithLineNumbers(diffContent: string): DiffLine[] {
|
|||
currentOldLine = parseInt(hunkMatch[1], 10);
|
||||
currentNewLine = parseInt(hunkMatch[2], 10);
|
||||
inHunk = true;
|
||||
result.push({ type: 'hunk', content: line });
|
||||
result.push({ type: "hunk", content: line });
|
||||
currentOldLine--;
|
||||
currentNewLine--;
|
||||
continue;
|
||||
}
|
||||
if (!inHunk) {
|
||||
if (
|
||||
line.startsWith('--- ') ||
|
||||
line.startsWith('+++ ') ||
|
||||
line.startsWith('diff --git') ||
|
||||
line.startsWith('index ')
|
||||
line.startsWith("--- ") ||
|
||||
line.startsWith("+++ ") ||
|
||||
line.startsWith("diff --git") ||
|
||||
line.startsWith("index ")
|
||||
)
|
||||
continue;
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith('+')) {
|
||||
if (line.startsWith("+")) {
|
||||
currentNewLine++;
|
||||
result.push({
|
||||
type: 'add',
|
||||
type: "add",
|
||||
newLine: currentNewLine,
|
||||
content: line.substring(1),
|
||||
});
|
||||
} else if (line.startsWith('-')) {
|
||||
} else if (line.startsWith("-")) {
|
||||
currentOldLine++;
|
||||
result.push({
|
||||
type: 'del',
|
||||
type: "del",
|
||||
oldLine: currentOldLine,
|
||||
content: line.substring(1),
|
||||
});
|
||||
} else if (line.startsWith(' ')) {
|
||||
} else if (line.startsWith(" ")) {
|
||||
currentOldLine++;
|
||||
currentNewLine++;
|
||||
result.push({
|
||||
type: 'context',
|
||||
type: "context",
|
||||
oldLine: currentOldLine,
|
||||
newLine: currentNewLine,
|
||||
content: line.substring(1),
|
||||
});
|
||||
} else if (line.startsWith('\\')) {
|
||||
result.push({ type: 'other', content: line });
|
||||
} else if (line.startsWith("\\")) {
|
||||
result.push({ type: "other", content: line });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) => {
|
||||
function useWordLevelDiff(oldContent: string, newContent: string) {
|
||||
return useMemo(() => {
|
||||
return diffWordsWithSpace(oldContent, newContent);
|
||||
}, [oldContent, newContent]);
|
||||
}
|
||||
|
||||
function renderWordLevelContent(
|
||||
changes: Change[],
|
||||
showType: "removed" | "added"
|
||||
): React.ReactNode {
|
||||
const segments: React.ReactNode[] = [];
|
||||
|
||||
changes.forEach((change, index) => {
|
||||
if (showType === "removed") {
|
||||
if (change.removed) {
|
||||
// Highlight removed words with darker red
|
||||
segments.push(
|
||||
<Text key={index} backgroundColor={COLORS.DELETION_HIGHLIGHT}>
|
||||
{change.value}
|
||||
</Text>
|
||||
);
|
||||
} else if (!change.added) {
|
||||
// Unchanged text - no special styling
|
||||
segments.push(change.value);
|
||||
}
|
||||
} else {
|
||||
if (change.added) {
|
||||
// Highlight added words with darker green
|
||||
segments.push(
|
||||
<Text key={index} backgroundColor={COLORS.ADDITION_HIGHLIGHT}>
|
||||
{change.value}
|
||||
</Text>
|
||||
);
|
||||
} else if (!change.removed) {
|
||||
// Unchanged text - no special styling
|
||||
segments.push(change.value);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return <>{segments}</>;
|
||||
}
|
||||
|
||||
const WordLevelDiffGroup: React.FC<{
|
||||
groupIndex: number;
|
||||
delLines: DiffLine[];
|
||||
addLines: DiffLine[];
|
||||
}> = ({ groupIndex, delLines, addLines }) => {
|
||||
const oldContent = delLines.map(l => l.content).join('\n');
|
||||
const newContent = addLines.map(l => l.content).join('\n');
|
||||
const changes = useWordLevelDiff(oldContent, newContent);
|
||||
|
||||
return (
|
||||
<Box key={`group-${groupIndex}`} flexDirection="column">
|
||||
<Box flexDirection="row">
|
||||
<Text color={COLORS.LINE_NUMBER}>
|
||||
{(delLines[0]?.oldLine ?? "").toString().padEnd(4)}{" "}
|
||||
</Text>
|
||||
<Text backgroundColor={COLORS.DELETION_BG}>- </Text>
|
||||
<Text backgroundColor={COLORS.DELETION_BG}>
|
||||
{renderWordLevelContent(changes, "removed")}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box flexDirection="row">
|
||||
<Text color={COLORS.LINE_NUMBER}>
|
||||
{(addLines[0]?.newLine ?? "").toString().padEnd(4)}{" "}
|
||||
</Text>
|
||||
<Text backgroundColor={COLORS.ADDITION_BG}>+ </Text>
|
||||
<Text backgroundColor={COLORS.ADDITION_BG}>
|
||||
{renderWordLevelContent(changes, "added")}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export const ColoredDiff: React.FC<{ diffContent: string }> = ({
|
||||
diffContent,
|
||||
}) => {
|
||||
const parsedLines = parseDiffWithLineNumbers(diffContent);
|
||||
|
||||
|
||||
if (parsedLines.length === 0) {
|
||||
return <Text color="gray">No changes detected.</Text>;
|
||||
}
|
||||
|
||||
const displayableLines = parsedLines.filter(
|
||||
(l) => l.type !== 'hunk' && l.type !== 'other',
|
||||
(l) => l.type !== "hunk" && l.type !== "other"
|
||||
);
|
||||
|
||||
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 = COLORS.ADDITION_BG;
|
||||
prefixSymbol = "+";
|
||||
break;
|
||||
case "del":
|
||||
gutterNumStr = (line.oldLine ?? "").toString();
|
||||
backgroundColor = COLORS.DELETION_BG;
|
||||
prefixSymbol = "-";
|
||||
break;
|
||||
case "context":
|
||||
gutterNumStr = (line.newLine ?? "").toString();
|
||||
dim = true;
|
||||
prefixSymbol = " ";
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box key={lineKey} flexDirection="row">
|
||||
<Text color={COLORS.LINE_NUMBER}>{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");
|
||||
|
||||
return (
|
||||
<WordLevelDiffGroup
|
||||
key={`group-${groupIndex}`}
|
||||
groupIndex={groupIndex}
|
||||
delLines={delLines}
|
||||
addLines={addLines}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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>
|
||||
|
|
@ -129,4 +270,4 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent })
|
|||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue