An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support filtering backlinks by block type https://github.com/siyuan-note/siyuan/issues/19257
Daniel7c5f6a481bfb
diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scssindex c4683205e4..0120800edf 100644--- a/app/src/assets/scss/protyle/_protyle.scss+++ b/app/src/assets/scss/protyle/_protyle.scss@@ -562,11 +562,14 @@}> .counter {- background-color: transparent;+ background-color: var(--b3-theme-background-light);color: var(--b3-theme-on-surface-light);+ height: 18px;+ line-height: 18px;+ padding: 0 4px;&:hover {- background-color: transparent;+ background-color: var(--b3-theme-background-light);color: var(--b3-theme-on-surface-light);}}diff --git a/app/src/layout/dock/BacklinkContent.ts b/app/src/layout/dock/BacklinkContent.tsindex eb2908ef22..c4bd8f2752 100644--- a/app/src/layout/dock/BacklinkContent.ts+++ b/app/src/layout/dock/BacklinkContent.ts@@ -853,6 +853,37 @@ export class BacklinkContent extends Model {}private showSourceFilterMenu(event: MouseEvent) {+ const blockTypeSubmenu: IMenu[] = [{+ label: window.siyuan.languages.all,+ checked: !this.sourceFilter.excludedBlockTypes.length,+ iconHTML: "",+ click: () => this.applySourceFilter({...this.sourceFilter, excludedBlockTypes: []}),+ }, {type: "separator"}];+ [+ ["NodeDocument", "doc"], ["NodeParagraph", "paragraph"], ["NodeHeading", "headings"],+ ["NodeList", "list1"], ["NodeListItem", "listItem"], ["NodeBlockquote", "quote"],+ ["NodeSuperBlock", "superBlock"], ["NodeCallout", "callout"],+ ["NodeTabs", "tabs"], ["NodeTabItem", "tabItem"], ["NodeAttributeView", "database"],+ ["NodeTable", "table"], ["NodeCodeBlock", "code"], ["NodeMathBlock", "math"],+ ["NodeBlockQueryEmbed", "embedBlock"], ["NodeVideo", "video"], ["NodeAudio", "audio"],+ ["NodeWidget", "widget"], ["NodeHTMLBlock", "HTML"], ["NodeIFrame", "IFrame"],+ ["NodeThematicBreak", "line"], ["NodeCustomBlock", "custom"],+ ].forEach(([type, label]) => {+ blockTypeSubmenu.push({+ label: window.siyuan.languages[label] || label,+ checked: !this.sourceFilter.excludedBlockTypes.includes(type),+ iconHTML: "",+ click: () => {+ const excluded = new Set(this.sourceFilter.excludedBlockTypes);+ if (excluded.has(type)) {+ excluded.delete(type);+ } else {+ excluded.add(type);+ }+ this.applySourceFilter({...this.sourceFilter, excludedBlockTypes: Array.from(excluded)});+ },+ });+ });const dailyNoteSubmenu = ([["all", window.siyuan.languages.all],["only", window.siyuan.languages.dailyNote],@@ -891,6 +922,12 @@ export class BacklinkContent extends Model {});window.siyuan.menus.menu.remove();+ window.siyuan.menus.menu.append(new MenuItem({+ icon: "iconListFilterPlus",+ label: window.siyuan.languages.type,+ type: "submenu",+ submenu: blockTypeSubmenu,+ }).element);window.siyuan.menus.menu.append(new MenuItem({icon: "iconCalendar",label: window.siyuan.languages.dailyNote,@@ -1007,13 +1044,16 @@ export class BacklinkContent extends Model {const viewStateGeneration = this.viewStateGeneration;const contextRequestVersion = this.contextRequestVersions[index];const requestGeneration = ++record.requestGeneration;- const param: IObject = {+ const param: {[key: string]: string | number | boolean | IBacklinkSourceFilter} = {defID: blockId,refTreeID: docId,highlight: !isSupportCSSHL(),keyword,};const notebookId = liElement.getAttribute("data-notebook-id");+ if (!isMention) {+ param.sourceFilter = getBacklinkSourceFilterParam(this.sourceFilter);+ }if (isEncryptedBox(notebookId)) {param.notebook = notebookId;}diff --git a/app/src/layout/dock/backlinkSourceFilter.test.ts b/app/src/layout/dock/backlinkSourceFilter.test.tsindex e90715b0ae..48147019da 100644--- a/app/src/layout/dock/backlinkSourceFilter.test.ts+++ b/app/src/layout/dock/backlinkSourceFilter.test.ts@@ -20,6 +20,16 @@ describe("backlink source filter", () => {dailyNote: "only",excludedNotebookIDs: ["box-a", "box-b"],excludeSelf: true,+ excludedBlockTypes: [],});});++ it("keeps a block type filter active and resets it to all types", () => {+ const filter = getBacklinkSourceFilterParam({+ ...createBacklinkSourceFilter(),+ excludedBlockTypes: ["NodeParagraph", "NodeAttributeView", "NodeParagraph", ""],+ });+ assert.deepEqual(filter.excludedBlockTypes, ["NodeAttributeView", "NodeParagraph"]);+ assert.equal(getBacklinkSourceFilterParam({...filter, excludedBlockTypes: []}), undefined);+ });});diff --git a/app/src/layout/dock/backlinkSourceFilter.ts b/app/src/layout/dock/backlinkSourceFilter.tsindex 5b18d10de8..e42ac22b45 100644--- a/app/src/layout/dock/backlinkSourceFilter.ts+++ b/app/src/layout/dock/backlinkSourceFilter.ts@@ -4,23 +4,27 @@ export interface IBacklinkSourceFilter {dailyNote: TBacklinkDailyNoteFilter;excludedNotebookIDs: string[];excludeSelf: boolean;+ excludedBlockTypes?: string[];}export const createBacklinkSourceFilter = (): IBacklinkSourceFilter => ({dailyNote: "all",excludedNotebookIDs: [],excludeSelf: false,+ excludedBlockTypes: [],});export const normalizeBacklinkSourceFilter = (filter: IBacklinkSourceFilter): IBacklinkSourceFilter => ({dailyNote: ["only", "exclude"].includes(filter.dailyNote) ? filter.dailyNote : "all",excludedNotebookIDs: Array.from(new Set(filter.excludedNotebookIDs.filter(Boolean))).sort(),excludeSelf: Boolean(filter.excludeSelf),+ excludedBlockTypes: Array.from(new Set((filter.excludedBlockTypes || []).filter(Boolean))).sort(),});export const getBacklinkSourceFilterParam = (filter: IBacklinkSourceFilter) => {const normalized = normalizeBacklinkSourceFilter(filter);- if (normalized.dailyNote === "all" && normalized.excludedNotebookIDs.length === 0 && !normalized.excludeSelf) {+ if (normalized.dailyNote === "all" && normalized.excludedNotebookIDs.length === 0 && !normalized.excludeSelf &&+ normalized.excludedBlockTypes.length === 0) {return;}return normalized;diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex 7248443ab3..bb4e750819 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -158,9 +158,9 @@ func getBacklinkDoc(c *gin.Context) {if encryptedNotebookDenied || !isBacklinkDocAccessible(c, refTreeID) {backlinks, keywords = []*model.Backlink{}, []string{}} else if notebook != "" && model.IsEncryptedBox(notebook) {- backlinks, keywords = model.GetBacklinkDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook)+ backlinks, keywords = model.GetBacklinkDocInBox(defID, refTreeID, keyword, containChildren, highlight, notebook, parseBacklinkSourceFilter(arg))} else {- backlinks, keywords = model.GetBacklinkDoc(defID, refTreeID, keyword, containChildren, highlight)+ backlinks, keywords = model.GetBacklinkDoc(defID, refTreeID, keyword, containChildren, highlight, parseBacklinkSourceFilter(arg))}keywords = canonicalBacklinkKeywords(keywords)items := newBacklinkContextResponses(backlinks)@@ -295,6 +295,13 @@ func parseBacklinkSourceFilter(arg map[string]any) *model.BacklinkSourceFilter {}filter := &model.BacklinkSourceFilter{}+ if blockTypes, ok := filterArg["excludedBlockTypes"].([]any); ok {+ for _, blockType := range blockTypes {+ if value, ok := blockType.(string); ok {+ filter.ExcludedBlockTypes = append(filter.ExcludedBlockTypes, value)+ }+ }+ }filter.DailyNote, _ = filterArg["dailyNote"].(string)filter.ExcludeSelf, _ = filterArg["excludeSelf"].(bool)if notebookIDs, ok := filterArg["excludedNotebookIDs"].([]any); ok {diff --git a/kernel/api/ref_filter_test.go b/kernel/api/ref_filter_test.goindex 3c0253f67a..4d2fefd986 100644--- a/kernel/api/ref_filter_test.go+++ b/kernel/api/ref_filter_test.go@@ -36,6 +36,7 @@ func TestParseBacklinkSourceFilter(t *testing.T) {"dailyNote": model.BacklinkDailyNoteExclude,"excludedNotebookIDs": []any{"box-b", "box-a", "box-b"},"excludeSelf": true,+ "excludedBlockTypes": []any{"NodeAttributeView", 42, "NodeParagraph", "NodeAttributeView", "unknown"},},})if nil == filter || model.BacklinkDailyNoteExclude != filter.DailyNote || !filter.ExcludeSelf {@@ -44,4 +45,7 @@ func TestParseBacklinkSourceFilter(t *testing.T) {if !reflect.DeepEqual([]string{"box-a", "box-b"}, filter.ExcludedNotebookIDs) {t.Fatalf("unexpected notebook IDs: %v", filter.ExcludedNotebookIDs)}+ if !reflect.DeepEqual([]string{"NodeAttributeView", "NodeParagraph"}, filter.ExcludedBlockTypes) {+ t.Fatalf("unexpected block types: %v", filter.ExcludedBlockTypes)+ }}diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex 799c352ab4..660e322870 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -159,6 +159,7 @@ type BacklinkSourceFilter struct {DailyNote string `json:"dailyNote"`ExcludedNotebookIDs []string `json:"excludedNotebookIDs"`ExcludeSelf bool `json:"excludeSelf"`+ ExcludedBlockTypes []string `json:"excludedBlockTypes"`}func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSourceFilter {@@ -180,13 +181,21 @@ func NormalizeBacklinkSourceFilter(filter *BacklinkSourceFilter) *BacklinkSourceexcludedNotebookIDs = append(excludedNotebookIDs, notebookID)}sort.Strings(excludedNotebookIDs)- if BacklinkDailyNoteAll == dailyNote && 0 == len(excludedNotebookIDs) && !filter.ExcludeSelf {+ excludedBlockTypes := []string{}+ for _, blockType := range filter.ExcludedBlockTypes {+ if "" != treenode.TypeAbbr(blockType) && !gulu.Str.Contains(blockType, excludedBlockTypes) {+ excludedBlockTypes = append(excludedBlockTypes, blockType)+ }+ }+ sort.Strings(excludedBlockTypes)+ if BacklinkDailyNoteAll == dailyNote && 0 == len(excludedNotebookIDs) && !filter.ExcludeSelf && 0 == len(excludedBlockTypes) {return nil}return &BacklinkSourceFilter{DailyNote: dailyNote,ExcludedNotebookIDs: excludedNotebookIDs,ExcludeSelf: filter.ExcludeSelf,+ ExcludedBlockTypes: excludedBlockTypes,}}@@ -250,7 +259,7 @@ func GetBackmentionDoc(defID, refTreeID, keyword string, containChildren, highlireturn}-func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlight bool) (ret []*Backlink, keywords []string) {+func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlight bool, filters ...*BacklinkSourceFilter) (ret []*Backlink, keywords []string) {keyword = strings.TrimSpace(keyword)if "" != keyword {keywords = strings.Split(keyword, " ")@@ -295,6 +304,9 @@ func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlightrefs = removeDuplicatedRefs(refs)linkRefs, _, _, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, encBoxIDUsed)+ if len(filters) > 0 {+ linkRefs = filterBacklinkSourcesInBox(linkRefs, rootID, encBoxIDUsed, filters[0])+ }refTree, err := LoadTreeByBlockID(refTreeID)if err != nil {logging.LogWarnf("load ref tree [%s] failed: %s", refTreeID, err)@@ -315,7 +327,7 @@ func GetBacklinkDoc(defID, refTreeID, keyword string, containChildren, highlightreturn}-func GetBacklinkDocInBox(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string) (ret []*Backlink, keywords []string) {+func GetBacklinkDocInBox(defID, refTreeID, keyword string, containChildren, highlight bool, boxID string, filters ...*BacklinkSourceFilter) (ret []*Backlink, keywords []string) {keyword = strings.TrimSpace(keyword)if "" != keyword {keywords = strings.Split(keyword, " ")@@ -342,6 +354,9 @@ func GetBacklinkDocInBox(defID, refTreeID, keyword string, containChildren, highrefs = removeDuplicatedRefs(refs)linkRefs, _, _, originalRefBlockIDs := buildLinkRefsInBox(rootID, refs, keywords, boxID)+ if len(filters) > 0 {+ linkRefs = filterBacklinkSourcesInBox(linkRefs, rootID, boxID, filters[0])+ }refTree, err := loadTreeByBlockIDInBox(refTreeID, boxID)if err != nil {logging.LogWarnf("load ref tree [%s] failed: %s", refTreeID, err)@@ -874,6 +889,9 @@ func filterBacklinkSources(linkRefs []*Block, defRootID string, filter *Backlinkif nil == linkRef || excludedNotebookIDs[linkRef.Box] || filter.ExcludeSelf && defRootID == linkRef.RootID {continue}+ if gulu.Str.Contains(linkRef.Type, filter.ExcludedBlockTypes) {+ continue+ }isDailyNote := dailyNoteRootIDs[linkRef.RootID]if BacklinkDailyNoteOnly == filter.DailyNote && !isDailyNote ||BacklinkDailyNoteExclude == filter.DailyNote && isDailyNote {diff --git a/kernel/model/backlink_source_filter_test.go b/kernel/model/backlink_source_filter_test.goindex e95e1ad36e..105296a8d1 100644--- a/kernel/model/backlink_source_filter_test.go+++ b/kernel/model/backlink_source_filter_test.go@@ -81,6 +81,26 @@ func TestIsDailyNoteBlock(t *testing.T) {}}+func TestBacklinkBlockTypeFilter(t *testing.T) {+ filter := NormalizeBacklinkSourceFilter(&BacklinkSourceFilter{+ ExcludedBlockTypes: []string{"NodeAttributeView", "", "unknown", "NodeAttributeView"},+ })+ if nil == filter || !reflect.DeepEqual(filter.ExcludedBlockTypes, []string{"NodeAttributeView"}) {+ t.Fatalf("unexpected block types: %+v", filter)+ }+ database := &Block{ID: "database", Type: "NodeAttributeView"}+ parent := &Block{ID: "parent", Type: "NodeHeading", Children: []*Block{database}}+ paragraph := &Block{ID: "paragraph", Type: "NodeParagraph", RootID: "same-document"}+ refs := []*Block{database, parent, paragraph}+ filtered := filterBacklinkSources(refs, "target", filter, nil)+ assertBacklinkSourceIDs(t, filtered, []string{"parent", "paragraph"})+ if len(parent.Children) != 1 || parent.Children[0] != database || len(refs) != 3 {+ t.Fatal("filter must preserve nested content and original references")+ }+ filter.ExcludedBlockTypes = append(filter.ExcludedBlockTypes, "NodeHeading", "NodeParagraph")+ assertBacklinkSourceIDs(t, filterBacklinkSources(refs, "target", filter, nil), []string{})+}+func assertBacklinkSourceIDs(t *testing.T, blocks []*Block, expected []string) {t.Helper()actual := make([]string, 0, len(blocks))