alinea
Version:
Headless git-based CMS
83 lines (81 loc) • 2.27 kB
JavaScript
import "../../../chunks/chunk-NZLE2WMY.js";
// src/dashboard/view/diff/DiffUtils.ts
import { ScalarShape } from "alinea/core/shape/ScalarShape";
function equals(a, b) {
if (a === b) return true;
if (!a || !b) return false;
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (!equals(a[i], b[i])) return false;
}
return true;
}
if (typeof a === "object" && typeof b === "object") {
const keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false;
for (const key of keys) {
if (!equals(a[key], b[key])) return false;
}
return true;
}
return false;
}
function computeLcs(a, b, equals2) {
const n = a.length;
const m = b.length;
const lcs = Array.from(Array(n + 1), () => Array(m + 1));
for (let i = 0; i <= n; i++) {
for (let j = 0; j <= m; j++) {
if (i === 0 || j === 0) {
lcs[i][j] = 0;
} else if (equals2(a[i - 1], b[j - 1])) {
lcs[i][j] = 1 + lcs[i - 1][j - 1];
} else {
lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);
}
}
}
return lcs;
}
function diffList(a, b, equals2) {
const lcs = computeLcs(a, b, equals2);
const results = [];
let i = a.length;
let j = b.length;
while (i !== 0 || j !== 0) {
if (i === 0) {
results.push({ type: "addition", value: b[j - 1] });
j -= 1;
} else if (j === 0) {
results.push({ type: "removal", value: a[i - 1] });
i -= 1;
} else if (equals2(a[i - 1], b[j - 1])) {
results.push({ type: "keep", old: a[i - 1], value: b[j - 1] });
i -= 1;
j -= 1;
} else if (lcs[i - 1][j] <= lcs[i][j - 1]) {
results.push({ type: "addition", value: b[j - 1] });
j -= 1;
} else {
results.push({ type: "removal", value: a[i - 1] });
i -= 1;
}
}
return results.reverse();
}
function diffRecord(kind, targetA, targetB) {
const types = Object.entries(kind.shapes);
return types.filter(([key, type]) => {
if (type instanceof ScalarShape) {
return targetA?.[key] !== targetB?.[key];
}
return !equals(targetA?.[key], targetB?.[key]);
});
}
export {
computeLcs,
diffList,
diffRecord,
equals
};