Skip to content

Instantly share code, notes, and snippets.

@KararTY
Created September 16, 2024 11:29
Show Gist options
  • Select an option

  • Save KararTY/73b33cde4596270ab7ceb99afa8b6754 to your computer and use it in GitHub Desktop.

Select an option

Save KararTY/73b33cde4596270ab7ceb99afa8b6754 to your computer and use it in GitHub Desktop.
JSON Diff + Text Diff
/**
* https://opensource.org/license/mit-0 - MIT No Attribution
*
* Copyright 2024 Karar Al-Remahy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import JSONDiffer from 'json-diff';
import { diffChars as CharDiffer } from 'diff';
/**
* Used to clean up object properties with changed values.
* @param {Record<string, string | number | { __old: string, __new: string }>} obj
*/
function cleanPropertyDiffChanges(obj) {
const entries = Object.entries(obj);
for (let index = 0; index < entries.length; index++) {
const [key, value] = entries[index];
if (!obj.___change) {
continue;
}
if (Array.isArray(value)) {
continue;
}
if (typeof value !== 'object') {
continue;
}
if (value == null) {
continue;
}
if (!(value.__old || value.__new)) {
continue;
}
const { __new } = value;
obj[key] = __new;
if (typeof obj.___change !== 'object') {
throw new Error('___change returned a non valid value.');
}
obj.___change = {
...(obj.___change || {}),
[key]: value,
};
}
for (let index = 0; index < entries.length; index++) {
const [key, value] = entries[index];
let cleanKey;
let v;
if (key.endsWith('__added') && key.length > '__added'.length) {
cleanKey = /** @type {string} */ (key.split('__').shift());
v = { __new: value };
} else if (key.endsWith('__deleted') && key.length > '__deleted'.length) {
cleanKey = /** @type {string} */ (key.split('__').shift());
v = { __old: value };
}
if (!cleanKey) {
continue;
}
if (typeof obj.___change !== 'object') {
throw new Error('___change returned a non valid value.');
}
obj[cleanKey] = value;
delete obj[key];
obj.___change = {
...(obj.___change || {}),
[cleanKey]: v,
};
}
if (typeof obj.___change === 'object') {
const { ___change } =
/** @type {{ ___change: { [x: string]: { __old: string, __new: string } } }} */ (
/** @type {unknown} */ (obj)
);
// This is a bit complicated, but we do this to use a different differ for text content.
if (typeof ___change.text === 'object') {
const { text } = ___change;
if (typeof text.__old === 'string' && typeof text.__new === 'string') {
const diff = CharDiffer(text.__old, text.__new);
// @ts-ignore
text.diff = diff;
}
// TODO: Needs more rules.
}
}
return obj;
}
// Empty space means value is the same, ~ means entry is modified, + means added, - means removed.
const jsonDiffArrayCharacters = [' ', '~', '+', '-'];
/**
* Used to clean end-result array.
* @param {any[]} list
*/
function diffSemanticsFlat(list) {
return list
.map((item) => {
return { ...item };
})
.map((item) => {
const change = item['0'];
let obj = item['1'];
if (!jsonDiffArrayCharacters.includes(change)) {
return item;
}
obj.___change = {
___type: change,
};
obj = cleanPropertyDiffChanges(obj);
if (obj.children) {
obj.children = diffSemanticsFlat(obj.children);
}
if (obj.type) {
obj.type = `diff-${obj.type}`;
}
return obj;
});
}
export function getDiffJSON(existingJSON, newJSON) {
const diff = JSONDiffer.diff(existingJSON, newJSON, { full: true, raw: true });
return {
...diff,
children: diffSemanticsFlat(diff.children),
};
}
const existingJSON = {
children: [
{
type: 'paragraph',
children: [{ text: 'abcdef' }],
},
],
};
const newJSON = {
children: [
{
type: 'paragraph',
children: [{ text: 'abc', bold: true }],
},
],
};
const output = getDiffJSON(existingJSON, newJSON);
const expectedOutput = {
children: [
{
type: 'diff-paragraph',
children: [
{
text: 'abc',
___change: {
___type: '~',
text: {
__old: 'abcdef',
__new: 'abc',
diff: [
{
count: 3,
added: false,
removed: false,
value: 'abc',
},
{
count: 3,
added: false,
removed: true,
value: 'def',
},
],
},
bold: {
__new: true,
},
},
bold: true,
},
],
___change: {
___type: '~',
},
},
],
};
console.log(JSON.stringify(output) === JSON.stringify(expectedOutput));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment