An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Filter tags while typing https://github.com/siyuan-note/siyuan/issues/11039
Danield0c5429a60ed
diff --git a/app/src/layout/dock/Tag.ts b/app/src/layout/dock/Tag.tsindex d3cdaae930..b2b8b99175 100644--- a/app/src/layout/dock/Tag.ts+++ b/app/src/layout/dock/Tag.ts@@ -11,12 +11,16 @@ import {App} from "../../index";import {openTagMenu} from "../../menus/tag";import {hasClosestByClassName} from "../../protyle/util/hasClosest";import {Constants} from "../../constants";+import {filterTagData, getTagFilterKeywords} from "./tagFilter";export class Tag extends Model {private openNodes: string[];private preFilterOpenNodes: string[];+ private data: IBlockTree[] = [];+ private filterData: IBlockTree[];private updating = false;private pendingUpdate: boolean;+ private filterLoadPending = false;public tree: Tree;private element: Element;@@ -65,17 +69,13 @@ export class Tag extends Model {filterIconElement.classList.remove("block__icon--active");filterIconElement.setAttribute("aria-label", window.siyuan.languages.filter);}- if (inputElement.dataset.value !== value) {- inputElement.dataset.value = value;- this.update();- }});- inputElement.addEventListener("keydown", (event: KeyboardEvent) => {- if (!event.isComposing && event.key === "Enter") {- inputElement.dataset.value = inputElement.value;- this.update();+ inputElement.addEventListener("input", (event: InputEvent) => {+ if (!event.isComposing) {+ this.filter();}});+ inputElement.addEventListener("compositionend", () => this.filter());this.tree = new Tree({element: this.element.lastElementChild as HTMLElement,@@ -222,17 +222,12 @@ export class Tag extends Model {this.updating = true;const element = this.element.querySelector('.block__icon[data-type="refresh"] svg');const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;- const keyword = inputElement.value;- const hasKeyword = keyword.trim().length > 0;- if (hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {- this.preFilterOpenNodes = this.tree.getExpandIds();- }+ const ignoreMaxListHintArg = getTagFilterKeywords(inputElement.value).length > 0 || ignoreMaxListHint;element.classList.add("fn__rotate");fetchPost("/api/tag/getTag", {sort: window.siyuan.config.tag.sort,app: Constants.SIYUAN_APPID,- ignoreMaxListHint,- k: keyword,+ ignoreMaxListHint: ignoreMaxListHintArg,}, response => {if (this.pendingUpdate !== undefined) {const pendingUpdate = this.pendingUpdate;@@ -241,25 +236,79 @@ export class Tag extends Model {this.update(pendingUpdate);return;}- if (!hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {- this.openNodes = this.tree.getExpandIds();+ this.data = response.data;+ this.filterData = ignoreMaxListHintArg ? response.data : undefined;+ this.filter();+ this.updating = false;+ element.classList.remove("fn__rotate");+ if (this.filterLoadPending) {+ this.filterLoadPending = false;+ this.loadFilterData();}- this.tree.updateData(response.data);- if (hasKeyword) {- this.tree.expandAll();- } else if (this.preFilterOpenNodes !== undefined) {- this.tree.collapseAll();- this.tree.setExpandIds(this.preFilterOpenNodes);- this.openNodes = this.preFilterOpenNodes;- this.preFilterOpenNodes = undefined;- } else if (this.openNodes !== undefined) {- this.tree.collapseAll();- this.tree.setExpandIds(this.openNodes);- } else {- this.openNodes = this.tree.getExpandIds();+ });+ }++ private loadFilterData() {+ const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;+ if (getTagFilterKeywords(inputElement.value).length === 0 || this.filterData) {+ this.filter();+ return;+ }+ if (this.updating) {+ this.filterLoadPending = true;+ return;+ }+ this.updating = true;+ const element = this.element.querySelector('.block__icon[data-type="refresh"] svg');+ element.classList.add("fn__rotate");+ fetchPost("/api/tag/getTag", {+ sort: window.siyuan.config.tag.sort,+ app: Constants.SIYUAN_APPID,+ ignoreMaxListHint: true,+ }, response => {+ if (this.pendingUpdate !== undefined) {+ const pendingUpdate = this.pendingUpdate;+ this.pendingUpdate = undefined;+ this.filterLoadPending = false;+ this.updating = false;+ this.update(pendingUpdate);+ return;}+ this.filterData = response.data;+ this.filterLoadPending = false;+ this.filter();this.updating = false;element.classList.remove("fn__rotate");});}++ private filter() {+ const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;+ const keywords = getTagFilterKeywords(inputElement.value);+ const hasKeyword = keywords.length > 0;+ if (hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {+ this.preFilterOpenNodes = this.tree.getExpandIds();+ } else if (!hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {+ this.openNodes = this.tree.getExpandIds();+ }+ if (hasKeyword && !this.filterData) {+ this.loadFilterData();+ return;+ }+ const data = hasKeyword ? filterTagData(this.filterData, keywords) : this.data;+ this.tree.updateData(data);+ if (hasKeyword) {+ this.tree.expandAll();+ } else if (this.preFilterOpenNodes !== undefined) {+ this.tree.collapseAll();+ this.tree.setExpandIds(this.preFilterOpenNodes);+ this.openNodes = this.preFilterOpenNodes;+ this.preFilterOpenNodes = undefined;+ } else if (this.openNodes !== undefined) {+ this.tree.collapseAll();+ this.tree.setExpandIds(this.openNodes);+ } else {+ this.openNodes = this.tree.getExpandIds();+ }+ }}diff --git a/app/src/layout/dock/tagFilter.test.ts b/app/src/layout/dock/tagFilter.test.tsnew file mode 100644index 0000000000..a127487ed7--- /dev/null+++ b/app/src/layout/dock/tagFilter.test.ts@@ -0,0 +1,40 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {filterTagData, getTagFilterKeywords} from "./tagFilter";++const tag = (label: string, children?: IBlockTree[]) => ({+ name: label.split("/").pop(),+ label,+ children,+} as IBlockTree);++describe("tag filtering", () => {+ it("splits keywords and ignores case and extra whitespace", () => {+ assert.deepEqual(getTagFilterKeywords(" Project TODO "), ["project", "todo"]);+ });++ it("requires every keyword to match the complete tag label", () => {+ const data = [+ tag("Project", [tag("Project/Status", [tag("Project/Status/Todo")]), tag("Project/Topic")]),+ tag("Archive"),+ ];+ const filtered = filterTagData(data, ["project", "todo"], value => value);+ assert.deepEqual(filtered.map(item => item.label), ["Project"]);+ assert.deepEqual(filtered[0].children.map(item => item.label), ["Project/Status"]);+ assert.deepEqual(filtered[0].children[0].children.map(item => item.label), ["Project/Status/Todo"]);+ assert.equal(data[0].children.length, 2);+ });++ it("keeps ancestors when only a child matches", () => {+ const filtered = filterTagData([+ tag("Project", [tag("Project/Status")]),+ ], ["status"], value => value);+ assert.equal(filtered[0].label, "Project");+ assert.equal(filtered[0].children[0].label, "Project/Status");+ });++ it("matches unescaped labels", () => {+ const filtered = filterTagData([tag("A/<Draft>")], ["<draft>"], value => value.replace("<", "<").replace(">", ">"));+ assert.equal(filtered.length, 1);+ });+});diff --git a/app/src/layout/dock/tagFilter.ts b/app/src/layout/dock/tagFilter.tsnew file mode 100644index 0000000000..84ad4ebe4b--- /dev/null+++ b/app/src/layout/dock/tagFilter.ts@@ -0,0 +1,18 @@+export const getTagFilterKeywords = (value: string) => {+ return value.toLowerCase().trim().split(/\s+/).filter(Boolean);+};++export const filterTagData = (+ data: IBlockTree[],+ keywords: string[],+ unescapeHTML: (value: string) => string = (value) => Lute.UnEscapeHTMLStr(value),+) => {+ return data.reduce<IBlockTree[]>((result, item) => {+ const children = filterTagData(item.children || [], keywords, unescapeHTML);+ const label = unescapeHTML(item.label || item.name).toLowerCase();+ if (keywords.every(keyword => label.includes(keyword)) || children.length > 0) {+ result.push({...item, children});+ }+ return result;+ }, []);+};diff --git a/app/src/mobile/dock/MobileTags.ts b/app/src/mobile/dock/MobileTags.tsindex 3c56cfd97e..61da472280 100644--- a/app/src/mobile/dock/MobileTags.ts+++ b/app/src/mobile/dock/MobileTags.ts@@ -6,14 +6,18 @@ import {popSearch} from "../menu/search";import {App} from "../../index";import {openTagMenu} from "../../menus/tag";import {Constants} from "../../constants";+import {filterTagData, getTagFilterKeywords} from "../../layout/dock/tagFilter";export class MobileTags {public element: HTMLElement;private tree: Tree;private openNodes: string[];private preFilterOpenNodes: string[];+ private data: IBlockTree[] = [];+ private filterData: IBlockTree[];private updating = false;private pendingUpdate: boolean;+ private filterLoadPending = false;constructor(app: App) {this.element = document.querySelector('#sidebar [data-type="sidebar-tag"]');@@ -44,17 +48,13 @@ export class MobileTags {} else {filterIconElement.classList.remove("toolbar__icon--active");}- if (inputElement.dataset.value !== value) {- inputElement.dataset.value = value;- this.update();- }});- inputElement.addEventListener("keydown", (event: KeyboardEvent) => {- if (!event.isComposing && event.key === "Enter") {- inputElement.dataset.value = inputElement.value;- this.update();+ inputElement.addEventListener("input", (event: InputEvent) => {+ if (!event.isComposing) {+ this.filter();}});+ inputElement.addEventListener("compositionend", () => this.filter());this.tree = new Tree({element: this.element.querySelector(".tagList") as HTMLElement,@@ -173,17 +173,12 @@ export class MobileTags {}this.updating = true;const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;- const keyword = inputElement.value;- const hasKeyword = keyword.trim().length > 0;- if (hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {- this.preFilterOpenNodes = this.tree.getExpandIds();- }+ const ignoreMaxListHintArg = getTagFilterKeywords(inputElement.value).length > 0 || ignoreMaxListHint;this.element.lastElementChild.classList.remove("fn__none");fetchPost("/api/tag/getTag", {sort: window.siyuan.config.tag.sort,app: Constants.SIYUAN_APPID,- ignoreMaxListHint,- k: keyword,+ ignoreMaxListHint: ignoreMaxListHintArg,}, response => {if (this.pendingUpdate !== undefined) {const pendingUpdate = this.pendingUpdate;@@ -192,25 +187,78 @@ export class MobileTags {this.update(pendingUpdate);return;}- if (!hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {- this.openNodes = this.tree.getExpandIds();+ this.data = response.data;+ this.filterData = ignoreMaxListHintArg ? response.data : undefined;+ this.filter();+ this.updating = false;+ this.element.lastElementChild.classList.add("fn__none");+ if (this.filterLoadPending) {+ this.filterLoadPending = false;+ this.loadFilterData();}- this.tree.updateData(response.data);- if (hasKeyword) {- this.tree.expandAll();- } else if (this.preFilterOpenNodes !== undefined) {- this.tree.collapseAll();- this.tree.setExpandIds(this.preFilterOpenNodes);- this.openNodes = this.preFilterOpenNodes;- this.preFilterOpenNodes = undefined;- } else if (this.openNodes !== undefined) {- this.tree.collapseAll();- this.tree.setExpandIds(this.openNodes);- } else {- this.openNodes = this.tree.getExpandIds();+ });+ }++ private loadFilterData() {+ const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;+ if (getTagFilterKeywords(inputElement.value).length === 0 || this.filterData) {+ this.filter();+ return;+ }+ if (this.updating) {+ this.filterLoadPending = true;+ return;+ }+ this.updating = true;+ this.element.lastElementChild.classList.remove("fn__none");+ fetchPost("/api/tag/getTag", {+ sort: window.siyuan.config.tag.sort,+ app: Constants.SIYUAN_APPID,+ ignoreMaxListHint: true,+ }, response => {+ if (this.pendingUpdate !== undefined) {+ const pendingUpdate = this.pendingUpdate;+ this.pendingUpdate = undefined;+ this.filterLoadPending = false;+ this.updating = false;+ this.update(pendingUpdate);+ return;}+ this.filterData = response.data;+ this.filterLoadPending = false;+ this.filter();this.updating = false;this.element.lastElementChild.classList.add("fn__none");});}++ private filter() {+ const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;+ const keywords = getTagFilterKeywords(inputElement.value);+ const hasKeyword = keywords.length > 0;+ if (hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {+ this.preFilterOpenNodes = this.tree.getExpandIds();+ } else if (!hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {+ this.openNodes = this.tree.getExpandIds();+ }+ if (hasKeyword && !this.filterData) {+ this.loadFilterData();+ return;+ }+ const data = hasKeyword ? filterTagData(this.filterData, keywords) : this.data;+ this.tree.updateData(data);+ if (hasKeyword) {+ this.tree.expandAll();+ } else if (this.preFilterOpenNodes !== undefined) {+ this.tree.collapseAll();+ this.tree.setExpandIds(this.preFilterOpenNodes);+ this.openNodes = this.preFilterOpenNodes;+ this.preFilterOpenNodes = undefined;+ } else if (this.openNodes !== undefined) {+ this.tree.collapseAll();+ this.tree.setExpandIds(this.openNodes);+ } else {+ this.openNodes = this.tree.getExpandIds();+ }+ }}diff --git a/kernel/api/tag.go b/kernel/api/tag.goindex e3cc4d0a2e..3cfbb16115 100644--- a/kernel/api/tag.go+++ b/kernel/api/tag.go@@ -35,13 +35,12 @@ func getTag(c *gin.Context) {}var ignoreMaxListHint bool- var app, keyword string+ var app stringvar sortVal float64if !util.ParseJsonArgs(arg, ret,// API `getTag` add an optional parameter `ignoreMaxListHint` https://github.com/siyuan-note/siyuan/issues/16000util.BindJsonArg("ignoreMaxListHint", &ignoreMaxListHint, false, false),util.BindJsonArg("app", &app, false, false),- util.BindJsonArg("k", &keyword, false, false),util.BindJsonArg("sort", &sortVal, false, false),) {return@@ -52,12 +51,13 @@ func getTag(c *gin.Context) {model.Conf.Save()}- var publishIgnore model.PublishAccess+ tags := model.BuildTags(ignoreMaxListHint, app, int(sortVal))+if model.IsReadOnlyRoleContext(c) {publishAccess := model.GetPublishAccess()- publishIgnore = model.GetInvisiblePublishAccess(publishAccess)+ publishIgnore := model.GetInvisiblePublishAccess(publishAccess)+ tags = model.FilterTagsByPublishIgnore(publishIgnore, tags)}- tags := model.BuildTagsByKeyword(ignoreMaxListHint, app, int(sortVal), keyword, publishIgnore)ret.Data = tags}diff --git a/kernel/model/tag.go b/kernel/model/tag.goindex 1f3a1b1ea9..b1d2a67507 100644--- a/kernel/model/tag.go+++ b/kernel/model/tag.go@@ -248,16 +248,11 @@ type Tag struct {type Tags []*Tagfunc BuildTags(ignoreMaxListHintArg bool, appID string, sortVal int) (ret *Tags) {- return BuildTagsByKeyword(ignoreMaxListHintArg, appID, sortVal, "", nil)-}--func BuildTagsByKeyword(ignoreMaxListHintArg bool, appID string, sortVal int, keyword string, publishIgnore PublishAccess) (ret *Tags) {FlushTxQueue()sql.FlushQueue()ret = &Tags{}- labels := labelTags(publishIgnore)- filterTagLabels(labels, keyword)+ labels := labelTags()tags := Tags{}for label := range labels {tags = buildTags(tags, strings.Split(label, "/"), 0)@@ -282,23 +277,6 @@ func BuildTagsByKeyword(ignoreMaxListHintArg bool, appID string, sortVal int, kereturn}-func filterTagLabels(labels map[string]Tags, keyword string) {- keywords := strings.Fields(strings.ToLower(keyword))- if 1 > len(keywords) {- return- }-- for label := range labels {- normalizedLabel := strings.ToLower(label)- for _, k := range keywords {- if !strings.Contains(normalizedLabel, k) {- delete(labels, label)- break- }- }- }-}-func countTag(tag *Tag, total *int) {*total += 1for _, child := range tag.tags {@@ -396,14 +374,11 @@ func labelBlocksByKeyword(keyword string) (ret map[string]TagBlocks) {return}-func labelTags(publishIgnore PublishAccess) (ret map[string]Tags) {+func labelTags() (ret map[string]Tags) {ret = map[string]Tags{}tagSpans := sql.QueryTagSpans("")for _, tagSpan := range tagSpans {- if !CheckPathAccessableByPublishIgnore(tagSpan.Box, tagSpan.Path, publishIgnore) {- continue- }label := util.UnescapeHTML(tagSpan.Content)if _, ok := ret[label]; ok {ret[label] = append(ret[label], &Tag{})diff --git a/kernel/model/tag_test.go b/kernel/model/tag_test.godeleted file mode 100644index 449bd9f699..0000000000--- a/kernel/model/tag_test.go+++ /dev/null@@ -1,59 +0,0 @@-// 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 (- "maps"- "slices"- "testing"-)--func TestFilterTagLabels(t *testing.T) {- tests := []struct {- name string- keyword string- expected []string- }{- {"empty", "", []string{"Project/Status/Todo", "Project/Topic", "资料/项目"}},- {"whitespace", " ", []string{"Project/Status/Todo", "Project/Topic", "资料/项目"}},- {"case insensitive", "status", []string{"Project/Status/Todo"}},- {"multiple keywords", "project todo", []string{"Project/Status/Todo"}},- {"multiple spaces", " project topic ", []string{"Project/Topic"}},- {"all keywords required", "project done", nil},- {"unicode", "资料 项目", []string{"资料/项目"}},- }-- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- labels := map[string]Tags{- "Project/Status/Todo": {{}, {}},- "Project/Topic": {{}},- "资料/项目": {},- }- filterTagLabels(labels, test.keyword)- actual := slices.Sorted(maps.Keys(labels))- expected := slices.Clone(test.expected)- slices.Sort(expected)- if !slices.Equal(actual, expected) {- t.Fatalf("expected labels %v, got %v", expected, actual)- }- if _, ok := labels["Project/Status/Todo"]; ok && len(labels["Project/Status/Todo"]) != 2 {- t.Fatal("filtering should preserve tag counts")- }- })- }-}