Skip to content

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

:bug: Limit block image export footnotes and assets to the selected scope https://github.com/siyuan-note/siyuan/issues/19609

Danielfe7de7a4fcc3
diff --git a/kernel/model/asset_download_read.go b/kernel/model/asset_download_read.go
index d17919173d..782468b7a1 100644
--- a/kernel/model/asset_download_read.go
+++ b/kernel/model/asset_download_read.go
@@ -140,6 +140,11 @@ func ensureReadableAssetLocal(absPath string) error {
// prepareExportAssets 在导出持有笔记本读锁或生成产物之前补齐文档引用的资源。
func prepareExportAssets(boxID string, docPaths []string, includeFootnotes ...bool) error {
+ return prepareExportAssetsInScope(boxID, docPaths, len(includeFootnotes) != 0 && includeFootnotes[0], "")
+}
+
+// prepareExportAssetsInScope 在单块导出时按块范围收集依赖,文档导出仍按文档路径收集。
+func prepareExportAssetsInScope(boxID string, docPaths []string, includeFootnotes bool, blockID string) error {
if boxID != "" && IsEncryptedBox(boxID) && !IsBoxUnlocked(boxID) {
return errors.New(Conf.Language(314))
}
@@ -175,36 +180,55 @@ func prepareExportAssets(boxID string, docPaths []string, includeFootnotes ...bo
if loadErr != nil {
return loadErr
}
- exportRefTrees(tree, &[]string{}, trees)
+ if blockID != "" {
+ block := getExportBlockTreeInBox(blockID, targetBoxID)
+ if block == nil || treenode.GetNodeInTree(tree, blockID) == nil {
+ return ErrBlockNotFound
+ }
+ trees[blockID] = selectExportTree(tree, block)
+ } else {
+ exportRefTrees(tree, &[]string{}, trees)
+ }
}
// 查询嵌入的资源属于导出依赖,按笔记本边界展开并去重,避免循环嵌入反复读取。
- var pending []*parse.Tree
+ type pendingTree struct {
+ key string
+ tree *parse.Tree
+ }
+ var pending []pendingTree
queued := map[string]bool{}
appendPending := func() {
for id, tree := range trees {
if !queued[id] {
queued[id] = true
- pending = append(pending, tree)
+ pending = append(pending, pendingTree{id, tree})
}
}
}
appendPending()
for i := 0; i < len(pending); i++ {
- tree := pending[i]
- if len(includeFootnotes) != 0 && includeFootnotes[0] && Conf.Export.BlockRefMode == 4 {
+ tree := pending[i].tree
+ if blockID != "" {
+ if err := treenode.MaterializeTableCellRichExport(tree.Root); err != nil {
+ return err
+ }
+ defer treenode.MaterializeTabTitles(tree.Root)()
+ }
+ if includeFootnotes && Conf.Export.BlockRefMode == 4 && tree.Root.Type == ast.NodeDocument {
// 按单文件导出的脚注展开规则收集资源,不受是否另行导出关联文档影响
order := []string{}
footnotes := map[string]*refAsFootnotes{}
depth := 0
- collectFootnotesDefs(tree, tree.ID, &order, footnotes, &depth)
+ collectFootnotesDefs0(tree, tree.Root, &order, footnotes, &depth)
defs, defsErr := resolveFootnotesDefs(&order, footnotes, tree, map[string]bool{},
Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight, false)
if defsErr != nil {
return defsErr
}
if defs != nil {
+ pruneExportFootnotes(tree.Root, defs, footnotes)
footnoteTree := *tree
- footnoteTree.ID, footnoteTree.Root = tree.ID+"-footnotes", defs
+ footnoteTree.ID, footnoteTree.Root = pending[i].key+"-footnotes", defs
trees[footnoteTree.ID] = &footnoteTree
}
}
@@ -221,7 +245,17 @@ func prepareExportAssets(boxID string, docPaths []string, includeFootnotes ...bo
}
for _, block := range blocks {
if embedded, loadErr := loadExportRelatedTree(block.ID, tree.Box); loadErr == nil {
- exportRefTrees(embedded, &[]string{}, trees)
+ if blockID != "" {
+ if trees[block.ID] != nil {
+ continue
+ }
+ bt := getExportBlockTreeInBox(block.ID, embedded.Box)
+ if bt != nil && treenode.GetNodeInTree(embedded, block.ID) != nil {
+ trees[block.ID] = selectExportTree(embedded, bt)
+ }
+ } else {
+ exportRefTrees(embedded, &[]string{}, trees)
+ }
}
}
return ast.WalkContinue
@@ -281,6 +315,9 @@ func prepareExportBlockAssets(id string, includeSubDocs bool) error {
return nil
}
docPaths := []string{bt.Path}
+ if bt.Type != "d" && !includeSubDocs {
+ return prepareExportAssetsInScope(bt.BoxID, docPaths, true, id)
+ }
if includeSubDocs {
if box := Conf.Box(bt.BoxID); box != nil {
listPath := strings.TrimSuffix(bt.Path, ".sy")
diff --git a/kernel/model/asset_download_regression_test.go b/kernel/model/asset_download_regression_test.go
index 19671f67b2..09b329418e 100644
--- a/kernel/model/asset_download_regression_test.go
+++ b/kernel/model/asset_download_regression_test.go
@@ -95,7 +95,12 @@ func TestAssetDownloadFootnoteExport(t *testing.T) {
appearancePath := util.AppearancePath
t.Cleanup(func() { util.AppearancePath = appearancePath })
util.AppearancePath = t.TempDir()
- if err := os.MkdirAll(filepath.Join(util.AppearancePath, "themes", Conf.Appearance.ThemeLight), 0755); err != nil {
+ for _, theme := range []string{Conf.Appearance.ThemeLight, Conf.Appearance.ThemeDark} {
+ if err := os.MkdirAll(filepath.Join(util.AppearancePath, "themes", theme), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.MkdirAll(filepath.Join(util.AppearancePath, "icons", Conf.Appearance.Icon), 0755); err != nil {
t.Fatal(err)
}
_, _, exportErr := exportMarkdownHTML(source.ID, exportDir, false, false)
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 2db88136b9..75a65ac699 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -1486,6 +1486,12 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle boo
func prepareExportTree(bt *treenode.BlockTree) (ret *parse.Tree) {
luteEngine := NewLute()
ret, _ = filesys.LoadTree(bt.BoxID, bt.Path, luteEngine)
+ return selectExportTree(ret, bt)
+}
+
+// selectExportTree 保留文档身份,仅将正文限制为目标块及其所属的标题内容。
+func selectExportTree(tree *parse.Tree, bt *treenode.BlockTree) (ret *parse.Tree) {
+ ret = tree
if "d" != bt.Type {
node := treenode.GetNodeInTree(ret, bt.ID)
nodes := []*ast.Node{node}
@@ -1497,7 +1503,7 @@ func prepareExportTree(bt *treenode.BlockTree) (ret *parse.Tree) {
}
oldRoot := ret.Root
- ret = parse.Parse("", []byte(""), luteEngine.ParseOptions)
+ ret = parse.Parse("", []byte(""), NewLute().ParseOptions)
first := ret.Root.FirstChild
for _, n := range nodes {
first.InsertBefore(n)
@@ -3267,7 +3273,7 @@ func exportTree(tree *parse.Tree, wysiwyg, richTableCells, keepFold, avHiddenCol
refFootnotesByID := make(map[string]*refAsFootnotes)
if 4 == blockRefMode && singleFile {
depth = 0
- collectFootnotesDefs(ret, ret.ID, &refFootnoteOrder, refFootnotesByID, &depth)
+ collectFootnotesDefs0(ret, ret.Root, &refFootnoteOrder, refFootnotesByID, &depth)
}
currentTreeNodeIDs := map[string]bool{}
@@ -3380,38 +3386,15 @@ func exportTree(tree *parse.Tree, wysiwyg, richTableCells, keepFold, avHiddenCol
n.Unlink()
}
+ var footnotesDefBlock *ast.Node
if 4 == blockRefMode { // 脚注+锚点哈希
unlinks = nil
- footnotesDefBlock, footnotesErr := resolveFootnotesDefs(&refFootnoteOrder, refFootnotesByID, ret, currentTreeNodeIDs, blockRefTextLeft, blockRefTextRight, richTableCells)
+ var footnotesErr error
+ footnotesDefBlock, footnotesErr = resolveFootnotesDefs(&refFootnoteOrder, refFootnotesByID, ret, currentTreeNodeIDs, blockRefTextLeft, blockRefTextRight, richTableCells)
if nil != footnotesErr {
return nil, footnotesErr
}
if nil != footnotesDefBlock {
- // 如果是聚焦导出,可能存在没有使用的脚注定义块,在这里进行清理
- // Improve focus export conversion of block refs to footnotes https://github.com/siyuan-note/siyuan/issues/10647
- footnotesRefs := ret.Root.ChildrenByType(ast.NodeFootnotesRef)
- for footnotesDef := footnotesDefBlock.FirstChild; nil != footnotesDef; footnotesDef = footnotesDef.Next {
- fnRefsInDef := footnotesDef.ChildrenByType(ast.NodeFootnotesRef)
- footnotesRefs = append(footnotesRefs, fnRefsInDef...)
- }
-
- for footnotesDef := footnotesDefBlock.FirstChild; nil != footnotesDef; footnotesDef = footnotesDef.Next {
- exist := false
- for _, ref := range footnotesRefs {
- if ref.FootnotesRefId == footnotesDef.FootnotesRefId {
- exist = true
- break
- }
- }
- if !exist {
- unlinks = append(unlinks, footnotesDef)
- }
- }
-
- for _, n := range unlinks {
- n.Unlink()
- }
-
ret.Root.AppendChild(footnotesDefBlock)
}
}
@@ -3948,6 +3931,7 @@ func exportTree(tree *parse.Tree, wysiwyg, richTableCells, keepFold, avHiddenCol
for _, n := range unlinks {
n.Unlink()
}
+ pruneExportFootnotes(ret.Root, footnotesDefBlock, nil)
return ret, nil
}
diff --git a/kernel/model/export_footnotes.go b/kernel/model/export_footnotes.go
new file mode 100644
index 0000000000..77ce631b65
--- /dev/null
+++ b/kernel/model/export_footnotes.go
@@ -0,0 +1,69 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package model
+
+import (
+ "strings"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+// pruneExportFootnotes 只保留从正文可达的脚注,缩略或折叠移除引用后不保留孤立引用链和环。
+// 资源预取时正文尚未转换为脚注引用,通过 footnotes 将块引用映射到脚注编号。
+func pruneExportFootnotes(root, defs *ast.Node, footnotes map[string]*refAsFootnotes) {
+ if defs == nil {
+ return
+ }
+ byID := map[string]*ast.Node{}
+ for def := defs.FirstChild; def != nil; def = def.Next {
+ byID[def.FootnotesRefId] = def
+ }
+ seen := map[string]bool{}
+ var pending []*ast.Node
+ collect := func(node *ast.Node) {
+ ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
+ if n == defs {
+ return ast.WalkSkipChildren
+ }
+ id := ""
+ if n.Type == ast.NodeFootnotesRef {
+ id = n.FootnotesRefId
+ } else if footnotes != nil {
+ defID := ""
+ if treenode.IsBlockRef(n) {
+ defID, _, _ = treenode.GetBlockRef(n)
+ } else if treenode.IsBlockLink(n) {
+ defID = strings.TrimPrefix(n.TextMarkAHref, "siyuan://blocks/")
+ }
+ if foot := footnotes[defID]; foot != nil {
+ id = foot.refNum
+ }
+ }
+ if def := byID[id]; def != nil && !seen[id] {
+ seen[id] = true
+ pending = append(pending, def)
+ }
+ return ast.WalkContinue
+ })
+ }
+ collect(root)
+ for i := 0; i < len(pending); i++ {
+ collect(pending[i])
+ }
+ for def := defs.FirstChild; def != nil; {
+ next := def.Next
+ if !seen[def.FootnotesRefId] {
+ def.Unlink()
+ }
+ def = next
+ }
+ if defs.FirstChild == nil {
+ defs.Unlink()
+ }
+}
diff --git a/kernel/model/export_footnotes_fts5_test.go b/kernel/model/export_footnotes_fts5_test.go
new file mode 100644
index 0000000000..31b841743a
--- /dev/null
+++ b/kernel/model/export_footnotes_fts5_test.go
@@ -0,0 +1,133 @@
+//go:build fts5
+
+package model
+
+import (
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestExportFootnotesAfterEmbedExpansion(t *testing.T) {
+ setupExportPublishTest(t)
+ const boxID = "20260918000000-box0001"
+ source := newFootnoteTestDoc(t, boxID, "source")
+ embedded := newFootnoteTestDoc(t, boxID, "embedded")
+ target := newFootnoteTestDoc(t, boxID, "footnote target")
+ embedded.Root.FirstChild.AppendChild(newFootnoteTestRef(target.Root.FirstChild.ID))
+ embed := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeBlockQueryEmbed}
+ embed.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript,
+ Tokens: []byte("SELECT * FROM blocks WHERE id = '" + embedded.Root.FirstChild.ID + "'")})
+ source.Root.AppendChild(embed)
+ for _, tree := range []*parse.Tree{source, embedded, target} {
+ writeAssetDownloadDocumentTest(t, tree)
+ sql.IndexTreeQueue(tree)
+ }
+ sql.FlushQueue()
+ _, content, _ := ExportHTMLWithTitle(embed.ID, "", true, false, false, false, "")
+ if !strings.Contains(content, "footnote target") || strings.Contains(content, "SELECT * FROM") {
+ t.Fatalf("image/PDF preview lost embedded footnote: %s", content)
+ }
+}
+
+func TestExportFootnotesAfterMerge(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ Conf.Export, Conf.Editor, Conf.Appearance = conf.NewExport(), conf.NewEditor(), conf.NewAppearance()
+ Conf.Search = conf.NewSearch()
+ oldAppearance := util.AppearancePath
+ util.AppearancePath = t.TempDir()
+ t.Cleanup(func() { util.AppearancePath = oldAppearance })
+ for _, dir := range []string{"themes/daylight", "themes/midnight", "icons/litheness"} {
+ if err := os.MkdirAll(filepath.Join(util.AppearancePath, dir), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ boxID := fixture.box.ID
+ source := newFootnoteTestDoc(t, boxID, "source")
+ child := newFootnoteTestDoc(t, boxID, "child")
+ child.Path = path.Join("/"+source.ID, child.ID+".sy")
+ child.HPath = "/source/child"
+ target := newFootnoteTestDoc(t, boxID, "merged footnote target")
+ child.Root.FirstChild.AppendChild(newFootnoteTestRef(target.Root.FirstChild.ID))
+ for _, tree := range []*parse.Tree{source, child, target} {
+ writeAssetDownloadDocumentTest(t, tree)
+ }
+ for _, docx := range []bool{false, true} {
+ _, content, err := exportMarkdownHTML(source.ID, t.TempDir(), docx, true)
+ if err != nil || !strings.Contains(content, "merged footnote target") {
+ t.Fatalf("merged HTML/Word export lost footnote: %v, %s", err, content)
+ }
+ }
+}
+
+func TestExportFootnotesPruneAfterAbbreviation(t *testing.T) {
+ setupExportPublishTest(t)
+ const boxID = "20260918000002-box0003"
+ source := newFootnoteTestDoc(t, boxID, "source")
+ target := newFootnoteTestDoc(t, boxID, "unreachable target")
+ local := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeParagraph}
+ local.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(strings.Repeat("long text ", 12))})
+ local.AppendChild(newFootnoteTestRef(target.Root.FirstChild.ID))
+ source.Root.AppendChild(local)
+ source.Root.FirstChild.AppendChild(newFootnoteTestRef(local.ID))
+ for _, tree := range []*parse.Tree{source, target} {
+ writeAssetDownloadDocumentTest(t, tree)
+ sql.IndexTreeQueue(tree)
+ }
+ sql.FlushQueue()
+ _, content, _ := ExportHTMLWithTitle(source.Root.FirstChild.ID, "", true, false, false, false, "")
+ if !strings.Contains(content, "long text") || strings.Contains(content, "unreachable target") {
+ t.Fatalf("abbreviated footnote retained an unreachable dependency: %s", content)
+ }
+}
+
+func TestExportBlockAssetsEmbeddedScopes(t *testing.T) {
+ setupExportPublishTest(t)
+ prepareAssetDownloadRepoTest(t)
+ Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()
+ Conf.FileTree = conf.NewFileTree()
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ const boxID = "20260918000003-box0004"
+ source := newFootnoteTestDoc(t, boxID, "source")
+ target := newFootnoteTestDoc(t, boxID, "clean target")
+ parsed := parse.Parse("", []byte("![image](assets/file.bin)"), util.NewLute().ParseOptions)
+ resource := parsed.Root.FirstChild
+ target.Root.AppendChild(resource)
+ var embeds []*ast.Node
+ for _, ids := range []string{
+ "'" + target.Root.FirstChild.ID + "'",
+ "'" + target.Root.FirstChild.ID + "', '" + resource.ID + "'",
+ } {
+ embed := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeBlockQueryEmbed}
+ embed.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript,
+ Tokens: []byte("SELECT * FROM blocks WHERE id IN (" + ids + ")")})
+ source.Root.AppendChild(embed)
+ embeds = append(embeds, embed)
+ }
+ for _, tree := range []*parse.Tree{source, target} {
+ writeAssetDownloadDocumentTest(t, tree)
+ sql.IndexTreeQueue(tree)
+ }
+ sql.FlushQueue()
+ if err := prepareExportBlockAssets(embeds[0].ID, false); err != nil {
+ t.Fatal(err)
+ }
+ assetPath := filepath.Join(util.DataDir, "assets", "file.bin")
+ if _, err := os.Stat(assetPath); !os.IsNotExist(err) {
+ t.Fatalf("embedding a paragraph downloaded its sibling's resource: %v", err)
+ }
+ if err := prepareExportBlockAssets(embeds[1].ID, false); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(assetPath); err != nil {
+ t.Fatalf("multiple embedded blocks in one document lost a resource: %v", err)
+ }
+}
diff --git a/kernel/model/export_footnotes_test.go b/kernel/model/export_footnotes_test.go
new file mode 100644
index 0000000000..8b34af32f2
--- /dev/null
+++ b/kernel/model/export_footnotes_test.go
@@ -0,0 +1,223 @@
+package model
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func newFootnoteTestRef(id string) *ast.Node {
+ return &ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: id,
+ TextMarkBlockRefSubtype: "s", TextMarkTextContent: "reference"}
+}
+
+func newFootnoteTestDoc(t *testing.T, boxID, text string) *parse.Tree {
+ t.Helper()
+ tree := treenode.NewTree(boxID, "/"+ast.NewNodeID()+".sy", "/"+text, text)
+ tree.Root.FirstChild.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(text)})
+ return tree
+}
+
+func TestExportFootnotesStayWithinBlockScope(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()
+ a := newFootnoteTestDoc(t, fixture.box.ID, "selected paragraph")
+ b := newFootnoteTestDoc(t, fixture.box.ID, "unrelated B")
+ c := newFootnoteTestDoc(t, fixture.box.ID, "unrelated C")
+ b.Root.FirstChild.AppendChild(newFootnoteTestRef(c.Root.FirstChild.ID))
+ c.Root.FirstChild.AppendChild(newFootnoteTestRef(b.Root.FirstChild.ID))
+ other := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeParagraph}
+ other.AppendChild(newFootnoteTestRef(b.Root.FirstChild.ID))
+ a.Root.AppendChild(other)
+ for _, tree := range []*parse.Tree{a, b, c} {
+ writeAssetDownloadDocumentTest(t, tree)
+ }
+ for _, scenario := range []struct {
+ name string
+ id string
+ want int
+ }{
+ {"plain block", a.Root.FirstChild.ID, 0},
+ {"referencing block", other.ID, 2},
+ {"whole document", a.ID, 2},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ tree := prepareExportTree(getExportBlockTree(scenario.id))
+ exported, err := exportTree(tree, true, true, false, true,
+ 4, 0, 0, "#", "#", "", "", false, "", false, true, true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := len(exported.Root.ChildrenByType(ast.NodeFootnotesDef)); got != scenario.want {
+ t.Fatalf("expected %d reachable footnotes, got %d", scenario.want, got)
+ }
+ if exported.ID != a.ID {
+ t.Fatal("block export changed document identity")
+ }
+ })
+ }
+}
+
+func TestExportBlockAssetsExcludeUnrelatedContent(t *testing.T) {
+ fixture, _, _, _ := prepareAssetDownloadDocumentTest(t)
+ a := newFootnoteTestDoc(t, fixture.box.ID, "selected")
+ b := newFootnoteTestDoc(t, fixture.box.ID, "unrelated resource")
+ parsed := parse.Parse("", []byte("![image](assets/file.bin)"), util.NewLute().ParseOptions)
+ b.Root.FirstChild.AppendChild(parsed.Root.FirstChild.FirstChild)
+ other := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeParagraph}
+ other.AppendChild(newFootnoteTestRef(b.Root.FirstChild.ID))
+ a.Root.AppendChild(other)
+ for _, tree := range []*parse.Tree{a, b} {
+ writeAssetDownloadDocumentTest(t, tree)
+ }
+ Conf.Export.IncludeRelatedDocs = true
+ if err := prepareExportBlockAssets(a.Root.FirstChild.ID, false); err != nil {
+ t.Fatal(err)
+ }
+ assetPath := filepath.Join(util.DataDir, "assets", "file.bin")
+ if _, err := os.Stat(assetPath); !os.IsNotExist(err) {
+ t.Fatalf("unrelated resource was downloaded: %v", err)
+ }
+ if err := prepareExportBlockAssets(other.ID, false); err != nil {
+ t.Fatal(err)
+ }
+ if content, err := os.ReadFile(assetPath); err != nil || !strings.Contains(string(content), "version one") {
+ t.Fatalf("reachable footnote resource was not downloaded: %q, %v", content, err)
+ }
+ if err := prepareExportBlockAssets(a.Root.FirstChild.ID, false); err != nil {
+ t.Fatalf("export without deferred resources failed: %v", err)
+ }
+}
+
+func TestExportFootnotesPruneUnreachable(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ refs []string
+ want []string
+ }{
+ {"no references", nil, nil},
+ {"reachable cycle", []string{"1"}, []string{"1", "2", "3"}},
+ {"isolated chain", []string{"6"}, []string{"6"}},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ root := &ast.Node{Type: ast.NodeDocument}
+ for _, id := range scenario.refs {
+ root.AppendChild(&ast.Node{Type: ast.NodeFootnotesRef, FootnotesRefId: id})
+ }
+ defs := &ast.Node{Type: ast.NodeFootnotesDefBlock}
+ for _, pair := range [][2]string{{"1", "2"}, {"2", "3"}, {"3", "2"}, {"4", "5"}, {"5", ""}, {"6", ""}} {
+ def := &ast.Node{Type: ast.NodeFootnotesDef, FootnotesRefId: pair[0]}
+ if pair[1] != "" {
+ def.AppendChild(&ast.Node{Type: ast.NodeFootnotesRef, FootnotesRefId: pair[1]})
+ }
+ defs.AppendChild(def)
+ }
+ root.AppendChild(defs)
+ pruneExportFootnotes(root, defs, nil)
+ var got []string
+ for _, def := range root.ChildrenByType(ast.NodeFootnotesDef) {
+ got = append(got, def.FootnotesRefId)
+ }
+ if !reflect.DeepEqual(got, scenario.want) {
+ t.Fatalf("expected reachable definitions %v, got %v", scenario.want, got)
+ }
+ if len(got) == 0 && root.ChildByType(ast.NodeFootnotesDefBlock) != nil {
+ t.Fatal("empty footnote separator was retained")
+ }
+ })
+ }
+}
+
+func TestExportFootnotesHeadingAndContainerScopes(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()
+ source := newFootnoteTestDoc(t, fixture.box.ID, "source")
+ target := newFootnoteTestDoc(t, fixture.box.ID, "target")
+ heading := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeHeading, HeadingLevel: 1}
+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("heading")})
+ child := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeParagraph}
+ child.AppendChild(newFootnoteTestRef(target.Root.FirstChild.ID))
+ nextHeading := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeHeading, HeadingLevel: 1}
+ nextHeading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("next")})
+ container := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeBlockquote}
+ local := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeParagraph}
+ local.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("local")})
+ reference := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeParagraph}
+ reference.AppendChild(newFootnoteTestRef(local.ID))
+ container.AppendChild(local)
+ container.AppendChild(reference)
+ for _, node := range []*ast.Node{heading, child, nextHeading, container} {
+ source.Root.AppendChild(node)
+ }
+ for _, tree := range []*parse.Tree{source, target} {
+ writeAssetDownloadDocumentTest(t, tree)
+ }
+ for _, scenario := range []struct {
+ name string
+ id string
+ want int
+ }{
+ {"heading includes children", heading.ID, 1},
+ {"container retains local anchor", container.ID, 0},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ tree, err := exportTree(prepareExportTree(getExportBlockTree(scenario.id)), true, true, false, true,
+ 4, 0, 0, "#", "#", "", "", false, "", false, true, true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := len(tree.Root.ChildrenByType(ast.NodeFootnotesDef)); got != scenario.want {
+ t.Fatalf("expected %d definitions, got %d", scenario.want, got)
+ }
+ if scenario.id == container.ID {
+ ref := treenode.GetNodeInTree(tree, reference.ID).FirstChild
+ if ref.TextMarkAHref != "#"+local.ID {
+ t.Fatalf("lost internal anchor: %q", ref.TextMarkAHref)
+ }
+ }
+ })
+ }
+}
+
+func TestExportFootnotesUseMaterializedTableContent(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ Conf.Export, Conf.Editor = conf.NewExport(), conf.NewEditor()
+ source := newFootnoteTestDoc(t, fixture.box.ID, "source")
+ target := newFootnoteTestDoc(t, fixture.box.ID, "target")
+ parsed := parse.Parse("", []byte("| Header |\n| --- |\n| value |"), util.NewLute().ParseOptions)
+ table := parsed.Root.FirstChild
+ cell := table.LastChild.FirstChild
+ cell.TableCellRich = &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: "((" + target.Root.FirstChild.ID + " 'target'))"}
+ if err := treenode.RefreshTableCellRichProjection(parsed.Root); err != nil {
+ t.Fatal(err)
+ }
+ source.Root.AppendChild(table)
+ for _, tree := range []*parse.Tree{source, target} {
+ writeAssetDownloadDocumentTest(t, tree)
+ }
+ exported, err := exportTree(prepareExportTree(getExportBlockTree(table.ID)), true, true, false, true,
+ 4, 0, 0, "#", "#", "", "", false, "", false, true, true, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := len(exported.Root.ChildrenByType(ast.NodeFootnotesDef)); got != 1 {
+ t.Fatalf("expected one footnote from materialized table, got %d", got)
+ }
+}
+
+func TestExportBlockAssetsRejectLockedNotebook(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ markRuntimeEncryptedBox(fixture.box.ID)
+ t.Cleanup(func() { forgetRuntimeEncryptedBox(fixture.box.ID) })
+ if err := prepareExportBlockAssets(fixture.childID, false); err == nil {
+ t.Fatal("locked notebook accepted for block resource preparation")
+ }
+}