User:Polygnotus/Scripts/DiffCompare.js: Difference between revisions

Content deleted Content added
No edit summary
No edit summary
 
(8 intermediate revisions by the same user not shown)
Line 1:
// https://github.com/google/diff-match-patch
 
$.ajax('https://cdn.jsdelivr.net/gh/google/diff-match-patch@master/javascript/diff_match_patch.js', {
dataType: 'script',
cache: true
}).then(function () {
const DEBUG = false;
 
function debug(...args) {
if (DEBUG) {
debug('[DiffCompare]', ...args);
}
}
 
debug('diff_match_patch library loaded successfully');
 
if (typeof diff_match_patch === 'undefined') {
console.error('diff_match_patch libraryis notundefined loadedafter loading');
return;
}
 
function showDiff(text1, text2) {
debug('showDiff called with:', { text1, text2 });
 
const dmp = new diff_match_patch();
debug('diff_match_patch instance created');
 
const diffs = dmp.diff_main(text1, text2);
debug('diffs created:', diffs);
 
dmp.diff_cleanupSemantic(diffs);
debug('diffs after cleanup:', diffs);
 
let html = '';
for (let i = 0; i < diffs.length; i++) {
constdebug(`Processing [opdiff ${i}:`, data] = diffs[i]);
const op = breakdiffs[i][0];
const data = diffs[i][1];
switch (op) {
case diff_match_patch.DIFF_INSERT-1: // DIFF_DELETE
html += '<ins style="background-color: #e6ffe6;">' + escapeHtml(data) + '</ins>';
break;
case diff_match_patch.DIFF_DELETE:
html += '<del style="background-color: #ffe6e6;">' + escapeHtml(data) + '</del>';
break;
case diff_match_patch.DIFF_EQUAL1: // DIFF_INSERT
html += '<ins style="background-color: #e6ffe6;">' + escapeHtml(data) + '</ins>';
break;
case 0: // DIFF_EQUAL
html += '<span>' + escapeHtml(data) + '</span>';
break;
default:
console.error(`Unknown diff operation: ${op}`);
}
}
debug('Final HTML:', html);
return html;
}
Line 44 ⟶ 70:
 
try {
debug('Attempting to generate diff');
const diffHtml = showDiff(oldText, newText);
console.logdebug('Diff result:',generation diffHtmlsuccessful');
// $debug('#diff-outputDiff result:').html(, diffHtml);
 
const diffContainer = $('<div>')
.attr('id', 'diff-output')
.css({
'border': '1px solid #a2a9b1',
'padding': '10px',
'margin-bottom': '20px',
'background-color': '#f8f9fa'
})
.html('<strong>Diff Result:</strong><br>' + diffHtml);
 
$('#bodyContent').prepend(diffContainer);
 
} catch (error) {
console.error('Error generating diff:', error);