tfrere's picture
tfrere HF Staff
Cursor
feat(versions): version history, agent revert and safer MCP edits
62809b0
Raw History Blame Contribute Delete
4.83 kB
/**
* Readable diff between two versions of an article: top-level blocks are
* matched with an LCS, and a removed block followed by an added block of
* the same type is shown as one edited block with a word diff.
*/
import * as Y from "yjs";
import { collectTextblocks, topLevelBlocks, yId } from "../mcp/y-blocks.js";
import { FRAGMENT, editScript } from "./doc-content.js";
export type DiffPart = { op: "same" | "add" | "del"; text: string };
export interface DiffBlock {
status: "same" | "added" | "removed" | "changed";
type: string;
text: string;
parts?: DiffPart[];
}
export interface FieldChange {
field: string;
before: string;
after: string;
}
export interface DocDiff {
blocks: DiffBlock[];
fields: FieldChange[];
stats: { added: number; removed: number; changed: number };
}
interface BlockInfo {
key: string;
type: string;
text: string;
}
function describeAtom(el: Y.XmlElement): string {
const a = el.getAttributes() as Record<string, any>;
const name = a.title || a.alt || a.caption || a.src || a.embedId || "";
return `[${el.nodeName}${name ? `: ${String(name).slice(0, 80)}` : ""}]`;
}
function blocksOf(doc: Y.Doc): BlockInfo[] {
const fragment = doc.getXmlFragment(FRAGMENT);
const texts = new Map<string, string[]>();
for (const tb of collectTextblocks(fragment)) {
const list = texts.get(tb.blockId) ?? [];
list.push(tb.text);
texts.set(tb.blockId, list);
}
return topLevelBlocks(fragment).map((el) => {
const lines = texts.get(yId(el));
return {
key: el.toString(),
type: el.nodeName,
text: lines?.length ? lines.join("\n") : describeAtom(el),
};
});
}
function wordDiff(before: string, after: string): DiffPart[] {
const a = before.split(/(\s+)/).filter(Boolean);
const b = after.split(/(\s+)/).filter(Boolean);
const parts: DiffPart[] = [];
const push = (op: DiffPart["op"], text: string) => {
const last = parts[parts.length - 1];
if (last?.op === op) last.text += text;
else parts.push({ op, text });
};
let i = 0;
for (const op of editScript(a, b)) {
if (op.kind === "keep") push("same", a[i++]);
else if (op.kind === "delete") push("del", a[i++]);
else push("add", b[op.index]);
}
return parts;
}
function fieldText(value: unknown): string {
if (value instanceof Y.AbstractType) value = value.toJSON();
if (value == null) return "";
return typeof value === "string" ? value : JSON.stringify(value);
}
function fieldChanges(from: Y.Doc, to: Y.Doc): FieldChange[] {
const changes: FieldChange[] = [];
const a = from.getMap("frontmatter");
const b = to.getMap("frontmatter");
for (const key of new Set([...a.keys(), ...b.keys()])) {
const before = fieldText(a.get(key));
const after = fieldText(b.get(key));
if (before !== after) changes.push({ field: key, before, after });
}
const names = (doc: Y.Doc) =>
doc
.getArray<any>("frontmatter.authors")
.toArray()
.map((x) => x?.name)
.filter(Boolean)
.join(", ");
if (names(from) !== names(to)) changes.push({ field: "authors", before: names(from), after: names(to) });
return changes;
}
/** Diff turning `from` (older) into `to` (newer). */
export function diffDocs(from: Y.Doc, to: Y.Doc): DocDiff {
const a = blocksOf(from);
const b = blocksOf(to);
const blocks: DiffBlock[] = [];
const stats = { added: 0, removed: 0, changed: 0 };
let removed: BlockInfo[] = [];
let added: BlockInfo[] = [];
const flush = () => {
const pairs = Math.min(removed.length, added.length);
for (let k = 0; k < pairs; k++) {
if (removed[k].type === added[k].type) {
blocks.push({ status: "changed", type: added[k].type, text: added[k].text, parts: wordDiff(removed[k].text, added[k].text) });
stats.changed++;
} else {
blocks.push({ status: "removed", type: removed[k].type, text: removed[k].text });
blocks.push({ status: "added", type: added[k].type, text: added[k].text });
stats.removed++;
stats.added++;
}
}
for (const r of removed.slice(pairs)) {
blocks.push({ status: "removed", type: r.type, text: r.text });
stats.removed++;
}
for (const x of added.slice(pairs)) {
blocks.push({ status: "added", type: x.type, text: x.text });
stats.added++;
}
removed = [];
added = [];
};
let i = 0;
for (const op of editScript(a.map((x) => x.key), b.map((x) => x.key))) {
if (op.kind === "keep") {
flush();
const block = a[i++];
blocks.push({ status: "same", type: block.type, text: block.text.slice(0, 240) });
} else if (op.kind === "delete") {
removed.push(a[i++]);
} else {
added.push(b[op.index]);
}
}
flush();
return { blocks, fields: fieldChanges(from, to), stats };
}