silverbullet/web/cm_util.ts

26 lines
786 B
TypeScript
Raw Permalink Normal View History

2024-08-22 02:03:30 +08:00
import diff, { DELETE, EQUAL, INSERT } from "fast-diff";
2024-01-26 18:10:35 +08:00
import type { ChangeSpec } from "@codemirror/state";
export function diffAndPrepareChanges(
oldString: string,
newString: string,
): ChangeSpec[] {
// Use the fast-diff library to compute the changes
const diffs = diff(oldString, newString);
// Convert the diffs to CodeMirror transactions
let startIndex = 0;
const changes: ChangeSpec[] = [];
for (const part of diffs) {
if (part[0] === INSERT) {
changes.push({ from: startIndex, insert: part[1] });
2024-08-22 02:03:30 +08:00
} else if (part[0] === EQUAL) {
startIndex += part[1].length;
2024-01-26 18:10:35 +08:00
} else if (part[0] === DELETE) {
changes.push({ from: startIndex, to: startIndex + part[1].length });
2024-08-22 02:03:30 +08:00
startIndex += part[1].length;
2024-01-26 18:10:35 +08:00
}
}
return changes;
}