Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support filtering in the tag panel https://github.com/siyuan-note/siyuan/issues/11039

Daniel4e4c3668900b
diff --git a/app/src/layout/dock/Tag.ts b/app/src/layout/dock/Tag.ts
index 2162bda29f..d3cdaae930 100644
--- a/app/src/layout/dock/Tag.ts
+++ b/app/src/layout/dock/Tag.ts
@@ -14,6 +14,9 @@ import {Constants} from "../../constants";
export class Tag extends Model {
private openNodes: string[];
+ private preFilterOpenNodes: string[];
+ private updating = false;
+ private pendingUpdate: boolean;
public tree: Tree;
private element: Element;
@@ -30,6 +33,9 @@ export class Tag extends Model {
this.element.innerHTML = `<div class="block__icons">
<div class="block__logo fn__flex-1">${window.siyuan.languages.tag}</div>
+ <input class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.filterKeywordEnter}" />
+ <span data-type="search" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.filter}"><svg><use xlink:href='#iconFilter'></use></svg></span>
+ <span class="fn__space"></span>
<span data-type="refresh" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.refresh}"><svg><use xlink:href='#iconRefresh'></use></svg></span>
<span class="fn__space"></span>
<span data-type="sort" class="block__icon ariaLabel${window.siyuan.config.readonly ? " fn__none" : ""}" data-position="north" aria-label="${window.siyuan.languages.sort}">
@@ -47,6 +53,29 @@ export class Tag extends Model {
<span data-type="min" class="block__icon ariaLabel" data-position="north" aria-label="${window.siyuan.languages.min}${updateHotkeyAfterTip(window.siyuan.config.keymap.general.closeTab.custom)}"><svg><use xlink:href='#iconMin'></use></svg></span>
</div>
<div class="fn__flex-1" style="margin-bottom: 8px"></div>`;
+ const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;
+ inputElement.addEventListener("blur", () => {
+ inputElement.classList.add("fn__none");
+ const filterIconElement = inputElement.nextElementSibling as HTMLElement;
+ const value = inputElement.value;
+ if (value.trim()) {
+ filterIconElement.classList.add("block__icon--active");
+ filterIconElement.setAttribute("aria-label", window.siyuan.languages.filter + " " + value);
+ } else {
+ 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();
+ }
+ });
this.tree = new Tree({
element: this.element.lastElementChild as HTMLElement,
@@ -76,6 +105,9 @@ export class Tag extends Model {
this.tree.expandAll();
});
this.element.addEventListener("click", (event: MouseEvent) => {
+ if ((event.target as HTMLElement).tagName === "INPUT") {
+ return;
+ }
setPanelFocus(this.element);
let target = event.target as HTMLElement;
while (target && !target.isEqualNode(this.element)) {
@@ -142,6 +174,10 @@ export class Tag extends Model {
case "refresh":
this.update();
break;
+ case "search":
+ inputElement.classList.remove("fn__none");
+ inputElement.select();
+ break;
}
}
target = target.parentElement;
@@ -179,25 +215,50 @@ export class Tag extends Model {
}
public update(ignoreMaxListHint = true) {
- const element = this.element.querySelector('.block__icon[data-type="refresh"] svg');
- if (element.classList.contains("fn__rotate")) {
+ if (this.updating) {
+ this.pendingUpdate = ignoreMaxListHint;
return;
}
+ 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();
+ }
element.classList.add("fn__rotate");
fetchPost("/api/tag/getTag", {
sort: window.siyuan.config.tag.sort,
app: Constants.SIYUAN_APPID,
- ignoreMaxListHint
+ ignoreMaxListHint,
+ k: keyword,
}, response => {
- if (this.openNodes) {
+ if (this.pendingUpdate !== undefined) {
+ const pendingUpdate = this.pendingUpdate;
+ this.pendingUpdate = undefined;
+ this.updating = false;
+ this.update(pendingUpdate);
+ return;
+ }
+ if (!hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {
this.openNodes = this.tree.getExpandIds();
}
this.tree.updateData(response.data);
- if (this.openNodes) {
+ 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();
}
+ this.updating = false;
element.classList.remove("fn__rotate");
});
}
diff --git a/app/src/mobile/dock/MobileTags.ts b/app/src/mobile/dock/MobileTags.ts
index 9854570ae1..3c56cfd97e 100644
--- a/app/src/mobile/dock/MobileTags.ts
+++ b/app/src/mobile/dock/MobileTags.ts
@@ -11,6 +11,9 @@ export class MobileTags {
public element: HTMLElement;
private tree: Tree;
private openNodes: string[];
+ private preFilterOpenNodes: string[];
+ private updating = false;
+ private pendingUpdate: boolean;
constructor(app: App) {
this.element = document.querySelector('#sidebar [data-type="sidebar-tag"]');
@@ -20,6 +23,9 @@ export class MobileTags {
${window.siyuan.languages.tag}
</div>
<span class="fn__space"></span>
+ <input class="b3-text-field search__label fn__none fn__size200" placeholder="${window.siyuan.languages.filterKeywordEnter}" />
+ <svg data-type="search" class="toolbar__icon"><use xlink:href='#iconFilter'></use></svg>
+ <span class="fn__space"></span>
<svg data-type="expand" class="toolbar__icon"><use xlink:href="#iconExpand"></use></svg>
<span class="fn__space"></span>
<svg data-type="collapse" class="toolbar__icon"><use xlink:href="#iconContract"></use></svg>
@@ -28,6 +34,27 @@ export class MobileTags {
</div>
<div class="fn__flex-1 tagList"></div>
<img style="position: absolute;top: 0;left: 0;height: 100%;width: 100%;padding: 30vw;box-sizing: border-box;" src="/stage/loading-pure.svg">`;
+ const inputElement = this.element.querySelector("input.b3-text-field.search__label") as HTMLInputElement;
+ inputElement.addEventListener("blur", () => {
+ inputElement.classList.add("fn__none");
+ const filterIconElement = inputElement.nextElementSibling as HTMLElement;
+ const value = inputElement.value;
+ if (value.trim()) {
+ filterIconElement.classList.add("toolbar__icon--active");
+ } 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();
+ }
+ });
this.tree = new Tree({
element: this.element.querySelector(".tagList") as HTMLElement,
@@ -55,6 +82,9 @@ export class MobileTags {
topExtHTML: window.siyuan.config.readonly ? undefined : '<span class="b3-list-item__action"><svg><use xlink:href="#iconMore"></use></svg></span>'
});
this.element.addEventListener("click", (event) => {
+ if ((event.target as HTMLElement).tagName === "INPUT") {
+ return;
+ }
let target = event.target as HTMLElement;
while (target && !target.isEqualNode(this.element)) {
if (target.classList.contains("toolbar__icon")) {
@@ -70,6 +100,10 @@ export class MobileTags {
event.preventDefault();
event.stopPropagation();
break;
+ case "search":
+ inputElement.classList.remove("fn__none");
+ inputElement.select();
+ break;
case "sort":
window.siyuan.menus.menu.remove();
window.siyuan.menus.menu.append(new MenuItem({
@@ -133,21 +167,49 @@ export class MobileTags {
}
public update(ignoreMaxListHint = true) {
+ if (this.updating) {
+ this.pendingUpdate = ignoreMaxListHint;
+ return;
+ }
+ 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();
+ }
this.element.lastElementChild.classList.remove("fn__none");
fetchPost("/api/tag/getTag", {
sort: window.siyuan.config.tag.sort,
app: Constants.SIYUAN_APPID,
ignoreMaxListHint,
+ k: keyword,
}, response => {
- if (this.openNodes) {
+ if (this.pendingUpdate !== undefined) {
+ const pendingUpdate = this.pendingUpdate;
+ this.pendingUpdate = undefined;
+ this.updating = false;
+ this.update(pendingUpdate);
+ return;
+ }
+ if (!hasKeyword && this.preFilterOpenNodes === undefined && this.openNodes !== undefined) {
this.openNodes = this.tree.getExpandIds();
}
this.tree.updateData(response.data);
- if (this.openNodes) {
+ 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();
}
+ this.updating = false;
this.element.lastElementChild.classList.add("fn__none");
});
}
diff --git a/kernel/api/tag.go b/kernel/api/tag.go
index 3cfbb16115..e3cc4d0a2e 100644
--- a/kernel/api/tag.go
+++ b/kernel/api/tag.go
@@ -35,12 +35,13 @@ func getTag(c *gin.Context) {
}
var ignoreMaxListHint bool
- var app string
+ var app, keyword string
var sortVal float64
if !util.ParseJsonArgs(arg, ret,
// API `getTag` add an optional parameter `ignoreMaxListHint` https://github.com/siyuan-note/siyuan/issues/16000
util.BindJsonArg("ignoreMaxListHint", &ignoreMaxListHint, false, false),
util.BindJsonArg("app", &app, false, false),
+ util.BindJsonArg("k", &keyword, false, false),
util.BindJsonArg("sort", &sortVal, false, false),
) {
return
@@ -51,13 +52,12 @@ func getTag(c *gin.Context) {
model.Conf.Save()
}
- tags := model.BuildTags(ignoreMaxListHint, app, int(sortVal))
-
+ var publishIgnore model.PublishAccess
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
- publishIgnore := model.GetInvisiblePublishAccess(publishAccess)
- tags = model.FilterTagsByPublishIgnore(publishIgnore, tags)
+ publishIgnore = model.GetInvisiblePublishAccess(publishAccess)
}
+ tags := model.BuildTagsByKeyword(ignoreMaxListHint, app, int(sortVal), keyword, publishIgnore)
ret.Data = tags
}
diff --git a/kernel/model/tag.go b/kernel/model/tag.go
index b1d2a67507..1f3a1b1ea9 100644
--- a/kernel/model/tag.go
+++ b/kernel/model/tag.go
@@ -248,11 +248,16 @@ type Tag struct {
type Tags []*Tag
func 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()
+ labels := labelTags(publishIgnore)
+ filterTagLabels(labels, keyword)
tags := Tags{}
for label := range labels {
tags = buildTags(tags, strings.Split(label, "/"), 0)
@@ -277,6 +282,23 @@ func BuildTags(ignoreMaxListHintArg bool, appID string, sortVal int) (ret *Tags)
return
}
+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 += 1
for _, child := range tag.tags {
@@ -374,11 +396,14 @@ func labelBlocksByKeyword(keyword string) (ret map[string]TagBlocks) {
return
}
-func labelTags() (ret map[string]Tags) {
+func labelTags(publishIgnore PublishAccess) (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.go
new file mode 100644
index 0000000000..449bd9f699
--- /dev/null
+++ b/kernel/model/tag_test.go
@@ -0,0 +1,59 @@
+// 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")
+ }
+ })
+ }
+}