Skip to content

Commit

Permalink
Add structured patch support to gh-pages
Browse files Browse the repository at this point in the history
Co-authored-by: Mark Amery <markrobertamery@gmail.com>
  • Loading branch information
codebymikey and ExplodingCabbage committed Sep 12, 2024
1 parent 076e1a4 commit 5de7766
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
33 changes: 32 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ <h1>Diff</h1>
<label><input type="radio" name="diff_type" value="diffChars" checked> Chars</label>
<label><input type="radio" name="diff_type" value="diffWords"> Words</label>
<label><input type="radio" name="diff_type" value="diffLines"> Lines</label>
<label><input type="radio" name="diff_type" value="diffPatch"> Patch</label>
</div>

<a href="https://github.com/kpdecker/jsdiff" class="source">github.com/kpdecker/jsdiff</a>
Expand All @@ -31,8 +32,34 @@ <h1>Diff</h1>
var result = document.getElementById('result');

function changed() {
var diff = Diff[window.diffType](a.textContent, b.textContent);
var fragment = document.createDocumentFragment();
var diff;
if (window.diffType === 'diffPatch') {
// We contort the patch into a similar data structure to that returned by diffChars,
// diffWords, etc so that the same rendering code below can work on both.
var pastHunkHeader = false;
diff = Diff.createTwoFilesPatch('a.txt', 'b.txt', a.textContent, b.textContent)
.split('\n')
.map(function(entry) {
const result = {
value: entry + '\n',
};
if (entry.startsWith('@@')) {
result.chunkHeader = true;
pastHunkHeader = true;
} else if (pastHunkHeader) {
if (entry.startsWith('-')) {
result.removed = true;
} else if (entry.startsWith('+')) {
result.added = true;
}
}
return result;
});
} else {
diff = Diff[window.diffType](a.textContent, b.textContent);
}

for (var i=0; i < diff.length; i++) {

if (diff[i].added && diff[i + 1] && diff[i + 1].removed) {
Expand All @@ -48,6 +75,10 @@ <h1>Diff</h1>
} else if (diff[i].added) {
node = document.createElement('ins');
node.appendChild(document.createTextNode(diff[i].value));
} else if (diff[i].chunkHeader) {
node = document.createElement('span');
node.setAttribute('class', 'chunk-header');
node.appendChild(document.createTextNode(diff[i].value));
} else {
node = document.createTextNode(diff[i].value);
}
Expand Down
4 changes: 4 additions & 0 deletions style.css
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ ins {
color: #406619;
text-decoration: none;
}
.chunk-header {
color: #8a008b;
text-decoration: none;
}

#result {
white-space: pre-wrap;
Expand Down

0 comments on commit 5de7766

Please sign in to comment.