Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add text difference checker #71

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions components/utils/text-difference.utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { calculateDiff, DiffResult } from "./text-difference.utils";

describe("text-difference.utils", () => {
it("should detect line additions, deletions, and unchanged lines", () => {
const oldText = "Line one\nLine to be removed\nLine three";
const newText = "Line one\nLine three\nLine four";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: "Line one", type: "unchanged" },
{ text: "Line to be removed", type: "removed" },
{ text: "Line three", type: "unchanged" },
{ text: "Line four", type: "added" },
];
expect(result).toEqual(expected);
});

it("should detect completely new lines", () => {
const oldText = "";
const newText = "New line one\nNew line two";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: "New line one", type: "added" },
{ text: "New line two", type: "added" },
];
expect(result).toEqual(expected);
});

it("should detect completely removed lines", () => {
const oldText = "Old line one\nOld line two";
const newText = "";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: "Old line one", type: "removed" },
{ text: "Old line two", type: "removed" },
];
expect(result).toEqual(expected);
});

it("should handle identical texts", () => {
const oldText = "Same line one\nSame line two";
const newText = "Same line one\nSame line two";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: "Same line one", type: "unchanged" },
{ text: "Same line two", type: "unchanged" },
];
expect(result).toEqual(expected);
});

it("should handle mixed changes", () => {
const oldText = "Line one\nLine two\nLine three\nLine four";
const newText = "Line one\nLine 2\nLine three\nLine four\nLine five";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: "Line one", type: "unchanged" },
{ text: "Line two", type: "removed" },
{ text: "Line 2", type: "added" },
{ text: "Line three", type: "unchanged" },
{ text: "Line four", type: "unchanged" },
{ text: "Line five", type: "added" },
];
expect(result).toEqual(expected);
});

it("should detect line changes as removals and additions", () => {
const oldText = "Hello world";
const newText = "Hello brave new world";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: "Hello world", type: "removed" },
{ text: "Hello brave new world", type: "added" },
];
expect(result).toEqual(expected);
});

it("should ignore the last empty line if present", () => {
const oldText = "Line one\nLine two\n";
const newText = "Line one\nLine two\nLine three\n";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: "Line one", type: "unchanged" },
{ text: "Line two", type: "unchanged" },
{ text: "Line three", type: "added" },
];
expect(result).toEqual(expected);
});

it("should throw an error when inputs are not strings", () => {
// @ts-expect-error Testing with invalid inputs
expect(() => calculateDiff(null, "Valid string")).toThrow(
"Failed to calculate text differences."
);

// @ts-expect-error Testing with invalid inputs
expect(() => calculateDiff("Valid string", undefined)).toThrow(
"Failed to calculate text differences."
);
});

it("should handle inputs with only whitespace", () => {
const oldText = " \n\t\n";
const newText = " \n\t\n";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: " ", type: "unchanged" },
{ text: "\t", type: "unchanged" },
];
expect(result).toEqual(expected);
});

it("should handle large texts efficiently", () => {
const oldText = Array.from(
{ length: 1000 },
(_, i) => `Line ${i + 1}`
).join("\n");
const newText = Array.from(
{ length: 1000 },
(_, i) => `Line ${i + 1}`
).join("\n");
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = Array.from({ length: 1000 }, (_, i) => ({
text: `Line ${i + 1}`,
type: "unchanged" as const,
}));
expect(result).toEqual(expected);
});

it("should handle texts without trailing newline correctly", () => {
const oldText = "Line one\nLine two";
const newText = "Line one\nLine two\nLine three";
const result = calculateDiff(oldText, newText);
const expected: DiffResult[] = [
{ text: "Line one", type: "unchanged" },
{ text: "Line two", type: "unchanged" },
{ text: "Line three", type: "added" },
];
expect(result).toEqual(expected);
});
});
38 changes: 38 additions & 0 deletions components/utils/text-difference.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { diffLines, Change } from "diff";

export type DiffResult = {
text: string;
type: "added" | "removed" | "unchanged";
};

