Skip to content

Instantly share code, notes, and snippets.

@sunil-bagde
Created June 4, 2021 12:07
Show Gist options
  • Select an option

  • Save sunil-bagde/6bfd9b13a2322c1bf747bb3c384ca14e to your computer and use it in GitHub Desktop.

Select an option

Save sunil-bagde/6bfd9b13a2322c1bf747bb3c384ca14e to your computer and use it in GitHub Desktop.
import React, { useState, useCallback, useMemo } from "react";
import ReactDOM from "react-dom";
import { Input, Button } from "antd";
import { diffLines, formatLines } from "unidiff";
import { parseDiff, Diff, Hunk } from "react-diff-view";
import { useInput } from "./hooks";
import "antd/dist/antd.min.css";
import "react-diff-view/style/index.css";
import tokenize from "./tokenize";
const EMPTY_HUNKS = [];
const renderToken = (token, defaultRender, i) => {
switch (token.type) {
case "space":
console.log(token);
return (
<span key={i} className="space">
{token.children &&
token.children.map((token, i) =>
renderToken(token, defaultRender, i)
)}
</span>
);
default:
return defaultRender(token, i);
}
};
function App() {
const oldText = useInput("");
const newText = useInput("");
const [{ type, hunks }, setDiff] = useState("");
const updateDiffText = useCallback(() => {
const diffText = formatLines(diffLines(oldText.value, newText.value), {
context: 3,
});
const [diff] = parseDiff(diffText, { nearbySequences: "zip" });
setDiff(diff);
}, [oldText.value, newText.value, setDiff]);
const tokens = useMemo(() => tokenize(hunks), [hunks]);
return (
<div>
<header className="header">
<div className="input">
<Input.TextArea
className="text"
rows={10}
placeholder="old text..."
{...oldText}
/>
<Input.TextArea
className="text"
rows={10}
placeholder="new text..."
{...newText}
/>
</div>
<Button
className="submit"
type="primary"
onClick={updateDiffText}
>
GENERATE DIFF
</Button>
</header>
<main>
<Diff
viewType="split"
diffType={type}
hunks={hunks || EMPTY_HUNKS}
tokens={tokens}
renderToken={renderToken}
>
{(hunks) =>
hunks.map((hunk) => (
<Hunk key={hunk.content} hunk={hunk} />
))
}
</Diff>
</main>
</div>
);
}
const rootElement = document.getElementById("root");
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment