Skip to content

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

Add heading and list subtype filters to search (#17597)

ashur8c181b998bb0
diff --git a/app/appearance/langs/ar_SA.json b/app/appearance/langs/ar_SA.json
index afdb1d9b31..08dfd6134b 100644
--- a/app/appearance/langs/ar_SA.json
+++ b/app/appearance/langs/ar_SA.json
@@ -1042,6 +1042,8 @@
"heading4": "عنوان 4",
"heading5": "عنوان 5",
"heading6": "عنوان 6",
+ "unorderedList": "قائمة غير مرتبة",
+ "searchSubTypeListTip": "الأنواع الفرعية للقائمة (مرتبة/غير مرتبة/مهمة) تنطبق أيضاً على عناصر القائمة",
"outlineExpandLevel": "مستوى التوسيع",
"expandAll": "توسيع الكل",
"outlineKeepCurrentExpand": "الحفاظ على التوسيع الحالي",
diff --git a/app/appearance/langs/de_DE.json b/app/appearance/langs/de_DE.json
index c4931c3152..0a37c4db8c 100644
--- a/app/appearance/langs/de_DE.json
+++ b/app/appearance/langs/de_DE.json
@@ -1042,6 +1042,8 @@
"heading4": "Überschrift 4",
"heading5": "Überschrift 5",
"heading6": "Überschrift 6",
+ "unorderedList": "Ungeordnete Liste",
+ "searchSubTypeListTip": "Listen-Untertypen (Geordnet/Ungeordnet/Aufgabe) gelten auch für Listenelemente",
"outlineExpandLevel": "Expansionsebene",
"expandAll": "Alle erweitern",
"outlineKeepCurrentExpand": "Aktuelle Erweiterung beibehalten",
diff --git a/app/appearance/langs/en_US.json b/app/appearance/langs/en_US.json
index 3356c0bfd4..b6cdb7971a 100644
--- a/app/appearance/langs/en_US.json
+++ b/app/appearance/langs/en_US.json
@@ -1042,6 +1042,8 @@
"heading4": "Heading 4",
"heading5": "Heading 5",
"heading6": "Heading 6",
+ "unorderedList": "Unordered List",
+ "searchSubTypeListTip": "List subtypes (Ordered/Unordered/Task) also apply to list items",
"outlineExpandLevel": "Expand level",
"expandAll": "Expand all",
"outlineKeepCurrentExpand": "Keep current expand",
diff --git a/app/appearance/langs/es_ES.json b/app/appearance/langs/es_ES.json
index dbd1488294..d605c3fd47 100644
--- a/app/appearance/langs/es_ES.json
+++ b/app/appearance/langs/es_ES.json
@@ -1042,6 +1042,8 @@
"heading4": "Encabezado 4",
"heading5": "Encabezado 5",
"heading6": "Encabezado 6",
+ "unorderedList": "Lista no ordenada",
+ "searchSubTypeListTip": "Los subtipos de lista (Ordenada/No ordenada/Tarea) también se aplican a los elementos de lista",
"outlineExpandLevel": "Nivel de expansión",
"expandAll": "Expandir todo",
"outlineKeepCurrentExpand": "Mantener la expansión actual",
diff --git a/app/appearance/langs/fr_FR.json b/app/appearance/langs/fr_FR.json
index 33fd1bf710..8a9ca220ee 100644
--- a/app/appearance/langs/fr_FR.json
+++ b/app/appearance/langs/fr_FR.json
@@ -1042,6 +1042,8 @@
"heading4": "Titre 4",
"heading5": "Titre 5",
"heading6": "Titre 6",
+ "unorderedList": "Liste non ordonnée",
+ "searchSubTypeListTip": "Les sous-types de liste (Ordonnée/Non ordonnée/Tâche) s'appliquent aussi aux éléments de liste",
"outlineExpandLevel": "Niveau d'expansion",
"expandAll": "Tout développer",
"outlineKeepCurrentExpand": "Maintenir le titre actuel développé",
diff --git a/app/appearance/langs/he_IL.json b/app/appearance/langs/he_IL.json
index 4a6909bea3..e912e0dd86 100644
--- a/app/appearance/langs/he_IL.json
+++ b/app/appearance/langs/he_IL.json
@@ -1042,6 +1042,8 @@
"heading4": "כותרת 4",
"heading5": "כותרת 5",
"heading6": "כותרת 6",
+ "unorderedList": "רשימה לא מסודרת",
+ "searchSubTypeListTip": "סוגי-משנה של רשימה (מסודרת/לא מסודרת/משימה) חלים גם על פריטי רשימה",
"outlineExpandLevel": "רמת הרחבה",
"expandAll": "הרחב הכל",
"outlineKeepCurrentExpand": "שמור כותרת נוכחית מורחבת",
diff --git a/app/appearance/langs/it_IT.json b/app/appearance/langs/it_IT.json
index 5f59bf2fd0..7d1be5b8ec 100644
--- a/app/appearance/langs/it_IT.json
+++ b/app/appearance/langs/it_IT.json
@@ -1042,6 +1042,8 @@
"heading4": "Titolo 4",
"heading5": "Titolo 5",
"heading6": "Titolo 6",
+ "unorderedList": "Elenco non ordinato",
+ "searchSubTypeListTip": "I sottotipi di elenco (Ordinato/Non ordinato/Attività) si applicano anche agli elementi dell'elenco",
"outlineExpandLevel": "Livello di espansione",
"expandAll": "Espandi tutto",
"outlineKeepCurrentExpand": "Mantieni espanso l'intestazione corrente",
diff --git a/app/appearance/langs/ja_JP.json b/app/appearance/langs/ja_JP.json
index a8eca683f4..0927690898 100644
--- a/app/appearance/langs/ja_JP.json
+++ b/app/appearance/langs/ja_JP.json
@@ -1042,6 +1042,8 @@
"heading4": "見出し4",
"heading5": "見出し5",
"heading6": "見出し6",
+ "unorderedList": "番号なしリスト",
+ "searchSubTypeListTip": "リストのサブタイプ(番号付き / 番号なし / タスク)はリスト項目にも適用されます",
"outlineExpandLevel": "展開レベル",
"expandAll": "すべて展開",
"outlineKeepCurrentExpand": "現在の見出しを展開し続ける",
diff --git a/app/appearance/langs/ko_KR.json b/app/appearance/langs/ko_KR.json
index 33e43be980..ab87d60f37 100644
--- a/app/appearance/langs/ko_KR.json
+++ b/app/appearance/langs/ko_KR.json
@@ -1042,6 +1042,8 @@
"heading4": "제목 4",
"heading5": "제목 5",
"heading6": "제목 6",
+ "unorderedList": "순서 없는 목록",
+ "searchSubTypeListTip": "목록 하위 유형(순서/순서 없음/작업)은 목록 항목에도 적용됩니다",
"outlineExpandLevel": "펼치기 레벨",
"expandAll": "모두 펼치기",
"outlineKeepCurrentExpand": "현재 펼침 상태 유지",
diff --git a/app/appearance/langs/pl_PL.json b/app/appearance/langs/pl_PL.json
index 2fd1f2dcf4..35457c1936 100644
--- a/app/appearance/langs/pl_PL.json
+++ b/app/appearance/langs/pl_PL.json
@@ -1042,6 +1042,8 @@
"heading4": "Nagłówek 4",
"heading5": "Nagłówek 5",
"heading6": "Nagłówek 6",
+ "unorderedList": "Lista nieuporządkowana",
+ "searchSubTypeListTip": "Podtypy list (Uporządkowana/Nieuporządkowana/Zadanie) dotyczą również elementów listy",
"outlineExpandLevel": "Poziom rozwinięcia",
"expandAll": "Rozwiń wszystko",
"outlineKeepCurrentExpand": "Utrzymuj bieżący tytuł rozwinięty",
diff --git a/app/appearance/langs/pt_BR.json b/app/appearance/langs/pt_BR.json
index d1e23f2948..00f2dbee01 100644
--- a/app/appearance/langs/pt_BR.json
+++ b/app/appearance/langs/pt_BR.json
@@ -1042,6 +1042,8 @@
"heading4": "Título 4",
"heading5": "Título 5",
"heading6": "Título 6",
+ "unorderedList": "Lista não ordenada",
+ "searchSubTypeListTip": "Os subtipos de lista (Ordenada/Não ordenada/Tarefa) também se aplicam aos itens da lista",
"outlineExpandLevel": "Nível de expansão",
"expandAll": "Expandir tudo",
"outlineKeepCurrentExpand": "Manter título atual expandido",
diff --git a/app/appearance/langs/ru_RU.json b/app/appearance/langs/ru_RU.json
index fb116008af..038ea7c27d 100644
--- a/app/appearance/langs/ru_RU.json
+++ b/app/appearance/langs/ru_RU.json
@@ -1042,6 +1042,8 @@
"heading4": "Заголовок 4",
"heading5": "Заголовок 5",
"heading6": "Заголовок 6",
+ "unorderedList": "Неупорядоченный список",
+ "searchSubTypeListTip": "Подтипы списков (Упорядоченный/Неупорядоченный/Задача) также применяются к элементам списка",
"outlineExpandLevel": "Уровень развёртывания",
"expandAll": "Развернуть все",
"outlineKeepCurrentExpand": "Сохранять текущий заголовок развёрнутым",
diff --git a/app/appearance/langs/sk_SK.json b/app/appearance/langs/sk_SK.json
index ddbb36a1cb..beafb033d0 100644
--- a/app/appearance/langs/sk_SK.json
+++ b/app/appearance/langs/sk_SK.json
@@ -1042,6 +1042,8 @@
"heading4": "Nadpis 4",
"heading5": "Nadpis 5",
"heading6": "Nadpis 6",
+ "unorderedList": "Neusporiadaný zoznam",
+ "searchSubTypeListTip": "Podtypy zoznamov (Usporiadaný/Neusporiadaný/Úloha) sa vzťahujú aj na položky zoznamu",
"outlineExpandLevel": "Úroveň rozbalenia",
"expandAll": "Rozbaliť všetko",
"outlineKeepCurrentExpand": "Ponechať aktuálne rozbalenie",
diff --git a/app/appearance/langs/tr_TR.json b/app/appearance/langs/tr_TR.json
index 0ea66bdc57..e2e0df3552 100644
--- a/app/appearance/langs/tr_TR.json
+++ b/app/appearance/langs/tr_TR.json
@@ -1042,6 +1042,8 @@
"heading4": "Başlık 4",
"heading5": "Başlık 5",
"heading6": "Başlık 6",
+ "unorderedList": "Sırasız liste",
+ "searchSubTypeListTip": "Liste alt türleri (Sıralı/Sırasız/Görev) liste öğelerine de uygulanır",
"outlineExpandLevel": "Tasarım genişleme seviyesi",
"expandAll": "Tümünü genişlet",
"outlineKeepCurrentExpand": "Mevcut genişlemeyi koru",
diff --git a/app/appearance/langs/uk_UA.json b/app/appearance/langs/uk_UA.json
index 6bf7ea8ee9..0f4e7334a3 100644
--- a/app/appearance/langs/uk_UA.json
+++ b/app/appearance/langs/uk_UA.json
@@ -1042,6 +1042,8 @@
"heading4": "Заголовок 4",
"heading5": "Заголовок 5",
"heading6": "Заголовок 6",
+ "unorderedList": "Неупорядкований список",
+ "searchSubTypeListTip": "Підтипи списків (Упорядкований/Неупорядкований/Завдання) також застосовуються до елементів списку",
"outlineExpandLevel": "Рівень розгортання",
"expandAll": "Розгорнути все",
"outlineKeepCurrentExpand": "Зберегти поточний стан розгортання",
diff --git a/app/appearance/langs/zh_CHT.json b/app/appearance/langs/zh_CHT.json
index b4b8b39fef..a194f8d5a5 100644
--- a/app/appearance/langs/zh_CHT.json
+++ b/app/appearance/langs/zh_CHT.json
@@ -1042,6 +1042,8 @@
"heading4": "四級標題",
"heading5": "五級標題",
"heading6": "六級標題",
+ "unorderedList": "無序列表",
+ "searchSubTypeListTip": "列表子類型(有序/無序/任務)同樣適用於列表項",
"outlineExpandLevel": "展開層級",
"expandAll": "全部展開",
"outlineKeepCurrentExpand": "保持當前標題展開",
diff --git a/app/appearance/langs/zh_CN.json b/app/appearance/langs/zh_CN.json
index d9ecee94c0..51bdfd71ef 100644
--- a/app/appearance/langs/zh_CN.json
+++ b/app/appearance/langs/zh_CN.json
@@ -1042,6 +1042,8 @@
"heading4": "四级标题",
"heading5": "五级标题",
"heading6": "六级标题",
+ "unorderedList": "无序列表",
+ "searchSubTypeListTip": "列表子类型(有序/无序/任务)同样适用于列表项",
"outlineExpandLevel": "展开层级",
"expandAll": "全部展开",
"outlineKeepCurrentExpand": "保持当前标题展开",
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.ts
index 7ad76d0928..a038e65b04 100644
--- a/app/src/mobile/menu/search.ts
+++ b/app/src/mobile/menu/search.ts
@@ -25,7 +25,7 @@ import {
} from "../../search/assets";
import {addClearButton} from "../../util/addClearButton";
import {checkFold} from "../../util/noRelyPCFunction";
-import {getDefaultType} from "../../search/getDefault";
+import {getDefaultSubType, getDefaultType} from "../../search/getDefault";
import {
saveAssetKeyList,
saveKeyList,
@@ -59,6 +59,7 @@ const replace = (element: Element, config: Config.IUILayoutTabSearchConfig, isAl
r: replaceInputElement.value,
ids: isAll ? [] : [currentId],
types: config.types,
+ subTypes: config.subTypes,
method: config.method,
replaceTypes: config.replaceTypes,
paths: config.idPath || [],
@@ -288,6 +289,7 @@ export const updateSearchResult = (config: Config.IUILayoutTabSearchConfig, elem
query: config.query,
method: config.method,
types: config.types,
+ subTypes: config.subTypes,
paths: config.idPath || [],
groupBy: config.group,
orderBy: config.sort,
@@ -416,6 +418,7 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTab
r: "",
page: 1,
types: getDefaultType(),
+ subTypes: getDefaultSubType(),
replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),
}, config);
}
@@ -562,6 +565,7 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTab
r: "",
page: 1,
types: getDefaultType(),
+ subTypes: getDefaultSubType(),
replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),
}, config);
element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");
diff --git a/app/src/protyle/util/compatibility.ts b/app/src/protyle/util/compatibility.ts
index 55ccccc648..5f00e9eb2d 100644
--- a/app/src/protyle/util/compatibility.ts
+++ b/app/src/protyle/util/compatibility.ts
@@ -8,7 +8,7 @@ import * as fs from "fs";
/// #if MOBILE
import {processSYLink} from "../../editor/openLink";
/// #endif
-import {getDefaultType} from "../../search/getDefault";
+import {getDefaultSubType, getDefaultType} from "../../search/getDefault";
import {showMessage} from "../../dialog/message";
export const isPhablet = () => {
@@ -554,6 +554,7 @@ export const getLocalStorage = (cb: () => void) => {
k: "",
r: "",
types: getDefaultType(),
+ subTypes: getDefaultSubType(),
replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),
};
defaultStorage[Constants.LOCAL_ZOOM] = 1;
@@ -589,6 +590,11 @@ export const getLocalStorage = (cb: () => void) => {
Object.keys(window.siyuan.storage[Constants.LOCAL_SEARCHDATA].replaceTypes).length === 0) {
window.siyuan.storage[Constants.LOCAL_SEARCHDATA].replaceTypes = Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES);
}
+ // Migrate stored search data to include subTypes when absent
+ if (!window.siyuan.storage[Constants.LOCAL_SEARCHDATA].subTypes ||
+ Object.keys(window.siyuan.storage[Constants.LOCAL_SEARCHDATA].subTypes).length === 0) {
+ window.siyuan.storage[Constants.LOCAL_SEARCHDATA].subTypes = getDefaultSubType();
+ }
cb();
});
};
diff --git a/app/src/search/getDefault.ts b/app/src/search/getDefault.ts
index 5a8874fc13..6843258953 100644
--- a/app/src/search/getDefault.ts
+++ b/app/src/search/getDefault.ts
@@ -21,3 +21,10 @@ export const getDefaultType = () => {
databaseBlock: window.siyuan.config.search.databaseBlock,
};
};
+
+export const getDefaultSubType = (): Config.IUILayoutTabSearchConfigSubTypes => {
+ return {
+ h1: false, h2: false, h3: false, h4: false, h5: false, h6: false,
+ o: false, u: false, t: false,
+ };
+};
diff --git a/app/src/search/menu.ts b/app/src/search/menu.ts
index d5f56514ff..36b90b9d87 100644
--- a/app/src/search/menu.ts
+++ b/app/src/search/menu.ts
@@ -8,6 +8,7 @@ import {escapeHtml} from "../util/escape";
import {setStorageVal} from "../protyle/util/compatibility";
import {confirmDialog} from "../dialog/confirmDialog";
import {goUnRef, updateSearchResult} from "../mobile/menu/search";
+import {getDefaultSubType} from "./getDefault";
export const filterMenu = (config: Config.IUILayoutTabSearchConfig, cb: () => void) => {
const filterDialog = new Dialog({
@@ -41,6 +42,9 @@ export const filterMenu = (config: Config.IUILayoutTabSearchConfig, cb: () => vo
<input class="b3-switch fn__flex-center" data-type="paragraph" type="checkbox"${config.types.paragraph ? " checked" : ""}>
</label>
<label class="fn__flex b3-label">
+ <span class="fn__flex-center" data-toggle-subtype="heading" style="cursor:pointer;padding-right:4px;display:inline-flex;align-items:center;">
+ <svg style="transition:transform 0.15s;width:10px;height:10px;"><use xlink:href="#iconRight"></use></svg>
+ </span>
<svg class="ft__on-surface svg fn__flex-center"><use xlink:href="#iconHeadings"></use></svg>
<span class="fn__space"></span>
<div class="fn__flex-1 fn__flex-center">
@@ -49,6 +53,16 @@ export const filterMenu = (config: Config.IUILayoutTabSearchConfig, cb: () => vo
<span class="fn__space"></span>
<input class="b3-switch fn__flex-center" data-type="heading" type="checkbox"${config.types.heading ? " checked" : ""}>
</label>
+ <div class="fn__none" data-subtype-group="heading">
+ ${(["h1", "h2", "h3", "h4", "h5", "h6"] as const).map((h) => `
+ <label class="fn__flex b3-label" style="padding-left:32px;">
+ <div class="fn__flex-1 fn__flex-center">
+ ${window.siyuan.languages["heading" + h.charAt(1)]}
+ </div>
+ <span class="fn__space"></span>
+ <input class="b3-switch fn__flex-center" data-subtype="${h}" type="checkbox"${config.subTypes?.[h] ? " checked" : ""}>
+ </label>`).join("")}
+ </div>
<label class="fn__flex b3-label">
<svg class="ft__on-surface svg fn__flex-center"><use xlink:href="#iconCode"></use></svg>
<span class="fn__space"></span>
@@ -149,14 +163,34 @@ export const filterMenu = (config: Config.IUILayoutTabSearchConfig, cb: () => vo
<input class="b3-switch fn__flex-center" data-type="superBlock" type="checkbox"${config.types.superBlock ? " checked" : ""}>
</label>
<label class="fn__flex b3-label">
+ <span class="fn__flex-center" data-toggle-subtype="list" style="cursor:pointer;padding-right:4px;display:inline-flex;align-items:center;">
+ <svg style="transition:transform 0.15s;width:10px;height:10px;"><use xlink:href="#iconRight"></use></svg>
+ </span>
<svg class="ft__on-surface svg fn__flex-center"><use xlink:href="#iconList"></use></svg>
<span class="fn__space"></span>
<div class="fn__flex-1 fn__flex-center">
- ${window.siyuan.languages.list1} <sup>[1]</sup>
+ ${window.siyuan.languages.list1} <sup>[1] [2]</sup>
</div>
<span class="fn__space"></span>
<input class="b3-switch fn__flex-center" data-type="list" type="checkbox"${config.types.list ? " checked" : ""}>
</label>
+ <div class="fn__none" data-subtype-group="list">
+ <label class="fn__flex b3-label" style="padding-left:32px;">
+ <div class="fn__flex-1 fn__flex-center">${window.siyuan.languages["ordered-list"]}</div>
+ <span class="fn__space"></span>
+ <input class="b3-switch fn__flex-center" data-subtype="o" type="checkbox"${config.subTypes?.o ? " checked" : ""}>
+ </label>
+ <label class="fn__flex b3-label" style="padding-left:32px;">
+ <div class="fn__flex-1 fn__flex-center">${window.siyuan.languages.unorderedList}</div>
+ <span class="fn__space"></span>
+ <input class="b3-switch fn__flex-center" data-subtype="u" type="checkbox"${config.subTypes?.u ? " checked" : ""}>
+ </label>
+ <label class="fn__flex b3-label" style="padding-left:32px;">
+ <div class="fn__flex-1 fn__flex-center">${window.siyuan.languages.check}</div>
+ <span class="fn__space"></span>
+ <input class="b3-switch fn__flex-center" data-subtype="t" type="checkbox"${config.subTypes?.t ? " checked" : ""}>
+ </label>
+ </div>
<label class="fn__flex b3-label">
<svg class="ft__on-surface svg fn__flex-center"><use xlink:href="#iconListItem"></use></svg>
<span class="fn__space"></span>
@@ -178,23 +212,101 @@ export const filterMenu = (config: Config.IUILayoutTabSearchConfig, cb: () => vo
<span class="fn__space"></span>
<div class="fn__flex-1">
<div class="b3-label__text">[1] ${window.siyuan.languages.containerBlockTip1}</div>
- </div>
+ <div class="b3-label__text">[2] ${window.siyuan.languages.searchSubTypeListTip}</div>
+ </div>
</div>
<div class="b3-dialog__action">
<button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>
<button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>
</div>`,
- width: isMobile() ? "92vw" : "520px",
+ width: isMobile() ? "92vw" : "600px",
height: "70vh",
});
filterDialog.element.setAttribute("data-key", Constants.DIALOG_SEARCHTYPE);
+ // Subtype expand/collapse toggles. preventDefault avoids the wrapping
+ // <label> from also toggling the parent type checkbox on chevron clicks.
+ filterDialog.element.querySelectorAll("[data-toggle-subtype]").forEach((toggle: HTMLElement) => {
+ toggle.addEventListener("click", (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ const groupKey = toggle.getAttribute("data-toggle-subtype");
+ const groupEl = filterDialog.element.querySelector(`[data-subtype-group="${groupKey}"]`);
+ const arrow = toggle.querySelector("svg") as SVGElement | null;
+ if (!groupEl) {
+ return;
+ }
+ const isHidden = groupEl.classList.toggle("fn__none");
+ if (arrow) {
+ arrow.style.transform = isHidden ? "" : "rotate(90deg)";
+ }
+ });
+ });
+ // Keep parent and subtype toggles in sync. buildTypeFilter drops subtype
+ // clauses when the parent type is disabled, so:
+ // - checking a subtype implies the user wants the parent included
+ // - unchecking a parent implies the user no longer wants its subtype filters
+ const subtypeParents: Record<string, string[]> = {
+ h1: ["heading"], h2: ["heading"], h3: ["heading"],
+ h4: ["heading"], h5: ["heading"], h6: ["heading"],
+ o: ["list", "listItem"],
+ u: ["list", "listItem"],
+ t: ["list", "listItem"],
+ };
+ const parentSubtypes: Record<string, string[]> = {
+ heading: ["h1", "h2", "h3", "h4", "h5", "h6"],
+ list: ["o", "u", "t"],
+ listItem: ["o", "u", "t"],
+ };
+ filterDialog.element.querySelectorAll("[data-subtype]").forEach((subtypeBox: HTMLInputElement) => {
+ subtypeBox.addEventListener("change", () => {
+ if (!subtypeBox.checked) {
+ return;
+ }
+ const subtype = subtypeBox.getAttribute("data-subtype");
+ const parents = subtypeParents[subtype];
+ if (!parents) {
+ return;
+ }
+ parents.forEach((parentType) => {
+ const parentBox = filterDialog.element.querySelector(`[data-type="${parentType}"]`) as HTMLInputElement | null;
+ if (parentBox && !parentBox.checked) {
+ parentBox.checked = true;
+ }
+ });
+ });
+ });
+ Object.keys(parentSubtypes).forEach((parentType) => {
+ const parentBox = filterDialog.element.querySelector(`[data-type="${parentType}"]`) as HTMLInputElement | null;
+ if (!parentBox) {
+ return;
+ }
+ parentBox.addEventListener("change", () => {
+ if (parentBox.checked) {
+ return;
+ }
+ parentSubtypes[parentType].forEach((subtype) => {
+ const subtypeBox = filterDialog.element.querySelector(`[data-subtype="${subtype}"]`) as HTMLInputElement | null;
+ if (subtypeBox && subtypeBox.checked) {
+ subtypeBox.checked = false;
+ }
+ });
+ });
+ });
const btnsElement = filterDialog.element.querySelectorAll(".b3-button");
btnsElement[0].addEventListener("click", () => {
filterDialog.destroy();
});
btnsElement[1].addEventListener("click", () => {
+ if (!config.subTypes) {
+ config.subTypes = getDefaultSubType();
+ }
filterDialog.element.querySelectorAll(".b3-switch").forEach((item: HTMLInputElement) => {
- config.types[item.getAttribute("data-type") as keyof (typeof config.types)] = item.checked;
+ const subtype = item.getAttribute("data-subtype");
+ if (subtype) {
+ config.subTypes[subtype as keyof Config.IUILayoutTabSearchConfigSubTypes] = item.checked;
+ } else {
+ config.types[item.getAttribute("data-type") as keyof (typeof config.types)] = item.checked;
+ }
});
cb();
window.siyuan.storage[Constants.LOCAL_SEARCHDATA] = Object.assign({}, config);
diff --git a/app/src/search/util.ts b/app/src/search/util.ts
index fcb62415cf..2caceb497c 100644
--- a/app/src/search/util.ts
+++ b/app/src/search/util.ts
@@ -41,7 +41,7 @@ import {resize} from "../protyle/util/resize";
import {addClearButton} from "../util/addClearButton";
import {checkFold} from "../util/noRelyPCFunction";
import {getUnRefList, openSearchUnRef, unRefMoreMenu} from "./unRef";
-import {getDefaultType} from "./getDefault";
+import {getDefaultSubType, getDefaultType} from "./getDefault";
import {isSupportCSSHL, searchMarkRender} from "../protyle/render/searchMarkRender";
import {saveKeyList, toggleAssetHistory, toggleReplaceHistory, toggleSearchHistory} from "./toggleHistory";
import {highlightById} from "../util/highlightById";
@@ -357,6 +357,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, ele
r: "",
page: 1,
types: getDefaultType(),
+ subTypes: getDefaultSubType(),
replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),
}, config, edit, true);
element.querySelector(".b3-chip--current")?.classList.remove("b3-chip--current");
@@ -423,6 +424,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, ele
r: "",
page: 1,
types: getDefaultType(),
+ subTypes: getDefaultSubType(),
replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),
}, config, edit, true);
}
@@ -623,6 +625,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, ele
r: "",
page: 1,
types: getDefaultType(),
+ subTypes: getDefaultSubType(),
replaceTypes: Object.assign({}, Constants.SIYUAN_DEFAULT_REPLACETYPES),
}, config, edit, true);
element.querySelector("#criteria .b3-chip--current")?.classList.remove("b3-chip--current");
@@ -1249,6 +1252,7 @@ export const replace = (element: Element, config: Config.IUILayoutTabSearchConfi
r: replaceInputElement.value,
method: config.method,
types: config.types,
+ subTypes: config.subTypes,
paths: config.idPath || [],
groupBy: config.group,
orderBy: config.sort,
@@ -1339,6 +1343,7 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCo
query: config.query,
method: config.method,
types: config.types,
+ subTypes: config.subTypes,
paths: config.idPath || [],
groupBy: config.group,
orderBy: config.sort,
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index a8e9330088..e1dcd2c86b 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -2222,6 +2222,26 @@ declare namespace Config {
*/
sort?: number;
types?: IUILayoutTabSearchConfigTypes;
+ subTypes?: IUILayoutTabSearchConfigSubTypes;
+ }
+
+ /**
+ * Search subtype filtering. When all flags within a category (heading or
+ * list) are false, that category is not subtype-filtered (parent type
+ * filter applies as before). When at least one flag is true, only blocks
+ * matching the selected subtypes are returned for that category.
+ */
+ export interface IUILayoutTabSearchConfigSubTypes {
+ h1: boolean;
+ h2: boolean;
+ h3: boolean;
+ h4: boolean;
+ h5: boolean;
+ h6: boolean;
+ // List subtypes — apply to both list and listItem
+ o: boolean;
+ u: boolean;
+ t: boolean;
}
/**
diff --git a/kernel/api/search.go b/kernel/api/search.go
index 7fe6947ab6..92b03101ed 100644
--- a/kernel/api/search.go
+++ b/kernel/api/search.go
@@ -123,7 +123,7 @@ func findReplace(c *gin.Context) {
return
}
- _, _, _, paths, boxes, types, method, orderBy, groupBy := parseSearchBlockArgs(arg)
+ _, _, _, paths, boxes, types, subTypes, method, orderBy, groupBy := parseSearchBlockArgs(arg)
k := arg["k"].(string)
r := arg["r"].(string)
@@ -143,7 +143,7 @@ func findReplace(c *gin.Context) {
}
}
- err := model.FindReplace(k, r, replaceTypes, ids, paths, boxes, types, method, orderBy, groupBy)
+ err := model.FindReplace(k, r, replaceTypes, ids, paths, boxes, types, subTypes, method, orderBy, groupBy)
if err != nil {
ret.Code = 1
ret.Msg = err.Error()
@@ -395,7 +395,7 @@ func fullTextSearchBlock(c *gin.Context) {
return
}
- page, pageSize, query, paths, boxes, types, method, orderBy, groupBy := parseSearchBlockArgs(arg)
+ page, pageSize, query, paths, boxes, types, subTypes, method, orderBy, groupBy := parseSearchBlockArgs(arg)
// SQL mode requires admin privileges, consistent with /api/query/sql
if method == 2 && !model.IsAdminRoleContext(c) {
@@ -404,7 +404,7 @@ func fullTextSearchBlock(c *gin.Context) {
return
}
- blocks, matchedBlockCount, matchedRootCount, pageCount, docMode := model.FullTextSearchBlock(query, boxes, paths, types, method, orderBy, groupBy, page, pageSize)
+ blocks, matchedBlockCount, matchedRootCount, pageCount, docMode := model.FullTextSearchBlock(query, boxes, paths, types, subTypes, method, orderBy, groupBy, page, pageSize)
if model.IsReadOnlyRoleContext(c) {
publishAccess := model.GetPublishAccess()
blocks = model.FilterBlocksByPublishAccess(c, publishAccess, blocks)
@@ -418,7 +418,7 @@ func fullTextSearchBlock(c *gin.Context) {
}
}
-func parseSearchBlockArgs(arg map[string]any) (page, pageSize int, query string, paths, boxes []string, types map[string]bool, method, orderBy, groupBy int) {
+func parseSearchBlockArgs(arg map[string]any) (page, pageSize int, query string, paths, boxes []string, types, subTypes map[string]bool, method, orderBy, groupBy int) {
page = 1
if nil != arg["page"] {
page = int(arg["page"].(float64))
@@ -465,6 +465,14 @@ func parseSearchBlockArgs(arg map[string]any) (page, pageSize int, query string,
}
}
+ if nil != arg["subTypes"] {
+ subTypesArg := arg["subTypes"].(map[string]any)
+ subTypes = map[string]bool{}
+ for t, b := range subTypesArg {
+ subTypes[t] = b.(bool)
+ }
+ }
+
// method:0:关键字,1:查询语法,2:SQL,3:正则表达式
methodArg := arg["method"]
if nil != methodArg {
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 25913c355b..59fdfb5863 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -653,7 +653,7 @@ func GetDoc(startID, endID, id string, index int, query string, queryTypes map[s
query = filterQueryInvisibleChars(query)
if "" != query && (0 == queryMethod || 1 == queryMethod || 3 == queryMethod) { // 只有关键字、查询语法和正则表达式搜索支持高亮
- typeFilter := buildTypeFilter(queryTypes)
+ typeFilter := buildTypeFilter(queryTypes, nil)
switch queryMethod {
case 0:
query = stringQuery(query)
diff --git a/kernel/model/search.go b/kernel/model/search.go
index 3415383ccb..ac9c7d4ba4 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -478,7 +478,7 @@ func prependNotebookNameInHPath(blocks []*Block) {
}
}
-func FindReplace(keyword, replacement string, replaceTypes map[string]bool, ids []string, paths, boxes []string, types map[string]bool, method, orderBy, groupBy int) (err error) {
+func FindReplace(keyword, replacement string, replaceTypes map[string]bool, ids []string, paths, boxes []string, types, subTypes map[string]bool, method, orderBy, groupBy int) (err error) {
// method:0:文本,1:查询语法,2:SQL,3:正则表达式
if 2 == method {
err = errors.New(Conf.Language(132))
@@ -520,7 +520,7 @@ func FindReplace(keyword, replacement string, replaceTypes map[string]bool, ids
if 1 > len(ids) {
// `Replace All` is no longer affected by pagination https://github.com/siyuan-note/siyuan/issues/8265
- blocks, _, _, _, _ := FullTextSearchBlock(keyword, boxes, paths, types, method, orderBy, groupBy, 1, math.MaxInt)
+ blocks, _, _, _, _ := FullTextSearchBlock(keyword, boxes, paths, types, subTypes, method, orderBy, groupBy, 1, math.MaxInt)
for _, block := range blocks {
ids = append(ids, block.ID)
}
@@ -1158,7 +1158,7 @@ func mergeSamePreNext(n *ast.Node) {
// method:0:关键字,1:查询语法,2:SQL,3:正则表达式
// orderBy: 0:按块类型(默认),1:按创建时间升序,2:按创建时间降序,3:按更新时间升序,4:按更新时间降序,5:按内容顺序(仅在按文档分组时),6:按相关度升序,7:按相关度降序
// groupBy:0:不分组,1:按文档分组
-func FullTextSearchBlock(query string, boxes, paths []string, types map[string]bool, method, orderBy, groupBy, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {
+func FullTextSearchBlock(query string, boxes, paths []string, types, subTypes map[string]bool, method, orderBy, groupBy, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool) {
ret = []*Block{}
if "" == query {
return
@@ -1181,7 +1181,7 @@ func FullTextSearchBlock(query string, boxes, paths []string, types map[string]b
orderByClause := buildOrderBy(query, method, orderBy)
switch method {
case 1: // 查询语法
- typeFilter := buildTypeFilter(types)
+ typeFilter := buildTypeFilter(types, subTypes)
boxFilter := buildBoxesFilter(boxes)
pathFilter := buildPathsFilter(paths)
if ast.IsNodeIDPattern(query) {
@@ -1192,12 +1192,12 @@ func FullTextSearchBlock(query string, boxes, paths []string, types map[string]b
case 2: // SQL
blocks, matchedBlockCount, matchedRootCount = searchBySQL(query, beforeLen, page, pageSize)
case 3: // 正则表达式
- typeFilter := buildTypeFilter(types)
+ typeFilter := buildTypeFilter(types, subTypes)
boxFilter := buildBoxesFilter(boxes)
pathFilter := buildPathsFilter(paths)
blocks, matchedBlockCount, matchedRootCount = fullTextSearchByRegexp(query, boxFilter, pathFilter, typeFilter, ignoreFilter, orderByClause, beforeLen, page, pageSize)
default: // 关键字
- typeFilter := buildTypeFilter(types)
+ typeFilter := buildTypeFilter(types, subTypes)
boxFilter := buildBoxesFilter(boxes)
pathFilter := buildPathsFilter(paths)
if ast.IsNodeIDPattern(query) {
@@ -1397,7 +1397,17 @@ func buildOrderBy(query string, method, orderBy int) string {
}
}
-func buildTypeFilter(types map[string]bool) string {
+// buildTypeFilter returns a complete SQL predicate (including outer parens)
+// suitable for appending after "AND". When subTypes is empty, the result is
+// equivalent to the previous "type IN (...)" behavior. When subTypes contains
+// at least one heading-level (h1..h6) or list (o/u/t) flag, the predicate is
+// extended so that the corresponding parent type (heading or list/listItem)
+// is restricted to the selected subtypes via "subtype IN (...)".
+//
+// Example output:
+//
+// (type IN ('p','c') OR (type = 'h' AND subtype IN ('h1','h2')))
+func buildTypeFilter(types, subTypes map[string]bool) string {
s := conf.NewSearch()
if err := copier.Copy(s, Conf.Search); err != nil {
logging.LogErrorf("copy search conf failed: %s", err)
@@ -1441,7 +1451,86 @@ func buildTypeFilter(types map[string]bool) string {
s.WidgetBlock = Conf.Search.WidgetBlock
s.Callout = Conf.Search.Callout
}
- return s.TypeFilter()
+
+ var headingSubs, listSubs []string
+ for _, h := range []string{"h1", "h2", "h3", "h4", "h5", "h6"} {
+ if subTypes[h] {
+ headingSubs = append(headingSubs, h)
+ }
+ }
+ for _, l := range []string{"o", "u", "t"} {
+ if subTypes[l] {
+ listSubs = append(listSubs, l)
+ }
+ }
+
+ var simpleTypes []string
+ addSimple := func(enabled bool, abbr string) {
+ if enabled {
+ simpleTypes = append(simpleTypes, abbr)
+ }
+ }
+ addSimple(s.Document, treenode.TypeAbbr(ast.NodeDocument.String()))
+ addSimple(s.CodeBlock, treenode.TypeAbbr(ast.NodeCodeBlock.String()))
+ addSimple(s.MathBlock, treenode.TypeAbbr(ast.NodeMathBlock.String()))
+ addSimple(s.Table, treenode.TypeAbbr(ast.NodeTable.String()))
+ addSimple(s.Blockquote, treenode.TypeAbbr(ast.NodeBlockquote.String()))
+ addSimple(s.SuperBlock, treenode.TypeAbbr(ast.NodeSuperBlock.String()))
+ addSimple(s.Paragraph, treenode.TypeAbbr(ast.NodeParagraph.String()))
+ addSimple(s.HTMLBlock, treenode.TypeAbbr(ast.NodeHTMLBlock.String()))
+ addSimple(s.EmbedBlock, treenode.TypeAbbr(ast.NodeBlockQueryEmbed.String()))
+ addSimple(s.DatabaseBlock, treenode.TypeAbbr(ast.NodeAttributeView.String()))
+ addSimple(s.AudioBlock, treenode.TypeAbbr(ast.NodeAudio.String()))
+ addSimple(s.VideoBlock, treenode.TypeAbbr(ast.NodeVideo.String()))
+ addSimple(s.IFrameBlock, treenode.TypeAbbr(ast.NodeIFrame.String()))
+ addSimple(s.WidgetBlock, treenode.TypeAbbr(ast.NodeWidget.String()))
+ addSimple(s.Callout, treenode.TypeAbbr(ast.NodeCallout.String()))
+
+ var clauses []string
+
+ if s.Heading {
+ headingAbbr := treenode.TypeAbbr(ast.NodeHeading.String())
+ if 0 == len(headingSubs) {
+ simpleTypes = append(simpleTypes, headingAbbr)
+ } else {
+ clauses = append(clauses, fmt.Sprintf("(type = '%s' AND subtype IN (%s))",
+ headingAbbr, sqlQuoteJoin(headingSubs)))
+ }
+ }
+
+ var listTypes []string
+ if s.List {
+ listTypes = append(listTypes, treenode.TypeAbbr(ast.NodeList.String()))
+ }
+ if s.ListItem {
+ listTypes = append(listTypes, treenode.TypeAbbr(ast.NodeListItem.String()))
+ }
+ if 0 < len(listTypes) {
+ if 0 == len(listSubs) {
+ simpleTypes = append(simpleTypes, listTypes...)
+ } else {
+ clauses = append(clauses, fmt.Sprintf("(type IN (%s) AND subtype IN (%s))",
+ sqlQuoteJoin(listTypes), sqlQuoteJoin(listSubs)))
+ }
+ }
+
+ if 0 < len(simpleTypes) {
+ clauses = append([]string{"type IN (" + sqlQuoteJoin(simpleTypes) + ")"}, clauses...)
+ }
+
+ if 0 == len(clauses) {
+ // Match nothing without producing invalid SQL when concatenated after AND.
+ return "(1 = 0)"
+ }
+ return "(" + strings.Join(clauses, " OR ") + ")"
+}
+
+func sqlQuoteJoin(items []string) string {
+ quoted := make([]string, len(items))
+ for i, item := range items {
+ quoted[i] = "'" + item + "'"
+ }
+ return strings.Join(quoted, ",")
}
func searchBySQL(stmt string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {
@@ -1585,7 +1674,7 @@ func extractID(content string) (ret string) {
func fullTextSearchByRegexp(exp, boxFilter, pathFilter, typeFilter, ignoreFilter, orderBy string, beforeLen, page, pageSize int) (ret []*Block, matchedBlockCount, matchedRootCount int) {
fieldFilter := fieldRegexp(exp)
- stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND type IN " + typeFilter
+ stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilter
stmt += boxFilter + pathFilter + ignoreFilter + " " + orderBy
regex, err := regexp.Compile(exp)
if nil != err {
@@ -1605,7 +1694,7 @@ func fullTextSearchByRegexp(exp, boxFilter, pathFilter, typeFilter, ignoreFilter
func fullTextSearchCountByRegexp(exp, boxFilter, pathFilter, typeFilter, ignoreFilter string) (matchedBlockCount, matchedRootCount int) {
fieldFilter := fieldRegexp(exp)
- stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `blocks` WHERE " + fieldFilter + " AND type IN " + typeFilter + ignoreFilter
+ stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilter + ignoreFilter
stmt += boxFilter + pathFilter
result, _ := sql.QueryNoLimit(stmt)
if 1 > len(result) {
@@ -1631,7 +1720,7 @@ func fullTextSearchByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFilter,
"snippet(" + table + ", 11, '" + search.SearchMarkLeft + "', '" + search.SearchMarkRight + "', '...', 512) AS content, " +
"fcontent, markdown, length, type, subtype, ial, sort, created, updated"
stmt := "SELECT " + projections + " FROM " + table + " WHERE (`" + table + "` MATCH '" + columnFilter() + ":(" + query + ")'"
- stmt += ") AND type IN " + typeFilter
+ stmt += ") AND " + typeFilter
stmt += boxFilter + pathFilter + ignoreFilter + " " + orderBy
stmt += " LIMIT " + strconv.Itoa(pageSize) + " OFFSET " + strconv.Itoa((page-1)*pageSize)
blocks := sql.SelectBlocksRawStmt(stmt, page, pageSize)
@@ -1651,7 +1740,7 @@ func fullTextSearchCountByFTS(query, boxFilter, pathFilter, typeFilter, ignoreFi
}
stmt := "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` FROM `" + table + "` WHERE (`" + table + "` MATCH '" + columnFilter() + ":(" + query + ")'"
- stmt += ") AND type IN " + typeFilter
+ stmt += ") AND " + typeFilter
stmt += boxFilter + pathFilter + ignoreFilter
result, _ := sql.QueryNoLimit(stmt)
if 1 > len(result) {
@@ -1678,7 +1767,7 @@ func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, typeFilter, igno
}
orderByLike += ")"
dMatchStmt := "SELECT root_id, MAX(CASE WHEN type = 'd' THEN (" + contentField + ") END) AS docContent" +
- " FROM blocks WHERE type IN " + typeFilter + boxFilter + pathFilter + ignoreFilter +
+ " FROM blocks WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter +
" GROUP BY root_id HAVING " + likeFilter + "ORDER BY " + orderByLike + " DESC, MAX(updated) DESC"
cteStmt := "WITH docBlocks AS (" + dMatchStmt + ")"
likeFilter = strings.ReplaceAll(likeFilter, "GROUP_CONCAT("+contentField+")", "concatContent")
@@ -1687,7 +1776,7 @@ func fullTextSearchByLikeWithRoot(query, boxFilter, pathFilter, typeFilter, igno
"(" + contentField + ") AS concatContent, " +
"(SELECT COUNT(root_id) FROM docBlocks) AS docs, " +
"(CASE WHEN (root_id IN (SELECT root_id FROM docBlocks) AND (" + strings.ReplaceAll(likeFilter, "concatContent", contentField) + ")) THEN 1 ELSE 0 END) AS blockSort" +
- " FROM blocks WHERE type IN " + typeFilter + boxFilter + pathFilter + ignoreFilter +
+ " FROM blocks WHERE " + typeFilter + boxFilter + pathFilter + ignoreFilter +
" AND (id IN (SELECT root_id FROM docBlocks " + limit + ") OR" +
" (root_id IN (SELECT root_id FROM docBlocks" + limit + ") AND (" + likeFilter + ")))"
if strings.Contains(orderBy, "ORDER BY rank DESC") {
@@ -1736,7 +1825,7 @@ func highlightByFTS(query, typeFilter, id string) (ret []string) {
"highlight(" + table + ", 17, '" + search.SearchMarkLeft + "', '" + search.SearchMarkRight + "') AS ial, " +
"sort, created, updated"
stmt := "SELECT " + projections + " FROM " + table + " WHERE (`" + table + "` MATCH '" + columnFilter() + ":(" + query + ")'"
- stmt += ") AND type IN " + typeFilter
+ stmt += ") AND " + typeFilter
stmt += " AND root_id = '" + id + "'"
stmt += " LIMIT " + strconv.Itoa(limit)
sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, limit)
@@ -1776,7 +1865,7 @@ func highlightByFTS(query, typeFilter, id string) (ret []string) {
func highlightByRegexp(query, typeFilter, id string) (ret []string) {
fieldFilter := fieldRegexp(query)
- stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND type IN " + typeFilter
+ stmt := "SELECT * FROM `blocks` WHERE " + fieldFilter + " AND " + typeFilter
stmt += " AND root_id = '" + id + "'"
regex, _ := regexp.Compile(query)
if nil == regex {