export function calculateDiff(oldText: string, newText: string): DiffResult[] {
try {
const normalizedOldText =
oldText === "" ? "" : oldText.endsWith("\n") ? oldText : oldText + "\n";
const normalizedNewText =
newText === "" ? "" : newText.endsWith("\n") ? newText : newText + "\n";

const diff: Change[] = diffLines(normalizedOldText, normalizedNewText);

return diff
.map((part) => {
const lineType: DiffResult["type"] = part.added
? "added"
: part.removed
? "removed"
: "unchanged";
const lines = part.value.split("\n").map((line) => ({
text: line,
type: lineType,
}));
// Remove the last empty line if present
if (lines[lines.length - 1]?.text === "") {
lines.pop();
}
return lines;
})
.flat();
} catch (error) {
throw new Error("Failed to calculate text differences.");
}
}
6 changes: 6 additions & 0 deletions components/utils/tools-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ export const tools = [
"Resize images while maintaining aspect ratio and choose between PNG and JPEG formats with our free tool.",
link: "/utilities/image-resizer",
},
{
title: "Text Difference Checker",
description:
"Compare two text files or strings and quickly identify differences between them.",
link: "/utilities/text-difference",
},
{
title: "JWT Parser",
description:
Expand Down
26 changes: 21 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"curlconverter": "^4.10.1",
"diff": "^7.0.0",
"js-yaml": "^4.1.0",
"lucide-react": "^0.414.0",
"next": "14.2.4",
Expand All @@ -37,6 +38,7 @@
"devDependencies": {
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
"@types/diff": "^5.2.2",
"@types/jest": "^29.5.12",
"@types/js-yaml": "^4.0.9",
"@types/node": "^20",
Expand Down
110 changes: 110 additions & 0 deletions pages/utilities/text-difference.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { useMemo, useState } from "react";
import { Textarea } from "@/components/ds/TextareaComponent";
import PageHeader from "@/components/PageHeader";
import { Card } from "@/components/ds/CardComponent";
import { Label } from "@/components/ds/LabelComponent";
import Header from "@/components/Header";
import { CMDK } from "@/components/CMDK";
import CallToActionGrid from "@/components/CallToActionGrid";
import Meta from "@/components/Meta";
import GitHubContribution from "@/components/GitHubContribution";
import { calculateDiff } from "@/components/utils/text-difference.utils";

export default function TextDifference() {
const [input1, setInput1] = useState("");
const [input2, setInput2] = useState("");
const [error, setError] = useState<string | null>(null);

const diffResults = useMemo(() => {
if (input1.trim() === "" && input2.trim() === "") {
ayshrj marked this conversation as resolved.
Show resolved Hide resolved
return [];
}
try {
const results = calculateDiff(input1, input2);
setError(null);
return results;
} catch (err) {
setError((err as Error).message || "An unexpected error occurred.");
return [];
}
}, [input1, input2]);

return (
<main>
<Meta
title="Text Difference Checker | Free, Open Source & Ad-free"
description="Compare two pieces of text and see the differences."
/>
<Header />
<CMDK />

<section className="container max-w-2xl mb-12">
<PageHeader
title="Text Difference Checker"
description="Fast, free, open source, ad-free tools."
/>
</section>

<section className="container max-w-2xl mb-6">
<Card className="flex flex-col p-6 hover:shadow-none shadow-none rounded-xl">
<div>
<Label>Text 1</Label>
<Textarea
rows={6}
placeholder="Paste first text here"
onChange={(e) => setInput1(e.currentTarget.value)}
className="mb-6"
value={input1}
/>

<Label>Text 2</Label>
<Textarea
rows={6}
placeholder="Paste second text here"
onChange={(e) => setInput2(e.currentTarget.value)}
className="mb-6"
value={input2}
/>

<div className="flex justify-between items-center mb-2">
<Label className="mb-0">Differences</Label>
</div>

{error ? (
<div className="mb-4 p-4 bg-destructive text-destructive-foreground rounded">
{error}
</div>
) : (
<div className="output-diff mb-4">
<pre className="p-4 overflow-auto font-mono text-sm">
{diffResults.map((line, index) => (
<div
key={index}
className={`flex items-start ${
line.type === "added"
? "bg-primary text-primary-foreground"
: line.type === "removed"
? "bg-destructive text-destructive-foreground"
: "bg-accent text-accent-foreground"
}`}
>
<span className="w-8 text-muted-foreground select-none text-right pr-2">
{index + 1}
</span>
<span className="whitespace-pre-wrap flex-1">
{line.text}
</span>
</div>
))}
</pre>
</div>
)}
</div>
</Card>
</section>

<GitHubContribution username="ayshrj" />
<CallToActionGrid />
</main>
);
}