An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve getBlockDefIDsByRefText https://github.com/siyuan-note/siyuan/issues/18166 (#18167)
Jeffrey Chend46e8de497c0
diff --git a/app/src/block/popover.ts b/app/src/block/popover.tsindex f7fd75804d..6b61146fd0 100644--- a/app/src/block/popover.ts+++ b/app/src/block/popover.ts@@ -1,5 +1,5 @@import {BlockPanel} from "./Panel";-import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName,} from "../protyle/util/hasClosest";+import {hasClosestByAttribute, hasClosestByClassName,} from "../protyle/util/hasClosest";import {fetchPost, fetchSyncPost} from "../util/fetch";import {hideTooltip, showTooltip, tooltipTargetElement} from "../dialog/tooltip";import {isLocalPath, parseSiYuanUriInfo} from "../util/pathName";@@ -450,14 +450,10 @@ export const showPopover = async (app: App, showRef = false) => {}}} else if (popoverTargetElement.getAttribute("data-type")?.indexOf("virtual-block-ref") > -1) {- const nodeElement = hasClosestBlock(popoverTargetElement);- if (nodeElement) {- const postResponse = await fetchSyncPost("/api/block/getBlockDefIDsByRefText", {- anchor: popoverTargetElement.textContent,- excludeIDs: [nodeElement.getAttribute("data-node-id")]- });- refDefs = postResponse.data.refDefs;- }+ const postResponse = await fetchSyncPost("/api/block/getBlockDefIDsByRefText", {+ anchor: popoverTargetElement.textContent,+ });+ refDefs = postResponse.data.refDefs;} else if (popoverTargetElement.getAttribute("data-type")?.split(" ").includes("a")) {// 以思源协议开头的链接refDefs = [{refID: parseSiYuanUriInfo(popoverTargetElement.getAttribute("data-href"))?.id ?? ""}];diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 1db9bc0144..9053b0fc77 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -3135,19 +3135,15 @@ export class WYSIWYG {if (virtualRefElement && range.toString() === "") {event.stopPropagation();event.preventDefault();- const blockElement = hasClosestBlock(virtualRefElement);- if (blockElement) {- fetchPost("/api/block/getBlockDefIDsByRefText", {- anchor: virtualRefElement.textContent,- excludeIDs: [blockElement.getAttribute("data-node-id")]- }, (response) => {- checkFold(response.data.refDefs[0].refID, (zoomIn) => {- mobileBlur = true;- activeBlur();- openMobileFileById(protyle.app, response.data.refDefs[0].refID, zoomIn ? [Constants.CB_GET_ALL] : [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL]);- });+ fetchPost("/api/block/getBlockDefIDsByRefText", {+ anchor: virtualRefElement.textContent,+ }, (response) => {+ checkFold(response.data.refDefs[0].refID, (zoomIn) => {+ mobileBlur = true;+ activeBlur();+ openMobileFileById(protyle.app, response.data.refDefs[0].refID, zoomIn ? [Constants.CB_GET_ALL] : [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL]);});- }+ });return;}/// #endifdiff --git a/kernel/api/block.go b/kernel/api/block.goindex 35543d1d1e..1718cec666 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -635,13 +635,7 @@ func getBlockDefIDsByRefText(c *gin.Context) {}anchor := arg["anchor"].(string)- excludeIDsArg := arg["excludeIDs"].([]any)- var excludeIDs []string- for _, excludeID := range excludeIDsArg {- excludeIDs = append(excludeIDs, excludeID.(string))- }- excludeIDs = nil // 不限制虚拟引用搜索自己 https://ld246.com/article/1633243424177- ids := model.GetBlockDefIDsByRefText(anchor, excludeIDs)+ ids := model.GetBlockDefIDsByRefText(anchor)var retRefDefs []model.RefDefsfor _, id := range ids {retRefDefs = append(retRefDefs, model.RefDefs{RefID: id, DefIDs: []string{}})diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.goindex 96a6d88fcf..bdc5d484d0 100644--- a/kernel/model/blockinfo.go+++ b/kernel/model/blockinfo.go@@ -438,8 +438,8 @@ func GetBlockRefIDsByFileAnnotationID(id string) []string {return sql.QueryRefIDsByAnnotationID(id)}-func GetBlockDefIDsByRefText(refText string, excludeIDs []string) (ret []string) {- ret = sql.QueryBlockDefIDsByRefText(refText, excludeIDs)+func GetBlockDefIDsByRefText(refText string) (ret []string) {+ ret = sql.QueryBlockDefIDsByRefText(refText)sort.Sort(sort.Reverse(sort.StringSlice(ret)))if 1 > len(ret) {ret = []string{}diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.goindex 2bb80257f1..201afd73dc 100644--- a/kernel/sql/block_query.go+++ b/kernel/sql/block_query.go@@ -231,34 +231,6 @@ func queryAliases(searchIgnoreLines []string) (ret []string) {return}-func queryDocIDsByTitle(title string, excludeIDs []string) (ret []string) {- ret = []string{}- notIn := "('" + strings.Join(excludeIDs, "','") + "')"-- sqlStmt := "SELECT id FROM blocks WHERE type = 'd' AND content LIKE ? AND id NOT IN " + notIn + " LIMIT ?"- if caseSensitive {- sqlStmt = "SELECT id FROM blocks WHERE type = 'd' AND content = ? AND id NOT IN " + notIn + " LIMIT ?"- }- rows, err := query(sqlStmt, title, 32)- if err != nil {- logging.LogErrorf("sql query [%s] failed: %s", sqlStmt, err)- return- }- defer rows.Close()-- set := hashset.New()- for rows.Next() {- var id string- rows.Scan(&id)- set.Add(id)- }-- for _, v := range set.Values() {- ret = append(ret, v.(string))- }- return-}-func queryDocTitles(searchIgnoreLines []string) (ret []string) {ret = []string{}sqlStmt := "SELECT content FROM blocks WHERE type = 'd'"diff --git a/kernel/sql/block_ref_query.go b/kernel/sql/block_ref_query.goindex 9f01a53b7e..16470cd7ec 100644--- a/kernel/sql/block_ref_query.go+++ b/kernel/sql/block_ref_query.go@@ -263,22 +263,24 @@ func getRefText(defBlockID string) string {return block.Content}-func QueryBlockDefIDsByRefText(refText string, excludeIDs []string) (ret []string) {- ret = queryDefIDsByDefText(refText, excludeIDs)- ret = append(ret, queryDefIDsByNameAlias(refText, excludeIDs)...)- ret = append(ret, queryDocIDsByTitle(refText, excludeIDs)...)+func QueryBlockDefIDsByRefText(refText string) (ret []string) {+ ret = queryDefIDsByDefText(refText)+ ret = append(ret, queryDefIDsByNameAliasAndDocTitle(refText)...)ret = gulu.Str.RemoveDuplicatedElem(ret)return}-func queryDefIDsByDefText(keyword string, excludeIDs []string) (ret []string) {+func queryDefIDsByDefText(keyword string) (ret []string) {ret = []string{}- notIn := "('" + strings.Join(excludeIDs, "','") + "')"- q := "SELECT DISTINCT(def_block_id) FROM refs WHERE content LIKE ? AND def_block_id NOT IN " + notIn+ var q, arg stringif caseSensitive {- q = "SELECT DISTINCT(def_block_id) FROM refs WHERE content = ? AND def_block_id NOT IN " + notIn+ q = "SELECT DISTINCT(def_block_id) FROM refs WHERE content = ?"+ arg = keyword+ } else {+ q = "SELECT DISTINCT(def_block_id) FROM refs WHERE content LIKE ? ESCAPE '\\'"+ arg = escapeLikePattern(keyword)}- rows, err := query(q, keyword)+ rows, err := query(q, arg)if err != nil {logging.LogErrorf("sql query failed: %s", err)return@@ -295,39 +297,38 @@ func queryDefIDsByDefText(keyword string, excludeIDs []string) (ret []string) {return}-func queryDefIDsByNameAlias(keyword string, excludeIDs []string) (ret []string) {+func queryDefIDsByNameAliasAndDocTitle(keyword string) (ret []string) {ret = []string{}- notIn := "('" + strings.Join(excludeIDs, "','") + "')"- rows, err := query("SELECT DISTINCT(id), name, alias FROM blocks WHERE (name = ? OR alias LIKE ?) AND id NOT IN "+notIn, keyword, "%"+keyword+"%")+ escaped := escapeLikePattern(keyword)+ aliasArg := "%," + escaped + ",%"+ var nameCond, docCond, exactArg string+ if caseSensitive {+ nameCond = "name = ?"+ docCond = "content = ?"+ exactArg = keyword+ } else {+ nameCond = "name LIKE ? ESCAPE '\\'"+ docCond = "content LIKE ? ESCAPE '\\'"+ exactArg = escaped+ }+ // 命名精确匹配;别名按逗号整段匹配(','||alias||',' LIKE '%,kw,%');文档标题单独 LIMIT 32+ // 大小写均跟随 caseSensitive / case_sensitive_like 配置;LIKE 参数转义 %/_/\ 以免通配符改变语义+ q := "SELECT id FROM blocks WHERE " + nameCond + " OR (',' || alias || ',') LIKE ? ESCAPE '\\'" ++ " UNION ALL SELECT id FROM (" ++ "SELECT id FROM blocks WHERE type = 'd' AND " + docCond + " LIMIT ?" ++ ")"+ rows, err := query(q, exactArg, aliasArg, exactArg, 32)if err != nil {logging.LogErrorf("sql query failed: %s", err)return}defer rows.Close()for rows.Next() {- var id, name, alias string- if err = rows.Scan(&id, &name, &alias); err != nil {+ var id string+ if err = rows.Scan(&id); err != nil {logging.LogErrorf("query scan field failed: %s", err)return}- if name == keyword {- ret = append(ret, id)- continue- }-- var hitAlias bool- aliases := strings.SplitSeq(alias, ",")- for a := range aliases {- if "" == a {- continue- }- if keyword == a {- hitAlias = true- }- }- if strings.Contains(alias, keyword) && !hitAlias {- continue- }ret = append(ret, id)}return