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: Improve opening database search results https://github.com/siyuan-note/siyuan/issues/12633
Daniel9b8e8956f997
diff --git a/app/src/boot/globalEvent/searchKeydown.ts b/app/src/boot/globalEvent/searchKeydown.tsindex 9f83e12d55..30acd11b0f 100644--- a/app/src/boot/globalEvent/searchKeydown.ts+++ b/app/src/boot/globalEvent/searchKeydown.ts@@ -17,6 +17,7 @@ import {writeText} from "../../protyle/util/compatibility";import {getUnRefList} from "../../search/unRef";import {toggleAssetHistory, toggleReplaceHistory, toggleSearchHistory} from "../../search/toggleHistory";import {Protyle} from "../../protyle";+import {getKeysByLiElement} from "../../search/menu";export const searchKeydown = (app: App, event: KeyboardEvent) => {if (getSelection().rangeCount === 0) {@@ -107,6 +108,9 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {}},openPosition: "right",+ nodeType: currentList.dataset.nodeType,+ method: config.method,+ keywords: getKeysByLiElement(currentList),});return true;}@@ -226,6 +230,9 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {dialog.destroy({focus: "false"});}},+ nodeType: currentList.dataset.nodeType,+ method: config.method,+ keywords: getKeysByLiElement(currentList),});}} else {diff --git a/app/src/editor/databaseRow.ts b/app/src/editor/databaseRow.tsindex 82cd45b177..3867ff07a7 100644--- a/app/src/editor/databaseRow.ts+++ b/app/src/editor/databaseRow.ts@@ -4,6 +4,7 @@ import type {App} from "../index";import {renderAVAttribute} from "../protyle/render/av/blockAttr";import {Protyle} from "../protyle";import {getEditorHorizontalPadding} from "../protyle/ui/padding";+import {searchMarkRender} from "../protyle/render/searchMarkRender";export const newDatabaseRowModel = (options: {app: App,@@ -15,6 +16,9 @@ export const newDatabaseRowModel = (options: {itemID: string,valueID: string,title: string,+ matchedValueID?: string,+ matchedKeyID?: string,+ keywords?: string[],},}) => {let customModel: Custom;@@ -51,14 +55,32 @@ export const newDatabaseRowModel = (options: {if (!previousBodyElement || !contextProtyle) {return;}+ const data = custom.data as typeof options.data;const bodyElement = document.createElement("div");bodyElement.className = "custom-attr protyle-db-row__body";previousBodyElement.replaceWith(bodyElement);updateLayout(custom);- renderAVAttribute(bodyElement, options.data.itemID, contextProtyle, (element) => {+ renderAVAttribute(bodyElement, data.itemID, contextProtyle, (element) => {updateTitle(custom, element);+ if (!data.keywords?.length) {+ return;+ }+ const rootElement = custom.element.querySelector<HTMLElement>(".protyle-content");+ if (!rootElement) {+ return;+ }+ const matchedElement = data.matchedValueID ?+ rootElement.querySelector(`[data-av-id="${data.avID}"] [data-id="${data.matchedValueID}"]`) :+ rootElement.querySelector(+ `[data-av-id="${data.avID}"] [data-col-id="${data.matchedKeyID}"][data-row-id="${data.itemID}"]`);+ searchMarkRender(contextProtyle, data.keywords, undefined, () => {+ matchedElement?.scrollIntoView({block: "center"});+ }, {+ rootElement,+ currentElement: matchedElement,+ });},- {avID: options.data.avID, itemID: options.data.itemID, valueID: options.data.valueID});+ {avID: data.avID, itemID: data.itemID, valueID: data.valueID});};const model = new Custom({app: options.app,@@ -92,6 +114,7 @@ export const newDatabaseRowModel = (options: {return;}contextProtyle = editor.protyle;+ custom.element.append(contextProtyle.highlight.styleElement);render(custom);},});diff --git a/app/src/protyle/render/av/attributePanel.ts b/app/src/protyle/render/av/attributePanel.tsindex 4b1b03f2a0..c6bf0fd37d 100644--- a/app/src/protyle/render/av/attributePanel.ts+++ b/app/src/protyle/render/av/attributePanel.ts@@ -26,6 +26,7 @@ export class AVAttributePanel {private collapsed: boolean;private activeAvID = "";private showEmptyFields = false;+ private renderCallbacks: ((element: HTMLElement) => void)[] = [];constructor(protyle: IProtyle) {this.protyle = protyle;@@ -105,9 +106,23 @@ export class AVAttributePanel {this.updateTabs();this.updateEmptyState();this.element.classList.toggle("fn__none", !renderedElement.querySelector("[data-av-id], .custom-attr__avbacklinks"));+ const callbacks = this.renderCallbacks.splice(0);+ callbacks.forEach(callback => callback(this.bodyElement));});}+ public afterRender(callback: (element: HTMLElement) => void) {+ if (!window.siyuan.config.editor.databaseAttrShow) {+ return;+ }+ if (this.element.dataset.rendered === "true" && !this.renderingTargetID) {+ callback(this.bodyElement);+ return;+ }+ this.renderCallbacks.push(callback);+ this.render();+ }+public refresh() {this.render(true);}diff --git a/app/src/protyle/render/av/openDatabaseRow.ts b/app/src/protyle/render/av/openDatabaseRow.tsindex 29dc8c7f80..a7ca9ba31c 100644--- a/app/src/protyle/render/av/openDatabaseRow.ts+++ b/app/src/protyle/render/av/openDatabaseRow.ts@@ -3,12 +3,15 @@ import {Constants} from "../../../constants";import {openMobileFileById} from "../../../mobile/editor";import {Dialog} from "../../../dialog";import {renderAVAttribute} from "./blockAttr";+import {Protyle} from "../../index";/// #elseimport {openFile, openFileById} from "../../../editor/util";import {Editor} from "../../../editor";import {getAllTabs} from "../../../layout/getAll";import {zoomOut} from "../../../menus/protyle";+import {Custom} from "../../../layout/dock/Custom";/// #endif+import {searchMarkRender} from "../searchMarkRender";export interface IDatabaseRowOpenData {avID: string;@@ -19,8 +22,26 @@ export interface IDatabaseRowOpenData {title: string;boundBlockID?: string;isDetached: boolean;+ matchedValueID?: string;+ matchedKeyID?: string;+ keywords?: string[];}+const highlightDatabaseRow = (protyle: IProtyle, rootElement: HTMLElement, data: IDatabaseRowOpenData) => {+ if (!data.keywords?.length) {+ return;+ }+ const matchedElement = data.matchedValueID ?+ rootElement.querySelector(`[data-av-id="${data.avID}"] [data-id="${data.matchedValueID}"]`) :+ rootElement.querySelector(`[data-av-id="${data.avID}"] [data-col-id="${data.matchedKeyID}"][data-row-id="${data.itemID}"]`);+ searchMarkRender(protyle, data.keywords, undefined, () => {+ matchedElement?.scrollIntoView({block: "center"});+ }, {+ rootElement,+ currentElement: matchedElement,+ });+};+/// #if MOBILEconst closeMobileDatabaseRow = () => {for (let i = window.siyuan.dialogs.length - 1; i >= 0; i--) {@@ -31,10 +52,11 @@ const closeMobileDatabaseRow = () => {}};-const openMobileDetachedDatabaseRow = (protyle: IProtyle, data: IDatabaseRowOpenData, title: string) => {+const openMobileDatabaseRow = (protyle: IProtyle, data: IDatabaseRowOpenData, title: string) => {closeMobileDatabaseRow();+ const context: { ghostProtyle?: Protyle } = {};const dialog = new Dialog({- content: `<div class="protyle-db-row protyle-db-row--mobile">+ content: `<div class="protyle-db-row protyle-db-row--mobile protyle-content"><div class="protyle-db-row__title"><svg><use xlink:href="#iconDatabase"></use></svg><span></span></div><div class="custom-attr protyle-db-row__body"></div></div>`,@@ -42,40 +64,58 @@ const openMobileDetachedDatabaseRow = (protyle: IProtyle, data: IDatabaseRowOpenheight: "100dvh",containerClassName: "b3-dialog__container--database-row",disableAnimation: true,+ destroyCallback() {+ context.ghostProtyle?.destroy();+ },});const rowElement = dialog.element.querySelector<HTMLElement>(".protyle-db-row");rowElement.dataset.protyleId = protyle.id;rowElement.querySelector(".protyle-db-row__title span").textContent = title;- renderAVAttribute(rowElement.querySelector<HTMLElement>(".protyle-db-row__body"), data.itemID, protyle, undefined, {- avID: data.avID,- itemID: data.itemID,- valueID: data.valueID,+ context.ghostProtyle = new Protyle(protyle.app, document.createElement("div"), {+ blockId: data.databaseBlockID,+ notebookId: data.notebookID,+ after(editor) {+ const contextProtyle = editor.protyle;+ rowElement.dataset.protyleId = contextProtyle.id;+ rowElement.append(contextProtyle.highlight.styleElement);+ renderAVAttribute(rowElement.querySelector<HTMLElement>(".protyle-db-row__body"), data.itemID, contextProtyle, () => {+ highlightDatabaseRow(contextProtyle, rowElement, data);+ }, {+ avID: data.avID,+ itemID: data.itemID,+ valueID: data.valueID,+ });+ },});};/// #else-const showDatabaseRowPreview = (model: Editor, blockID: string) => {+const showDatabaseRowPreview = (model: Editor, data: IDatabaseRowOpenData) => {if (!model?.editor?.protyle) {return;}- model.editor.protyle.element.dataset.databaseRowId = blockID;- model.editor.protyle.databaseAttributePanel?.expand();- model.editor.protyle.contentElement.scrollTop = 0;+ const editorProtyle = model.editor.protyle;+ editorProtyle.element.dataset.databaseRowId = data.boundBlockID || "";+ editorProtyle.databaseAttributePanel?.expand(data.avID);+ editorProtyle.contentElement.scrollTop = 0;+ editorProtyle.databaseAttributePanel?.afterRender(() => {+ highlightDatabaseRow(editorProtyle, editorProtyle.contentElement, data);+ });};-const focusDatabaseRowPreview = (model: Editor, blockID: string) => {+const focusDatabaseRowPreview = (model: Editor, data: IDatabaseRowOpenData) => {const editorProtyle = model?.editor?.protyle;- if (!editorProtyle) {+ if (!editorProtyle || !data.boundBlockID) {return;}- if (editorProtyle.block.showAll && editorProtyle.block.id === blockID) {- showDatabaseRowPreview(model, blockID);+ if (editorProtyle.block.showAll && editorProtyle.block.id === data.boundBlockID) {+ showDatabaseRowPreview(model, data);return;}zoomOut({protyle: editorProtyle,- id: blockID,+ id: data.boundBlockID,reload: true,- callback: () => showDatabaseRowPreview(model, blockID),+ callback: () => showDatabaseRowPreview(model, data),});};@@ -99,33 +139,41 @@ const getDatabaseRowPreviewTab = (blockID: string) => {};/// #endif-export const openDatabaseRowByData = (protyle: IProtyle, data: IDatabaseRowOpenData) => {+export const openDatabaseRowByData = async (protyle: IProtyle, data: IDatabaseRowOpenData, options?: {+ position?: string,+}) => {const title = data.title || window.siyuan.languages.untitled;+ const openStandalone = data.isDetached || !window.siyuan.config.editor.databaseAttrShow;/// #if MOBILE- if (data.isDetached) {- openMobileDetachedDatabaseRow(protyle, data, title);- return;+ if (openStandalone) {+ openMobileDatabaseRow(protyle, data, title);+ return true;}if (!data.boundBlockID) {- return;+ return false;}closeMobileDatabaseRow();window.siyuan.menus.menu.remove();openMobileFileById(protyle.app, data.boundBlockID, [Constants.CB_GET_ALL, Constants.CB_GET_FOCUS],undefined, undefined, (editorProtyle) => {editorProtyle.element.dataset.databaseRowId = data.boundBlockID;- editorProtyle.databaseAttributePanel?.expand();+ editorProtyle.databaseAttributePanel?.expand(data.avID);editorProtyle.contentElement.scrollTop = 0;+ editorProtyle.databaseAttributePanel?.afterRender(() => {+ highlightDatabaseRow(editorProtyle, editorProtyle.contentElement, data);+ });}, true);+ return true;/// #else- if (data.isDetached) {+ if (openStandalone) {if (!data.databaseBlockID) {- return;+ return false;}- openFile({+ const opened = await openFile({app: protyle.app,- position: "right",- removeCurrentTab: false,+ position: options ? options.position : "right",+ removeCurrentTab: options ? undefined : false,+ openNewTab: options ? undefined : true,custom: {id: "siyuan-database-row",icon: "iconDatabase",@@ -137,14 +185,35 @@ export const openDatabaseRowByData = (protyle: IProtyle, data: IDatabaseRowOpenDitemID: data.itemID,valueID: data.valueID,title,+ matchedValueID: data.matchedValueID,+ matchedKeyID: data.matchedKeyID,+ keywords: data.keywords,},},+ afterOpen(model) {+ if (model instanceof Custom) {+ Object.assign(model.data, data, {blockID: data.databaseBlockID, notebookId: data.notebookID});+ model.update();+ }+ },});- return;+ return Boolean(opened);}if (!data.boundBlockID) {- return;+ return false;+ }+ if (options) {+ const opened = await openFileById({+ app: protyle.app,+ id: data.boundBlockID,+ position: options.position,+ zoomIn: true,+ afterOpen(model: Editor) {+ focusDatabaseRowPreview(model, data);+ },+ });+ return Boolean(opened);}const openedTab = getDatabaseRowPreviewTab(data.boundBlockID);if (openedTab) {@@ -165,11 +234,11 @@ export const openDatabaseRowByData = (protyle: IProtyle, data: IDatabaseRowOpenDopenedTab.parent.switchTab(openedTab.headElement);openedTab.parent.showHeading();if (openedModel instanceof Editor) {- focusDatabaseRowPreview(openedModel, data.boundBlockID);+ focusDatabaseRowPreview(openedModel as Editor, data);}- return;+ return true;}- openFileById({+ const opened = await openFileById({app: protyle.app,id: data.boundBlockID,position: "right",@@ -177,8 +246,9 @@ export const openDatabaseRowByData = (protyle: IProtyle, data: IDatabaseRowOpenDremoveCurrentTab: false,zoomIn: true,afterOpen(model: Editor) {- showDatabaseRowPreview(model, data.boundBlockID);+ showDatabaseRowPreview(model, data);},});+ return Boolean(opened);/// #endif};diff --git a/app/src/protyle/render/searchMarkRender.ts b/app/src/protyle/render/searchMarkRender.tsindex 1cab32c6f6..c4a776a780 100644--- a/app/src/protyle/render/searchMarkRender.ts+++ b/app/src/protyle/render/searchMarkRender.ts@@ -1,7 +1,11 @@import {Constants} from "../../constants";import {isInEmbedBlock} from "../util/hasClosest";-export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: string | number, cb?: () => void) => {+export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: string | number, cb?: () => void,+ options?: {+ rootElement?: HTMLElement,+ currentElement?: Element,+ }) => {if (!isSupportCSSHL() || ((!keys || keys.length === 0) && !hlId)) {return;}@@ -11,8 +15,8 @@ export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: strinprotyle.highlight.rangeIndex = 0;protyle.highlight.ranges = [];let isSetHL = false;- let hlBlockElement: Element;- if (typeof hlId === "string") {+ let hlBlockElement = options?.currentElement;+ if (!hlBlockElement && typeof hlId === "string") {Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id='${hlId}']`)).find(item => {if (!isInEmbedBlock(item)) {hlBlockElement = item;@@ -29,8 +33,9 @@ export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: strinconst textNodes: Node[] = [];const textNodesSize: number[] = [];let currentSize = 0;+ const rootElement = options?.rootElement || protyle.contentElement;- const treeWalker = document.createTreeWalker(protyle.contentElement, NodeFilter.SHOW_TEXT);+ const treeWalker = document.createTreeWalker(rootElement, NodeFilter.SHOW_TEXT);let currentNode = treeWalker.nextNode();while (currentNode) {textNodes.push(currentNode);@@ -39,7 +44,7 @@ export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: strincurrentNode = treeWalker.nextNode();}- const text = protyle.contentElement.textContent;+ const text = rootElement.textContent;const rangeIndexes: { range: Range, startIndex: number, isCurrent: boolean }[] = [];if (keys && keys.length > 0) {keys.forEach(key => {diff --git a/app/src/search/menu.ts b/app/src/search/menu.tsindex eb6a90df0a..c5aa87e9ba 100644--- a/app/src/search/menu.ts+++ b/app/src/search/menu.ts@@ -777,7 +777,7 @@ export const initCriteriaMenu = (element: HTMLElement, data: Config.IUILayoutTab});};-export const getKeyByLiElement = (element: HTMLElement) => {+export const getKeysByLiElement = (element: HTMLElement) => {const keys: string[] = [];element.querySelectorAll(".b3-list-item__text mark").forEach(item => {keys.push(item.textContent);@@ -787,5 +787,9 @@ export const getKeyByLiElement = (element: HTMLElement) => {keys.push(item.textContent);});}- return [...new Set(keys)].join(" ");+ return [...new Set(keys)];+};++export const getKeyByLiElement = (element: HTMLElement) => {+ return getKeysByLiElement(element).join(" ");};diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex 4d38a02e7f..2ed090c51f 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -4,7 +4,7 @@ import * as path from "path";/// #endifimport {Constants} from "../constants";import {escapeAriaLabel, escapeHtml} from "../util/escape";-import {fetchPost} from "../util/fetch";+import {fetchPost, fetchSyncPost} from "../util/fetch";import {openFile, openFileById} from "../editor/util";import {showMessage} from "../dialog/message";import {reloadProtyle} from "../protyle/util/reload";@@ -21,6 +21,7 @@ import {newFile} from "../util/newFile";import {filterMenu,getKeyByLiElement,+ getKeysByLiElement,initCriteriaMenu,moreMenu,queryMenu,@@ -48,6 +49,7 @@ import {highlightById} from "../util/highlightById";import {getSelectionOffset} from "../protyle/util/selection";import {electronUndo} from "../protyle/undo";import {getContenteditableElement} from "../protyle/wysiwyg/getBlock";+import {IDatabaseRowOpenData, openDatabaseRowByData} from "../protyle/render/av/openDatabaseRow";export const openGlobalSearch = (app: App, text: string, replace: boolean, searchData?: Config.IUILayoutTabSearchConfig) => {text = text.trim();@@ -833,6 +835,9 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, eleid: target.getAttribute("data-node-id"),cb: closeCB,openPosition: "right",+ nodeType: target.dataset.nodeType,+ method: config.method,+ keywords: getKeysByLiElement(target),});} else if (!target.classList.contains("b3-list-item--focus")) {(searchType === "doc" ? searchPanelElement : unRefPanelElement).querySelector(".b3-list-item--focus").classList.remove("b3-list-item--focus");@@ -865,7 +870,10 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, elerootId: target.getAttribute("data-root-id"),protyle: edit.protyle,id: target.getAttribute("data-node-id"),- cb: closeCB+ cb: closeCB,+ nodeType: target.dataset.nodeType,+ method: config.method,+ keywords: getKeysByLiElement(target),});}}@@ -928,12 +936,45 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, elereturn {edit, unRefEdit};};-export const openSearchEditor = (options: {+export const openSearchEditor = async (options: {protyle: IProtyle,openPosition?: string,id: string,rootId: string,- cb: () => void+ cb: () => void,+ nodeType?: string,+ method?: number,+ keywords?: string[],+}) => {+ if (options.nodeType === "NodeAttributeView" && typeof options.method === "number" && [0, 1, 3].includes(options.method) &&+ options.keywords?.length > 0) {+ try {+ const response = await fetchSyncPost("/api/av/getAttributeViewSearchTarget", {+ id: options.id,+ keywords: options.keywords,+ });+ if (response.code === 0 && response.data) {+ const opened = await openDatabaseRowByData(options.protyle, response.data as IDatabaseRowOpenData, {+ position: options.openPosition,+ });+ if (opened) {+ options.cb?.();+ return;+ }+ }+ } catch (e) {+ console.warn("Resolve attribute view search target failed:", e);+ }+ }+ openSearchBlockEditor(options);+};++const openSearchBlockEditor = (options: {+ protyle: IProtyle,+ openPosition?: string,+ id: string,+ rootId: string,+ cb: () => void,}) => {let currentRange = (options.rootId === options.protyle.block.rootID && options.id === options.protyle.block.id) ?options.protyle.highlight.ranges[options.protyle.highlight.rangeIndex] : null;@@ -1456,7 +1497,7 @@ ${unicode2Emoji(getNotebookIcon(item.box) || window.siyuan.storage[Constants.LOCif (childItem.refCount) {countHTML = `<span class="popover__block counter b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.ref}">${childItem.refCount}</span>`;}- resultHTML += `<div style="padding-left: 36px" data-type="search-item" class="b3-list-item" data-node-id="${childItem.id}" data-root-id="${childItem.rootID}">+ resultHTML += `<div style="padding-left: 36px" data-type="search-item" class="b3-list-item" data-node-id="${childItem.id}" data-root-id="${childItem.rootID}" data-node-type="${childItem.type || ""}"><svg class="b3-list-item__graphic popover__block" data-id="${childItem.id}"><use xlink:href="#${getIconByType(childItem.type)}"></use></svg>${unicode2Emoji(childItem.ial.icon, "b3-list-item__graphic", true)}<span class="b3-list-item__text">${childItem.content}</span>@@ -1478,7 +1519,7 @@ ${countHTML}if (item.refCount) {countHTML = `<span class="popover__block counter b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.ref}">${item.refCount}</span>`;}- resultHTML += `<div data-type="search-item" class="b3-list-item" data-node-id="${item.id}" data-root-id="${item.rootID}">+ resultHTML += `<div data-type="search-item" class="b3-list-item" data-node-id="${item.id}" data-root-id="${item.rootID}" data-node-type="${item.type || ""}"><svg class="b3-list-item__graphic popover__block" data-id="${item.id}"><use xlink:href="#${getIconByType(item.type)}"></use></svg>${unicode2Emoji(item.ial.icon, "b3-list-item__graphic", true)}<span class="b3-list-item__text">${item.content}</span>diff --git a/kernel/api/av.go b/kernel/api/av.goindex 83ddd96e7d..ba794e2228 100644--- a/kernel/api/av.go+++ b/kernel/api/av.go@@ -1293,6 +1293,26 @@ func getAttributeViewKeys(c *gin.Context) {ret.Data = blockAttributeViewKeys}+func getAttributeViewSearchTarget(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ defer c.JSON(http.StatusOK, ret)++ arg, ok := util.JsonArg(c, ret)+ if !ok {+ return+ }++ id, _ := arg["id"].(string)+ keywordsArg, _ := arg["keywords"].([]any)+ var keywords []string+ for _, keywordArg := range keywordsArg {+ if keyword, ok := keywordArg.(string); ok {+ keywords = append(keywords, keyword)+ }+ }+ ret.Data = model.GetAttributeViewSearchTarget(id, keywords)+}+func getAttributeViewBacklinks(c *gin.Context) {ret := gulu.Ret.NewResult()defer c.JSON(http.StatusOK, ret)diff --git a/kernel/api/router.go b/kernel/api/router.goindex e75cdb3961..7e03ec1b6e 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -529,6 +529,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/av/renderHistoryAttributeView", model.CheckAuth, model.CheckAdminRole, renderHistoryAttributeView)ginServer.Handle("POST", "/api/av/renderSnapshotAttributeView", model.CheckAuth, model.CheckAdminRole, renderSnapshotAttributeView)ginServer.Handle("POST", "/api/av/getAttributeViewKeys", model.CheckAuth, getAttributeViewKeys)+ ginServer.Handle("POST", "/api/av/getAttributeViewSearchTarget", model.CheckAuth, getAttributeViewSearchTarget)ginServer.Handle("POST", "/api/av/getAttributeViewFieldViews", model.CheckAuth, model.CheckReadonly, getAttributeViewFieldViews)ginServer.Handle("POST", "/api/av/getAttributeViewBacklinks", model.CheckAuth, getAttributeViewBacklinks)ginServer.Handle("POST", "/api/av/setAttributeViewBlockAttr", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAttributeViewBlockAttr)diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.goindex 19a3487044..a6fae39d1e 100644--- a/kernel/model/attribute_view_render.go+++ b/kernel/model/attribute_view_render.go@@ -47,6 +47,184 @@ type AttributeViewRenderTarget struct {PageSize int `json:"pageSize"`}+type AttributeViewSearchTarget struct {+ AvID string `json:"avID"`+ DatabaseBlockID string `json:"databaseBlockID"`+ NotebookID string `json:"notebookID"`+ ItemID string `json:"itemID"`+ ValueID string `json:"valueID"`+ MatchedValueID string `json:"matchedValueID"`+ MatchedKeyID string `json:"matchedKeyID"`+ Title string `json:"title"`+ BoundBlockID string `json:"boundBlockID"`+ IsDetached bool `json:"isDetached"`+ Keywords []string `json:"keywords"`+}++type attributeViewSearchMatch struct {+ valueID string+ keyID string+}++func GetAttributeViewSearchTarget(blockID string, keywords []string) (ret *AttributeViewSearchTarget) {+ waitForSyncingStorages()++ node, tree, _ := getNodeByBlockID(nil, blockID)+ if nil == node || nil == tree || ast.NodeAttributeView != node.Type || "" == node.AttributeViewID {+ return+ }++ var attrView *av.AttributeView+ var err error+ if IsEncryptedBox(tree.Box) {+ attrView, err = av.ParseAttributeViewInBox(node.AttributeViewID, tree.Box)+ } else {+ attrView, err = av.ParseAttributeView(node.AttributeViewID)+ }+ if nil == attrView {+ logging.LogErrorf("parse attribute view [%s] failed: %s", node.AttributeViewID, err)+ return+ }++ keywords = normalizeAttributeViewSearchKeywords(keywords)+ if 1 > len(keywords) {+ return+ }+ matches := getAttributeViewSearchMatches(attrView, keywords)+ if 1 > len(matches) {+ return+ }++ var orderedItemIDs []string+ blockValues := attrView.GetBlockKeyValues()+ pageSize := len(matches) + 1+ if nil != blockValues && len(blockValues.Values) >= pageSize {+ pageSize = len(blockValues.Values) + 1+ }+ target := &AttributeViewRenderTarget{Status: "viewNotFound"}+ viewable, renderErr := renderAttributeView(attrView, blockID, "", "", 1, pageSize, nil, false, target, "")+ if nil == renderErr {+ orderedItemIDs = appendAttributeViewSearchItemIDs(orderedItemIDs, viewable, false)+ orderedItemIDs = appendAttributeViewSearchItemIDs(orderedItemIDs, viewable, true)+ } else {+ logging.LogWarnf("render attribute view [%s] for search target failed: %s", attrView.ID, renderErr)+ }+ if nil != blockValues {+ for _, value := range blockValues.Values {+ if nil != value {+ orderedItemIDs = append(orderedItemIDs, value.BlockID)+ }+ }+ }++ visited := map[string]bool{}+ for _, itemID := range orderedItemIDs {+ if visited[itemID] {+ continue+ }+ visited[itemID] = true+ match := matches[itemID]+ if nil == match {+ continue+ }+ blockValue := attrView.GetBlockValue(itemID)+ if nil == blockValue || nil == blockValue.Block {+ continue+ }+ ret = &AttributeViewSearchTarget{+ AvID: attrView.ID,+ DatabaseBlockID: blockID,+ NotebookID: tree.Box,+ ItemID: itemID,+ ValueID: blockValue.ID,+ MatchedValueID: match.valueID,+ MatchedKeyID: match.keyID,+ Title: blockValue.String(true),+ BoundBlockID: blockValue.Block.ID,+ IsDetached: blockValue.IsDetached || "" == blockValue.Block.ID,+ Keywords: keywords,+ }+ return+ }+ return+}++func normalizeAttributeViewSearchKeywords(keywords []string) (ret []string) {+ added := map[string]bool{}+ for _, keyword := range keywords {+ keyword = strings.TrimSpace(keyword)+ if "" == keyword || added[keyword] {+ continue+ }+ added[keyword] = true+ ret = append(ret, keyword)+ }+ return+}++func getAttributeViewSearchMatches(attrView *av.AttributeView, keywords []string) (ret map[string]*attributeViewSearchMatch) {+ ret = map[string]*attributeViewSearchMatch{}+ for _, keyValues := range attrView.KeyValues {+ if nil == keyValues || nil == keyValues.Key {+ continue+ }+ for _, value := range keyValues.Values {+ if nil == value || "" == value.BlockID || nil != ret[value.BlockID] {+ continue+ }+ content := value.String(true)+ for _, keyword := range keywords {+ if strings.Contains(content, keyword) {+ ret[value.BlockID] = &attributeViewSearchMatch{valueID: value.ID, keyID: keyValues.Key.ID}+ break+ }+ }+ }+ }+ return+}++func appendAttributeViewSearchItemIDs(itemIDs []string, viewable av.Viewable, hiddenGroups bool) []string {+ if nil == viewable {+ return itemIDs+ }+ baseInstance := getAttributeViewBaseInstance(viewable)+ if nil != baseInstance && 0 < len(baseInstance.Groups) {+ for _, group := range baseInstance.Groups {+ if (0 != group.GetGroupHidden()) != hiddenGroups {+ continue+ }+ if collection, ok := group.(av.Collection); ok {+ for _, item := range collection.GetItems() {+ itemIDs = append(itemIDs, item.GetID())+ }+ }+ }+ return itemIDs+ }+ if hiddenGroups {+ return itemIDs+ }+ if collection, ok := viewable.(av.Collection); ok {+ for _, item := range collection.GetItems() {+ itemIDs = append(itemIDs, item.GetID())+ }+ }+ return itemIDs+}++func getAttributeViewBaseInstance(viewable av.Viewable) (ret *av.BaseInstance) {+ switch instance := viewable.(type) {+ case *av.Table:+ ret = instance.BaseInstance+ case *av.Gallery:+ ret = instance.BaseInstance+ case *av.Kanban:+ ret = instance.BaseInstance+ }+ return+}+func RenderAttributeView(blockID, avID, viewID, query string, page, pageSize int, groupPaging map[string]any, createIfNotExist, ignoreRows bool) (viewable av.Viewable, attrView *av.AttributeView, err error) {viewable, attrView, _, err = RenderAttributeViewWithTarget(blockID, avID, viewID, query, page, pageSize, groupPaging, "", createIfNotExist, ignoreRows, "", "")returndiff --git a/kernel/model/attribute_view_render_target_test.go b/kernel/model/attribute_view_render_target_test.goindex ab141065aa..08d51c2086 100644--- a/kernel/model/attribute_view_render_target_test.go+++ b/kernel/model/attribute_view_render_target_test.go@@ -47,6 +47,72 @@ func TestResolveAttributeViewTargetGroupID(t *testing.T) {}}+func TestGetAttributeViewSearchMatches(t *testing.T) {+ attrView := &av.AttributeView{KeyValues: []*av.KeyValues{+ {+ Key: &av.Key{ID: "20260726000000-keyaaaa"},+ Values: []*av.Value{+ {+ ID: "20260726000000-valueaa",+ BlockID: "20260726000000-itemaaa",+ Type: av.KeyTypeText,+ Text: &av.ValueText{Content: "First Match"},+ },+ },+ },+ {+ Key: &av.Key{ID: "20260726000000-keybbbb"},+ Values: []*av.Value{+ {+ ID: "20260726000000-valuebb",+ BlockID: "20260726000000-itemaaa",+ Type: av.KeyTypeText,+ Text: &av.ValueText{Content: "Second Match"},+ },+ },+ },+ }}++ matches := getAttributeViewSearchMatches(attrView, []string{"Match"})+ match := matches["20260726000000-itemaaa"]+ if nil == match {+ t.Fatal("search match not found")+ }+ if "20260726000000-valueaa" != match.valueID || "20260726000000-keyaaaa" != match.keyID {+ t.Fatalf("unexpected search match: %+v", match)+ }+ if 0 != len(getAttributeViewSearchMatches(attrView, []string{"match"})) {+ t.Fatal("search match should preserve the case of highlighted keywords")+ }+}++func TestAppendAttributeViewSearchItemIDs(t *testing.T) {+ hiddenGroup := &av.Table{+ BaseInstance: &av.BaseInstance{GroupHidden: 2},+ Rows: []*av.TableRow{{ID: "20260726000000-hiddena"}},+ }+ visibleGroup := &av.Table{+ BaseInstance: &av.BaseInstance{},+ Rows: []*av.TableRow{+ {ID: "20260726000000-visiblea"},+ {ID: "20260726000000-visibleb"},+ },+ }+ viewable := &av.Table{BaseInstance: &av.BaseInstance{Groups: []av.Viewable{hiddenGroup, visibleGroup}}}++ itemIDs := appendAttributeViewSearchItemIDs(nil, viewable, false)+ itemIDs = appendAttributeViewSearchItemIDs(itemIDs, viewable, true)+ expected := []string{"20260726000000-visiblea", "20260726000000-visibleb", "20260726000000-hiddena"}+ if len(expected) != len(itemIDs) {+ t.Fatalf("unexpected item IDs: %+v", itemIDs)+ }+ for i, itemID := range itemIDs {+ if expected[i] != itemID {+ t.Fatalf("unexpected item IDs: %+v", itemIDs)+ }+ }+}+func TestGetAttributeViewPasteRowsFromTable(t *testing.T) {table := &av.Table{Rows: []*av.TableRow{{ID: "20260723000000-itemaaa"},