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 searching view names in Add to Database https://github.com/siyuan-note/siyuan/issues/16406
Daniel7ff2512eb83a
diff --git a/app/src/protyle/render/av/action.ts b/app/src/protyle/render/av/action.tsindex dc4b88b696..e20110e0d6 100644--- a/app/src/protyle/render/av/action.ts+++ b/app/src/protyle/render/av/action.ts@@ -906,40 +906,46 @@ export const avContextmenu = (protyle: IProtyle, rowElement: HTMLElement, positilabel: window.siyuan.languages.addToDatabase,icon: "iconDatabase",click() {- openSearchAV(blockElement.getAttribute("data-av-id"), rowElement, (listItemElement) => {- const srcs: IOperationSrcs[] = [];- const sourceIds: string[] = [];- selectedItemInfos.forEach((item, index) => {- const primaryInfo = primaryRows[index];- srcs.push({- itemID: Lute.NewNodeID(),- content: primaryInfo.content,- id: primaryInfo.blockID,- isDetached: primaryInfo.isDetached,+ openSearchAV({+ avID: blockElement.getAttribute("data-av-id"),+ target: rowElement,+ purpose: "addToDatabase",+ blockID: blockElement.getAttribute("data-node-id"),+ callback: (listItemElement) => {+ const srcs: IOperationSrcs[] = [];+ const sourceIds: string[] = [];+ selectedItemInfos.forEach((item, index) => {+ const primaryInfo = primaryRows[index];+ srcs.push({+ itemID: Lute.NewNodeID(),+ content: primaryInfo.content,+ id: primaryInfo.blockID,+ isDetached: primaryInfo.isDetached,+ });+ sourceIds.push(item.itemID);});- sourceIds.push(item.itemID);- });- const avID = listItemElement.dataset.avId;- const viewID = listItemElement.dataset.viewId;- transaction(protyle, [{- action: "insertAttrViewBlock",- ignoreDefaultFill: viewID ? false : true,- viewID,- avID,- srcs,- context: {ignoreTip: "true"},- blockID: listItemElement.dataset.blockId,- groupID: rowElement.parentElement.getAttribute("data-group-id")- }, {- action: "doUpdateUpdated",- id: listItemElement.dataset.blockId,- data: dayjs().format("YYYYMMDDHHmmss"),- }], [{- action: "removeAttrViewBlock",- srcIDs: sourceIds,- avID,- }]);- }, true, blockElement.getAttribute("data-node-id"));+ const avID = listItemElement.dataset.avId;+ const viewID = listItemElement.dataset.viewId;+ transaction(protyle, [{+ action: "insertAttrViewBlock",+ ignoreDefaultFill: viewID ? false : true,+ viewID,+ avID,+ srcs,+ context: {ignoreTip: "true"},+ blockID: listItemElement.dataset.blockId,+ groupID: rowElement.parentElement.getAttribute("data-group-id")+ }, {+ action: "doUpdateUpdated",+ id: listItemElement.dataset.blockId,+ data: dayjs().format("YYYYMMDDHHmmss"),+ }], [{+ action: "removeAttrViewBlock",+ srcIDs: sourceIds,+ avID,+ }]);+ }+ });}});if (selectedItemInfos.length === 1) {diff --git a/app/src/protyle/render/av/addToDatabase.ts b/app/src/protyle/render/av/addToDatabase.tsindex d77c38aeb7..4e89b40441 100644--- a/app/src/protyle/render/av/addToDatabase.ts+++ b/app/src/protyle/render/av/addToDatabase.ts@@ -18,53 +18,63 @@ export const addFilesToDatabase = (fileLiElements: Element[]) => {}});if (srcs.length > 0) {- openSearchAV("", fileLiElements[0] as HTMLElement, (listItemElement) => {- const avID = listItemElement.dataset.avId;- const viewID = listItemElement.dataset.viewId;- transaction(undefined, [{- action: "insertAttrViewBlock",- ignoreDefaultFill: viewID ? false : true,- viewID,- avID,- srcs,- blockID: listItemElement.dataset.blockId,- context: getAVFilteredTipContext(viewID ? "view" : "database"),- }, {- action: "doUpdateUpdated",- id: listItemElement.dataset.blockId,- data: dayjs().format("YYYYMMDDHHmmss"),- }]);+ openSearchAV({+ avID: "",+ target: fileLiElements[0] as HTMLElement,+ purpose: "addToDatabase",+ callback: (listItemElement) => {+ const avID = listItemElement.dataset.avId;+ const viewID = listItemElement.dataset.viewId;+ transaction(undefined, [{+ action: "insertAttrViewBlock",+ ignoreDefaultFill: viewID ? false : true,+ viewID,+ avID,+ srcs,+ blockID: listItemElement.dataset.blockId,+ context: getAVFilteredTipContext(viewID ? "view" : "database"),+ }, {+ action: "doUpdateUpdated",+ id: listItemElement.dataset.blockId,+ data: dayjs().format("YYYYMMDDHHmmss"),+ }]);+ }});}};export const addEditorToDatabase = (protyle: IProtyle, range: Range, type?: string) => {if ((range && protyle.title?.editElement?.contains(range.startContainer)) || type === "title") {- openSearchAV("", protyle.breadcrumb.element, (listItemElement) => {- const avID = listItemElement.dataset.avId;- const viewID = listItemElement.dataset.viewId;- transaction(protyle, [{- action: "insertAttrViewBlock",- ignoreDefaultFill: viewID ? false : true,- viewID,- avID,- srcs: [{- itemID: Lute.NewNodeID(),- id: protyle.block.rootID,- isDetached: false- }],- blockID: listItemElement.dataset.blockId,- context: getAVFilteredTipContext(viewID ? "view" : "database", protyle),- }, {- action: "doUpdateUpdated",- id: listItemElement.dataset.blockId,- data: dayjs().format("YYYYMMDDHHmmss"),- }], [{- action: "removeAttrViewBlock",- srcIDs: [protyle.block.rootID],- avID,- }]);- focusByRange(range);+ openSearchAV({+ avID: "",+ target: protyle.breadcrumb.element,+ purpose: "addToDatabase",+ callback: (listItemElement) => {+ const avID = listItemElement.dataset.avId;+ const viewID = listItemElement.dataset.viewId;+ transaction(protyle, [{+ action: "insertAttrViewBlock",+ ignoreDefaultFill: viewID ? false : true,+ viewID,+ avID,+ srcs: [{+ itemID: Lute.NewNodeID(),+ id: protyle.block.rootID,+ isDetached: false+ }],+ blockID: listItemElement.dataset.blockId,+ context: getAVFilteredTipContext(viewID ? "view" : "database", protyle),+ }, {+ action: "doUpdateUpdated",+ id: listItemElement.dataset.blockId,+ data: dayjs().format("YYYYMMDDHHmmss"),+ }], [{+ action: "removeAttrViewBlock",+ srcIDs: [protyle.block.rootID],+ avID,+ }]);+ focusByRange(range);+ }});} else {let targetElement: HTMLElement;@@ -86,37 +96,42 @@ export const addEditorToDatabase = (protyle: IProtyle, range: Range, type?: stritargetElement = protyle.wysiwyg.element;ids.push(protyle.block.rootID);}- openSearchAV("", targetElement, (listItemElement) => {- const srcIDs: string[] = [];- const srcs: IOperationSrcs[] = [];- ids.forEach(item => {- srcIDs.push(item);- srcs.push({- itemID: Lute.NewNodeID(),- id: item,- isDetached: false+ openSearchAV({+ avID: "",+ target: targetElement,+ purpose: "addToDatabase",+ callback: (listItemElement) => {+ const srcIDs: string[] = [];+ const srcs: IOperationSrcs[] = [];+ ids.forEach(item => {+ srcIDs.push(item);+ srcs.push({+ itemID: Lute.NewNodeID(),+ id: item,+ isDetached: false+ });});- });- const avID = listItemElement.dataset.avId;- const viewID = listItemElement.dataset.viewId;- transaction(protyle, [{- action: "insertAttrViewBlock",- ignoreDefaultFill: viewID ? false : true,- viewID,- avID,- srcs,- blockID: listItemElement.dataset.blockId,- context: getAVFilteredTipContext(viewID ? "view" : "database", protyle),- }, {- action: "doUpdateUpdated",- id: listItemElement.dataset.blockId,- data: dayjs().format("YYYYMMDDHHmmss"),- }], [{- action: "removeAttrViewBlock",- srcIDs,- avID,- }]);- focusByRange(range);+ const avID = listItemElement.dataset.avId;+ const viewID = listItemElement.dataset.viewId;+ transaction(protyle, [{+ action: "insertAttrViewBlock",+ ignoreDefaultFill: viewID ? false : true,+ viewID,+ avID,+ srcs,+ blockID: listItemElement.dataset.blockId,+ context: getAVFilteredTipContext(viewID ? "view" : "database", protyle),+ }, {+ action: "doUpdateUpdated",+ id: listItemElement.dataset.blockId,+ data: dayjs().format("YYYYMMDDHHmmss"),+ }], [{+ action: "removeAttrViewBlock",+ srcIDs,+ avID,+ }]);+ focusByRange(range);+ }});}};diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex da4a206955..96e76abd95 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -1371,7 +1371,12 @@ export const openMenuPanel = (options: {event.stopPropagation();break;} else if (type === "goSearchAV") {- openSearchAV(avID, target, undefined, false, options.blockElement.getAttribute("data-node-id"));+ openSearchAV({+ avID,+ target,+ purpose: "selectRelation",+ blockID: options.blockElement.getAttribute("data-node-id"),+ });event.preventDefault();event.stopPropagation();break;diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.tsindex 1f0f02dece..a53fc33322 100644--- a/app/src/protyle/render/av/relation.ts+++ b/app/src/protyle/render/av/relation.ts@@ -23,26 +23,50 @@ interface IAVItem {avName: string;blockID: string;hPath: string;+ matched?: boolean;viewName: string;viewID: string;viewLayout: string;}+type TSearchAVPurpose = "addToDatabase" | "selectRelation";++interface IOpenSearchAVOptions {+ avID: string;+ target: HTMLElement;+ callback?: (element: HTMLElement) => void;+ purpose: TSearchAVPurpose;+ blockID?: string;+}+const RELATION_PAGE_SIZE = 16;-const genSearchList = (element: Element, keyword: string, avId?: string, excludes = true, blockID?: string, cb?: () => void) => {+const SEARCH_AV_LOADING_HTML = '<img style="margin: 0 auto;display: block;width: 64px;height: 64px" src="/stage/loading-pure.svg">';++const genSearchList = (element: Element, keyword: string, options: IOpenSearchAVOptions, signal: AbortSignal,+ cb?: () => void) => {+ const showViews = options.purpose === "addToDatabase";fetchPost("/api/av/searchAttributeView", {keyword,- avID: avId,- blockID,- excludes: (excludes && avId) ? [avId] : undefined+ avID: options.avID,+ blockID: options.blockID,+ excludes: (showViews && options.avID) ? [options.avID] : undefined,+ includeViewMatches: showViews,}, (response) => {let html = "";- response.data.results.forEach((item: IAVItem & { children: IAVItem[] }, index: number) => {- const hasChildren = item.children && item.children.length > 0 && excludes;- html += `<div class="b3-list-item b3-list-item--narrow${index === 0 ? " b3-list-item--focus" : ""}" data-av-id="${item.avID}" data-block-id="${item.blockID}">- <span class="b3-list-item__toggle b3-list-item__toggle--hl${excludes ? "" : " fn__none"}" style="height:auto;align-self: stretch;margin: 4px 0;">- <svg class="b3-list-item__arrow">${hasChildren ? '<use xlink:href="#iconRight"></use>' : ""}</svg>+ const results = response.data.results as Array<IAVItem & { children: IAVItem[] }>;+ const hasMatchedView = showViews && results.some((item) => item.children?.some((subItem) => subItem.matched));+ let focusAssigned = false;+ results.forEach((item, index) => {+ const hasChildren = item.children && item.children.length > 0 && showViews;+ const expandChildren = hasChildren && item.children.some((subItem) => subItem.matched);+ const focusParent = !hasMatchedView && index === 0;+ if (focusParent) {+ focusAssigned = true;+ }+ html += `<div class="b3-list-item b3-list-item--narrow${focusParent ? " b3-list-item--focus" : ""}" data-av-id="${item.avID}" data-block-id="${item.blockID}">+ <span class="b3-list-item__toggle b3-list-item__toggle--hl${showViews ? "" : " fn__none"}" style="height:auto;align-self: stretch;margin: 4px 0;">+ <svg class="b3-list-item__arrow${expandChildren ? " b3-list-item__arrow--open" : ""}">${hasChildren ? '<use xlink:href="#iconRight"></use>' : ""}</svg></span><span class="fn__space--small"></span><div class="b3-list-item--two fn__flex-1">@@ -51,13 +75,17 @@ const genSearchList = (element: Element, keyword: string, avId?: string, exclude</div><div class="b3-list-item__meta b3-list-item__showall">${escapeLessThans(item.hPath)}</div></div>- <svg aria-label="${window.siyuan.languages.thisDatabase}" style="margin: 0 0 0 4px" class="b3-list-item__hinticon ariaLabel${item.avID === avId ? "" : " fn__none"}"><use xlink:href="#iconInfo"></use></svg>+ <svg aria-label="${window.siyuan.languages.thisDatabase}" style="margin: 0 0 0 4px" class="b3-list-item__hinticon ariaLabel${item.avID === options.avID ? "" : " fn__none"}"><use xlink:href="#iconInfo"></use></svg></div>`;if (hasChildren) {- html += '<div class="fn__none">';+ html += `<div class="${expandChildren ? "" : "fn__none"}">`;item.children.forEach((subItem) => {const viewDefaultName = getViewName(subItem.viewLayout);- html += `<div style="padding-left: 48px;" class="b3-list-item b3-list-item--narrow" data-av-id="${subItem.avID}" data-view-id="${subItem.viewID}">+ const focusView = !focusAssigned && Boolean(subItem.matched);+ if (focusView) {+ focusAssigned = true;+ }+ html += `<div style="padding-left: 48px;" class="b3-list-item b3-list-item--narrow${focusView ? " b3-list-item--focus" : ""}" data-av-id="${subItem.avID}" data-view-id="${subItem.viewID}" data-block-id="${subItem.blockID}"><span class="b3-list-item__text">${escapeHtml(subItem.viewName)}</span><span class="b3-list-item__meta">${viewDefaultName}</span></div>`;@@ -69,7 +97,7 @@ const genSearchList = (element: Element, keyword: string, avId?: string, excludeif (cb) {cb();}- });+ }, undefined, undefined, signal);};const setDatabase = (avId: string, element: HTMLElement, item: HTMLElement) => {@@ -82,7 +110,7 @@ const setDatabase = (avId: string, element: HTMLElement, item: HTMLElement) => {}};-export const openSearchAV = (avId: string, target: HTMLElement, cb?: (element: HTMLElement) => void, excludes = true, blockID?: string) => {+export const openSearchAV = (options: IOpenSearchAVOptions) => {window.siyuan.menus.menu.remove();const menu = new Menu();menu.addItem({@@ -92,12 +120,48 @@ export const openSearchAV = (avId: string, target: HTMLElement, cb?: (element: H<input class="b3-text-field fn__flex-shrink"/><div class="fn__hr"></div><div class="b3-list fn__flex-1 b3-list--background">- <img style="margin: 0 auto;display: block;width: 64px;height: 64px" src="/stage/loading-pure.svg">+ ${SEARCH_AV_LOADING_HTML}</div></div>`,bind(element) {- const listElement = element.querySelector(".b3-list");- const inputElement = element.querySelector("input");+ const listElement = element.querySelector(".b3-list") as HTMLElement;+ const inputElement = element.querySelector("input") as HTMLInputElement;+ let searchTimer = 0;+ let requestSequence = 0;+ let controller: AbortController;+ const loadList = (keyword: string, cb?: () => void) => {+ controller?.abort();+ controller = new AbortController();+ const currentSequence = ++requestSequence;+ genSearchList(listElement, keyword, options, controller.signal, () => {+ if (currentSequence !== requestSequence) {+ return;+ }+ cb?.();+ });+ };+ const search = () => {+ controller?.abort();+ requestSequence++;+ clearTimeout(searchTimer);+ listElement.innerHTML = SEARCH_AV_LOADING_HTML;+ searchTimer = window.setTimeout(() => {+ loadList(inputElement.value);+ }, Constants.TIMEOUT_INPUT);+ };+ const selectItem = (listItemElement?: HTMLElement) => {+ if (!listItemElement) {+ return;+ }+ clearTimeout(searchTimer);+ controller?.abort();+ if (options.callback) {+ options.callback(listItemElement);+ } else {+ setDatabase(options.avID, options.target, listItemElement);+ }+ window.siyuan.menus.menu.remove();+ };inputElement.addEventListener("keydown", (event: KeyboardEvent) => {if (event.isComposing) {return;@@ -107,12 +171,7 @@ export const openSearchAV = (avId: string, target: HTMLElement, cb?: (element: Hevent.preventDefault();event.stopPropagation();const listItemElement = listElement.querySelector(".b3-list-item--focus") as HTMLElement;- if (cb) {- cb(listItemElement);- } else {- setDatabase(avId, target, listItemElement);- }- window.siyuan.menus.menu.remove();+ selectItem(listItemElement);}});inputElement.addEventListener("input", (event: InputEvent) => {@@ -120,10 +179,10 @@ export const openSearchAV = (avId: string, target: HTMLElement, cb?: (element: Hif (event.isComposing) {return;}- genSearchList(listElement, inputElement.value, avId, excludes, blockID);+ search();});inputElement.addEventListener("compositionend", () => {- genSearchList(listElement, inputElement.value, avId, excludes, blockID);+ search();});element.lastElementChild.addEventListener("click", (event) => {let clickTarget = event.target as HTMLElement;@@ -142,19 +201,14 @@ export const openSearchAV = (avId: string, target: HTMLElement, cb?: (element: H} else if (clickTarget.classList.contains("b3-list-item")) {event.preventDefault();event.stopPropagation();- if (cb) {- cb(clickTarget);- } else {- setDatabase(avId, target, clickTarget);- }- window.siyuan.menus.menu.remove();+ selectItem(clickTarget);break;}clickTarget = clickTarget.parentElement;}});- genSearchList(listElement, "", avId, excludes, blockID, () => {- const rect = target.getBoundingClientRect();+ loadList("", () => {+ const rect = options.target.getBoundingClientRect();menu.open({x: rect.left,y: rect.bottom,@@ -165,7 +219,7 @@ export const openSearchAV = (avId: string, target: HTMLElement, cb?: (element: H}});menu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");- const popoverElement = hasTopClosestByClassName(target, "block__popover", true);+ const popoverElement = hasTopClosestByClassName(options.target, "block__popover", true);menu.element.setAttribute("data-from", popoverElement ? popoverElement.dataset.level + "popover" : "app");};diff --git a/kernel/api/av.go b/kernel/api/av.goindex 78c6bc9484..c694fbaa8d 100644--- a/kernel/api/av.go+++ b/kernel/api/av.go@@ -992,7 +992,14 @@ func searchAttributeView(c *gin.Context) {excludes = append(excludes, e.(string))}}- results := model.SearchAttributeView(keyword, excludes, currentAvID, currentBlockID)+ includeViewMatches, _ := arg["includeViewMatches"].(bool)+ results := model.SearchAttributeView(model.SearchAttributeViewOptions{+ Keyword: keyword,+ ExcludeAvIDs: excludes,+ CurrentAvID: currentAvID,+ CurrentBlockID: currentBlockID,+ IncludeViewMatches: includeViewMatches,+ })ret.Data = map[string]any{"results": results,}diff --git a/kernel/av/av.go b/kernel/av/av.goindex e67a30ee9b..e39a50c28e 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -534,6 +534,64 @@ func GetAttributeViewNameInBox(avID, boxID string) (ret string, err error) {return getAttributeViewNameByPathInBox(avJSONPath, boxID)}+type AttributeViewSearchView struct {+ ID string `json:"id"`+ Name string `json:"name"`+ LayoutType LayoutType `json:"type"`+}++type AttributeViewSearchInfo struct {+ Spec int `json:"spec"`+ Name string `json:"name"`+ Views []*AttributeViewSearchView `json:"views"`+}++func parseAttributeViewSearchInfo(data []byte) (ret *AttributeViewSearchInfo, err error) {+ ret = &AttributeViewSearchInfo{}+ if err = json.Unmarshal(data, ret); err != nil {+ return+ }+ err = CheckSpec(&AttributeView{Spec: ret.Spec})+ return+}++func GetAttributeViewSearchInfoInBox(avID, boxID string) (ret *AttributeViewSearchInfo, err error) {+ avJSONPath, avBoxID := FindAttributeViewPathInBox(avID, boxID)+ if avJSONPath == "" {+ return+ }++ if cached, ok := cache.GetAVSearchDataInBox[*AttributeViewSearchInfo](avID, avBoxID); ok {+ return cached, nil+ }++ var data []byte+ if cached, ok := cache.GetAVDataInBox(avID, avBoxID); ok {+ data = cached+ } else {+ if data, err = filelock.ReadFile(avJSONPath); err != nil {+ logging.LogErrorf("read attribute view [%s] failed: %s", avJSONPath, err)+ return+ }+ if avBoxID != "" {+ if data, err = decryptAVData(avBoxID, avID, data); err != nil {+ logging.LogErrorf("decrypt attribute view [%s] failed: %s", avJSONPath, err)+ return+ }+ } else if util.IsCiphertext(data) {+ return+ }+ cache.SetAVDataInBox(avID, avBoxID, data)+ }++ if ret, err = parseAttributeViewSearchInfo(data); err != nil {+ logging.LogErrorf("unmarshal attribute view search info [%s] failed: %s", avID, err)+ return nil, err+ }+ cache.SetAVSearchDataInBox(avID, avBoxID, ret)+ return+}+func GetAttributeViewContent(avID string) (content string) {if "" == avID {returndiff --git a/kernel/av/av_search_test.go b/kernel/av/av_search_test.gonew file mode 100644index 0000000000..875ea03fad--- /dev/null+++ b/kernel/av/av_search_test.go@@ -0,0 +1,50 @@+// 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 av++import "testing"++func TestParseAttributeViewSearchInfo(t *testing.T) {+ data := []byte(`{+ "spec": 6,+ "name": "Schedule",+ "keyValues": [{"key": {"name": "Ignored"}}],+ "views": [+ {"id": "view-1", "name": "状态:进行", "type": "table", "table": {"columns": []}},+ {"id": "view-2", "name": "分类:项目", "type": "gallery", "gallery": {"fields": []}}+ ]+ }`)++ info, err := parseAttributeViewSearchInfo(data)+ if err != nil {+ t.Fatalf("parse search info failed: %s", err)+ }+ if info.Name != "Schedule" || len(info.Views) != 2 {+ t.Fatalf("unexpected search info: %+v", info)+ }+ if info.Views[0].ID != "view-1" || info.Views[0].Name != "状态:进行" ||+ info.Views[0].LayoutType != LayoutTypeTable {+ t.Fatalf("unexpected first view: %+v", info.Views[0])+ }+ if info.Views[1].LayoutType != LayoutTypeGallery {+ t.Fatalf("unexpected second view: %+v", info.Views[1])+ }++ if _, err = parseAttributeViewSearchInfo([]byte(`{"spec": 7}`)); err != ErrSpecTooNew {+ t.Fatalf("expected newer spec error, got %v", err)+ }+}diff --git a/kernel/cache/av.go b/kernel/cache/av.goindex dce61a9e58..0034cc5450 100644--- a/kernel/cache/av.go+++ b/kernel/cache/av.go@@ -31,6 +31,9 @@ var avCache, _ = ristretto.NewCache(&ristretto.Config{var avCacheKeys = map[string]map[string]struct{}{}var avCacheKeysLock sync.Mutex+var avSearchDataCache = map[string]any{}+var avSearchDataCacheLock sync.RWMutex+func avCacheKey(avID, boxID string) string {return boxID + "\x00" + avID}@@ -57,6 +60,7 @@ func SetAVDataInBox(avID, boxID string, raw []byte) {}key := avCacheKey(avID, boxID)avCache.Set(key, raw, int64(len(raw)))+ removeAVSearchDataByKey(key)avCacheKeysLock.Lock()defer avCacheKeysLock.Unlock()@@ -71,6 +75,7 @@ func SetAVDataInBox(avID, boxID string, raw []byte) {func RemoveAVDataInBox(avID, boxID string) {key := avCacheKey(avID, boxID)avCache.Del(key)+ removeAVSearchDataByKey(key)avCacheKeysLock.Lock()defer avCacheKeysLock.Unlock()@@ -92,7 +97,9 @@ func RemoveAVData(avID string) {avCache.Del(avCacheKey(avID, ""))for key := range keys {avCache.Del(key)+ removeAVSearchDataByKey(key)}+ removeAVSearchDataByKey(avCacheKey(avID, ""))}func ClearAVCache() {@@ -100,4 +107,34 @@ func ClearAVCache() {avCacheKeys = map[string]map[string]struct{}{}avCacheKeysLock.Unlock()avCache.Clear()++ avSearchDataCacheLock.Lock()+ avSearchDataCache = map[string]any{}+ avSearchDataCacheLock.Unlock()+}++func GetAVSearchDataInBox[T any](avID, boxID string) (ret T, ok bool) {+ avSearchDataCacheLock.RLock()+ data := avSearchDataCache[avCacheKey(avID, boxID)]+ avSearchDataCacheLock.RUnlock()+ if data == nil {+ return+ }+ ret, ok = data.(T)+ return+}++func SetAVSearchDataInBox(avID, boxID string, data any) {+ if data == nil {+ return+ }+ avSearchDataCacheLock.Lock()+ avSearchDataCache[avCacheKey(avID, boxID)] = data+ avSearchDataCacheLock.Unlock()+}++func removeAVSearchDataByKey(key string) {+ avSearchDataCacheLock.Lock()+ delete(avSearchDataCache, key)+ avSearchDataCacheLock.Unlock()}diff --git a/kernel/cache/av_test.go b/kernel/cache/av_test.gonew file mode 100644index 0000000000..789549f619--- /dev/null+++ b/kernel/cache/av_test.go@@ -0,0 +1,40 @@+// 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 cache++import "testing"++func TestAVSearchDataInvalidation(t *testing.T) {+ const avID = "20260728120000-search"+ const boxID = "20260728120000-box"++ SetAVSearchDataInBox(avID, boxID, "cached")+ if cached, ok := GetAVSearchDataInBox[string](avID, boxID); !ok || cached != "cached" {+ t.Fatalf("unexpected cached search data: %q, %v", cached, ok)+ }++ SetAVDataInBox(avID, boxID, []byte("{}"))+ if _, ok := GetAVSearchDataInBox[string](avID, boxID); ok {+ t.Fatal("setting AV data should invalidate search data")+ }++ SetAVSearchDataInBox(avID, boxID, "cached")+ RemoveAVDataInBox(avID, boxID)+ if _, ok := GetAVSearchDataInBox[string](avID, boxID); ok {+ t.Fatal("removing AV data should invalidate search data")+ }+}diff --git a/kernel/cli/cmd/database.go b/kernel/cli/cmd/database.goindex 3db74890ee..f14d2b5995 100644--- a/kernel/cli/cmd/database.go+++ b/kernel/cli/cmd/database.go@@ -40,7 +40,7 @@ var databaseSearchCmd = &cobra.Command{Short: "Search databases by name",Args: cobra.MinimumNArgs(1),RunE: func(cmd *cobra.Command, args []string) error {- results := model.SearchAttributeView(args[0], nil, "", "")+ results := model.SearchAttributeView(model.SearchAttributeViewOptions{Keyword: args[0]})switch outputFormat {case "json":data, _ := json.MarshalIndent(results, "", " ")diff --git a/kernel/mcp/tools/database.go b/kernel/mcp/tools/database.goindex 5e7590841c..c14f694dc2 100644--- a/kernel/mcp/tools/database.go+++ b/kernel/mcp/tools/database.go@@ -102,7 +102,7 @@ func databaseSearch(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "keyword is required"}}, IsError: true}, nil}- results := model.SearchAttributeView(keyword, nil, "", "")+ results := model.SearchAttributeView(model.SearchAttributeViewOptions{Keyword: keyword})if len(results) == 0 {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no attribute views found"}}}, nil}diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex 30a05561a9..877e752252 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -2669,31 +2669,59 @@ type AvSearchResult struct {ViewLayout av.LayoutType `json:"viewLayout"`BlockID string `json:"blockID"`HPath string `json:"hPath"`+ Matched bool `json:"matched,omitempty"`Children []*AvSearchResult `json:"children,omitempty"`}type AvSearchTempResult struct {- AvID string- AvName string- AvUpdated int64- Score float64+ AvID string+ AvName string+ AvUpdated int64+ Score float64+ SearchInfo *av.AttributeViewSearchInfo+ MatchedViewIDs map[string]bool}-func SearchAttributeView(keyword string, excludeAvIDs []string, currentAvID, currentBlockID string) (ret []*AvSearchResult) {+type SearchAttributeViewOptions struct {+ Keyword string+ ExcludeAvIDs []string+ CurrentAvID string+ CurrentBlockID string+ IncludeViewMatches bool+}++func matchAttributeViewSearchName(name string, keywords []string) (score float64, hit bool) {+ if name == "" || len(keywords) == 0 {+ return+ }++ lowerName := strings.ToLower(name)+ hit = true+ for _, keyword := range keywords {+ lowerKeyword := strings.ToLower(keyword)+ if !strings.Contains(lowerName, lowerKeyword) {+ return 0, false+ }+ score += smetrics.JaroWinkler(name, keyword, 0.7, 4)+ }+ return+}++func SearchAttributeView(options SearchAttributeViewOptions) (ret []*AvSearchResult) {waitForSyncingStorages()ret = []*AvSearchResult{}- keyword = strings.TrimSpace(keyword)+ keyword := strings.TrimSpace(options.Keyword)keywords := strings.Fields(keyword)var avSearchTmpResults []*AvSearchTempResultboxID := ""- if currentBlockID != "" {- if bt := treenode.GetBlockTree(currentBlockID); nil != bt && IsEncryptedBox(bt.BoxID) {+ if options.CurrentBlockID != "" {+ if bt := treenode.GetBlockTree(options.CurrentBlockID); nil != bt && IsEncryptedBox(bt.BoxID) {boxID = bt.BoxID}- } else if currentAvID != "" {- _, boxID = av.FindAttributeViewPath(currentAvID)+ } else if options.CurrentAvID != "" {+ _, boxID = av.FindAttributeViewPath(options.CurrentAvID)}avDir := filepath.Join(util.DataDir, "storage", "av")if boxID != "" {@@ -2720,7 +2748,7 @@ func SearchAttributeView(keyword string, excludeAvIDs []string, currentAvID, curcontinue}- if gulu.Str.Contains(id, excludeAvIDs) {+ if gulu.Str.Contains(id, options.ExcludeAvIDs) {continue}@@ -2728,23 +2756,42 @@ func SearchAttributeView(keyword string, excludeAvIDs []string, currentAvID, curcontinue}- name, _ := av.GetAttributeViewNameInBox(id, boxID)+ var searchInfo *av.AttributeViewSearchInfo+ var name string+ if options.IncludeViewMatches && keyword != "" {+ searchInfo, _ = av.GetAttributeViewSearchInfoInBox(id, boxID)+ if searchInfo != nil {+ name = searchInfo.Name+ }+ }+ if searchInfo == nil {+ name, _ = av.GetAttributeViewNameInBox(id, boxID)+ }+info, _ := entry.Info()if "" != keyword {- score := 0.0- hit := false- for _, k := range keywords {- if strings.Contains(strings.ToLower(name), strings.ToLower(k)) {- score += smetrics.JaroWinkler(name, k, 0.7, 4)- hit = true- } else {- hit = false- break+ score, hit := matchAttributeViewSearchName(name, keywords)+ matchedViewIDs := map[string]bool{}+ if options.IncludeViewMatches && searchInfo != nil {+ for _, view := range searchInfo.Views {+ viewScore, viewHit := matchAttributeViewSearchName(view.Name, keywords)+ if viewHit {+ matchedViewIDs[view.ID] = true+ if viewScore > score {+ score = viewScore+ }+ }}}- if hit {- a := &AvSearchTempResult{AvID: id, AvName: name, Score: score}+ if hit || len(matchedViewIDs) > 0 {+ a := &AvSearchTempResult{+ AvID: id,+ AvName: name,+ Score: score,+ SearchInfo: searchInfo,+ MatchedViewIDs: matchedViewIDs,+ }if nil != info && !info.ModTime().IsZero() {a.AvUpdated = info.ModTime().UnixMilli()}@@ -2795,8 +2842,11 @@ func SearchAttributeView(keyword string, excludeAvIDs []string, currentAvID, curcontinue}- attrView, _ := av.ParseAttributeViewInBox(tmpResult.AvID, boxID)- if nil == attrView {+ searchInfo := tmpResult.SearchInfo+ if searchInfo == nil {+ searchInfo, _ = av.GetAttributeViewSearchInfoInBox(tmpResult.AvID, boxID)+ }+ if searchInfo == nil {continue}@@ -2810,11 +2860,6 @@ func SearchAttributeView(keyword string, excludeAvIDs []string, currentAvID, curhPath = box.Name + hPath}- name := tmpResult.AvName- if "" == name {- name = Conf.language(267)- }-parent := &AvSearchResult{AvID: tmpResult.AvID,AvName: tmpResult.AvName,@@ -2823,7 +2868,7 @@ func SearchAttributeView(keyword string, excludeAvIDs []string, currentAvID, cur}ret = append(ret, parent)- for _, view := range attrView.Views {+ for _, view := range searchInfo.Views {child := &AvSearchResult{AvID: tmpResult.AvID,AvName: tmpResult.AvName,@@ -2832,6 +2877,7 @@ func SearchAttributeView(keyword string, excludeAvIDs []string, currentAvID, curViewLayout: view.LayoutType,BlockID: node.ID,HPath: hPath,+ Matched: tmpResult.MatchedViewIDs[view.ID],}parent.Children = append(parent.Children, child)}diff --git a/kernel/model/attribute_view_search_test.go b/kernel/model/attribute_view_search_test.gonew file mode 100644index 0000000000..06b09fdd53--- /dev/null+++ b/kernel/model/attribute_view_search_test.go@@ -0,0 +1,44 @@+// 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 "testing"++func TestMatchAttributeViewSearchName(t *testing.T) {+ tests := []struct {+ name string+ keywords []string+ hit bool+ }{+ {name: "Schedule", keywords: []string{"schedule"}, hit: true},+ {name: "状态:进行", keywords: []string{"状态", "进行"}, hit: true},+ {name: "状态:进行", keywords: []string{"状态", "结束"}, hit: false},+ {name: "Database View", keywords: []string{"DATA", "view"}, hit: true},+ {name: "", keywords: []string{"view"}, hit: false},+ {name: "View", keywords: nil, hit: false},+ }++ for _, test := range tests {+ score, hit := matchAttributeViewSearchName(test.name, test.keywords)+ if hit != test.hit {+ t.Fatalf("unexpected match result for %q and %v: %v", test.name, test.keywords, hit)+ }+ if hit && score <= 0 {+ t.Fatalf("expected positive score for %q and %v", test.name, test.keywords)+ }+ }+}