File size: 4,833 Bytes
62809b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/**
 * 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 };
}