Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Improve document version comparison accuracy https://github.com/siyuan-note/siyuan/issues/11601

Daniele5e672d6e042
diff --git a/app/src/assets/scss/business/_history.scss b/app/src/assets/scss/business/_history.scss
index b7cb164991..3c9015120a 100644
--- a/app/src/assets/scss/business/_history.scss
+++ b/app/src/assets/scss/business/_history.scss
@@ -286,6 +286,12 @@
}
}
+@media (hover: none) {
+ .history__side .b3-list-item--hide-action > [data-type="selectVersion"] {
+ display: flex;
+ }
+}
+
@keyframes history-diff-focus {
0%,
40% {
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 1e088c9cbf..8cee949103 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -1348,13 +1348,17 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
matchDialog = undefined;
}
if (matchDialog) {
+ let handled = false;
if (matchDialog.element.getAttribute("data-key") === Constants.DIALOG_VIEWCARDS) {
matchDialog.element.dispatchEvent(new CustomEvent("click", {detail: event.key.toLowerCase()}));
+ handled = true;
} else if (matchDialog.element.getAttribute("data-key") === Constants.DIALOG_HISTORYCOMPARE) {
- historyKeydown(event, matchDialog);
+ handled = historyKeydown(event, matchDialog);
+ }
+ if (handled) {
+ event.preventDefault();
+ return;
}
- event.preventDefault();
- return;
}
}
diff --git a/app/src/history/diff.ts b/app/src/history/diff.ts
index 6ad6ad463f..6488278aa2 100644
--- a/app/src/history/diff.ts
+++ b/app/src/history/diff.ts
@@ -13,6 +13,7 @@ import {renderAssetsPreview} from "../asset/renderAssets";
import {resizeSide} from "./resizeSide";
import {confirmDialog} from "../dialog/confirmDialog";
import {showDocVersionDiff} from "./docDiff";
+import {pairSnapshotFilesByPath} from "./snapshotDiffCore";
type SnapshotDiffAggregate = "all" | "data" | "extension" | "other";
type SnapshotFileKind = "document" | "database" | "asset" | "plugin" | "widget" | "template" | "snippet" | "bazaar" | "workspaceData" | "other";
@@ -141,10 +142,9 @@ const buildSnapshotDiffResult = (data: {
removesRight: SnapshotFile[];
}): SnapshotDiffResult => {
return {
- updates: (data.updatesLeft || []).map((file, index) => ({
- file,
- compareFile: data.updatesRight?.[index],
- kind: getSnapshotFileKind(file.path),
+ updates: pairSnapshotFilesByPath(data.updatesLeft || [], data.updatesRight || []).map((item) => ({
+ ...item,
+ kind: getSnapshotFileKind(item.file.path),
})),
adds: (data.addsLeft || []).map((file) => ({
file,
diff --git a/app/src/history/docDiff.ts b/app/src/history/docDiff.ts
index 1eb9433418..c46f7dd7b0 100644
--- a/app/src/history/docDiff.ts
+++ b/app/src/history/docDiff.ts
@@ -246,7 +246,7 @@ export const showDocVersionDiff = (app: App, firstRef: IDocVersionRef, secondRef
const focusDifference = (step: number) => {
if (!diff || visibleDifferences.length === 0) {
- return;
+ return false;
}
differenceIndex = (differenceIndex + step + visibleDifferences.length) % visibleDifferences.length;
rootElement.querySelectorAll(".history__diff--focus").forEach((item) => {
@@ -273,6 +273,7 @@ export const showDocVersionDiff = (app: App, firstRef: IDocVersionRef, secondRef
isSyncingScroll = false;
});
renderCount();
+ return true;
};
const setupScrollSync = () => {
@@ -366,11 +367,13 @@ export const showDocVersionDiff = (app: App, firstRef: IDocVersionRef, secondRef
type: leftRef.type,
id: leftRef.id || "",
path: leftRef.path || "",
+ snapshot: leftRef.snapshot || "",
},
right: {
type: rightRef.type,
id: rightRef.id || "",
path: rightRef.path || "",
+ snapshot: rightRef.snapshot || "",
}
});
if (isDestroyed || currentRequestId !== requestId) {
@@ -418,10 +421,14 @@ export const showDocVersionDiff = (app: App, firstRef: IDocVersionRef, secondRef
}
});
dialog.element.addEventListener("historyKeydown", (event: CustomEvent<string>) => {
+ let handled = false;
if (event.detail === "ArrowUp") {
- focusDifference(-1);
+ handled = focusDifference(-1);
} else if (event.detail === "ArrowDown") {
- focusDifference(1);
+ handled = focusDifference(1);
+ }
+ if (handled) {
+ event.preventDefault();
}
});
diff --git a/app/src/history/keydown.ts b/app/src/history/keydown.ts
index 035be82b7f..7caacac2da 100644
--- a/app/src/history/keydown.ts
+++ b/app/src/history/keydown.ts
@@ -3,43 +3,45 @@ import {Dialog} from "../dialog";
export const historyKeydown = (event: KeyboardEvent, dialog: Dialog) => {
if (dialog.element.querySelector(".history__doc-compare")) {
if (["ArrowUp", "ArrowDown"].includes(event.key)) {
- dialog.element.dispatchEvent(new CustomEvent("historyKeydown", {detail: event.key}));
+ const keydownEvent = new CustomEvent("historyKeydown", {
+ cancelable: true,
+ detail: event.key,
+ });
+ dialog.element.dispatchEvent(keydownEvent);
+ return keydownEvent.defaultPrevented;
}
- return;
+ return false;
+ }
+ if (!["ArrowUp", "ArrowDown"].includes(event.key)) {
+ return false;
}
let currentItem = dialog.element.querySelector(".history__side .b3-list-item--focus");
const items = Array.from(dialog.element.querySelectorAll(".history__side .b3-list-item[data-id]"));
if (items.length < 2) {
- return;
+ return false;
}
if (!currentItem) {
currentItem = items[0];
} else {
currentItem.classList.remove("b3-list-item--focus");
- if (event.key === "Home") {
- currentItem = items[0];
- } else if (event.key === "End") {
- currentItem = items[items.length - 1];
- } else {
- items.find((item, index) => {
- if (item === currentItem) {
- if (event.key === "ArrowUp") {
- if (index === 0) {
- currentItem = items[items.length - 1];
- } else {
- currentItem = items[index - 1];
- }
- } else if (event.key === "ArrowDown") {
- if (index === items.length - 1) {
- currentItem = items[0];
- } else {
- currentItem = items[index + 1];
- }
+ items.find((item, index) => {
+ if (item === currentItem) {
+ if (event.key === "ArrowUp") {
+ if (index === 0) {
+ currentItem = items[items.length - 1];
+ } else {
+ currentItem = items[index - 1];
+ }
+ } else if (event.key === "ArrowDown") {
+ if (index === items.length - 1) {
+ currentItem = items[0];
+ } else {
+ currentItem = items[index + 1];
}
- return true;
}
- });
- }
+ return true;
+ }
+ });
}
currentItem.classList.add("b3-list-item--focus");
if (currentItem.parentElement.classList.contains("fn__none")) {
@@ -55,4 +57,5 @@ export const historyKeydown = (event: KeyboardEvent, dialog: Dialog) => {
currentItem.scrollIntoView();
}
dialog.element.dispatchEvent(new CustomEvent("click", {detail: event.key.toLowerCase()}));
+ return true;
};
diff --git a/app/src/history/snapshotDiffCore.test.ts b/app/src/history/snapshotDiffCore.test.ts
new file mode 100644
index 0000000000..78d2e9ef3e
--- /dev/null
+++ b/app/src/history/snapshotDiffCore.test.ts
@@ -0,0 +1,22 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {pairSnapshotFilesByPath} from "./snapshotDiffCore";
+
+describe("pairSnapshotFilesByPath", () => {
+ it("pairs updated files by path when one side contains an unmatched file", () => {
+ const left = [
+ {path: "/data/a.sy", id: "left-a"},
+ {path: "/data/b.sy", id: "left-b"},
+ ];
+ const right = [
+ {path: "/data/missing.sy", id: "right-missing"},
+ {path: "/data/b.sy", id: "right-b"},
+ {path: "\\data\\a.sy", id: "right-a"},
+ ];
+
+ const paired = pairSnapshotFilesByPath(left, right);
+
+ assert.equal(paired[0].compareFile?.id, "right-a");
+ assert.equal(paired[1].compareFile?.id, "right-b");
+ });
+});
diff --git a/app/src/history/snapshotDiffCore.ts b/app/src/history/snapshotDiffCore.ts
new file mode 100644
index 0000000000..0f93ea18be
--- /dev/null
+++ b/app/src/history/snapshotDiffCore.ts
@@ -0,0 +1,9 @@
+export const pairSnapshotFilesByPath = <T extends {path: string}>(left: T[], right: T[]) => {
+ const rightByPath = new Map(right.map((file) => {
+ return [file.path.replaceAll("\\", "/"), file];
+ }));
+ return left.map((file) => ({
+ file,
+ compareFile: rightByPath.get(file.path.replaceAll("\\", "/")),
+ }));
+};
diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.go
index cbc939711b..f16a124b67 100644
--- a/kernel/filesys/tree.go
+++ b/kernel/filesys/tree.go
@@ -211,6 +211,19 @@ func LoadTree(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, err erro
return
}
+// NormalizeTreeForRead 对只读树应用与文件加载一致的规范化处理,但不写回磁盘。
+func NormalizeTreeForRead(tree *parse.Tree) (err error) {
+ if nil == tree || nil == tree.Root {
+ return errors.New("tree is empty")
+ }
+ if err = treenode.CheckSpec(tree); nil != err {
+ return
+ }
+ treenode.UpgradeSpec(tree)
+ escapeAttributeValues(tree)
+ return
+}
+
func LoadTreeByData(data []byte, boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, err error) {
ret, err = parseJSON2Tree(boxID, p, data, luteEngine)
if nil != err {
diff --git a/kernel/model/history_diff.go b/kernel/model/history_diff.go
index 344d7cfcd4..3c085fcd87 100644
--- a/kernel/model/history_diff.go
+++ b/kernel/model/history_diff.go
@@ -150,6 +150,14 @@ func DiffDocVersions(leftRef, rightRef *DocVersionRef) (ret *DocVersionDiffResul
ret.Right = renderLargeDocVersion(right)
return
}
+ left.av, err = loadDocVersionAttributeViewSignatures(leftRef, left)
+ if err != nil {
+ return nil, err
+ }
+ right.av, err = loadDocVersionAttributeViewSignatures(rightRef, right)
+ if err != nil {
+ return nil, err
+ }
leftBlocks, leftChildren, leftOrder := collectDocDiffBlocks(left.tree, left.av)
rightBlocks, rightChildren, rightOrder := collectDocDiffBlocks(right.tree, right.av)
@@ -230,12 +238,6 @@ func loadDocVersion(ref *DocVersionRef) (ret *loadedDocVersion, err error) {
if nil != ret.tree && "" == ret.title {
ret.title = ret.tree.Root.IALAttr("title")
}
- if nil != ret.tree {
- ret.av, err = loadDocVersionAttributeViewSignatures(ref, ret)
- if err != nil {
- return nil, err
- }
- }
if "" == ret.title {
ret.title = ret.rootID
}
@@ -426,10 +428,9 @@ func parseDocVersionTree(data []byte, rootID string) (ret *parse.Tree, err error
if err != nil {
return
}
- if err = treenode.CheckSpec(ret); err != nil {
+ if err = filesys.NormalizeTreeForRead(ret); err != nil {
return nil, err
}
- treenode.UpgradeSpec(ret)
if ast.IsNodeIDPattern(rootID) && rootID != ret.Root.ID {
ret.ID = rootID
ret.Root.ID = rootID
@@ -645,7 +646,7 @@ func docDiffBlockSignatureWithAttributeViews(block *ast.Node, attributeViews map
if !entering {
return ast.WalkContinue
}
- if n != block && n.IsBlock() {
+ if n != block && n.IsBlock() && "" != n.ID {
return ast.WalkSkipChildren
}
builder.WriteByte('|')
@@ -752,124 +753,71 @@ func filterSharedDocBlockIDs(ids []string, other map[string]*docDiffBlock) (ret
return
}
-func markDocInlineDiff(left, right *ast.Node) {
- leftRunes, leftSegments, leftOK := collectDocTextSegments(left)
- rightRunes, rightSegments, rightOK := collectDocTextSegments(right)
- if leftOK && rightOK {
- matches, ok := lcsMatches(leftRunes, rightRunes, docDiffMaxLCSCells)
- if ok {
- leftChanged := make([]bool, len(leftRunes))
- rightChanged := make([]bool, len(rightRunes))
- for i := range leftChanged {
- leftChanged[i] = true
- }
- for i := range rightChanged {
- rightChanged[i] = true
- }
- for _, match := range matches {
- leftChanged[match[0]] = false
- rightChanged[match[1]] = false
- }
- leftSignatures := docTextSegmentSignatures(leftSegments, len(leftRunes))
- rightSignatures := docTextSegmentSignatures(rightSegments, len(rightRunes))
- for _, match := range matches {
- if leftSignatures[match[0]] != rightSignatures[match[1]] {
- leftChanged[match[0]] = true
- rightChanged[match[1]] = true
- }
- }
- applyDocTextDiff(leftSegments, leftChanged)
- applyDocTextDiff(rightSegments, rightChanged)
- }
- }
- markDocAtomicInlineDiff(left, right)
+type docInlineTokenKey struct {
+ kind uint8
+ content string
+ context string
}
type docAtomicInline struct {
- node *ast.Node
- signature string
+ node *ast.Node
+ index int
+}
+
+func markDocInlineDiff(left, right *ast.Node) {
+ markDocInlineDiffWithBudget(left, right, &docDiffLCSBudget{remaining: docDiffMaxTotalLCSCells})
}
-func markDocAtomicInlineDiff(left, right *ast.Node) {
- leftNodes := collectDocAtomicInlineNodes(left)
- rightNodes := collectDocAtomicInlineNodes(right)
- leftSignatures := make([]string, 0, len(leftNodes))
- rightSignatures := make([]string, 0, len(rightNodes))
- for _, item := range leftNodes {
- leftSignatures = append(leftSignatures, item.signature)
- }
- for _, item := range rightNodes {
- rightSignatures = append(rightSignatures, item.signature)
- }
- matches, ok := lcsMatches(leftSignatures, rightSignatures, docDiffMaxLCSCells)
+func markDocInlineDiffWithBudget(left, right *ast.Node, budget *docDiffLCSBudget) {
+ leftTokens, leftSegments, leftAtomic := collectDocInlineTokens(left)
+ rightTokens, rightSegments, rightAtomic := collectDocInlineTokens(right)
+ matches, ok := lcsMatchesWithBudget(leftTokens, rightTokens, docDiffMaxLCSCells, budget)
if !ok {
return
}
- leftMatched := make([]bool, len(leftNodes))
- rightMatched := make([]bool, len(rightNodes))
+ leftChanged := make([]bool, len(leftTokens))
+ rightChanged := make([]bool, len(rightTokens))
+ for i := range leftChanged {
+ leftChanged[i] = true
+ }
+ for i := range rightChanged {
+ rightChanged[i] = true
+ }
for _, match := range matches {
- leftMatched[match[0]] = true
- rightMatched[match[1]] = true
+ leftChanged[match[0]] = false
+ rightChanged[match[1]] = false
}
- for i, item := range leftNodes {
- if !leftMatched[i] {
- item.node.SetIALAttr("data-history-diff", "inline")
+ leftSignatures := docTextSegmentSignatures(leftSegments, len(leftTokens))
+ rightSignatures := docTextSegmentSignatures(rightSegments, len(rightTokens))
+ for _, match := range matches {
+ if 0 == leftTokens[match[0]].kind && leftSignatures[match[0]] != rightSignatures[match[1]] {
+ leftChanged[match[0]] = true
+ rightChanged[match[1]] = true
}
}
- for i, item := range rightNodes {
- if !rightMatched[i] {
+ applyDocTextDiff(leftSegments, leftChanged)
+ applyDocTextDiff(rightSegments, rightChanged)
+ for _, item := range leftAtomic {
+ if leftChanged[item.index] {
item.node.SetIALAttr("data-history-diff", "inline")
}
}
-}
-
-func collectDocAtomicInlineNodes(block *ast.Node) (ret []*docAtomicInline) {
- ast.Walk(block, func(n *ast.Node, entering bool) ast.WalkStatus {
- if !entering {
- return ast.WalkContinue
- }
- if n != block && n.IsBlock() {
- return ast.WalkSkipChildren
- }
- if ast.NodeTextMark != n.Type || "" != n.TextMarkTextContent {
- return ast.WalkContinue
- }
- ret = append(ret, &docAtomicInline{
- node: n,
- signature: strings.Join([]string{
- n.TextMarkType,
- n.TextMarkInlineMathContent,
- n.TextMarkAHref,
- n.TextMarkATitle,
- n.TextMarkBlockRefID,
- n.TextMarkFileAnnotationRefID,
- n.TextMarkInlineMemoContent,
- }, "\x00"),
- })
- return ast.WalkContinue
- })
- return
-}
-
-func docTextSegmentSignatures(segments []*docTextSegment, length int) (ret []string) {
- ret = make([]string, length)
- for _, segment := range segments {
- for i := segment.start; i < segment.end; i++ {
- ret[i] = segment.signature
+ for _, item := range rightAtomic {
+ if rightChanged[item.index] {
+ item.node.SetIALAttr("data-history-diff", "inline")
}
}
- return
}
-func collectDocTextSegments(block *ast.Node) (runes []rune, segments []*docTextSegment, ok bool) {
- ok = true
+func collectDocInlineTokens(block *ast.Node) (tokens []docInlineTokenKey, segments []*docTextSegment, atomic []*docAtomicInline) {
ast.Walk(block, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
- if n != block && n.IsBlock() {
+ if n != block && n.IsBlock() && "" != n.ID {
return ast.WalkSkipChildren
}
+ context := docInlineStructuralContext(n, block)
var visible []rune
var storedRuns []string
switch n.Type {
@@ -880,6 +828,9 @@ func collectDocTextSegments(block *ast.Node) (runes []rune, segments []*docTextS
}
case ast.NodeTextMark:
if "" == n.TextMarkTextContent || n.IsTextMarkType("inline-math") {
+ signature := docAtomicInlineSignature(n)
+ atomic = append(atomic, &docAtomicInline{node: n, index: len(tokens)})
+ tokens = append(tokens, docInlineTokenKey{kind: 1, content: signature, context: context})
return ast.WalkContinue
}
visible, storedRuns = decodeDocTextMarkContent(n)
@@ -889,12 +840,14 @@ func collectDocTextSegments(block *ast.Node) (runes []rune, segments []*docTextS
if 0 == len(visible) {
return ast.WalkContinue
}
- start := len(runes)
- runes = append(runes, visible...)
+ start := len(tokens)
+ for _, r := range visible {
+ tokens = append(tokens, docInlineTokenKey{content: string(r), context: context})
+ }
segments = append(segments, &docTextSegment{
node: n,
start: start,
- end: len(runes),
+ end: len(tokens),
storedRuns: storedRuns,
signature: docTextNodeSignature(n),
})
@@ -903,6 +856,48 @@ func collectDocTextSegments(block *ast.Node) (runes []rune, segments []*docTextS
return
}
+func docAtomicInlineSignature(node *ast.Node) string {
+ return strings.Join([]string{
+ node.TextMarkType,
+ node.TextMarkInlineMathContent,
+ node.TextMarkAHref,
+ node.TextMarkATitle,
+ node.TextMarkBlockRefID,
+ node.TextMarkFileAnnotationRefID,
+ node.TextMarkInlineMemoContent,
+ }, "\x00")
+}
+
+func docInlineStructuralContext(node, block *ast.Node) string {
+ var parts []string
+ for parent := node.Parent; nil != parent && parent != block; parent = parent.Parent {
+ if ast.NodeTableRow != parent.Type && ast.NodeTableCell != parent.Type {
+ continue
+ }
+ index := 0
+ for previous := parent.Previous; nil != previous; previous = previous.Previous {
+ if previous.Type == parent.Type {
+ index++
+ }
+ }
+ parts = append(parts, parent.Type.String()+":"+strconv.Itoa(index))
+ }
+ for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
+ parts[i], parts[j] = parts[j], parts[i]
+ }
+ return strings.Join(parts, "/")
+}
+
+func docTextSegmentSignatures(segments []*docTextSegment, length int) (ret []string) {
+ ret = make([]string, length)
+ for _, segment := range segments {
+ for i := segment.start; i < segment.end; i++ {
+ ret[i] = segment.signature
+ }
+ }
+ return
+}
+
func docTextNodeSignature(node *ast.Node) string {
if ast.NodeText == node.Type {
return node.Type.String()
@@ -1042,11 +1037,48 @@ func cloneDocTextNode(node *ast.Node) *ast.Node {
}
func lcsMatches[T comparable](left, right []T, maxCells int) (matches [][2]int, ok bool) {
+ return lcsMatchesWithBudget(left, right, maxCells, &docDiffLCSBudget{remaining: maxCells})
+}
+
+func lcsMatchesWithBudget[T comparable](left, right []T, maxCells int,
+ budget *docDiffLCSBudget) (matches [][2]int, ok bool) {
if 0 == len(left) || 0 == len(right) {
return [][2]int{}, true
}
- if len(left) > maxCells/len(right) {
- return nil, false
+ prefix := 0
+ for prefix < len(left) && prefix < len(right) && left[prefix] == right[prefix] {
+ matches = append(matches, [2]int{prefix, prefix})
+ prefix++
+ }
+ suffix := 0
+ for prefix+suffix < len(left) && prefix+suffix < len(right) &&
+ left[len(left)-suffix-1] == right[len(right)-suffix-1] {
+ suffix++
+ }
+ leftMiddle := left[prefix : len(left)-suffix]
+ rightMiddle := right[prefix : len(right)-suffix]
+ if 0 < len(leftMiddle) && 0 < len(rightMiddle) {
+ height := len(leftMiddle) + 1
+ width := len(rightMiddle) + 1
+ if height > maxCells/width || nil == budget || height > budget.remaining/width {
+ return nil, false
+ }
+ cells := height * width
+ budget.remaining -= cells
+ middleMatches := lcsMatchesTable(leftMiddle, rightMiddle)
+ for _, match := range middleMatches {
+ matches = append(matches, [2]int{match[0] + prefix, match[1] + prefix})
+ }
+ }
+ for i := suffix; 0 < i; i-- {
+ matches = append(matches, [2]int{len(left) - i, len(right) - i})
+ }
+ return matches, true
+}
+
+func lcsMatchesTable[T comparable](left, right []T) (matches [][2]int) {
+ if 0 == len(left) || 0 == len(right) {
+ return
}
width := len(right) + 1
table := make([]int, (len(left)+1)*width)
@@ -1073,7 +1105,7 @@ func lcsMatches[T comparable](left, right []T, maxCells int) (matches [][2]int,
j++
}
}
- return matches, true
+ return matches
}
func setDocDiffBlockAttrs(node *ast.Node, statuses []string) {
diff --git a/kernel/model/history_diff_test.go b/kernel/model/history_diff_test.go
index e033c4e6dd..0c6f9d3bee 100644
--- a/kernel/model/history_diff_test.go
+++ b/kernel/model/history_diff_test.go
@@ -22,6 +22,9 @@ import (
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
+ "github.com/88250/lute/render"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -42,11 +45,42 @@ func TestDocDiffLCSMatches(t *testing.T) {
}
func TestDocDiffLCSBudget(t *testing.T) {
- if _, ok := lcsMatches(make([]rune, 2000), make([]rune, 2000), docDiffMaxLCSCells); ok {
+ left := make([]rune, 2000)
+ right := make([]rune, 2000)
+ for i := range left {
+ left[i] = 'a'
+ right[i] = 'b'
+ }
+ if _, ok := lcsMatches(left, right, docDiffMaxLCSCells); ok {
t.Fatal("expected LCS calculation to exceed its budget")
}
}
+func TestDocDiffLCSCumulativeBudget(t *testing.T) {
+ left := make([]int, 1000)
+ right := make([]int, 1000)
+ for i := range left {
+ left[i] = i
+ right[i] = i + len(left)
+ }
+ budget := &docDiffLCSBudget{remaining: 1_500_000}
+ if _, ok := lcsMatchesWithBudget(left, right, docDiffMaxLCSCells, budget); !ok {
+ t.Fatal("expected the first LCS calculation to fit the cumulative budget")
+ }
+ if _, ok := lcsMatchesWithBudget(left, right, docDiffMaxLCSCells, budget); ok {
+ t.Fatal("expected the second LCS calculation to exceed the cumulative budget")
+ }
+}
+
+func TestDocDiffLCSEqualFastPath(t *testing.T) {
+ values := make([]rune, 3000)
+ budget := &docDiffLCSBudget{remaining: 0}
+ matches, ok := lcsMatchesWithBudget(values, values, docDiffMaxLCSCells, budget)
+ if !ok || len(matches) != len(values) {
+ t.Fatal("expected equal values to use the LCS fast path")
+ }
+}
+
func TestDecodeDocTextMarkContentPreservesEntities(t *testing.T) {
node := &ast.Node{
Type: ast.NodeTextMark,
@@ -128,6 +162,58 @@ func TestMarkDocInlineMathDiff(t *testing.T) {
}
}
+func TestMarkDocInlineMathMove(t *testing.T) {
+ left := &ast.Node{Type: ast.NodeParagraph, ID: "20260729000000-left01"}
+ left.AppendChild(&ast.Node{
+ Type: ast.NodeTextMark,
+ TextMarkType: "inline-math",
+ TextMarkInlineMathContent: "a+b",
+ })
+ left.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("text")})
+ right := &ast.Node{Type: ast.NodeParagraph, ID: "20260729000000-right1"}
+ right.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("text")})
+ right.AppendChild(&ast.Node{
+ Type: ast.NodeTextMark,
+ TextMarkType: "inline-math",
+ TextMarkInlineMathContent: "a+b",
+ })
+
+ markDocInlineDiff(left, right)
+
+ if "inline" != left.FirstChild.IALAttr("data-history-diff") {
+ t.Fatal("expected the moved inline math on the left to be marked")
+ }
+ if "inline" != right.LastChild.IALAttr("data-history-diff") {
+ t.Fatal("expected the moved inline math on the right to be marked")
+ }
+}
+
+func TestMarkDocInlineTableCellBoundary(t *testing.T) {
+ newTable := func(first, second string) *ast.Node {
+ table := &ast.Node{Type: ast.NodeTable, ID: "20260729000000-table01"}
+ row := &ast.Node{Type: ast.NodeTableRow}
+ firstCell := &ast.Node{Type: ast.NodeTableCell}
+ firstCell.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(first)})
+ secondCell := &ast.Node{Type: ast.NodeTableCell}
+ secondCell.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(second)})
+ row.AppendChild(firstCell)
+ row.AppendChild(secondCell)
+ table.AppendChild(row)
+ return table
+ }
+ left := newTable("ab", "c")
+ right := newTable("a", "bc")
+
+ markDocInlineDiff(left, right)
+
+ if dom := util.NewLute().RenderNodeBlockDOM(left); !strings.Contains(dom, `data-history-diff="inline"`) {
+ t.Fatalf("expected text moved across table cells to be marked, got [%s]", dom)
+ }
+ if dom := util.NewLute().RenderNodeBlockDOM(right); !strings.Contains(dom, `data-history-diff="inline"`) {
+ t.Fatalf("expected text moved across table cells to be marked, got [%s]", dom)
+ }
+}
+
func TestRenderFallbackDocVersionUsesRawContent(t *testing.T) {
version := &loadedDocVersion{
tree: &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument, ID: "20260729000000-root001"}},
@@ -143,6 +229,33 @@ func TestRenderFallbackDocVersionUsesRawContent(t *testing.T) {
}
}
+func TestParseDocVersionTreeNormalizesSpecAndRootID(t *testing.T) {
+ oldConf := Conf
+ Conf = NewAppConf()
+ Conf.Editor = conf.NewEditor()
+ Conf.Export = conf.NewExport()
+ defer func() {
+ Conf = oldConf
+ }()
+ luteEngine := NewLute()
+ tree := parse.Parse("", []byte("content"), luteEngine.ParseOptions)
+ tree.Root.ID = "20260729000000-oldroot"
+ tree.Root.SetIALAttr("id", tree.Root.ID)
+ tree.Root.Spec = ""
+ data := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions).Render()
+
+ normalized, err := parseDocVersionTree(data, "20260729000000-newroot")
+ if err != nil {
+ t.Fatalf("expected document version normalization to succeed: %s", err)
+ }
+ if treenode.CurrentSpec != normalized.Root.Spec {
+ t.Fatalf("expected spec [%s], got [%s]", treenode.CurrentSpec, normalized.Root.Spec)
+ }
+ if "20260729000000-newroot" != normalized.Root.ID {
+ t.Fatalf("expected normalized root ID, got [%s]", normalized.Root.ID)
+ }
+}
+
func TestDocDiffBlockSignatureIgnoresDescendantsAndDisplayAttrs(t *testing.T) {
left := &ast.Node{
Type: ast.NodeBlockquote,
@@ -172,6 +285,35 @@ func TestDocDiffBlockSignatureIgnoresDescendantsAndDisplayAttrs(t *testing.T) {
}
}
+func TestDocDiffBlockSignatureIncludesAttributeViewContent(t *testing.T) {
+ block := &ast.Node{
+ Type: ast.NodeAttributeView,
+ ID: "20260729000000-block01",
+ AttributeViewID: "20260729000000-view001",
+ }
+ left := docDiffBlockSignatureWithAttributeViews(block, map[string]string{block.AttributeViewID: "left"})
+ right := docDiffBlockSignatureWithAttributeViews(block, map[string]string{block.AttributeViewID: "right"})
+ if left == right {
+ t.Fatal("expected attribute view content to affect the block signature")
+ }
+}
+
+func TestMergeDocDiffBlockOrder(t *testing.T) {
+ order := mergeDocDiffBlockOrder(
+ []string{"a", "deleted-before", "b", "deleted-after"},
+ []string{"a", "added", "b"},
+ )
+ expected := []string{"a", "added", "deleted-before", "b", "deleted-after"}
+ if len(order) != len(expected) {
+ t.Fatalf("expected %d block IDs, got %d", len(expected), len(order))
+ }
+ for i, id := range expected {
+ if order[i] != id {
+ t.Fatalf("expected block ID [%s] at index %d, got [%s]", id, i, order[i])
+ }
+ }
+}
+
func TestDetectMovedDocBlocks(t *testing.T) {
left := map[string]*docDiffBlock{
"a": {parentID: "root"},
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 9b89f395b9..5a8097ca5a 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -576,8 +576,8 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
}
luteEngine := NewLute()
for _, removeRight := range diff.RemovesRight {
- title, _, parseErr := parseTitleInSnapshot(removeRight.ID, repo, luteEngine)
- if "" == title || nil != parseErr {
+ title, _, _ := parseTitleInSnapshot(removeRight.ID, repo, luteEngine)
+ if "" == title {
continue
}
@@ -594,8 +594,8 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
}
for _, addLeft := range diff.AddsLeft {
- title, _, parseErr := parseTitleInSnapshot(addLeft.ID, repo, luteEngine)
- if "" == title || nil != parseErr {
+ title, _, _ := parseTitleInSnapshot(addLeft.ID, repo, luteEngine)
+ if "" == title {
continue
}
@@ -612,8 +612,8 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
}
for _, updateLeft := range diff.UpdatesLeft {
- title, _, parseErr := parseTitleInSnapshot(updateLeft.ID, repo, luteEngine)
- if "" == title || nil != parseErr {
+ title, _, _ := parseTitleInSnapshot(updateLeft.ID, repo, luteEngine)
+ if "" == title {
continue
}
@@ -630,8 +630,8 @@ func DiffRepoSnapshots(left, right string) (ret *LeftRightDiff, err error) {
}
for _, updateRight := range diff.UpdatesRight {
- title, _, parseErr := parseTitleInSnapshot(updateRight.ID, repo, luteEngine)
- if "" == title || nil != parseErr {
+ title, _, _ := parseTitleInSnapshot(updateRight.ID, repo, luteEngine)
+ if "" == title {
continue
}