Skip to content

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

:bug: Preserve explicit descendant identities in DOM updates https://github.com/siyuan-note/siyuan/issues/21010

Daniel846a56186c08
diff --git a/kernel/model/block_update.go b/kernel/model/block_update.go
index d0f9fbea5b..ad528f402a 100644
--- a/kernel/model/block_update.go
+++ b/kernel/model/block_update.go
@@ -26,6 +26,7 @@ import (
"github.com/88250/lute/parse"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
+ htmlparser "golang.org/x/net/html"
)
// BlockUpdateInput 描述一个外部块更新请求。
@@ -158,7 +159,11 @@ func buildBlockUpdateOperations(inputs []BlockUpdateInput, resolveTree blockUpda
}
updatedNode.SetIALAttr("id", input.ID)
- pinDescendantBlockIDs(oldNode, updatedNode)
+ var explicitIDs map[string]bool
+ if input.DataType == "dom" {
+ explicitIDs = explicitBlockUpdateDOMIDs(input.Data)
+ }
+ pinDescendantBlockIDs(oldNode, updatedNode, explicitIDs)
data = luteEngine.Tree2BlockDOM(normalizedTree, luteEngine.RenderOptions, luteEngine.ParseOptions)
operations = append(operations, &Operation{
Action: "update",
@@ -261,30 +266,70 @@ func resolveBlockUpdateNode(oldNode, root *ast.Node) (updatedNode *ast.Node, err
// 子块 ID,导致指向子块的块引用、反链、闪卡等失效。
// 匹配规则:按同级内容块顺序对齐,类型一致才沿用旧 ID;类型不一致时向后查找同类型的旧子块重新
// 对齐,这样插入或删除子块后其余子块仍能匹配上旧 ID,新增的子块保持新生成的 ID。
-func pinDescendantBlockIDs(oldNode, updatedNode *ast.Node) {
- oldChildren := blockChildrenOf(oldNode)
- oldIndex := 0
- for _, newChild := range blockChildrenOf(updatedNode) {
- if oldIndex >= len(oldChildren) {
- break
+// DOM 显式提供的身份优先保留,位置回退不能占用这些身份。
+func pinDescendantBlockIDs(oldNode, updatedNode *ast.Node, explicitIDs map[string]bool) {
+ oldByID := map[string]*ast.Node{}
+ ast.Walk(oldNode, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && n.IsBlock() && n.ID != "" {
+ oldByID[n.ID] = n
}
- if oldChildren[oldIndex].Type != newChild.Type {
- if aligned := alignBlockUpdateChild(oldChildren, oldIndex, newChild.Type); 0 > aligned {
+ return ast.WalkContinue
+ })
+ var pin func(*ast.Node, *ast.Node)
+ pin = func(oldNode, updatedNode *ast.Node) {
+ oldChildren := blockChildrenOf(oldNode)
+ oldIndex := 0
+ for _, newChild := range blockChildrenOf(updatedNode) {
+ // Explicit DOM identities take precedence, even when reordered or newly inserted.
+ if explicitIDs[newChild.ID] {
+ if oldChild := oldByID[newChild.ID]; oldChild != nil {
+ pin(oldChild, newChild)
+ }
continue
- } else {
- oldIndex = aligned
+ }
+ // Do not assign an ID already reserved by another explicitly identified block.
+ for oldIndex < len(oldChildren) && explicitIDs[oldChildren[oldIndex].ID] {
+ oldIndex++
+ }
+ if oldIndex >= len(oldChildren) {
+ continue
+ }
+ if oldChildren[oldIndex].Type != newChild.Type {
+ if aligned := alignBlockUpdateChild(oldChildren, oldIndex, newChild.Type, explicitIDs); 0 > aligned {
+ continue
+ } else {
+ oldIndex = aligned
+ }
+ }
+ newChild.SetIALAttr("id", oldChildren[oldIndex].ID)
+ pin(oldChildren[oldIndex], newChild)
+ oldIndex++
+ }
+ }
+ pin(oldNode, updatedNode)
+}
+
+func explicitBlockUpdateDOMIDs(dom string) map[string]bool {
+ ids := map[string]bool{}
+ tokens := htmlparser.NewTokenizer(strings.NewReader(dom))
+ for {
+ switch tokens.Next() {
+ case htmlparser.ErrorToken:
+ return ids
+ case htmlparser.StartTagToken, htmlparser.SelfClosingTagToken:
+ for _, attr := range tokens.Token().Attr {
+ if attr.Key == "data-node-id" && ast.IsNodeIDPattern(attr.Val) {
+ ids[attr.Val] = true
+ }
}
}
- newChild.SetIALAttr("id", oldChildren[oldIndex].ID)
- pinDescendantBlockIDs(oldChildren[oldIndex], newChild)
- oldIndex++
}
}
// alignBlockUpdateChild 从 start 起向后查找第一个指定类型的旧子块,返回其下标;找不到返回 -1。
-func alignBlockUpdateChild(oldChildren []*ast.Node, start int, childType ast.NodeType) int {
+func alignBlockUpdateChild(oldChildren []*ast.Node, start int, childType ast.NodeType, reserved map[string]bool) int {
for i := start; i < len(oldChildren); i++ {
- if oldChildren[i].Type == childType {
+ if oldChildren[i].Type == childType && !reserved[oldChildren[i].ID] {
return i
}
}
diff --git a/kernel/model/block_update_fts5_test.go b/kernel/model/block_update_fts5_test.go
new file mode 100644
index 0000000000..eab671c3c1
--- /dev/null
+++ b/kernel/model/block_update_fts5_test.go
@@ -0,0 +1,56 @@
+//go:build fts5
+
+package model
+
+import (
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestContainerDOMReorderKeepsPersistedContentIdentity(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ tree, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ quote := &ast.Node{Type: ast.NodeBlockquote, ID: ast.NewNodeID()}
+ quote.SetIALAttr("id", quote.ID)
+ want := map[string]string{}
+ for _, text := range []string{"A", "B"} {
+ p := treenode.NewParagraph(ast.NewNodeID())
+ p.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(text)})
+ quote.AppendChild(p)
+ want[p.ID] = text
+ }
+ tree.Root.AppendChild(quote)
+ if err := indexWriteTreeUpsertQueue(tree); err != nil {
+ t.Fatal(err)
+ }
+ sql.FlushQueue()
+ engine := util.NewLute()
+ domTree := engine.BlockDOM2Tree(GetBlockDOM(quote.ID))
+ updated := firstContentBlock(domTree.Root)
+ children := blockChildrenOf(updated)
+ children[1].Unlink()
+ updated.PrependChild(children[1])
+ dom := engine.Tree2BlockDOM(domTree, engine.RenderOptions, engine.ParseOptions)
+ if _, _, err = PerformBlockUpdates([]BlockUpdateInput{{ID: quote.ID, DataType: "dom", Data: dom}}); err != nil {
+ t.Fatal(err)
+ }
+ actual, err := filesys.LoadTree(tree.Box, tree.Path, engine)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for id, text := range want {
+ p := treenode.GetNodeInTree(actual, id)
+ if p == nil || p.FirstChild == nil || string(p.FirstChild.Tokens) != text {
+ t.Fatalf("persisted identity %s no longer contains %s", id, text)
+ }
+ }
+}
diff --git a/kernel/model/block_update_test.go b/kernel/model/block_update_test.go
index 38bf08c341..7041052551 100644
--- a/kernel/model/block_update_test.go
+++ b/kernel/model/block_update_test.go
@@ -17,6 +17,7 @@
package model
import (
+ "regexp"
"strings"
"testing"
@@ -408,3 +409,85 @@ func parseBlockUpdateDOMIDs(t *testing.T, name, data string) map[string]bool {
})
return ids
}
+
+func TestBuildBlockUpdateOperationsPreservesExplicitDOMIdentity(t *testing.T) {
+ for _, mode := range []string{"reorder", "insert", "insertWithoutID", "positionalFallback"} {
+ t.Run(mode, func(t *testing.T) {
+ engine := util.NewLute()
+ root := &ast.Node{Type: ast.NodeDocument, ID: updateTestRoot}
+ quote := &ast.Node{Type: ast.NodeBlockquote, ID: updateTestList}
+ quote.SetIALAttr("id", quote.ID)
+ paragraph := func(id, text string) *ast.Node {
+ n := &ast.Node{Type: ast.NodeParagraph, ID: id}
+ if id != "" {
+ n.SetIALAttr("id", id)
+ }
+ n.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(text)})
+ return n
+ }
+ quote.AppendChild(paragraph(updateTestPara1, "A"))
+ quote.AppendChild(paragraph(updateTestPara2, "B"))
+ root.AppendChild(quote)
+ updated := &ast.Node{Type: ast.NodeBlockquote, ID: quote.ID}
+ updated.SetIALAttr("id", quote.ID)
+ want := map[string]string{"A": updateTestPara1, "B": updateTestPara2}
+ switch mode {
+ case "reorder":
+ updated.AppendChild(paragraph(updateTestPara2, "B"))
+ updated.AppendChild(paragraph(updateTestPara1, "A"))
+ case "insert", "insertWithoutID":
+ id := ast.NewNodeID()
+ if mode == "insertWithoutID" {
+ id = ""
+ } else {
+ want["new"] = id
+ }
+ updated.AppendChild(paragraph(id, "new"))
+ updated.AppendChild(paragraph(updateTestPara1, "A"))
+ updated.AppendChild(paragraph(updateTestPara2, "B"))
+ case "positionalFallback":
+ updated.AppendChild(paragraph("", "A"))
+ updated.AppendChild(paragraph("", "B"))
+ }
+ tree := &parse.Tree{ID: root.ID, Box: updateTestBoxID, Root: root}
+ dom := engine.RenderNodeBlockDOM(updated)
+ if mode == "positionalFallback" || mode == "insertWithoutID" {
+ dom = regexp.MustCompile(`data-node-id="[^"]+"`).ReplaceAllStringFunc(dom, func(attr string) string {
+ if strings.Contains(attr, quote.ID) {
+ return attr
+ }
+ if mode == "insertWithoutID" && (strings.Contains(attr, updateTestPara1) || strings.Contains(attr, updateTestPara2)) {
+ return attr
+ }
+ return ""
+ })
+ }
+ ops, _, err := buildBlockUpdateOperations([]BlockUpdateInput{{ID: quote.ID, DataType: "dom", Data: dom}},
+ func(id string) *treenode.BlockTree {
+ return &treenode.BlockTree{ID: id, RootID: root.ID, BoxID: updateTestBoxID}
+ },
+ func(string) (*parse.Tree, error) { return tree, nil })
+ if err != nil {
+ t.Fatal(err)
+ }
+ actual := engine.BlockDOM2Tree(ops[0].Data.(string))
+ seen := map[string]bool{}
+ ast.Walk(actual.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && n.Type == ast.NodeParagraph {
+ if seen[n.ID] {
+ t.Fatalf("duplicate paragraph ID: %s", n.ID)
+ }
+ seen[n.ID] = true
+ text := string(n.FirstChild.Tokens)
+ if id := want[text]; id != "" && n.ID != id {
+ t.Fatalf("%s identity = %s, want %s", text, n.ID, id)
+ }
+ if text == "new" && (n.ID == updateTestPara1 || n.ID == updateTestPara2) {
+ t.Fatal("new content stole an existing identity")
+ }
+ }
+ return ast.WalkContinue
+ })
+ })
+ }
+}