Skip to content

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

:sparkles: Support locating database backlink items and fields https://github.com/siyuan-note/siyuan/issues/19174

Daniel8864a663a0a9
diff --git a/app/src/protyle/render/av/backlink.ts b/app/src/protyle/render/av/backlink.ts
new file mode 100644
index 0000000000..3ddf1f55b6
--- /dev/null
+++ b/app/src/protyle/render/av/backlink.ts
@@ -0,0 +1,83 @@
+import {setAVLocateRequest} from "./locate";
+import {avRender} from "./render";
+
+export interface IBacklinkAVTarget {
+ blockID: string;
+ matches: {
+ itemID: string;
+ keyID: string;
+ valueID: string;
+ title: string;
+ keyName: string;
+ defIDs: string[];
+ }[];
+}
+
+// 每个反链副本独立定位,避免同 ID 的正文或其他反链数据库接收到定位请求。
+export const prepareBacklinkAV = (element: HTMLElement, protyle: IProtyle, targets: IBacklinkAVTarget[],
+ selections: Map<string, string>, scrollState?: {pending: boolean}) => {
+ const databases = element.matches(".av[data-node-id]") ? [element] :
+ Array.from(element.querySelectorAll<HTMLElement>(".av[data-node-id]"));
+ databases.forEach(database => {
+ const target = targets.find(item => item.blockID === database.dataset.nodeId);
+ if (!target?.matches.length) {
+ return;
+ }
+ const navigation = document.createElement("div");
+ navigation.className = "fn__flex fn__flex-center";
+ navigation.classList.toggle("fn__none", database.classList.contains("fn__none"));
+ navigation.contentEditable = "false";
+ const select = document.createElement("select");
+ select.className = "b3-select fn__flex-1";
+ select.style.minWidth = "0";
+ select.setAttribute("aria-label", window.siyuan.languages.ref);
+ target.matches.forEach((match, index) => {
+ const option = document.createElement("option");
+ option.value = index.toString();
+ option.textContent = `${index + 1}/${target.matches.length} ${match.title || window.siyuan.languages.untitled} - ${match.keyName}`;
+ select.appendChild(option);
+ });
+ const previousIndex = target.matches.findIndex(match => match.valueID === selections.get(target.blockID));
+ select.selectedIndex = Math.max(0, previousIndex);
+ const locate = (scroll: boolean) => {
+ const match = target.matches[select.selectedIndex];
+ selections.set(target.blockID, match.valueID);
+ database.querySelectorAll(".def--mark").forEach(item => item.classList.remove("def--mark"));
+ setAVLocateRequest(database, {
+ itemID: match.itemID,
+ keyID: match.keyID,
+ defIDs: match.defIDs,
+ select: false,
+ highlight: true,
+ persistView: false,
+ scroll,
+ });
+ };
+ const navigate = () => {
+ if (!database.isConnected) {
+ return;
+ }
+ locate(true);
+ database.removeAttribute("data-render");
+ void avRender(database, protyle);
+ };
+ select.addEventListener("change", navigate);
+ navigation.appendChild(select);
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "b3-button b3-button--outline fn__flex-shrink";
+ button.textContent = window.siyuan.languages.jumpTo;
+ button.addEventListener("click", navigate);
+ navigation.appendChild(button);
+ // 控件位于数据库块外,数据库重新渲染不会移除命中位置列表。
+ ["click", "mousedown", "keydown", "change"].forEach(type => {
+ navigation.addEventListener(type, event => event.stopPropagation());
+ });
+ database.before(navigation);
+ // 首次展开仅滚动到首个数据库命中,刷新和其他副本保留阅读位置。
+ locate(scrollState?.pending === true);
+ if (scrollState) {
+ scrollState.pending = false;
+ }
+ });
+};
diff --git a/app/src/protyle/render/av/locate.ts b/app/src/protyle/render/av/locate.ts
index 3d583bb2ba..a46086868f 100644
--- a/app/src/protyle/render/av/locate.ts
+++ b/app/src/protyle/render/av/locate.ts
@@ -11,6 +11,9 @@ import {applyAVColorPalette, getAVCustomColors} from "./color";
export interface IAVLocateRequest {
itemID: string;
+ keyID?: string;
+ defIDs?: string[];
+ scroll?: boolean;
groupID?: string;
viewID?: string;
select?: boolean;
@@ -389,11 +392,24 @@ export const finishAVLocate = (blockElement: HTMLElement, protyle: IProtyle, dat
}
return;
}
- if (data.viewType === "table" && data.target.index === 0 && !data.target.groupID) {
- const contentRect = protyle.contentElement.getBoundingClientRect();
- protyle.contentElement.scrollTop += blockElement.getBoundingClientRect().top - contentRect.top;
- } else {
- scrollCenter(protyle, targetElement, "center");
+ if (request.keyID) {
+ const item = bodyElement?.querySelector<HTMLElement>(`.av__row[data-id="${request.itemID}"], .av__gallery-item[data-id="${request.itemID}"]`);
+ const cell = item?.querySelector<HTMLElement>(`[data-col-id="${request.keyID}"], [data-field-id="${request.keyID}"]`);
+ if (cell) {
+ targetElement = cell;
+ const refs = Array.from(cell.querySelectorAll<HTMLElement>('[data-type~="block-ref"][data-id]'))
+ .filter(ref => request.defIDs?.includes(ref.dataset.id));
+ refs.forEach(ref => ref.classList.add("def--mark"));
+ targetElement = refs[0] || cell;
+ }
+ }
+ if (request.scroll !== false) {
+ if (!request.keyID && data.viewType === "table" && data.target.index === 0 && !data.target.groupID) {
+ const contentRect = protyle.contentElement.getBoundingClientRect();
+ protyle.contentElement.scrollTop += blockElement.getBoundingClientRect().top - contentRect.top;
+ } else {
+ scrollCenter(protyle, targetElement, "center");
+ }
}
if (data.viewType === "kanban") {
const kanbanElement = blockElement.querySelector(".av__kanban") as HTMLElement;
@@ -403,6 +419,14 @@ export const finishAVLocate = (blockElement: HTMLElement, protyle: IProtyle, dat
kanbanElement.scrollLeft += targetRect.left + targetRect.width / 2 - (kanbanRect.left + kanbanRect.width / 2);
}
}
+ if (data.viewType === "table" && request.keyID) {
+ const scroller = blockElement.querySelector<HTMLElement>(".av__scroll");
+ const rect = scroller?.getBoundingClientRect();
+ const targetRect = targetElement.getBoundingClientRect();
+ if (scroller && (targetRect.left < rect.left || targetRect.right > rect.right)) {
+ scroller.scrollLeft += targetRect.left - rect.left;
+ }
+ }
if (request.highlight) {
highlightLocatedItem(blockElement, protyle, data.viewType, groupQuery, request.itemID);
}
diff --git a/app/src/protyle/wysiwyg/renderBacklink.ts b/app/src/protyle/wysiwyg/renderBacklink.ts
index f3f592c47e..dd76e95a2b 100644
--- a/app/src/protyle/wysiwyg/renderBacklink.ts
+++ b/app/src/protyle/wysiwyg/renderBacklink.ts
@@ -17,8 +17,10 @@ import {
markViewFoldDefault,
} from "../util/viewFold";
import {normalizeHTMLAssetIFrameBlockDOM} from "../../asset/html";
+import {IBacklinkAVTarget, prepareBacklinkAV} from "../render/av/backlink";
interface IBacklinkData {
+ attributeViewTargets?: IBacklinkAVTarget[],
id?: string,
revision?: string,
blockPaths: IBreadcrumb[],
@@ -29,6 +31,8 @@ interface IBacklinkData {
interface IBacklinkDOMRecord {
revision: string,
anchor: HTMLElement,
+ targets: IBacklinkAVTarget[],
+ selections: Map<string, string>,
}
const backlinkDOMRecords = new WeakMap<IProtyle, Map<string, IBacklinkDOMRecord>>();
@@ -60,28 +64,32 @@ const createBacklinkDOMRecord = (item: IBacklinkData, index: number, id: string)
record: {
revision: item.revision || "",
anchor: nodes[0] as HTMLElement,
+ targets: item.attributeViewTargets || [],
+ selections: new Map<string, string>(),
},
nodes,
};
};
-const renderBacklinkDOMNodes = (protyle: IProtyle, nodes: Node[]) => {
- nodes.forEach(item => {
+const renderBacklinkDOMNodes = (protyle: IProtyle, nodes: Node[], record: IBacklinkDOMRecord, scrollState: {pending: boolean}) => {
+ return Promise.all(nodes.map(async item => {
if (!(item instanceof HTMLElement)) {
return;
}
improveBreadcrumbAppearance(item);
processRender(item);
highlightRender(item);
- avRender(item, protyle);
+ prepareBacklinkAV(item, protyle, record.targets, record.selections, scrollState);
+ await avRender(item, protyle);
blockRender(protyle, item);
- });
+ }));
};
export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[]) => {
protyle.block.showAll = true;
const element = protyle.wysiwyg.element;
let records = backlinkDOMRecords.get(protyle);
+ const scrollState = {pending: !records || records.size === 0};
if (!records) {
records = new Map<string, IBacklinkDOMRecord>();
backlinkDOMRecords.set(protyle, records);
@@ -97,7 +105,7 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])
}
});
- const changedNodes: Node[][] = [];
+ const changedNodes: {nodes: Node[], record: IBacklinkDOMRecord}[] = [];
const orderedRecords: IBacklinkDOMRecord[] = [];
backlinkData.forEach((item, index) => {
const id = item.id || `legacy-${index}`;
@@ -110,6 +118,7 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])
clearViewFoldDefaults(protyle, id);
const created = createBacklinkDOMRecord(item, index, id);
if (record) {
+ created.record.selections = record.selections;
created.nodes.forEach(node => element.insertBefore(node, record.anchor));
removeBacklinkDOMRecord(record);
} else {
@@ -117,7 +126,7 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])
}
record = created.record;
records.set(id, record);
- changedNodes.push(created.nodes);
+ changedNodes.push({nodes: created.nodes, record});
}
orderedRecords.push(record);
});
@@ -139,13 +148,14 @@ export const renderBacklink = (protyle: IProtyle, backlinkData: IBacklinkData[])
}
});
const applyPromises: Promise<void>[] = [];
- changedNodes.forEach(nodes => {
- renderBacklinkDOMNodes(protyle, nodes);
- nodes.forEach(node => {
- if (node instanceof HTMLElement) {
- applyPromises.push(applyViewFoldStates(protyle, node));
- }
- });
+ changedNodes.forEach(({nodes, record}) => {
+ applyPromises.push(renderBacklinkDOMNodes(protyle, nodes, record, scrollState).then(async () => {
+ await Promise.all(nodes.map(node => {
+ if (node instanceof HTMLElement) {
+ return applyViewFoldStates(protyle, node);
+ }
+ }));
+ }));
});
removeLoading(protyle);
if (window.siyuan.config.readonly || window.siyuan.config.editor.readOnly) {
@@ -214,6 +224,12 @@ export const loadBreadcrumb = (protyle: IProtyle, element: HTMLElement) => {
normalizeHTMLAssetIFrameBlockDOM(setBacklinkFold(getResponse.data.content, true)));
clearViewFoldDefaults(protyle, element.parentElement.getAttribute("data-backlink-id"));
processRender(element.parentElement.parentElement);
+ const record = backlinkDOMRecords.get(protyle)?.get(element.parentElement.dataset.backlinkId);
+ getBacklinkDOMNodes(element.parentElement).forEach(node => {
+ if (node instanceof HTMLElement) {
+ prepareBacklinkAV(node, protyle, record?.targets || [], record?.selections || new Map());
+ }
+ });
avRender(element.parentElement.parentElement, protyle);
blockRender(protyle, element.parentElement.parentElement);
void applyViewFoldStates(protyle);
diff --git a/kernel/api/ref_revision.go b/kernel/api/ref_revision.go
index 21851b2f99..ee7f82c3ff 100644
--- a/kernel/api/ref_revision.go
+++ b/kernel/api/ref_revision.go
@@ -31,11 +31,12 @@ type backlinkPathResponse struct {
}
type backlinkContextResponse struct {
- ID string `json:"id"`
- DOM string `json:"dom"`
- BlockPaths []*model.BlockPath `json:"blockPaths"`
- Expand bool `json:"expand"`
- Revision string `json:"revision"`
+ AttributeViewTargets []*model.BacklinkAttributeViewTarget `json:"attributeViewTargets,omitempty"`
+ ID string `json:"id"`
+ DOM string `json:"dom"`
+ BlockPaths []*model.BlockPath `json:"blockPaths"`
+ Expand bool `json:"expand"`
+ Revision string `json:"revision"`
}
type backlinkListResponse struct {
@@ -116,17 +117,19 @@ func newBacklinkContextResponses(backlinks []*model.Backlink) (ret []*backlinkCo
ret = make([]*backlinkContextResponse, 0, len(backlinks))
for _, item := range backlinks {
response := &backlinkContextResponse{
- ID: item.ID,
- DOM: item.DOM,
- BlockPaths: item.BlockPaths,
- Expand: item.Expand,
+ AttributeViewTargets: item.AttributeViewTargets,
+ ID: item.ID,
+ DOM: item.DOM,
+ BlockPaths: item.BlockPaths,
+ Expand: item.Expand,
}
response.Revision = hashBacklinkRevision("bci1:", struct {
- ID string
- DOM string
- BlockPaths []*model.BlockPath
- Expand bool
- }{response.ID, response.DOM, response.BlockPaths, response.Expand})
+ AttributeViewTargets []*model.BacklinkAttributeViewTarget
+ ID string
+ DOM string
+ BlockPaths []*model.BlockPath
+ Expand bool
+ }{response.AttributeViewTargets, response.ID, response.DOM, response.BlockPaths, response.Expand})
ret = append(ret, response)
}
return
diff --git a/kernel/api/ref_revision_test.go b/kernel/api/ref_revision_test.go
index 92d64b5231..6c9b649853 100644
--- a/kernel/api/ref_revision_test.go
+++ b/kernel/api/ref_revision_test.go
@@ -51,6 +51,22 @@ func TestCanonicalBacklinkKeywords(t *testing.T) {
}
}
+func TestBacklinkContextRevisionIncludesAttributeViewTargets(t *testing.T) {
+ context := &model.Backlink{ID: "database", DOM: "unchanged"}
+ before := newBacklinkContextResponses([]*model.Backlink{context})[0].Revision
+ context.AttributeViewTargets = []*model.BacklinkAttributeViewTarget{{BlockID: "database", Matches: []*model.BacklinkAttributeViewMatch{
+ {ItemID: "row", KeyID: "field", ValueID: "cell", DefIDs: []string{"definition"}},
+ }}}
+ response := newBacklinkContextResponses([]*model.Backlink{context})[0]
+ if response.Revision == before || len(response.AttributeViewTargets) != 1 {
+ t.Fatal("target metadata must be returned and invalidate the context revision")
+ }
+ context.AttributeViewTargets[0].Matches[0].ItemID = "another-row"
+ if response.Revision == newBacklinkContextResponses([]*model.Backlink{context})[0].Revision {
+ t.Fatal("a changed target row must invalidate the context revision")
+ }
+}
+
func TestNewBacklinkResponses(t *testing.T) {
paths := []*model.Path{{ID: "20260725000000-source", Name: "Source", Count: 2}}
pathResponses := newBacklinkPathResponses(paths)
diff --git a/kernel/model/backlink.go b/kernel/model/backlink.go
index f116f5daad..6966149d7a 100644
--- a/kernel/model/backlink.go
+++ b/kernel/model/backlink.go
@@ -139,10 +139,11 @@ func refreshCrossTreeMoveRefs(refreshes []crossTreeMoveRefRefresh) {
}
type Backlink struct {
- ID string `json:"id"`
- DOM string `json:"dom"`
- BlockPaths []*BlockPath `json:"blockPaths"`
- Expand bool `json:"expand"`
+ AttributeViewTargets []*BacklinkAttributeViewTarget `json:"attributeViewTargets,omitempty"`
+ ID string `json:"id"`
+ DOM string `json:"dom"`
+ BlockPaths []*BlockPath `json:"blockPaths"`
+ Expand bool `json:"expand"`
node *ast.Node // 仅用于按文档内容顺序排序
}
@@ -232,7 +233,7 @@ func GetBackmentionDoc(defID, refTreeID, keyword string, containChildren, highli
var refTree *parse.Tree
trees := filesys.LoadTrees(mentionBlockIDs)
for id, tree := range trees {
- backlink := buildBacklink(id, tree, originalRefBlockIDs, mentionKeywords, highlight, luteEngine)
+ backlink := buildBacklink(id, tree, originalRefBlockIDs, mentionKeywords, highlight, luteEngine, nil)
if nil != backlink {
ret = append(ret, backlink)
}
@@ -299,9 +300,10 @@ func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlight
return
}
+ avTargets := backlinkAttributeViewTargets(refTree, tmpRefs)
luteEngine := util.NewLute()
for _, linkRef := range linkRefs {
- backlink := buildBacklink(linkRef.ID, refTree, originalRefBlockIDs, keywords, highlight, luteEngine)
+ backlink := buildBacklink(linkRef.ID, refTree, originalRefBlockIDs, keywords, highlight, luteEngine, avTargets)
if nil != backlink {
ret = append(ret, backlink)
}
@@ -345,9 +347,10 @@ func GetBacklinkDocInBox(defID, refTreeID, keyword string, containChildren, high
return
}
+ avTargets := backlinkAttributeViewTargets(refTree, tmpRefs)
luteEngine := util.NewLute()
for _, linkRef := range linkRefs {
- backlink := buildBacklink(linkRef.ID, refTree, originalRefBlockIDs, keywords, highlight, luteEngine)
+ backlink := buildBacklink(linkRef.ID, refTree, originalRefBlockIDs, keywords, highlight, luteEngine, avTargets)
if nil != backlink {
ret = append(ret, backlink)
}
@@ -405,7 +408,7 @@ func GetBackmentionDocInBox(defID, refTreeID, keyword string, containChildren, h
if loadErr != nil || tree == nil {
continue
}
- backlink := buildBacklink(id, tree, originalRefBlockIDs, mentionKeywords, highlight, luteEngine)
+ backlink := buildBacklink(id, tree, originalRefBlockIDs, mentionKeywords, highlight, luteEngine, nil)
if nil != backlink {
ret = append(ret, backlink)
}
@@ -451,7 +454,7 @@ func sortBacklinks(backlinks []*Backlink, tree *parse.Tree) {
})
}
-func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[string]string, keywords []string, highlight bool, luteEngine *lute.Lute) (ret *Backlink) {
+func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[string]string, keywords []string, highlight bool, luteEngine *lute.Lute, avTargets map[string]*BacklinkAttributeViewTarget) (ret *Backlink) {
node := treenode.GetNodeInTree(refTree, refID)
if nil == node {
return
@@ -494,6 +497,9 @@ func buildBacklink(refID string, refTree *parse.Tree, originalRefBlockIDs map[st
dom := renderVisibleBlockDOMByNodes(renderNodes, luteEngine)
ret = &Backlink{ID: refID, DOM: dom, BlockPaths: blockPaths, Expand: expand, node: node}
+ if 0 < len(avTargets) {
+ appendBacklinkAttributeViewTargets(ret, renderNodes, avTargets)
+ }
return
}
diff --git a/kernel/model/backlink_attribute_view.go b/kernel/model/backlink_attribute_view.go
new file mode 100644
index 0000000000..60fd7352b2
--- /dev/null
+++ b/kernel/model/backlink_attribute_view.go
@@ -0,0 +1,126 @@
+package model
+
+import (
+ "sort"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+)
+
+type BacklinkAttributeViewTarget struct {
+ BlockID string `json:"blockID"`
+ Matches []*BacklinkAttributeViewMatch `json:"matches"`
+}
+
+type BacklinkAttributeViewMatch struct {
+ ItemID string `json:"itemID"`
+ KeyID string `json:"keyID"`
+ ValueID string `json:"valueID"`
+ Title string `json:"title"`
+ KeyName string `json:"keyName"`
+ DefIDs []string `json:"defIDs"`
+}
+
+// 读取当前来源数据解析引用位置,索引仍按数据库块聚合,不改变引用计数和存储格式。
+func backlinkAttributeViewTargets(tree *parse.Tree, refs []*sql.Ref) map[string]*BacklinkAttributeViewTarget {
+ ret := map[string]*BacklinkAttributeViewTarget{}
+ if nil == tree || nil == tree.Root {
+ return ret
+ }
+ definitions := map[string]map[string]bool{}
+ for _, ref := range refs {
+ if nil == ref || sql.AttributeViewRefType != ref.Type || ref.RootID != tree.ID ||
+ ref.Box != tree.Box || ref.Path != tree.Path {
+ continue
+ }
+ if nil == definitions[ref.BlockID] {
+ definitions[ref.BlockID] = map[string]bool{}
+ }
+ definitions[ref.BlockID][ref.DefBlockID] = true
+ }
+ boxID := attributeViewRefQueryBoxID(tree.Box)
+ views := map[string]*av.AttributeView{}
+ for blockID, defIDs := range definitions {
+ node := treenode.GetNodeInTree(tree, blockID)
+ if nil == node || ast.NodeAttributeView != node.Type || "" == node.AttributeViewID {
+ continue
+ }
+ attrView, loaded := views[node.AttributeViewID]
+ if !loaded {
+ var err error
+ attrView, err = av.ParseAttributeViewInBox(node.AttributeViewID, boxID)
+ if nil != err {
+ logging.LogWarnf("read backlink attribute view [%s] failed: %s", node.AttributeViewID, err)
+ attrView = nil
+ }
+ views[node.AttributeViewID] = attrView
+ }
+ if matches := backlinkAttributeViewMatches(attrView, defIDs); 0 < len(matches) {
+ ret[blockID] = &BacklinkAttributeViewTarget{BlockID: blockID, Matches: matches}
+ }
+ }
+ return ret
+}
+
+func backlinkAttributeViewMatches(attrView *av.AttributeView, defIDs map[string]bool) (ret []*BacklinkAttributeViewMatch) {
+ if nil == attrView || 0 == len(defIDs) {
+ return
+ }
+ items := getAttributeViewBacklinkBlockValues(attrView)
+ for _, kv := range attrView.KeyValues {
+ if nil == kv || nil == kv.Key || av.KeyTypeText != kv.Key.Type {
+ continue
+ }
+ for _, value := range kv.Values {
+ if nil == value || nil == value.Text || !value.Text.IsRich() {
+ continue
+ }
+ item := items[value.BlockID]
+ if nil == item || nil == item.Block {
+ continue
+ }
+ fragment, err := av.ParseValueTextRich(value.Text.Rich)
+ if nil != err || nil == fragment || nil == fragment.Root {
+ continue
+ }
+ matched := map[string]bool{}
+ for _, defID := range getRefDefIDs(fragment.Root) {
+ if defIDs[defID] {
+ matched[defID] = true
+ }
+ }
+ if 0 == len(matched) {
+ continue
+ }
+ match := &BacklinkAttributeViewMatch{
+ ItemID: value.BlockID, KeyID: kv.Key.ID, ValueID: value.ID,
+ Title: item.Block.Content, KeyName: kv.Key.Name,
+ }
+ for defID := range matched {
+ match.DefIDs = append(match.DefIDs, defID)
+ }
+ sort.Strings(match.DefIDs)
+ ret = append(ret, match)
+ }
+ }
+ return
+}
+
+func appendBacklinkAttributeViewTargets(backlink *Backlink, nodes []*ast.Node, targets map[string]*BacklinkAttributeViewTarget) {
+ seen := map[string]bool{}
+ for _, node := range nodes {
+ ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if entering && ast.NodeAttributeView == n.Type && !seen[n.ID] {
+ if target := targets[n.ID]; nil != target {
+ backlink.AttributeViewTargets = append(backlink.AttributeViewTargets, target)
+ seen[n.ID] = true
+ }
+ }
+ return ast.WalkContinue
+ })
+ }
+}
diff --git a/kernel/model/backlink_attribute_view_test.go b/kernel/model/backlink_attribute_view_test.go
new file mode 100644
index 0000000000..88484d1893
--- /dev/null
+++ b/kernel/model/backlink_attribute_view_test.go
@@ -0,0 +1,85 @@
+package model
+
+import (
+ "reflect"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+)
+
+func TestBacklinkAttributeViewMatches(t *testing.T) {
+ const first = "20260906150000-def0001"
+ const second = "20260906150001-def0002"
+ rich := func(row, id, content string) *av.Value {
+ return &av.Value{ID: id, BlockID: row, Type: av.KeyTypeText, Text: &av.ValueText{Rich: &av.ValueTextRich{
+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown, Content: content,
+ }}}
+ }
+ reference := "((" + first + " \"Same title\"))"
+ view := &av.AttributeView{KeyValues: []*av.KeyValues{
+ {Key: &av.Key{ID: "primary", Type: av.KeyTypeBlock}, Values: []*av.Value{
+ {BlockID: "row1", Block: &av.ValueBlock{Content: "First row"}},
+ {BlockID: "row2", Block: &av.ValueBlock{Content: "Second row"}},
+ }},
+ {Key: &av.Key{ID: "text1", Name: "First field", Type: av.KeyTypeText}, Values: []*av.Value{
+ rich("row1", "value1", reference+" "+reference+" (("+second+" \"Child\"))"),
+ rich("row2", "value2", reference),
+ rich("removed", "orphan", reference),
+ {BlockID: "row1", Text: &av.ValueText{Content: reference}},
+ rich("row1", "same-anchor", "((20260906150002-other01 \"Same title\"))"),
+ }},
+ {Key: &av.Key{ID: "text2", Name: "Second field", Type: av.KeyTypeText}, Values: []*av.Value{rich("row1", "value3", reference)}},
+ {Key: &av.Key{ID: "rollup", Type: av.KeyTypeRollup}, Values: []*av.Value{rich("row1", "derived", reference)}},
+ }}
+ want := []*BacklinkAttributeViewMatch{
+ {ItemID: "row1", KeyID: "text1", ValueID: "value1", Title: "First row", KeyName: "First field", DefIDs: []string{first, second}},
+ {ItemID: "row2", KeyID: "text1", ValueID: "value2", Title: "Second row", KeyName: "First field", DefIDs: []string{first}},
+ {ItemID: "row1", KeyID: "text2", ValueID: "value3", Title: "First row", KeyName: "Second field", DefIDs: []string{first}},
+ }
+ if got := backlinkAttributeViewMatches(view, map[string]bool{first: true, second: true}); !reflect.DeepEqual(got, want) {
+ t.Fatalf("unexpected matches: %#v", got)
+ }
+ if got := backlinkAttributeViewMatches(view, map[string]bool{"missing": true}); len(got) != 0 {
+ t.Fatalf("unrelated definition matched: %+v", got)
+ }
+}
+
+func TestBacklinkAttributeViewTargetsRespectCarrier(t *testing.T) {
+ const boxID = "20260906160000-box0001"
+ const rootID = "20260906160001-root001"
+ const avID = "20260906160002-av00001"
+ const blockID = "20260906160003-db00001"
+ const mirrorID = "20260906160004-db00002"
+ const defID = "20260906160005-def0001"
+ setupExportRelatedTest(t, boxID)
+ setupAttributeViewRefI18n(t)
+ view := av.NewAttributeView(avID)
+ view.GetBlockKeyValues().Values = []*av.Value{{BlockID: "row", Block: &av.ValueBlock{Content: "Row"}}}
+ view.KeyValues = append(view.KeyValues, &av.KeyValues{Key: &av.Key{ID: "text", Type: av.KeyTypeText}, Values: []*av.Value{
+ {ID: "cell", BlockID: "row", Text: &av.ValueText{Rich: &av.ValueTextRich{
+ Spec: av.ValueTextRichSpec, Format: av.ValueTextRichFormatKramdown, Content: "((" + defID + " \"Target\"))",
+ }}},
+ }})
+ if err := av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ tree := newAttributeViewRefCarrierTestTree(boxID, rootID, avID, blockID, mirrorID)
+ ref := &sql.Ref{Type: sql.AttributeViewRefType, BlockID: blockID, DefBlockID: defID, RootID: rootID, Box: boxID, Path: tree.Path}
+ got := backlinkAttributeViewTargets(tree, []*sql.Ref{ref})
+ if len(got) != 1 || got[blockID] == nil || len(got[blockID].Matches) != 1 || got[mirrorID] != nil {
+ t.Fatalf("unexpected carrier targets: %+v", got)
+ }
+ ref.Box = "other-box"
+ if got = backlinkAttributeViewTargets(tree, []*sql.Ref{ref}); len(got) != 0 {
+ t.Fatalf("cross-notebook reference matched: %+v", got)
+ }
+ const encryptedBoxID = "20260906160006-boxenc1"
+ markRuntimeEncryptedBox(encryptedBoxID)
+ t.Cleanup(func() { forgetRuntimeEncryptedBox(encryptedBoxID) })
+ tree.Box = encryptedBoxID
+ ref.Box = encryptedBoxID
+ if got = backlinkAttributeViewTargets(tree, []*sql.Ref{ref}); len(got) != 0 {
+ t.Fatalf("encrypted carrier fell back to the global attribute view: %+v", got)
+ }
+}