Skip to content

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

:sparkles: Support transitive backlinks for document blocks https://github.com/siyuan-note/siyuan/issues/10990

Daniel88de47273121
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index 3b07b60cc6..87b010accf 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -424,13 +424,15 @@ func getBacklinkRenderNodes(n *ast.Node, originalRefBlockIDs map[string]string)
return
}
- for headingFirstSpan := c; nil != headingFirstSpan; headingFirstSpan = headingFirstSpan.Next {
- if treenode.IsBlockRef(headingFirstSpan) {
- continue
- }
- if "" != strings.TrimSpace(headingFirstSpan.Text()) {
- expand = false
- break
+ if "" == originalRefBlockIDs[n.ID] {
+ for headingFirstSpan := c; nil != headingFirstSpan; headingFirstSpan = headingFirstSpan.Next {
+ if treenode.IsBlockRef(headingFirstSpan) {
+ continue
+ }
+ if "" != strings.TrimSpace(headingFirstSpan.Text()) {
+ expand = false
+ break
+ }
}
}
@@ -625,32 +627,30 @@ func GetBacklinkInBox(id, keyword, mentionKeyword string, beforeLen int, contain
}
var linkRefs []*Block
- processedParagraphs := hashset.New()
- var paragraphParentIDs []string
+ var backlinkRefBlocks []*Block
for _, link := range links {
for _, ref := range link.Refs {
- if "NodeParagraph" == ref.Type {
- paragraphParentIDs = append(paragraphParentIDs, ref.ParentID)
- }
+ backlinkRefBlocks = append(backlinkRefBlocks, ref)
}
}
- paragraphParents := sql.GetBlocksInBox(paragraphParentIDs, boxID)
- for _, p := range paragraphParents {
- if nil == p {
+ coveredRefIDs := map[string]bool{}
+ originalRefBlockIDs := map[string]string{}
+ for _, mapping := range buildBacklinkParentMappings(backlinkRefBlocks, boxID) {
+ parent := sql.GetBlockInBox(mapping.parent.ID, boxID)
+ if nil == parent {
continue
}
-
- if "i" == p.Type || "h" == p.Type {
- linkRefs = append(linkRefs, fromSQLBlock(p, keyword, beforeLen))
- processedParagraphs.Add(p.ID)
+ originalRefBlockIDs[mapping.parent.ID] = mapping.refBlock.ID
+ for refID := range mapping.coveredRefIDs {
+ coveredRefIDs[refID] = true
}
+ linkRefsCount -= len(mapping.coveredRefIDs) - 1
+ linkRefs = append(linkRefs, fromSQLBlock(parent, keyword, beforeLen))
}
for _, link := range links {
for _, ref := range link.Refs {
- if "NodeParagraph" == ref.Type {
- if processedParagraphs.Contains(ref.ParentID) {
- continue
- }
+ if coveredRefIDs[ref.ID] {
+ continue
}
ref.DefID = link.ID
@@ -664,7 +664,7 @@ func GetBacklinkInBox(id, keyword, mentionKeyword string, beforeLen int, contain
linkRefs = append(linkRefs, ref)
}
}
- linkPaths = toSubTreeInBox(linkRefs, keyword, boxID)
+ linkPaths = toSubTreeInBox(linkRefs, keyword, boxID, originalRefBlockIDs)
mentions, _ := buildTreeBackmentionInBox(sqlBlock, linkRefs, mentionKeyword, excludeBacklinkIDs, beforeLen, boxID)
mentionsCount = len(mentions)
@@ -734,74 +734,36 @@ func buildLinkRefsInBox(defRootID string, refs []*sql.Ref, keywords []string, bo
refsCount += len(link.Refs)
}
- parentRefParagraphs := map[string]*Block{}
- var paragraphParentIDs []string
+ var backlinkRefBlocks []*Block
for _, link := range links {
for _, ref := range link.Refs {
- if "NodeParagraph" == ref.Type {
- parentRefParagraphs[ref.ParentID] = ref
- paragraphParentIDs = append(paragraphParentIDs, ref.ParentID)
- }
+ backlinkRefBlocks = append(backlinkRefBlocks, ref)
}
}
- refsCountDelta := len(paragraphParentIDs)
- paragraphParentIDs = gulu.Str.RemoveDuplicatedElem(paragraphParentIDs)
- refsCountDelta -= len(paragraphParentIDs)
- refsCount -= refsCountDelta
- sqlParagraphParents := sql.GetBlocksInBox(paragraphParentIDs, boxID)
- paragraphParents := fromSQLBlocks(&sqlParagraphParents, "", 12)
-
- luteEngine := util.NewLute()
originalRefBlockIDs = map[string]string{}
- processedParagraphs := hashset.New()
- for _, parent := range paragraphParents {
- if nil == parent {
- continue
+ refBlocksByID := map[string]*Block{}
+ for _, refBlock := range backlinkRefBlocks {
+ refBlocksByID[refBlock.ID] = refBlock
+ }
+ coveredRefIDs := map[string]bool{}
+ for _, mapping := range buildBacklinkParentMappings(backlinkRefBlocks, boxID) {
+ originalRefBlockIDs[mapping.parent.ID] = mapping.refBlock.ID
+ for refID := range mapping.coveredRefIDs {
+ coveredRefIDs[refID] = true
}
- if "NodeListItem" == parent.Type || "NodeBlockquote" == parent.Type || "NodeSuperBlock" == parent.Type || "NodeCallout" == parent.Type {
- refBlock := parentRefParagraphs[parent.ID]
- if nil == refBlock {
- continue
- }
-
- paragraphUseParentLi := true
- if "NodeListItem" == parent.Type && parent.FContent != refBlock.Content {
- if inlineTree := parse.Inline("", []byte(refBlock.Markdown), luteEngine.ParseOptions); nil != inlineTree {
- for c := inlineTree.Root.FirstChild.FirstChild; c != nil; c = c.Next {
- if treenode.IsBlockRef(c) {
- continue
- }
-
- if "" != strings.TrimSpace(c.Text()) {
- paragraphUseParentLi = false
- break
- }
- }
- }
- }
-
- if paragraphUseParentLi {
- processedParagraphs.Add(parent.ID)
- }
-
- originalRefBlockIDs[parent.ID] = refBlock.ID
- if !matchBacklinkKeyword(parent, keywords) {
- refsCount--
- continue
- }
-
- if paragraphUseParentLi {
- ret = append(ret, parent)
- }
+ if !matchBacklinkParentMapping(mapping, refBlocksByID, keywords, boxID) {
+ refsCount -= len(mapping.coveredRefIDs)
+ continue
}
+
+ refsCount -= len(mapping.coveredRefIDs) - 1
+ ret = append(ret, mapping.parent)
}
for _, link := range links {
for _, ref := range link.Refs {
- if "NodeParagraph" == ref.Type {
- if processedParagraphs.Contains(ref.ParentID) {
- continue
- }
+ if coveredRefIDs[ref.ID] {
+ continue
}
if !matchBacklinkKeyword(ref, keywords) {
@@ -821,7 +783,7 @@ func buildLinkRefsInBox(defRootID string, refs []*sql.Ref, keywords []string, bo
var headingIDs []string
for _, link := range links {
for _, ref := range link.Refs {
- if "NodeHeading" == ref.Type {
+ if "NodeHeading" == ref.Type && !coveredRefIDs[ref.ID] {
headingRefChildren[ref.ID] = ref
headingIDs = append(headingIDs, ref.ID)
}
diff --git a/kernel/model/backlink_parent.go b/kernel/model/backlink_parent.go
new file mode 100644
index 0000000000..de2ebcdc26
--- /dev/null
+++ b/kernel/model/backlink_parent.go
@@ -0,0 +1,293 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "sort"
+ "strings"
+
+ "github.com/88250/lute"
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type backlinkParentMapping struct {
+ parent *Block
+ refBlock *Block
+ coveredRefIDs map[string]bool
+ coveredIDs map[string]bool
+}
+
+func buildBacklinkParentMappings(refBlocks []*Block, boxID string) (ret []*backlinkParentMapping) {
+ parentRefParagraphs := map[string][]*Block{}
+ var paragraphParentIDs []string
+ for _, refBlock := range refBlocks {
+ if nil == refBlock || "NodeParagraph" != refBlock.Type {
+ continue
+ }
+
+ parentRefParagraphs[refBlock.ParentID] = append(parentRefParagraphs[refBlock.ParentID], refBlock)
+ paragraphParentIDs = append(paragraphParentIDs, refBlock.ParentID)
+ }
+ paragraphParentIDs = uniqueBacklinkStrings(paragraphParentIDs)
+ sqlParagraphParents := sql.GetBlocksInBox(paragraphParentIDs, boxID)
+ paragraphParents := fromSQLBlocks(&sqlParagraphParents, "", 12)
+
+ luteEngine := util.NewLute()
+ treeCache := map[string]*parse.Tree{}
+ var mappings []*backlinkParentMapping
+ for _, parent := range paragraphParents {
+ if nil == parent {
+ continue
+ }
+
+ refBlock := selectBacklinkParentRef(parent, parentRefParagraphs[parent.ID], boxID, luteEngine, treeCache)
+ if nil == refBlock {
+ continue
+ }
+
+ mappings = append(mappings, &backlinkParentMapping{
+ parent: parent,
+ refBlock: refBlock,
+ coveredRefIDs: map[string]bool{},
+ coveredIDs: map[string]bool{parent.ID: true},
+ })
+ }
+
+ propagatedDocIDs := map[string]bool{}
+ for _, mapping := range mappings {
+ if "NodeDocument" == mapping.parent.Type {
+ propagatedDocIDs[mapping.parent.ID] = true
+ for _, refBlock := range refBlocks {
+ if nil != refBlock && refBlock.RootID == mapping.parent.ID {
+ mapping.coveredRefIDs[refBlock.ID] = true
+ }
+ }
+ ret = append(ret, mapping)
+ }
+ }
+
+ var headingMappings []*backlinkParentMapping
+ for _, mapping := range mappings {
+ if "NodeHeading" != mapping.parent.Type || propagatedDocIDs[mapping.parent.RootID] {
+ continue
+ }
+
+ mapping.coveredIDs = backlinkHeadingCoveredIDs(mapping.parent, boxID, treeCache)
+ for _, refBlock := range refBlocks {
+ if nil != refBlock && mapping.coveredIDs[refBlock.ID] {
+ mapping.coveredRefIDs[refBlock.ID] = true
+ }
+ }
+ headingMappings = append(headingMappings, mapping)
+ }
+ sort.SliceStable(headingMappings, func(i, j int) bool {
+ return len(headingMappings[i].coveredIDs) > len(headingMappings[j].coveredIDs)
+ })
+
+ headingCoveredIDs := map[string]bool{}
+ for _, mapping := range headingMappings {
+ if headingCoveredIDs[mapping.parent.ID] {
+ continue
+ }
+
+ ret = append(ret, mapping)
+ for id := range mapping.coveredIDs {
+ headingCoveredIDs[id] = true
+ }
+ }
+
+ for _, mapping := range mappings {
+ if "NodeDocument" == mapping.parent.Type || "NodeHeading" == mapping.parent.Type ||
+ propagatedDocIDs[mapping.parent.RootID] || headingCoveredIDs[mapping.parent.ID] {
+ continue
+ }
+
+ for _, refBlock := range parentRefParagraphs[mapping.parent.ID] {
+ mapping.coveredRefIDs[refBlock.ID] = true
+ }
+ ret = append(ret, mapping)
+ }
+ return
+}
+
+func matchBacklinkParentMapping(mapping *backlinkParentMapping, refBlocksByID map[string]*Block, keywords []string,
+ boxID string) bool {
+ if matchBacklinkKeyword(mapping.parent, keywords) {
+ return true
+ }
+ for refID := range mapping.coveredRefIDs {
+ if refBlock := refBlocksByID[refID]; nil != refBlock && matchBacklinkKeyword(refBlock, keywords) {
+ return true
+ }
+ }
+ if 0 < len(keywords) && ("NodeDocument" == mapping.parent.Type || "NodeHeading" == mapping.parent.Type) {
+ sqlBlocks := sql.GetChildBlocksInBox(mapping.parent.ID, "", -1, boxID)
+ for _, block := range fromSQLBlocks(&sqlBlocks, "", 12) {
+ if nil != block && matchBacklinkKeyword(block, keywords) {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func selectBacklinkParentRef(parent *Block, refBlocks []*Block, boxID string, luteEngine *lute.Lute,
+ treeCache map[string]*parse.Tree) *Block {
+ if "NodeListItem" == parent.Type {
+ for _, refBlock := range refBlocks {
+ if parent.FContent == refBlock.Content {
+ return refBlock
+ }
+ }
+ for _, refBlock := range refBlocks {
+ if isPureBlockRefParagraph(refBlock, luteEngine) {
+ return refBlock
+ }
+ }
+ return nil
+ }
+
+ for _, refBlock := range refBlocks {
+ switch parent.Type {
+ case "NodeBlockquote", "NodeSuperBlock", "NodeCallout":
+ return refBlock
+ case "NodeDocument", "NodeHeading":
+ if isPureBlockRefParagraph(refBlock, luteEngine) &&
+ isFirstBacklinkParentParagraph(refBlock, parent, boxID, treeCache) {
+ return refBlock
+ }
+ }
+ }
+ return nil
+}
+
+func isPureBlockRefParagraph(block *Block, luteEngine *lute.Lute) bool {
+ if nil == block || "NodeParagraph" != block.Type {
+ return false
+ }
+
+ inlineTree := parse.Inline("", []byte(block.Markdown), luteEngine.ParseOptions)
+ if nil == inlineTree || nil == inlineTree.Root.FirstChild {
+ return false
+ }
+
+ hasBlockRef := false
+ for node := inlineTree.Root.FirstChild.FirstChild; nil != node; node = node.Next {
+ if treenode.IsBlockRef(node) {
+ hasBlockRef = true
+ continue
+ }
+ if ast.NodeText == node.Type && "" == strings.TrimSpace(node.Text()) {
+ continue
+ }
+ return false
+ }
+ return hasBlockRef
+}
+
+func isFirstBacklinkParentParagraph(refBlock, parent *Block, boxID string, treeCache map[string]*parse.Tree) bool {
+ tree := backlinkRefTree(refBlock, boxID, treeCache)
+ if nil == tree {
+ return false
+ }
+
+ node := treenode.GetNodeInTree(tree, refBlock.ID)
+ if nil == node {
+ return false
+ }
+ return isFirstBacklinkParentParagraphNode(node, parent)
+}
+
+func isFirstBacklinkParentParagraphNode(node *ast.Node, parent *Block) bool {
+ previous := treenode.PreviousBlock(node)
+ if "NodeDocument" == parent.Type {
+ actualParent := treenode.ParentBlock(node)
+ return nil != actualParent && actualParent.ID == parent.ID && nil == previous
+ }
+ return "NodeHeading" == parent.Type && nil != previous && previous.ID == parent.ID
+}
+
+func backlinkHeadingCoveredIDs(parent *Block, boxID string, treeCache map[string]*parse.Tree) (ret map[string]bool) {
+ ret = map[string]bool{parent.ID: true}
+ tree := backlinkRefTree(parent, boxID, treeCache)
+ if nil == tree {
+ return
+ }
+
+ heading := treenode.GetNodeInTree(tree, parent.ID)
+ if nil == heading || ast.NodeHeading != heading.Type {
+ return
+ }
+
+ for _, child := range treenode.HeadingChildren(heading) {
+ ast.Walk(child, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && "" != node.ID && node.IsBlock() {
+ ret[node.ID] = true
+ }
+ return ast.WalkContinue
+ })
+ }
+ return
+}
+
+func backlinkRefTree(block *Block, boxID string, treeCache map[string]*parse.Tree) *parse.Tree {
+ if nil == block {
+ return nil
+ }
+ if tree, ok := treeCache[block.RootID]; ok {
+ return tree
+ }
+
+ tree, _ := loadTreeByBlockIDInBox(block.RootID, boxID)
+ treeCache[block.RootID] = tree
+ return tree
+}
+
+func uniqueBacklinkStrings(values []string) (ret []string) {
+ seen := map[string]bool{}
+ for _, value := range values {
+ if seen[value] {
+ continue
+ }
+ seen[value] = true
+ ret = append(ret, value)
+ }
+ return
+}
+
+func mergeBacklinkRefDefs(refDefs []*RefDefs) (ret []*RefDefs) {
+ ret = []*RefDefs{}
+ merged := map[string]*RefDefs{}
+ for _, refDef := range refDefs {
+ if nil == refDef {
+ continue
+ }
+
+ existing := merged[refDef.RefID]
+ if nil == existing {
+ existing = &RefDefs{RefID: refDef.RefID, DefIDs: []string{}}
+ merged[refDef.RefID] = existing
+ ret = append(ret, existing)
+ }
+ existing.DefIDs = uniqueBacklinkStrings(append(existing.DefIDs, refDef.DefIDs...))
+ }
+ return
+}
diff --git a/kernel/model/backlink_parent_test.go b/kernel/model/backlink_parent_test.go
new file mode 100644
index 0000000000..923b50c2c7
--- /dev/null
+++ b/kernel/model/backlink_parent_test.go
@@ -0,0 +1,213 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestIsPureBlockRefParagraph(t *testing.T) {
+ luteEngine := util.NewLute()
+ tests := []struct {
+ name string
+ markdown string
+ expected bool
+ }{
+ {"single reference", `((20240101000000-abcdefg "foo"))`, true},
+ {"multiple references", `((20240101000000-abcdefg "foo")) ((20240101000001-abcdefg "bar"))`, true},
+ {"reference with text", `topic ((20240101000000-abcdefg "foo"))`, false},
+ {"reference with image", `((20240101000000-abcdefg "foo")) ![](assets/image.png)`, false},
+ {"reference with tag", `((20240101000000-abcdefg "foo")) #tag#`, false},
+ {"plain text", "topic", false},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ block := &Block{Type: "NodeParagraph", Markdown: test.markdown}
+ if actual := isPureBlockRefParagraph(block, luteEngine); actual != test.expected {
+ t.Fatalf("isPureBlockRefParagraph(%q) = %v, expected %v", test.markdown, actual, test.expected)
+ }
+ })
+ }
+}
+
+func TestIsFirstBacklinkParentParagraphNode(t *testing.T) {
+ document := &ast.Node{Type: ast.NodeDocument, ID: "document"}
+ firstParagraph := &ast.Node{Type: ast.NodeParagraph, ID: "first"}
+ secondParagraph := &ast.Node{Type: ast.NodeParagraph, ID: "second"}
+ document.AppendChild(firstParagraph)
+ document.AppendChild(secondParagraph)
+
+ documentBlock := &Block{ID: document.ID, Type: "NodeDocument"}
+ if !isFirstBacklinkParentParagraphNode(firstParagraph, documentBlock) {
+ t.Fatal("the first document paragraph should propagate to the document")
+ }
+ if isFirstBacklinkParentParagraphNode(secondParagraph, documentBlock) {
+ t.Fatal("a non-first document paragraph should not propagate to the document")
+ }
+
+ heading := &ast.Node{Type: ast.NodeHeading, ID: "heading", HeadingLevel: 1}
+ headingFirstParagraph := &ast.Node{Type: ast.NodeParagraph, ID: "heading-first"}
+ headingSecondParagraph := &ast.Node{Type: ast.NodeParagraph, ID: "heading-second"}
+ document.AppendChild(heading)
+ document.AppendChild(headingFirstParagraph)
+ document.AppendChild(headingSecondParagraph)
+
+ headingBlock := &Block{ID: heading.ID, Type: "NodeHeading"}
+ if !isFirstBacklinkParentParagraphNode(headingFirstParagraph, headingBlock) {
+ t.Fatal("the first paragraph below a heading should propagate to the heading")
+ }
+ if isFirstBacklinkParentParagraphNode(headingSecondParagraph, headingBlock) {
+ t.Fatal("a non-first paragraph below a heading should not propagate to the heading")
+ }
+}
+
+func TestSelectDocumentAndHeadingBacklinkParentRef(t *testing.T) {
+ document := &ast.Node{Type: ast.NodeDocument, ID: "document"}
+ documentRefNode := &ast.Node{Type: ast.NodeParagraph, ID: "document-ref"}
+ heading := &ast.Node{Type: ast.NodeHeading, ID: "heading", HeadingLevel: 1}
+ headingRefNode := &ast.Node{Type: ast.NodeParagraph, ID: "heading-ref"}
+ document.AppendChild(documentRefNode)
+ document.AppendChild(heading)
+ document.AppendChild(headingRefNode)
+
+ treeCache := map[string]*parse.Tree{
+ document.ID: {Root: document},
+ }
+ luteEngine := util.NewLute()
+ documentRef := &Block{
+ ID: documentRefNode.ID,
+ RootID: document.ID,
+ Type: "NodeParagraph",
+ Markdown: `((20240101000000-abcdefg "foo"))`,
+ }
+ headingRef := &Block{
+ ID: headingRefNode.ID,
+ RootID: document.ID,
+ Type: "NodeParagraph",
+ Markdown: `((20240101000000-abcdefg "foo"))`,
+ }
+ if selected := selectBacklinkParentRef(
+ &Block{ID: document.ID, Type: "NodeDocument"},
+ []*Block{documentRef},
+ "",
+ luteEngine,
+ treeCache,
+ ); selected != documentRef {
+ t.Fatal("the first pure-reference paragraph should propagate to the document")
+ }
+ if selected := selectBacklinkParentRef(
+ &Block{ID: heading.ID, Type: "NodeHeading"},
+ []*Block{headingRef},
+ "",
+ luteEngine,
+ treeCache,
+ ); selected != headingRef {
+ t.Fatal("the first pure-reference paragraph below a heading should propagate to the heading")
+ }
+
+ documentRef.Markdown = `topic ((20240101000000-abcdefg "foo"))`
+ if selected := selectBacklinkParentRef(
+ &Block{ID: document.ID, Type: "NodeDocument"},
+ []*Block{documentRef},
+ "",
+ luteEngine,
+ treeCache,
+ ); nil != selected {
+ t.Fatal("a paragraph containing other text should not propagate to the document")
+ }
+}
+
+func TestSelectListItemBacklinkParentRefPrefersFirstLeaf(t *testing.T) {
+ luteEngine := util.NewLute()
+ firstLeaf := &Block{
+ ID: "first-leaf",
+ Type: "NodeParagraph",
+ Content: "topic reference",
+ Markdown: `topic ((20240101000000-abcdefg "foo"))`,
+ }
+ pureRef := &Block{
+ ID: "pure-reference",
+ Type: "NodeParagraph",
+ Content: "reference",
+ Markdown: `((20240101000000-abcdefg "foo"))`,
+ }
+ parent := &Block{ID: "list-item", Type: "NodeListItem", FContent: firstLeaf.Content}
+
+ selected := selectBacklinkParentRef(
+ parent,
+ []*Block{pureRef, firstLeaf},
+ "",
+ luteEngine,
+ map[string]*parse.Tree{},
+ )
+ if selected != firstLeaf {
+ t.Fatal("the first leaf reference should be selected regardless of SQL result order")
+ }
+}
+
+func TestGetBacklinkRenderNodesExpandsPropagatedHeading(t *testing.T) {
+ document := &ast.Node{Type: ast.NodeDocument, ID: "document"}
+ heading := &ast.Node{Type: ast.NodeHeading, ID: "heading", HeadingLevel: 1}
+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("Heading")})
+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}
+ document.AppendChild(heading)
+ document.AppendChild(paragraph)
+
+ nodes, expand := getBacklinkRenderNodes(heading, map[string]string{heading.ID: paragraph.ID})
+ if !expand {
+ t.Fatal("a heading propagated by its first paragraph should be expanded")
+ }
+ if 2 != len(nodes) || nodes[0] != heading || nodes[1] != paragraph {
+ t.Fatal("the propagated heading should render the heading and its children")
+ }
+}
+
+func TestRenderBacklinkDocument(t *testing.T) {
+ document := &ast.Node{Type: ast.NodeDocument, ID: "document"}
+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("document content")})
+ document.AppendChild(paragraph)
+
+ nodes, _ := getBacklinkRenderNodes(document, nil)
+ dom := renderVisibleBlockDOMByNodes(nodes, util.NewLute())
+ if !strings.Contains(dom, "document content") {
+ t.Fatalf("rendered document backlink does not contain its content: %s", dom)
+ }
+}
+
+func TestMergeBacklinkRefDefs(t *testing.T) {
+ if refDefs := mergeBacklinkRefDefs(nil); nil == refDefs || 0 != len(refDefs) {
+ t.Fatal("empty merged ref defs should remain an empty slice")
+ }
+
+ refDefs := mergeBacklinkRefDefs([]*RefDefs{
+ {RefID: "parent", DefIDs: []string{"definition-a"}},
+ {RefID: "parent", DefIDs: []string{"definition-a", "definition-b"}},
+ {RefID: "other", DefIDs: []string{"definition-c"}},
+ })
+ if 2 != len(refDefs) {
+ t.Fatalf("merged ref defs length = %d, expected 2", len(refDefs))
+ }
+ if 2 != len(refDefs[0].DefIDs) {
+ t.Fatalf("merged definition IDs length = %d, expected 2", len(refDefs[0].DefIDs))
+ }
+}
diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.go
index d66a6b3d35..45064bfd97 100644
--- a/kernel/model/blockinfo.go
+++ b/kernel/model/blockinfo.go
@@ -28,7 +28,6 @@ import (
"github.com/88250/lute/ast"
"github.com/88250/lute/editor"
"github.com/88250/lute/parse"
- "github.com/emirpasic/gods/sets/hashset"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/filesys"
@@ -108,7 +107,7 @@ func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error) {
bt := treenode.GetBlockTreeInBox(blockID, boxID)
refDefs := queryBlockRefDefsInBox(bt, bt.BoxID)
- buildBacklinkListItemRefsInBox(refDefs, bt.BoxID)
+ refDefs, _ = buildBacklinkListItemRefsInBox(refDefs, bt.BoxID)
var refIDs []string
for _, refDef := range refDefs {
refIDs = append(refIDs, refDef.RefID)
@@ -214,7 +213,7 @@ func GetDocsInfo(blockIDs []string, queryRefCount bool, queryAv bool) (rets []*B
if queryRefCount {
var refIDs []string
refDefs := queryBlockRefDefs(bts[blockID])
- buildBacklinkListItemRefs(refDefs)
+ refDefs, _ = buildBacklinkListItemRefs(refDefs)
for _, refDef := range refDefs {
refIDs = append(refIDs, refDef.RefID)
}
@@ -410,7 +409,7 @@ func GetBlockRefsInBox(defID, boxID string) (refDefs []*RefDefs, originalRefBloc
// 加密笔记本的 refs 在加密 db,用 bt.BoxID 路由
refDefs = queryBlockRefDefsInBox(bt, bt.BoxID)
- originalRefBlockIDs = buildBacklinkListItemRefsInBox(refDefs, bt.BoxID)
+ refDefs, originalRefBlockIDs = buildBacklinkListItemRefsInBox(refDefs, bt.BoxID)
return
}
@@ -694,11 +693,11 @@ func buildBlockBreadcrumb(node *ast.Node, excludeTypes []string, isEmbedBlock bo
return
}
-func buildBacklinkListItemRefs(refDefs []*RefDefs) (originalRefBlockIDs map[string]string) {
+func buildBacklinkListItemRefs(refDefs []*RefDefs) (retRefDefs []*RefDefs, originalRefBlockIDs map[string]string) {
return buildBacklinkListItemRefsInBox(refDefs, "")
}
-func buildBacklinkListItemRefsInBox(refDefs []*RefDefs, boxID string) (originalRefBlockIDs map[string]string) {
+func buildBacklinkListItemRefsInBox(refDefs []*RefDefs, boxID string) (retRefDefs []*RefDefs, originalRefBlockIDs map[string]string) {
originalRefBlockIDs = map[string]string{}
var refIDs []string
@@ -707,59 +706,14 @@ func buildBacklinkListItemRefsInBox(refDefs []*RefDefs, boxID string) (originalR
}
sqlRefBlocks := sql.GetBlocksInBox(refIDs, boxID)
refBlocks := fromSQLBlocks(&sqlRefBlocks, "", 12)
-
- parentRefParagraphs := map[string]*Block{}
- var paragraphParentIDs []string
- for _, ref := range refBlocks {
- if nil != ref && "NodeParagraph" == ref.Type {
- parentRefParagraphs[ref.ParentID] = ref
- paragraphParentIDs = append(paragraphParentIDs, ref.ParentID)
- }
- }
- sqlParagraphParents := sql.GetBlocksInBox(paragraphParentIDs, boxID)
- paragraphParents := fromSQLBlocks(&sqlParagraphParents, "", 12)
-
- luteEngine := util.NewLute()
- processedParagraphs := hashset.New()
- for _, parent := range paragraphParents {
- if nil == parent {
- continue
- }
-
- if "NodeListItem" == parent.Type || "NodeBlockquote" == parent.Type || "NodeSuperBlock" == parent.Type || "NodeCallout" == parent.Type {
- refBlock := parentRefParagraphs[parent.ID]
- if nil == refBlock {
- continue
+ for _, mapping := range buildBacklinkParentMappings(refBlocks, boxID) {
+ for _, refDef := range refDefs {
+ if mapping.coveredRefIDs[refDef.RefID] {
+ refDef.RefID = mapping.parent.ID
}
-
- paragraphUseParentLi := true
- if "NodeListItem" == parent.Type && parent.FContent != refBlock.Content {
- if inlineTree := parse.Inline("", []byte(refBlock.Markdown), luteEngine.ParseOptions); nil != inlineTree {
- for c := inlineTree.Root.FirstChild.FirstChild; c != nil; c = c.Next {
- if treenode.IsBlockRef(c) {
- continue
- }
-
- if "" != strings.TrimSpace(c.Text()) {
- paragraphUseParentLi = false
- break
- }
- }
- }
- }
-
- if paragraphUseParentLi {
- for _, refDef := range refDefs {
- if refDef.RefID == refBlock.ID {
- refDef.RefID = parent.ID
- break
- }
- }
- processedParagraphs.Add(parent.ID)
- }
-
- originalRefBlockIDs[parent.ID] = refBlock.ID
}
+ originalRefBlockIDs[mapping.parent.ID] = mapping.refBlock.ID
}
+ retRefDefs = mergeBacklinkRefDefs(refDefs)
return
}
diff --git a/kernel/model/path.go b/kernel/model/path.go
index ec4825216c..c41fc20a26 100644
--- a/kernel/model/path.go
+++ b/kernel/model/path.go
@@ -188,11 +188,11 @@ func toFlatTree(blocks []*Block, baseDepth int, typ string, tree *parse.Tree) (r
}
func toSubTree(blocks []*Block, keyword string) (ret []*Path) {
- return toSubTreeInBox(blocks, keyword, "")
+ return toSubTreeInBox(blocks, keyword, "", nil)
}
// toSubTreeInBox 与 toSubTree 一致,但按 boxID 路由到加密 db 或全局 db。
-func toSubTreeInBox(blocks []*Block, keyword, boxID string) (ret []*Path) {
+func toSubTreeInBox(blocks []*Block, keyword, boxID string, originalRefBlockIDs map[string]string) (ret []*Path) {
keyword = strings.TrimSpace(keyword)
var blockRoots []*Block
for _, block := range blocks {
@@ -218,7 +218,23 @@ func toSubTreeInBox(blocks []*Block, keyword, boxID string) (ret []*Path) {
Count: len(root.Children),
}
for _, c := range root.Children {
- if "NodeListItem" == c.Type {
+ if "NodeDocument" == c.Type && "" != originalRefBlockIDs[c.ID] {
+ tree, _ := loadTreeByBlockIDInBox(c.RootID, boxID)
+ if nil == tree {
+ continue
+ }
+ for child := tree.Root.FirstChild; nil != child; child = child.Next {
+ if "" == child.ID || !child.IsBlock() {
+ continue
+ }
+ subBlock, _ := getBlock(child.ID, tree)
+ if nil == subBlock {
+ continue
+ }
+ subBlock.Depth = 1
+ treeNode.Blocks = append(treeNode.Blocks, subBlock)
+ }
+ } else if "NodeListItem" == c.Type {
tree, _ := loadTreeByBlockIDInBox(c.RootID, boxID)
li := treenode.GetNodeInTree(tree, c.ID)
if nil == li || nil == li.FirstChild {
@@ -248,8 +264,14 @@ func toSubTreeInBox(blocks []*Block, keyword, boxID string) (ret []*Path) {
Count: 1,
}
+ refNode := li.FirstChild
+ if originalRefBlockID := originalRefBlockIDs[li.ID]; "" != originalRefBlockID {
+ if originalRefBlock := treenode.GetNodeInTree(tree, originalRefBlockID); nil != originalRefBlock {
+ refNode = originalRefBlock
+ }
+ }
unfold := true
- for liFirstBlockSpan := li.FirstChild.FirstChild; nil != liFirstBlockSpan; liFirstBlockSpan = liFirstBlockSpan.Next {
+ for liFirstBlockSpan := refNode.FirstChild; nil != liFirstBlockSpan; liFirstBlockSpan = liFirstBlockSpan.Next {
if treenode.IsBlockRef(liFirstBlockSpan) {
continue
}
@@ -321,13 +343,17 @@ func toSubTreeInBox(blocks []*Block, keyword, boxID string) (ret []*Path) {
treeNode.Children = append(treeNode.Children, subRoot)
}
} else if "NodeHeading" == c.Type {
- tree, _ := LoadTreeByBlockID(c.RootID)
+ tree, _ := loadTreeByBlockIDInBox(c.RootID, boxID)
h := treenode.GetNodeInTree(tree, c.ID)
if nil == h {
continue
}
- name := sql.GetBlock(h.ID).Content
+ sqlHeading := sql.GetBlockInBox(h.ID, boxID)
+ if nil == sqlHeading {
+ continue
+ }
+ name := sqlHeading.Content
parentPos := 0
if "" != keyword {
parentPos, name = search.MarkText(name, keyword, 12, Conf.Search.CaseSensitive)
@@ -343,14 +369,17 @@ func toSubTreeInBox(blocks []*Block, keyword, boxID string) (ret []*Path) {
Count: 1,
}
- unfold := true
- for headingFirstSpan := h.FirstChild; nil != headingFirstSpan; headingFirstSpan = headingFirstSpan.Next {
- if treenode.IsBlockRef(headingFirstSpan) {
- continue
- }
- if "" != strings.TrimSpace(headingFirstSpan.Text()) {
- unfold = false
- break
+ unfold := "" != originalRefBlockIDs[h.ID]
+ if !unfold {
+ unfold = true
+ for headingFirstSpan := h.FirstChild; nil != headingFirstSpan; headingFirstSpan = headingFirstSpan.Next {
+ if treenode.IsBlockRef(headingFirstSpan) {
+ continue
+ }
+ if "" != strings.TrimSpace(headingFirstSpan.Text()) {
+ unfold = false
+ break
+ }
}
}
diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.go
index a40c9f153a..d3adb0d37e 100644
--- a/kernel/model/publish_access.go
+++ b/kernel/model/publish_access.go
@@ -1350,7 +1350,7 @@ func FilterRefDefsByPublishIgnore(publishIgnore PublishAccess, refDefs []*RefDef
retRefDefs = append(retRefDefs, refDef)
}
}
- originalRefBlockIDs = buildBacklinkListItemRefs(retRefDefs)
+ retRefDefs, originalRefBlockIDs = buildBacklinkListItemRefs(retRefDefs)
return
}