Skip to content

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

:art: Locate blocks referencing missing assets https://github.com/siyuan-note/siyuan/issues/8471

Daniel2a2627bf4151
diff --git a/app/src/config/assets.ts b/app/src/config/assets.ts
index 3a262d2ee9..72d467efc1 100644
--- a/app/src/config/assets.ts
+++ b/app/src/config/assets.ts
@@ -1,4 +1,4 @@
-import {escapeHtml} from "../util/escape";
+import {escapeAttr, escapeHtml} from "../util/escape";
import {confirmDialog} from "../dialog/confirmDialog";
import {isBrowser, isMobile} from "../util/functions";
import {hasClosestByClassName} from "../protyle/util/hasClosest";
@@ -296,7 +296,8 @@ const assets = {
},
_renderList: (data: {
item: string,
- name: string
+ name: string,
+ blockIDs?: string[]
}[], element: Element, type: "unRefAV" | "unrefAssets" | "lostAssets") => {
let html = "";
let boxOpenHTML = "";
@@ -313,8 +314,12 @@ const assets = {
}
const mobile = isMobile();
data.forEach((item) => {
+ const hasBlockPopover = type === "lostAssets" && item.blockIDs?.length > 0;
+ const blockPopoverData = hasBlockPopover
+ ? ` data-id="${escapeAttr(JSON.stringify(item.blockIDs))}"`
+ : "";
html += `<li data-tab-type="${type}" data-item="${item.item}" class="b3-list-item${mobile ? "" : " b3-list-item--hide-action"}">
- <span class="b3-list-item__text">${escapeHtml(item.name || item.item)}</span>
+ <span class="b3-list-item__text${hasBlockPopover ? " popover__block" : ""}"${blockPopoverData}>${escapeHtml(item.name || item.item)}</span>
<span data-type="copy" class="ariaLabel b3-list-item__action" aria-label="${type === "unRefAV" ? window.siyuan.languages.copyMirror : window.siyuan.languages.copy}">
<svg><use xlink:href="#iconCopy"></use></svg>
</span>
diff --git a/kernel/model/assets.go b/kernel/model/assets.go
index 1c6edad8ef..56ac1af5f8 100644
--- a/kernel/model/assets.go
+++ b/kernel/model/assets.go
@@ -1273,9 +1273,10 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {
}
type UnusedItem struct {
- Item string `json:"item"`
- Name string `json:"name"`
- ModTime time.Time `json:"-"`
+ Item string `json:"item"`
+ Name string `json:"name"`
+ BlockIDs []string `json:"blockIDs,omitempty"`
+ ModTime time.Time `json:"-"`
}
func UnusedAssets(sorted bool) (ret []*UnusedItem) {
@@ -1477,12 +1478,12 @@ func MissingAssets() (ret []*UnusedItem) {
return
}
luteEngine := util.NewLute()
+ destBlockIDs := map[string]map[string]bool{}
for _, notebook := range notebooks {
if notebook.Closed {
continue
}
- dests := map[string]bool{}
pages := pagedPaths(filepath.Join(util.DataDir, notebook.ID), 32)
for _, paths := range pages {
var trees []*parse.Tree
@@ -1494,58 +1495,113 @@ func MissingAssets() (ret []*UnusedItem) {
trees = append(trees, tree)
}
for _, tree := range trees {
- for _, d := range getAssetsLinkDests(tree.Root, false) {
- dests[d] = true
- }
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering {
+ return ast.WalkContinue
+ }
+
+ blockID := assetLinkDestBlockID(n)
+ for _, dest := range getAssetLinkDestsByNode(n, false) {
+ addAssetLinkDestBlockID(destBlockIDs, dest, blockID)
+ }
+ return ast.WalkContinue
+ })
if titleImgPath := treenode.GetDocTitleImgPath(tree.Root); "" != titleImgPath {
// 题头图计入
if !util.IsAssetLinkDest([]byte(titleImgPath), false) {
continue
}
- dests[titleImgPath] = true
+ addAssetLinkDestBlockID(destBlockIDs, titleImgPath, tree.Root.ID)
}
}
}
+ }
- for dest := range dests {
- if !strings.HasPrefix(dest, "assets/") {
- continue
+ for dest, blockIDSet := range destBlockIDs {
+ if "" == assetsPathMap[dest] {
+ if strings.HasPrefix(dest, "assets/.") {
+ // Assets starting with `.` should not be considered missing assets https://github.com/siyuan-note/siyuan/issues/8821
+ if filelock.IsExist(filepath.Join(util.DataDir, dest)) {
+ continue
+ }
}
- if idx := strings.Index(dest, "?"); 0 < idx {
- dest = dest[:idx]
+ blockIDs := make([]string, 0, len(blockIDSet))
+ for blockID := range blockIDSet {
+ blockIDs = append(blockIDs, blockID)
}
+ sort.Strings(blockIDs)
+ ret = append(ret, &UnusedItem{Item: dest, Name: path.Base(dest), BlockIDs: blockIDs})
+ }
+ }
+ sort.Slice(ret, func(i, j int) bool {
+ return ret[i].Item < ret[j].Item
+ })
+ return
+}
- if strings.HasSuffix(dest, "/") {
- continue
- }
+func addAssetLinkDestBlockID(destBlockIDs map[string]map[string]bool, dest, blockID string) {
+ dest = normalizeMissingAssetLinkDest(dest)
+ if "" == dest {
+ return
+ }
- if strings.Contains(strings.ToLower(dest), ".pdf/") {
- if idx := strings.LastIndex(dest, "/"); -1 < idx {
- if ast.IsNodeIDPattern(dest[idx+1:]) {
- // PDF 标注不计入 https://github.com/siyuan-note/siyuan/issues/13891
- continue
- }
- }
- }
+ blockIDs := destBlockIDs[dest]
+ if nil == blockIDs {
+ blockIDs = map[string]bool{}
+ destBlockIDs[dest] = blockIDs
+ }
+ if "" != blockID {
+ blockIDs[blockID] = true
+ }
+}
- if "" == assetsPathMap[dest] {
- if strings.HasPrefix(dest, "assets/.") {
- // Assets starting with `.` should not be considered missing assets https://github.com/siyuan-note/siyuan/issues/8821
- if !filelock.IsExist(filepath.Join(util.DataDir, dest)) {
- name := path.Base(dest)
- ret = append(ret, &UnusedItem{Item: dest, Name: name})
- }
- } else {
- name := path.Base(dest)
- ret = append(ret, &UnusedItem{Item: dest, Name: name})
- }
- continue
- }
+func normalizeMissingAssetLinkDest(dest string) string {
+ dest = strings.TrimSpace(dest)
+ if !strings.HasPrefix(dest, "assets/") {
+ return ""
+ }
+ if idx := strings.Index(dest, "?"); 0 < idx {
+ dest = dest[:idx]
+ }
+ if strings.HasSuffix(dest, "/") || strings.HasSuffix(dest, ".rtfd") {
+ return ""
+ }
+ if strings.Contains(strings.ToLower(dest), ".pdf/") {
+ if idx := strings.LastIndex(dest, "/"); -1 < idx && ast.IsNodeIDPattern(dest[idx+1:]) {
+ // PDF 标注不计入 https://github.com/siyuan-note/siyuan/issues/13891
+ return ""
}
}
- return
+ return dest
+}
+
+func assetLinkDestBlockID(node *ast.Node) string {
+ if node.IsBlock() && "" != node.ID {
+ return node.ID
+ }
+ if block := treenode.ParentBlock(node); nil != block {
+ return block.ID
+ }
+ return ""
+}
+
+func getAssetLinkDestsByNode(node *ast.Node, includeServePath bool) []string {
+ if !node.IsBlock() && ast.NodeLinkDest != node.Type && ast.NodeHTMLBlock != node.Type && ast.NodeInlineHTML != node.Type &&
+ ast.NodeIFrame != node.Type && ast.NodeWidget != node.Type && ast.NodeAudio != node.Type && ast.NodeVideo != node.Type &&
+ ast.NodeAttributeView != node.Type && !node.IsTextMarkType("a") && !node.IsTextMarkType("file-annotation-ref") {
+ return nil
+ }
+
+ // 复用统一的资源链接提取逻辑,但仅处理当前节点,避免重复遍历子树。
+ nodeCopy := *node
+ nodeCopy.Parent = nil
+ nodeCopy.Previous = nil
+ nodeCopy.Next = nil
+ nodeCopy.FirstChild = nil
+ nodeCopy.LastChild = nil
+ return getAssetsLinkDests(&nodeCopy, includeServePath)
}
func emojisInTree(tree *parse.Tree) (ret []string) {
diff --git a/kernel/model/assets_test.go b/kernel/model/assets_test.go
new file mode 100644
index 0000000000..dd2a570b4b
--- /dev/null
+++ b/kernel/model/assets_test.go
@@ -0,0 +1,70 @@
+// 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 (
+ "reflect"
+ "testing"
+
+ "github.com/88250/lute/ast"
+)
+
+func TestNormalizeMissingAssetLinkDest(t *testing.T) {
+ tests := []struct {
+ name string
+ dest string
+ want string
+ }{
+ {name: "asset", dest: "assets/image.png", want: "assets/image.png"},
+ {name: "query", dest: "assets/document.pdf?page=2", want: "assets/document.pdf"},
+ {name: "folder", dest: "assets/images/", want: ""},
+ {name: "rtfd", dest: "assets/document.rtfd", want: ""},
+ {name: "pdf annotation", dest: "assets/document.pdf/20200101000000-abcdefg", want: ""},
+ {name: "external", dest: "https://example.com/image.png", want: ""},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if got := normalizeMissingAssetLinkDest(test.dest); got != test.want {
+ t.Fatalf("normalize missing asset link destination: got %q, want %q", got, test.want)
+ }
+ })
+ }
+}
+
+func TestGetAssetLinkDestsByNode(t *testing.T) {
+ const blockID = "20200101000000-abcdefg"
+ root := &ast.Node{Type: ast.NodeDocument}
+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: blockID}
+ paragraph.SetIALAttr("custom-data-assets", "assets/custom.png")
+ linkDest := &ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("assets/image.png")}
+ root.AppendChild(paragraph)
+ paragraph.AppendChild(linkDest)
+
+ want := []string{"assets/custom.png", "assets/image.png"}
+ if got := getAssetsLinkDests(root, false); !reflect.DeepEqual(got, want) {
+ t.Fatalf("get asset link destinations: got %v, want %v", got, want)
+ }
+ if got := getAssetLinkDestsByNode(paragraph, false); !reflect.DeepEqual(got, []string{"assets/custom.png"}) {
+ t.Fatalf("get block asset link destinations: got %v, want %v", got, []string{"assets/custom.png"})
+ }
+ if got := getAssetLinkDestsByNode(linkDest, false); !reflect.DeepEqual(got, []string{"assets/image.png"}) {
+ t.Fatalf("get inline asset link destinations: got %v, want %v", got, []string{"assets/image.png"})
+ }
+ if got := assetLinkDestBlockID(linkDest); got != blockID {
+ t.Fatalf("get asset link destination block ID: got %q, want %q", got, blockID)
+ }
+}