Skip to content

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

:art: Support precise database relation filters https://github.com/siyuan-note/siyuan/issues/15599

Daniel42ea3de1bc58
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 874adb6ed1..e852ff84d7 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "اختر العناصر المرتبطة",
+ "filterOperatorContainsAnyItem": "يحتوي على أي عنصر",
+ "filterOperatorDoesNotContainAnyItem": "لا يحتوي على أي عنصر",
+ "filterOperatorContainsKeyword": "يحتوي على كلمة مفتاحية",
+ "filterOperatorDoesNotContainKeyword": "لا يحتوي على كلمة مفتاحية",
"showInAllViews": "إظهار في جميع العروض",
"hideInAllViews": "إخفاء في جميع العروض",
"fieldVisibility": "إمكانية رؤية الحقل",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 3d81dbd808..1526d3c1f8 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Verknüpfte Einträge auswählen",
+ "filterOperatorContainsAnyItem": "Enthält eines",
+ "filterOperatorDoesNotContainAnyItem": "Enthält keines",
+ "filterOperatorContainsKeyword": "Enthält Schlüsselwort",
+ "filterOperatorDoesNotContainKeyword": "Enthält Schlüsselwort nicht",
"showInAllViews": "In allen Ansichten anzeigen",
"hideInAllViews": "In allen Ansichten ausblenden",
"fieldVisibility": "Feldsichtbarkeit",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 0be0365e00..3619b05ac5 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Select entries",
+ "filterOperatorContainsAnyItem": "Contains any item",
+ "filterOperatorDoesNotContainAnyItem": "Does not contain any item",
+ "filterOperatorContainsKeyword": "Contains keyword",
+ "filterOperatorDoesNotContainKeyword": "Does not contain keyword",
"showInAllViews": "Show in all views",
"hideInAllViews": "Hide in all views",
"fieldVisibility": "Field visibility",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index e605d62b44..35e52cbbd1 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Seleccionar elementos relacionados",
+ "filterOperatorContainsAnyItem": "Contiene cualquiera",
+ "filterOperatorDoesNotContainAnyItem": "No contiene ninguno",
+ "filterOperatorContainsKeyword": "Contiene palabra clave",
+ "filterOperatorDoesNotContainKeyword": "No contiene palabra clave",
"showInAllViews": "Mostrar en todas las vistas",
"hideInAllViews": "Ocultar en todas las vistas",
"fieldVisibility": "Visibilidad del campo",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 9634aca550..3fc1075f2c 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Sélectionner des éléments liés",
+ "filterOperatorContainsAnyItem": "Contient au moins un élément",
+ "filterOperatorDoesNotContainAnyItem": "Ne contient aucun élément",
+ "filterOperatorContainsKeyword": "Contient le mot-clé",
+ "filterOperatorDoesNotContainKeyword": "Ne contient pas le mot-clé",
"showInAllViews": "Afficher dans toutes les vues",
"hideInAllViews": "Masquer dans toutes les vues",
"fieldVisibility": "Visibilité du champ",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index fa945d90f7..18398e40e9 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "בחירת פריטים מקושרים",
+ "filterOperatorContainsAnyItem": "מכיל פריט כלשהו",
+ "filterOperatorDoesNotContainAnyItem": "אינו מכיל אף פריט",
+ "filterOperatorContainsKeyword": "מכיל מילת מפתח",
+ "filterOperatorDoesNotContainKeyword": "אינו מכיל מילת מפתח",
"showInAllViews": "הצגה בכל התצוגות",
"hideInAllViews": "הסתרה בכל התצוגות",
"fieldVisibility": "נראות השדה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 75b061e4ed..0ced304d08 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "संबंधित आइटम चुनें",
+ "filterOperatorContainsAnyItem": "किसी भी आइटम को शामिल करता है",
+ "filterOperatorDoesNotContainAnyItem": "किसी भी आइटम को शामिल नहीं करता",
+ "filterOperatorContainsKeyword": "कीवर्ड शामिल करता है",
+ "filterOperatorDoesNotContainKeyword": "कीवर्ड शामिल नहीं करता",
"showInAllViews": "सभी दृश्यों में दिखाएँ",
"hideInAllViews": "सभी दृश्यों में छिपाएँ",
"fieldVisibility": "फ़ील्ड दृश्यता",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index dc48c30077..855d0f1cc1 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Pilih item terkait",
+ "filterOperatorContainsAnyItem": "Berisi salah satu item",
+ "filterOperatorDoesNotContainAnyItem": "Tidak berisi item apa pun",
+ "filterOperatorContainsKeyword": "Berisi kata kunci",
+ "filterOperatorDoesNotContainKeyword": "Tidak berisi kata kunci",
"showInAllViews": "Tampilkan di semua tampilan",
"hideInAllViews": "Sembunyikan di semua tampilan",
"fieldVisibility": "Visibilitas bidang",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 067c00f54c..55c0fc6eec 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Seleziona elementi collegati",
+ "filterOperatorContainsAnyItem": "Contiene almeno un elemento",
+ "filterOperatorDoesNotContainAnyItem": "Non contiene alcun elemento",
+ "filterOperatorContainsKeyword": "Contiene parola chiave",
+ "filterOperatorDoesNotContainKeyword": "Non contiene parola chiave",
"showInAllViews": "Mostra in tutte le viste",
"hideInAllViews": "Nascondi in tutte le viste",
"fieldVisibility": "Visibilità del campo",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index b7d9324c30..b93bc3db3b 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "関連項目を選択",
+ "filterOperatorContainsAnyItem": "いずれかを含む",
+ "filterOperatorDoesNotContainAnyItem": "いずれも含まない",
+ "filterOperatorContainsKeyword": "キーワードを含む",
+ "filterOperatorDoesNotContainKeyword": "キーワードを含まない",
"showInAllViews": "すべてのビューで表示",
"hideInAllViews": "すべてのビューで非表示",
"fieldVisibility": "フィールドの表示",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 046d61abbc..f5ba6fc589 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "연결 항목 선택",
+ "filterOperatorContainsAnyItem": "항목 중 하나 포함",
+ "filterOperatorDoesNotContainAnyItem": "어떤 항목도 포함하지 않음",
+ "filterOperatorContainsKeyword": "키워드 포함",
+ "filterOperatorDoesNotContainKeyword": "키워드 미포함",
"showInAllViews": "모든 뷰에서 표시",
"hideInAllViews": "모든 뷰에서 숨기기",
"fieldVisibility": "필드 표시",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 68324ad765..d88e42de66 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Gerelateerde items selecteren",
+ "filterOperatorContainsAnyItem": "Bevat een van de items",
+ "filterOperatorDoesNotContainAnyItem": "Bevat geen van de items",
+ "filterOperatorContainsKeyword": "Bevat trefwoord",
+ "filterOperatorDoesNotContainKeyword": "Bevat trefwoord niet",
"showInAllViews": "Tonen in alle weergaven",
"hideInAllViews": "Verbergen in alle weergaven",
"fieldVisibility": "Zichtbaarheid van veld",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 54ea086756..076f24fd57 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Wybierz powiązane elementy",
+ "filterOperatorContainsAnyItem": "Zawiera dowolny element",
+ "filterOperatorDoesNotContainAnyItem": "Nie zawiera żadnego elementu",
+ "filterOperatorContainsKeyword": "Zawiera słowo kluczowe",
+ "filterOperatorDoesNotContainKeyword": "Nie zawiera słowa kluczowego",
"showInAllViews": "Pokaż we wszystkich widokach",
"hideInAllViews": "Ukryj we wszystkich widokach",
"fieldVisibility": "Widoczność pola",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 316f8368ee..869d962228 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Selecionar itens relacionados",
+ "filterOperatorContainsAnyItem": "Contém qualquer item",
+ "filterOperatorDoesNotContainAnyItem": "Não contém nenhum item",
+ "filterOperatorContainsKeyword": "Contém palavra-chave",
+ "filterOperatorDoesNotContainKeyword": "Não contém palavra-chave",
"showInAllViews": "Mostrar em todas as visualizações",
"hideInAllViews": "Ocultar em todas as visualizações",
"fieldVisibility": "Visibilidade do campo",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index a31ad0766a..ea24454755 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Выбрать связанные элементы",
+ "filterOperatorContainsAnyItem": "Содержит любой элемент",
+ "filterOperatorDoesNotContainAnyItem": "Не содержит ни одного элемента",
+ "filterOperatorContainsKeyword": "Содержит ключевое слово",
+ "filterOperatorDoesNotContainKeyword": "Не содержит ключевое слово",
"showInAllViews": "Показать во всех представлениях",
"hideInAllViews": "Скрыть во всех представлениях",
"fieldVisibility": "Видимость поля",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index f93ca4e05e..9fa7176113 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Vybrať súvisiace položky",
+ "filterOperatorContainsAnyItem": "Obsahuje ľubovoľnú položku",
+ "filterOperatorDoesNotContainAnyItem": "Neobsahuje žiadnu položku",
+ "filterOperatorContainsKeyword": "Obsahuje kľúčové slovo",
+ "filterOperatorDoesNotContainKeyword": "Neobsahuje kľúčové slovo",
"showInAllViews": "Zobraziť vo všetkých zobrazeniach",
"hideInAllViews": "Skryť vo všetkých zobrazeniach",
"fieldVisibility": "Viditeľnosť poľa",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 22948f5ea9..0a2cb02a0d 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "เลือกรายการที่เชื่อมโยง",
+ "filterOperatorContainsAnyItem": "มีรายการใดรายการหนึ่ง",
+ "filterOperatorDoesNotContainAnyItem": "ไม่มีรายการใดเลย",
+ "filterOperatorContainsKeyword": "มีคำสำคัญ",
+ "filterOperatorDoesNotContainKeyword": "ไม่มีคำสำคัญ",
"showInAllViews": "แสดงในทุกมุมมอง",
"hideInAllViews": "ซ่อนในทุกมุมมอง",
"fieldVisibility": "การมองเห็นฟิลด์",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 1fdaf22634..f93a815e0f 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "İlişkili öğeleri seç",
+ "filterOperatorContainsAnyItem": "Herhangi bir öğeyi içerir",
+ "filterOperatorDoesNotContainAnyItem": "Hiçbir öğeyi içermez",
+ "filterOperatorContainsKeyword": "Anahtar sözcük içerir",
+ "filterOperatorDoesNotContainKeyword": "Anahtar sözcük içermez",
"showInAllViews": "Tüm görünümlerde göster",
"hideInAllViews": "Tüm görünümlerde gizle",
"fieldVisibility": "Alan görünürlüğü",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 6fb64b6057..6ae98347ea 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "Вибрати пов’язані елементи",
+ "filterOperatorContainsAnyItem": "Містить будь-який елемент",
+ "filterOperatorDoesNotContainAnyItem": "Не містить жодного елемента",
+ "filterOperatorContainsKeyword": "Містить ключове слово",
+ "filterOperatorDoesNotContainKeyword": "Не містить ключового слова",
"showInAllViews": "Показати в усіх поданнях",
"hideInAllViews": "Приховати в усіх поданнях",
"fieldVisibility": "Видимість поля",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index e14c135f7a..b697ae5be4 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "选择条目",
+ "filterOperatorContainsAnyItem": "包含任一",
+ "filterOperatorDoesNotContainAnyItem": "不包含任一",
+ "filterOperatorContainsKeyword": "包含关键字",
+ "filterOperatorDoesNotContainKeyword": "不包含关键字",
"showInAllViews": "在所有视图中显示",
"hideInAllViews": "在所有视图中隐藏",
"fieldVisibility": "字段可见性",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index f6c9761709..4d1df05209 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,9 @@
{
+ "selectRelationItems": "選擇項目",
+ "filterOperatorContainsAnyItem": "包含任一項",
+ "filterOperatorDoesNotContainAnyItem": "不包含任一項",
+ "filterOperatorContainsKeyword": "包含關鍵字",
+ "filterOperatorDoesNotContainKeyword": "不包含關鍵字",
"showInAllViews": "在所有視圖中顯示",
"hideInAllViews": "在所有視圖中隱藏",
"fieldVisibility": "欄位可見性",
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index 0ffbf4d719..12f40e8e65 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -1365,6 +1365,122 @@
font-size: 14px;
width: 100%;
}
+
+ .av__relation-filter-trigger {
+ max-width: 280px;
+
+ .av__relation-filter-chip {
+ max-width: 112px;
+ }
+ }
+
+ .av__relation-filter-dropdown {
+ display: flex;
+ flex-direction: column;
+ max-height: 320px;
+ overflow: hidden;
+ }
+
+ .av__relation-filter-selected {
+ display: flex;
+ align-items: flex-start;
+ gap: 4px;
+ margin-bottom: 4px;
+
+ &:empty {
+ display: none;
+ }
+ }
+
+ .av__relation-filter-selected-chips {
+ display: flex;
+ flex: 1;
+ flex-wrap: wrap;
+ gap: 4px;
+ max-height: 88px;
+ overflow-y: auto;
+ }
+
+ .av__relation-filter-chip {
+ display: inline-flex;
+ align-items: center;
+ min-width: 0;
+ max-width: 180px;
+ gap: 4px;
+ background-color: var(--b3-list-hover);
+ color: var(--b3-theme-on-background);
+ }
+
+ .av__relation-filter-id,
+ .av__relation-filter-option-id {
+ flex-shrink: 0;
+ color: var(--b3-theme-on-surface);
+ font-size: 11px;
+ }
+
+ .av__relation-filter-remove {
+ display: inline-flex;
+ flex-shrink: 0;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--b3-theme-on-surface);
+ cursor: pointer;
+
+ svg {
+ width: 12px;
+ height: 12px;
+ }
+ }
+
+ .av__relation-filter-clear {
+ flex-shrink: 0;
+ padding: 2px 4px;
+ }
+
+ .av__relation-filter-count {
+ flex-shrink: 0;
+ }
+
+ .av__relation-filter-options {
+ display: flex;
+ flex-direction: column;
+ min-height: 28px;
+ max-height: 180px;
+ overflow-y: auto;
+ }
+
+ .av__relation-filter-option {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ min-height: 30px;
+ padding: 4px 6px;
+ border: 0;
+ border-radius: var(--b3-border-radius);
+ background: transparent;
+ color: var(--b3-theme-on-background);
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+
+ &:hover,
+ &:focus-visible {
+ background-color: var(--b3-list-hover);
+ }
+ }
+
+ .av__relation-filter-option-icon,
+ .av__relation-filter-option-check {
+ width: 14px;
+ height: 14px;
+ flex-shrink: 0;
+ }
+
+ .av__relation-filter-option-check {
+ margin-left: auto;
+ }
}
}
diff --git a/app/src/protyle/render/av/filter.ts b/app/src/protyle/render/av/filter.ts
index 006375d07a..cfb7d0b271 100644
--- a/app/src/protyle/render/av/filter.ts
+++ b/app/src/protyle/render/av/filter.ts
@@ -10,7 +10,13 @@ import {fetchPost, fetchSyncPost} from "../../../util/fetch";
import {getFieldsByData} from "./view";
import {Constants} from "../../../constants";
-export const getDefaultOperatorByType = (type: TAVCol) => {
+const isExactRelationOperator = (operator: string) =>
+ operator === "Contains any item" || operator === "Does not contain any item";
+
+export const getDefaultOperatorByType = (type: TAVCol, isRollup = false) => {
+ if (type === "relation" && !isRollup) {
+ return "Contains any item";
+ }
if (["select", "number", "date", "created", "updated"].includes(type)) {
return "=";
}
@@ -355,7 +361,7 @@ export const convertGroupToFilter = (nodes: IAVFilter[], path: string): boolean
// ============ 内联化筛选编辑(替代 setFilter 弹层) ============
// getOperatorSelectByType 按值类型生成操作符 <select> 的 option HTML,标记当前 operator 为 selected。
-const getOperatorSelectByType = (type: TAVCol, currentOperator: string): string => {
+const getOperatorSelectByType = (type: TAVCol, currentOperator: string, isRollup: boolean): string => {
const opt = (value: string, label: string) => `<option ${value === currentOperator ? "selected" : ""} value="${value}">${label}</option>`;
switch (type) {
case "checkbox":
@@ -388,9 +394,21 @@ const getOperatorSelectByType = (type: TAVCol, currentOperator: string): string
opt(">=", "&GreaterEqual;") + opt("<=", "&le;") +
opt("Is empty", window.siyuan.languages.filterOperatorIsEmpty) + opt("Is not empty", window.siyuan.languages.filterOperatorIsNotEmpty);
case "mSelect":
- case "relation":
return opt("Contains", window.siyuan.languages.filterOperatorContains) + opt("Does not contains", window.siyuan.languages.filterOperatorDoesNotContain) +
opt("Is empty", window.siyuan.languages.filterOperatorIsEmpty) + opt("Is not empty", window.siyuan.languages.filterOperatorIsNotEmpty);
+ case "relation":
+ if (isRollup) {
+ return opt("Contains", window.siyuan.languages.filterOperatorContains) +
+ opt("Does not contains", window.siyuan.languages.filterOperatorDoesNotContain) +
+ opt("Is empty", window.siyuan.languages.filterOperatorIsEmpty) +
+ opt("Is not empty", window.siyuan.languages.filterOperatorIsNotEmpty);
+ }
+ return opt("Contains any item", window.siyuan.languages.filterOperatorContainsAnyItem) +
+ opt("Does not contain any item", window.siyuan.languages.filterOperatorDoesNotContainAnyItem) +
+ opt("Contains", window.siyuan.languages.filterOperatorContainsKeyword) +
+ opt("Does not contains", window.siyuan.languages.filterOperatorDoesNotContainKeyword) +
+ opt("Is empty", window.siyuan.languages.filterOperatorIsEmpty) +
+ opt("Is not empty", window.siyuan.languages.filterOperatorIsNotEmpty);
case "select":
return opt("=", window.siyuan.languages.filterOperatorIs) + opt("!=", window.siyuan.languages.filterOperatorIsNot) +
opt("Is empty", window.siyuan.languages.filterOperatorIsEmpty) + opt("Is not empty", window.siyuan.languages.filterOperatorIsNotEmpty);
@@ -400,6 +418,29 @@ const getOperatorSelectByType = (type: TAVCol, currentOperator: string): string
};
const rollupTargetColumns = new WeakMap<IAVColumn, IAVColumn>();
+const relationFilterLabelCache = new Map<string, string>();
+
+const getRelationFilterCacheKey = (avID: string, blockID: string) => `${avID}\n${blockID}`;
+
+const parseRelationFilterBlockIDs = (value: string | string[]): string[] => {
+ try {
+ const blockIDs = Array.isArray(value) ? value : JSON.parse(value || "[]");
+ return Array.isArray(blockIDs)
+ ? Array.from(new Set(blockIDs.filter((item) => "string" === typeof item && item)))
+ : [];
+ } catch (e) {
+ return [];
+ }
+};
+
+const cacheRelationFilterValues = (avID: string, values: IAVCellValue[]) => {
+ values.forEach((value) => {
+ if (value.blockID) {
+ const cacheKey = getRelationFilterCacheKey(avID, value.blockID);
+ relationFilterLabelCache.set(cacheKey, value.block?.content || window.siyuan.languages.untitled);
+ }
+ });
+};
// prepareFilterColumns 加载汇总字段指向的原始字段,使筛选控件可以按原始类型展示。
export const prepareFilterColumns = async (data: IAV) => {
@@ -424,7 +465,45 @@ export const prepareFilterColumns = async (data: IAV) => {
rollupTargetColumns.set(column, targetColumn);
}
});
- await Promise.all(tasks);
+ const relationSelections = new Map<string, Set<string>>();
+ const collectRelationSelections = (filters: IAVFilter[]) => {
+ filters.forEach((filter) => {
+ if (filter.filters) {
+ collectRelationSelections(filter.filters);
+ return;
+ }
+ if (!isExactRelationOperator(filter.operator)) {
+ return;
+ }
+ const column = fields.find((item) => item.id === filter.column);
+ const targetAVID = column?.type === "relation" ? column.relation?.avID : "";
+ if (!targetAVID) {
+ return;
+ }
+ let blockIDs = relationSelections.get(targetAVID);
+ if (!blockIDs) {
+ blockIDs = new Set<string>();
+ relationSelections.set(targetAVID, blockIDs);
+ }
+ filter.value?.relation?.blockIDs?.forEach((blockID) => blockIDs.add(blockID));
+ });
+ };
+ collectRelationSelections(getRootFilters(data));
+ const relationTasks = Array.from(relationSelections.entries()).map(async ([targetAVID, blockIDs]) => {
+ if (0 === blockIDs.size) {
+ return;
+ }
+ try {
+ const response = await fetchSyncPost("/api/av/getAttributeViewPrimaryKeyValues", {
+ id: targetAVID,
+ blockIDs: Array.from(blockIDs),
+ });
+ cacheRelationFilterValues(targetAVID, response.data?.rows?.values || []);
+ } catch (e) {
+ // 候选显示名加载失败不应阻止筛选面板打开,控件会保留行 ID 并允许重新搜索。
+ }
+ });
+ await Promise.all([...tasks, ...relationTasks]);
};
// resolveFilterValueType 解析 filter 实际的值类型。
@@ -469,7 +548,7 @@ const genEmptyFilterValue = (column: IAVColumn): { operator: TAVFilterOperator,
const emptyRollup = {type: "rollup", rollup: {contents: []}} as IAVCellValue;
const {type} = resolveFilterValueType({value: emptyRollup} as IAVFilter, column);
return {
- operator: getDefaultOperatorByType(type),
+ operator: getDefaultOperatorByType(type, true),
value: {
type: "rollup",
rollup: {contents: [genEmptyCellValue(type)]},
@@ -486,7 +565,7 @@ const genInlineFilterHTML = (filter: IAVFilter, colData: IAVColumn, path: string
const valueHidden = isEmptyOp ? " fn__none" : "";
// 操作符 select
- const operatorSelect = `<select class="b3-select" data-type="operation" data-path="${path}">${getOperatorSelectByType(valueType, operator)}</select>`;
+ const operatorSelect = `<select class="b3-select" data-type="operation" data-path="${path}">${getOperatorSelectByType(valueType, operator, isRollup)}</select>`;
// 量化器 select(rollup/mAsset 才有)
const quantifierSelect = (isRollup || valueType === "mAsset")
@@ -519,6 +598,10 @@ const genInlineFilterHTML = (filter: IAVFilter, colData: IAVColumn, path: string
const {trigger, dropdown} = genInlineSelectHTML(filter, valueColumn, path, valueType);
valueHTML = trigger;
extraHTML = dropdown; // 下拉面板放 valueContainer 外,fixed 定位不影响行宽
+ } else if (valueType === "relation" && !isRollup && isExactRelationOperator(operator)) {
+ const {trigger, dropdown} = genInlineRelationHTML(filter, valueColumn, path);
+ valueHTML = trigger;
+ extraHTML = dropdown;
} else if (valueType === "relation") {
const content = filterValue?.relation?.blockIDs?.[0] || "";
valueHTML = `<input class="b3-text-field b3-text-field--text fn__flex-1" value="${escapeFilterValue(content)}" data-type="filterValue" data-type-rel="relation" data-path="${path}">`;
@@ -604,6 +687,55 @@ ${searchInput}<div class="av__select-options" data-type="selectOptions" data-pat
return {trigger, dropdown};
};
+const getRelationFilterLabel = (avID: string, blockID: string) => {
+ return relationFilterLabelCache.get(getRelationFilterCacheKey(avID, blockID)) ||
+ window.siyuan.languages.untitled;
+};
+
+const genRelationFilterChip = (avID: string, blockID: string, removable: boolean, path: string) => {
+ const label = getRelationFilterLabel(avID, blockID);
+ const suffix = blockID.slice(-7);
+ const removeButton = removable
+ ? `<button type="button" class="av__relation-filter-remove" data-type="relationFilterRemove" data-path="${path}" data-id="${escapeAttr(blockID)}" aria-label="${window.siyuan.languages.remove}">
+<svg><use xlink:href="#iconCloseRound"></use></svg></button>`
+ : "";
+ return `<span class="b3-chip b3-chip--middle av__relation-filter-chip" title="${escapeAttr(blockID)}">
+<span class="fn__ellipsis">${escapeHtml(label)}</span><span class="av__relation-filter-id">${escapeHtml(suffix)}</span>${removeButton}</span>`;
+};
+
+const genRelationFilterTriggerContent = (avID: string, blockIDs: string[], path: string) => {
+ if (0 === blockIDs.length) {
+ return `<span class="ft__on-surface fn__ellipsis">${window.siyuan.languages.selectRelationItems}</span>`;
+ }
+ const visibleBlockIDs = blockIDs.slice(0, 2);
+ const overflow = blockIDs.length - visibleBlockIDs.length;
+ return visibleBlockIDs.map((blockID) => genRelationFilterChip(avID, blockID, false, path)).join("") +
+ (0 < overflow ? `<span class="b3-chip b3-chip--middle av__relation-filter-count">+${overflow}</span>` : "");
+};
+
+const genRelationFilterSelectedHTML = (avID: string, blockIDs: string[], path: string) => {
+ if (0 === blockIDs.length) {
+ return "";
+ }
+ return `<div class="av__relation-filter-selected-chips">${blockIDs.map((blockID) =>
+ genRelationFilterChip(avID, blockID, true, path)).join("")}</div>
+<button type="button" class="b3-button b3-button--text av__relation-filter-clear" data-type="relationFilterClear" data-path="${path}">${window.siyuan.languages.clear}</button>`;
+};
+
+const genInlineRelationHTML = (filter: IAVFilter, colData: IAVColumn, path: string): { trigger: string, dropdown: string } => {
+ const avID = colData.relation?.avID || "";
+ const selectedBlockIDs = parseRelationFilterBlockIDs(getFilterCellValue(filter)?.relation?.blockIDs || []);
+ const selectedAttr = escapeAttr(JSON.stringify(selectedBlockIDs));
+ const trigger = `<span class="av__select-trigger av__relation-filter-trigger" data-type="relationFilterTrigger" data-path="${path}" data-av-id="${escapeAttr(avID)}">
+${genRelationFilterTriggerContent(avID, selectedBlockIDs, path)}<svg class="av__select-trigger-arrow"><use xlink:href="#iconDown"></use></svg></span>`;
+ const dropdown = `<div class="av__select-dropdown av__relation-filter-dropdown" data-type="relationFilterDropdown" data-path="${path}" data-av-id="${escapeAttr(avID)}" data-selected="${selectedAttr}" style="display:none;">
+<div class="av__relation-filter-selected" data-type="relationFilterSelected" data-path="${path}">${genRelationFilterSelectedHTML(avID, selectedBlockIDs, path)}</div>
+<input class="b3-text-field" placeholder="${window.siyuan.languages.search}" data-type="relationFilterSearch" data-path="${path}">
+<div class="av__relation-filter-options" data-type="relationFilterOptions" data-path="${path}"></div>
+</div>`;
+ return {trigger, dropdown};
+};
+
// readInlineValue 从叶子行内 DOM 读取值,按类型返回 { value, relativeDate, relativeDate2 }。
// 修正点①:date 用 data-type 精确定位,废弃全局 textElements 索引。
const readInlineValue = (rowElement: HTMLElement, valueType: TAVCol, operator: string, filter: IAVFilter): { newValue: IAVCellValue, relativeDate: IAVRelativeDate, relativeDate2: IAVRelativeDate } => {
@@ -621,8 +753,17 @@ const readInlineValue = (rowElement: HTMLElement, valueType: TAVCol, operator: s
const isChecked = select?.value !== "false";
newValue = genCellValue("checkbox", {checked: isChecked});
} else if (valueType === "relation") {
- const input = rowElement.querySelector('[data-type="filterValue"]') as HTMLInputElement;
- newValue = input?.value ? genCellValue("relation", input.value) : genEmptyCellValue("relation");
+ if (isExactRelationOperator(operator)) {
+ const dropdown = rowElement.querySelector('[data-type="relationFilterDropdown"]') as HTMLElement;
+ const blockIDs = parseRelationFilterBlockIDs(dropdown?.dataset.selected || []);
+ newValue = {
+ type: "relation",
+ relation: {blockIDs, contents: []},
+ };
+ } else {
+ const input = rowElement.querySelector('[data-type="filterValue"]') as HTMLInputElement;
+ newValue = input?.value ? genCellValue("relation", input.value) : genEmptyCellValue("relation");
+ }
} else if (["text", "url", "block", "email", "phone", "template", "mAsset", "number"].includes(valueType)) {
const input = rowElement.querySelector('[data-type="filterValue"]') as HTMLInputElement;
const val = input?.value || "";
@@ -784,6 +925,101 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
commitFilter(data, path, newFilter, protyle, blockID, avID, menuElement, reRender);
};
+ const getRelationFilterSelection = (dropdown: HTMLElement): string[] => {
+ return parseRelationFilterBlockIDs(dropdown.dataset.selected || []);
+ };
+
+ const positionRelationFilterDropdown = (dropdown: HTMLElement, trigger: HTMLElement) => {
+ const rect = trigger.getBoundingClientRect();
+ const dropdownWidth = Math.min(Math.max(rect.width, 280), window.innerWidth - 16);
+ dropdown.style.left = Math.max(8, Math.min(rect.left, window.innerWidth - dropdownWidth - 8)) + "px";
+ dropdown.style.width = dropdownWidth + "px";
+ const dropdownHeight = dropdown.offsetHeight;
+ dropdown.style.top = window.innerHeight - rect.bottom < dropdownHeight + 8 && rect.top > dropdownHeight + 8
+ ? rect.top - dropdownHeight - 4 + "px"
+ : rect.bottom + 4 + "px";
+ };
+
+ const renderRelationFilterSelection = (path: string, dropdown: HTMLElement, selectedBlockIDs: string[]) => {
+ const targetAVID = dropdown.dataset.avId || "";
+ dropdown.dataset.selected = JSON.stringify(selectedBlockIDs);
+ const selectedElement = dropdown.querySelector('[data-type="relationFilterSelected"]') as HTMLElement;
+ if (selectedElement) {
+ selectedElement.innerHTML = genRelationFilterSelectedHTML(targetAVID, selectedBlockIDs, path);
+ }
+ const trigger = menuElement.querySelector(`[data-type="relationFilterTrigger"][data-path="${path}"]`) as HTMLElement;
+ if (trigger) {
+ trigger.innerHTML = genRelationFilterTriggerContent(targetAVID, selectedBlockIDs, path) +
+ '<svg class="av__select-trigger-arrow"><use xlink:href="#iconDown"></use></svg>';
+ }
+ const selectedSet = new Set(selectedBlockIDs);
+ dropdown.querySelectorAll('[data-type="relationFilterOption"]').forEach((option: HTMLElement) => {
+ const useElement = option.querySelector(".av__relation-filter-option-check use");
+ useElement?.setAttribute("xlink:href", selectedSet.has(option.dataset.id) ? "#iconCheck" : "#iconUncheck");
+ });
+ if (trigger && "none" !== dropdown.style.display) {
+ positionRelationFilterDropdown(dropdown, trigger);
+ }
+ };
+
+ const commitRelationFilterSelection = (path: string, dropdown: HTMLElement, selectedBlockIDs: string[]) => {
+ const filter = getFilterByPath(getEditableFilters(data), path);
+ if (!filter) {
+ return;
+ }
+ const newFilter: IAVFilter = {
+ ...filter,
+ value: {
+ type: "relation",
+ relation: {blockIDs: selectedBlockIDs, contents: []},
+ },
+ };
+ commitFilter(data, path, newFilter, protyle, blockID, avID, menuElement, false);
+ renderRelationFilterSelection(path, dropdown, selectedBlockIDs);
+ };
+
+ const renderRelationFilterOptions = (dropdown: HTMLElement, values: IAVCellValue[]) => {
+ const path = dropdown.dataset.path;
+ const targetAVID = dropdown.dataset.avId || "";
+ const selectedSet = new Set(getRelationFilterSelection(dropdown));
+ cacheRelationFilterValues(targetAVID, values);
+ const optionsElement = dropdown.querySelector('[data-type="relationFilterOptions"]') as HTMLElement;
+ if (!optionsElement) {
+ return;
+ }
+ optionsElement.innerHTML = values.map((value) => {
+ const rowID = value.blockID;
+ if (!rowID) {
+ return "";
+ }
+ const label = value.block?.content || window.siyuan.languages.untitled;
+ return `<button type="button" class="av__relation-filter-option" data-type="relationFilterOption" data-path="${path}" data-id="${escapeAttr(rowID)}">
+<svg class="av__relation-filter-option-icon"><use xlink:href="#iconFile"></use></svg>
+<span class="fn__ellipsis">${escapeHtml(label)}</span>
+<span class="av__relation-filter-option-id">${escapeHtml(rowID.slice(-7))}</span>
+<svg class="av__relation-filter-option-check"><use xlink:href="#${selectedSet.has(rowID) ? "iconCheck" : "iconUncheck"}"></use></svg>
+</button>`;
+ }).join("");
+ renderRelationFilterSelection(path, dropdown, getRelationFilterSelection(dropdown));
+ };
+
+ const searchRelationFilterOptions = (dropdown: HTMLElement, keyword: string) => {
+ const targetAVID = dropdown.dataset.avId;
+ if (!targetAVID) {
+ return;
+ }
+ dropdown.dataset.keyword = keyword;
+ fetchPost("/api/av/getAttributeViewPrimaryKeyValues", {
+ id: targetAVID,
+ keyword,
+ }, response => {
+ if (dropdown.dataset.keyword !== keyword) {
+ return;
+ }
+ renderRelationFilterOptions(dropdown, response.data?.rows?.values || []);
+ });
+ };
+
// operator change:切换操作符,可能需要重渲染(结构变化如 Is between/Is empty)
panelElement.addEventListener("change", (event: Event) => {
const target = event.target as HTMLElement;
@@ -811,12 +1047,14 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// 判断是否结构变化(需重渲染):date 的 Is between 切换、空操作符切换
const filter = getFilterByPath(getEditableFilters(data), path);
const colData = findColData(path);
- const {type: valueType} = resolveFilterValueType(filter, colData);
+ const {type: valueType, isRollup} = resolveFilterValueType(filter, colData);
const newOp = (target as HTMLSelectElement).value;
const oldOp = filter.operator;
const structureChange = (["date", "created", "updated"].includes(valueType) &&
((newOp === "Is between") !== (oldOp === "Is between"))) ||
- ((newOp === "Is empty" || newOp === "Is not empty") !== (oldOp === "Is empty" || oldOp === "Is not empty"));
+ ((newOp === "Is empty" || newOp === "Is not empty") !== (oldOp === "Is empty" || oldOp === "Is not empty")) ||
+ (valueType === "relation" && !isRollup &&
+ (isExactRelationOperator(newOp) !== isExactRelationOperator(oldOp)));
saveRow(row, path, structureChange);
} else if (type === "quantifier" || type?.startsWith("dataDirection") || type?.startsWith("dateType")) {
// 量化器、日期方向、日期类型变化:保存。dateType 切换绝对/相对、dataDirection 切换“当前/前/后”
@@ -942,6 +1180,66 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
event.stopImmediatePropagation();
});
+ // 精确关联筛选:打开远程搜索下拉,并在下拉内增删选中的关联行。
+ panelElement.addEventListener("click", (event: MouseEvent) => {
+ const target = event.target as HTMLElement;
+ const trigger = target.closest('[data-type="relationFilterTrigger"]') as HTMLElement;
+ if (trigger) {
+ const path = trigger.dataset.path;
+ const dropdown = menuElement.querySelector(
+ `[data-type="relationFilterDropdown"][data-path="${path}"]`) as HTMLElement;
+ if (!dropdown) {
+ return;
+ }
+ menuElement.querySelectorAll('[data-type="relationFilterDropdown"]').forEach((element: HTMLElement) => {
+ if (element !== dropdown) {
+ element.style.display = "none";
+ }
+ });
+ if ("none" !== dropdown.style.display) {
+ dropdown.style.display = "none";
+ event.stopImmediatePropagation();
+ return;
+ }
+ dropdown.style.zIndex = (++window.siyuan.zIndex).toString();
+ dropdown.style.visibility = "hidden";
+ dropdown.style.display = "flex";
+ positionRelationFilterDropdown(dropdown, trigger);
+ dropdown.style.visibility = "";
+ const searchInput = dropdown.querySelector('[data-type="relationFilterSearch"]') as HTMLInputElement;
+ searchRelationFilterOptions(dropdown, searchInput?.value || "");
+ searchInput?.focus();
+ event.stopImmediatePropagation();
+ return;
+ }
+
+ const option = target.closest('[data-type="relationFilterOption"]') as HTMLElement;
+ const removeButton = target.closest('[data-type="relationFilterRemove"]') as HTMLElement;
+ const clearButton = target.closest('[data-type="relationFilterClear"]') as HTMLElement;
+ const action = option || removeButton || clearButton;
+ if (!action) {
+ return;
+ }
+ const path = action.dataset.path;
+ const dropdown = action.closest('[data-type="relationFilterDropdown"]') as HTMLElement;
+ if (!path || !dropdown) {
+ return;
+ }
+ let selectedBlockIDs = getRelationFilterSelection(dropdown);
+ if (option) {
+ const rowID = option.dataset.id;
+ selectedBlockIDs = selectedBlockIDs.includes(rowID)
+ ? selectedBlockIDs.filter((blockID) => blockID !== rowID)
+ : [...selectedBlockIDs, rowID];
+ } else if (removeButton) {
+ selectedBlockIDs = selectedBlockIDs.filter((blockID) => blockID !== removeButton.dataset.id);
+ } else {
+ selectedBlockIDs = [];
+ }
+ commitRelationFilterSelection(path, dropdown, selectedBlockIDs);
+ event.stopImmediatePropagation();
+ });
+
// 点击面板空白处收起所有 select 下拉
panelElement.addEventListener("click", (event: MouseEvent) => {
const target = event.target as HTMLElement;
@@ -950,6 +1248,12 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
el.style.display = "none";
});
}
+ if (!target.closest('[data-type="relationFilterTrigger"]') &&
+ !target.closest('[data-type="relationFilterDropdown"]')) {
+ menuElement.querySelectorAll('[data-type="relationFilterDropdown"]').forEach((el: HTMLElement) => {
+ el.style.display = "none";
+ });
+ }
if (!target.closest('[data-type-rel="relation"]') && !target.closest('[data-type="relList"]')) {
menuElement.querySelectorAll('[data-type="relList"]').forEach((el: HTMLElement) => {
el.style.display = "none";
@@ -960,7 +1264,12 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// select 搜索过滤
panelElement.addEventListener("input", (event: InputEvent) => {
const target = event.target as HTMLElement;
- if (target.dataset.type === "filterSearch") {
+ if (target.dataset.type === "relationFilterSearch") {
+ const dropdown = target.closest('[data-type="relationFilterDropdown"]') as HTMLElement;
+ if (dropdown) {
+ searchRelationFilterOptions(dropdown, (target as HTMLInputElement).value);
+ }
+ } else if (target.dataset.type === "filterSearch") {
const path = target.dataset.path;
// 下拉面板在行外,用 path 查找 dropdown 内的选项
const dropdown = menuElement.querySelector(`[data-type="selectDropdown"][data-path="${path}"]`);
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 08141d5790..8d2cb25da9 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -127,6 +127,8 @@ type TAVFilterOperator =
| "<="
| "Contains"
| "Does not contains"
+ | "Contains any item"
+ | "Does not contain any item"
| "Is empty"
| "Is not empty"
| "Starts with"
diff --git a/kernel/api/av.go b/kernel/api/av.go
index 0f2d7bec78..8dbedad27e 100644
--- a/kernel/api/av.go
+++ b/kernel/api/av.go
@@ -428,7 +428,17 @@ func getAttributeViewPrimaryKeyValues(c *gin.Context) {
if keywordArg := arg["keyword"]; nil != keywordArg {
keyword = keywordArg.(string)
}
- attributeViewName, databaseBlockIDs, rows, err := model.GetAttributeViewPrimaryKeyValues(id, keyword, page, pageSize)
+ var blockIDs []string
+ if blockIDsArg := arg["blockIDs"]; nil != blockIDsArg {
+ if blockIDArgs, ok := blockIDsArg.([]any); ok {
+ for _, blockIDArg := range blockIDArgs {
+ if blockID, ok := blockIDArg.(string); ok && "" != blockID {
+ blockIDs = append(blockIDs, blockID)
+ }
+ }
+ }
+ }
+ attributeViewName, databaseBlockIDs, rows, err := model.GetAttributeViewPrimaryKeyValues(id, keyword, blockIDs, page, pageSize)
if err != nil {
ret.Code = -1
ret.Msg = err.Error()
diff --git a/kernel/av/filter.go b/kernel/av/filter.go
index a53acf3062..b9b7ecffa3 100644
--- a/kernel/av/filter.go
+++ b/kernel/av/filter.go
@@ -79,21 +79,23 @@ type RelativeDate struct {
type FilterOperator string
const (
- FilterOperatorIsEqual FilterOperator = "="
- FilterOperatorIsNotEqual FilterOperator = "!="
- FilterOperatorIsGreater FilterOperator = ">"
- FilterOperatorIsGreaterOrEqual FilterOperator = ">="
- FilterOperatorIsLess FilterOperator = "<"
- FilterOperatorIsLessOrEqual FilterOperator = "<="
- FilterOperatorContains FilterOperator = "Contains"
- FilterOperatorDoesNotContain FilterOperator = "Does not contains"
- FilterOperatorIsEmpty FilterOperator = "Is empty"
- FilterOperatorIsNotEmpty FilterOperator = "Is not empty"
- FilterOperatorStartsWith FilterOperator = "Starts with"
- FilterOperatorEndsWith FilterOperator = "Ends with"
- FilterOperatorIsBetween FilterOperator = "Is between"
- FilterOperatorIsTrue FilterOperator = "Is true"
- FilterOperatorIsFalse FilterOperator = "Is false"
+ FilterOperatorIsEqual FilterOperator = "="
+ FilterOperatorIsNotEqual FilterOperator = "!="
+ FilterOperatorIsGreater FilterOperator = ">"
+ FilterOperatorIsGreaterOrEqual FilterOperator = ">="
+ FilterOperatorIsLess FilterOperator = "<"
+ FilterOperatorIsLessOrEqual FilterOperator = "<="
+ FilterOperatorContains FilterOperator = "Contains"
+ FilterOperatorDoesNotContain FilterOperator = "Does not contains"
+ FilterOperatorContainsAnyItem FilterOperator = "Contains any item"
+ FilterOperatorDoesNotContainAnyItem FilterOperator = "Does not contain any item"
+ FilterOperatorIsEmpty FilterOperator = "Is empty"
+ FilterOperatorIsNotEmpty FilterOperator = "Is not empty"
+ FilterOperatorStartsWith FilterOperator = "Starts with"
+ FilterOperatorEndsWith FilterOperator = "Ends with"
+ FilterOperatorIsBetween FilterOperator = "Is between"
+ FilterOperatorIsTrue FilterOperator = "Is true"
+ FilterOperatorIsFalse FilterOperator = "Is false"
)
type FilterQuantifier string
@@ -242,21 +244,35 @@ func evalNode(node *ViewFilter, values []*Value, colIndexByColumn map[string]int
// evalLeaf 对叶子过滤节点做单元格级判定,保留扁平时代 Filter() 的空值特判与 text 豁免语义。
func evalLeaf(filter *ViewFilter, values []*Value, index int, attrView *AttributeView, itemID string, rollupFurtherCollections map[string]Collection, cachedAttrViews map[string]*AttributeView) bool {
if 0 > index || index >= len(values) {
- return false
+ return evalMissingLeaf(filter)
}
- operator := filter.Operator
if nil == values[index] {
- // 单元格无值:Is not empty 不过、Is empty 过、其余操作符一律不过
- if FilterOperatorIsNotEmpty == operator {
- return false
- } else if FilterOperatorIsEmpty == operator {
+ return evalMissingLeaf(filter)
+ }
+
+ return values[index].Filter(filter, attrView, itemID, rollupFurtherCollections, cachedAttrViews)
+}
+
+func evalMissingLeaf(filter *ViewFilter) bool {
+ if nil == filter {
+ return false
+ }
+ switch filter.Operator {
+ case FilterOperatorIsEmpty:
+ return true
+ case FilterOperatorIsNotEmpty:
+ return false
+ case FilterOperatorContainsAnyItem, FilterOperatorDoesNotContainAnyItem:
+ if !isExactRelationFilter(filter) || nil == filter.Value.Relation ||
+ 1 > len(filter.Value.Relation.BlockIDs) {
return true
}
+ return FilterOperatorDoesNotContainAnyItem == filter.Operator
+ default:
+ // 单元格无值时,其余操作符一律不过。
return false
}
-
- return values[index].Filter(filter, attrView, itemID, rollupFurtherCollections, cachedAttrViews)
}
// remapFilterColumns 递归将过滤节点树中所有叶子引用的列 ID 映射为新 ID(用于复制视图)。
@@ -363,6 +379,128 @@ func RemoveSelectOptionFromFilters(filters []*ViewFilter, column, optionContent
return
}
+// RemoveRelationItemsFromFilters 递归移除精确关联筛选中的指定行 ID,并裁剪删空的叶子与分组。
+func RemoveRelationItemsFromFilters(filters []*ViewFilter, column string, itemIDs []string) (ret []*ViewFilter, changed bool) {
+ removedIDs := map[string]bool{}
+ for _, itemID := range itemIDs {
+ removedIDs[itemID] = true
+ }
+
+ for _, filter := range filters {
+ if nil == filter {
+ continue
+ }
+ if filter.IsGroup() {
+ children, childrenChanged := RemoveRelationItemsFromFilters(filter.Filters, column, itemIDs)
+ if !childrenChanged {
+ ret = append(ret, filter)
+ continue
+ }
+ changed = true
+ filter.Filters = children
+ if 0 < len(children) {
+ ret = append(ret, filter)
+ }
+ continue
+ }
+ if filter.Column != column || !isExactRelationFilter(filter) {
+ ret = append(ret, filter)
+ continue
+ }
+ if nil == filter.Value.Relation {
+ changed = true
+ continue
+ }
+
+ blockIDs := filter.Value.Relation.BlockIDs[:0]
+ for _, blockID := range filter.Value.Relation.BlockIDs {
+ if removedIDs[blockID] {
+ changed = true
+ continue
+ }
+ blockIDs = append(blockIDs, blockID)
+ }
+ filter.Value.Relation.BlockIDs = blockIDs
+ if 0 < len(blockIDs) {
+ ret = append(ret, filter)
+ } else {
+ changed = true
+ }
+ }
+ return
+}
+
+// RemoveExactRelationFiltersByColumn 递归移除指定关联列的精确筛选,并裁剪变空的分组。
+func RemoveExactRelationFiltersByColumn(filters []*ViewFilter, column string) (ret []*ViewFilter, changed bool) {
+ for _, filter := range filters {
+ if nil == filter {
+ continue
+ }
+ if filter.IsGroup() {
+ children, childrenChanged := RemoveExactRelationFiltersByColumn(filter.Filters, column)
+ if !childrenChanged {
+ ret = append(ret, filter)
+ continue
+ }
+ changed = true
+ filter.Filters = children
+ if 0 < len(children) {
+ ret = append(ret, filter)
+ }
+ continue
+ }
+ if filter.Column == column && isExactRelationFilter(filter) {
+ changed = true
+ continue
+ }
+ ret = append(ret, filter)
+ }
+ return
+}
+
+func isExactRelationFilter(filter *ViewFilter) bool {
+ return nil != filter && nil != filter.Value && KeyTypeRelation == filter.Value.Type &&
+ (FilterOperatorContainsAnyItem == filter.Operator || FilterOperatorDoesNotContainAnyItem == filter.Operator)
+}
+
+// RemoveRelationFilterItems 移除所有指向目标数据库的精确关联筛选项。
+func (attrView *AttributeView) RemoveRelationFilterItems(targetAvID string, itemIDs []string) (changed bool) {
+ for _, keyValues := range attrView.KeyValues {
+ key := keyValues.Key
+ if nil == key || KeyTypeRelation != key.Type || nil == key.Relation || targetAvID != key.Relation.AvID {
+ continue
+ }
+ for _, view := range attrView.Views {
+ filters, filtersChanged := RemoveRelationItemsFromFilters(view.Filters, key.ID, itemIDs)
+ if !filtersChanged {
+ continue
+ }
+ changed = true
+ view.Filters = filters
+ if 0 == len(view.Filters) {
+ view.Filters = []*ViewFilter{{Combination: FilterCombinationAnd}}
+ }
+ }
+ }
+ return
+}
+
+// RemoveExactRelationFilters 移除指定关联列的全部精确筛选。
+func (attrView *AttributeView) RemoveExactRelationFilters(column string) (changed bool) {
+ for _, view := range attrView.Views {
+ filters, filtersChanged := RemoveExactRelationFiltersByColumn(view.Filters, column)
+ if !filtersChanged {
+ continue
+ }
+ changed = true
+ view.Filters = filters
+ if 0 == len(view.Filters) {
+ view.Filters = []*ViewFilter{{Combination: FilterCombinationAnd}}
+ }
+ }
+ return
+}
+
// RenameSelectOptionInFilters 递归将引用指定列的 select/mSelect 叶子中的旧选项名改为新名与新颜色。
func RenameSelectOptionInFilters(filters []*ViewFilter, column, oldContent, newContent, newColor string) {
for _, f := range filters {
@@ -609,12 +747,30 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID s
}
}
- // 单独处理关联
+ // 单独处理精确关联
+ if KeyTypeRelation == value.Type && nil != filter.Value && KeyTypeRelation == filter.Value.Type &&
+ isExactRelationFilter(filter) {
+ if nil == filter.Value.Relation || 1 > len(filter.Value.Relation.BlockIDs) {
+ return true
+ }
+
+ if nil != value.Relation {
+ for _, blockID := range value.Relation.BlockIDs {
+ for _, filterBlockID := range filter.Value.Relation.BlockIDs {
+ if blockID == filterBlockID {
+ return FilterOperatorContainsAnyItem == filter.Operator
+ }
+ }
+ }
+ }
+ return FilterOperatorDoesNotContainAnyItem == filter.Operator
+ }
+
+ // 单独处理关键字关联
if nil != value.Relation && KeyTypeRelation == value.Type && nil != filter.Value && KeyTypeRelation == filter.Value.Type && nil != filter.Value.Relation {
if 1 > len(filter.Value.Relation.BlockIDs) {
return true
}
-
for _, relationValue := range value.Relation.Contents {
filterValue := &Value{Type: KeyTypeBlock, Block: &ValueBlock{Content: filter.Value.Relation.BlockIDs[0]}}
@@ -1346,6 +1502,9 @@ func (filter *ViewFilter) IsValid() bool {
}
if FilterOperatorIsEmpty != filter.Operator && FilterOperatorIsNotEmpty != filter.Operator {
+ if isExactRelationFilter(filter) {
+ return nil != filter.Value.Relation && 0 < len(filter.Value.Relation.BlockIDs)
+ }
if filter.Value.IsEmpty() && nil == filter.RelativeDate {
return false
}
diff --git a/kernel/av/filter_test.go b/kernel/av/filter_test.go
index 4745a2ffac..15f447a42a 100644
--- a/kernel/av/filter_test.go
+++ b/kernel/av/filter_test.go
@@ -235,6 +235,171 @@ func TestRemoveSelectOptionFromFilters(t *testing.T) {
}
}
+func TestExactRelationFilter(t *testing.T) {
+ value := &Value{
+ Type: KeyTypeRelation,
+ Relation: &ValueRelation{
+ BlockIDs: []string{"row-a", "row-b"},
+ Contents: []*Value{{Type: KeyTypeBlock, Block: &ValueBlock{Content: "同名主键"}}},
+ },
+ }
+ filter := &ViewFilter{
+ Operator: FilterOperatorContainsAnyItem,
+ Value: &Value{
+ Type: KeyTypeRelation,
+ Relation: &ValueRelation{BlockIDs: []string{"row-b", "row-c"}},
+ },
+ }
+ if !value.Filter(filter, nil, "", nil, nil) {
+ t.Fatalf("relation containing a selected row ID should pass")
+ }
+
+ filter.Operator = FilterOperatorDoesNotContainAnyItem
+ if value.Filter(filter, nil, "", nil, nil) {
+ t.Fatalf("relation containing a selected row ID should fail the negative operator")
+ }
+
+ filter.Value.Relation.BlockIDs = []string{"row-c"}
+ if !value.Filter(filter, nil, "", nil, nil) {
+ t.Fatalf("relation without selected row IDs should pass the negative operator")
+ }
+
+ filter.Operator = FilterOperatorContainsAnyItem
+ if value.Filter(filter, nil, "", nil, nil) {
+ t.Fatalf("relation without selected row IDs should fail the positive operator")
+ }
+
+ filter.Value.Relation.BlockIDs = nil
+ if !value.Filter(filter, nil, "", nil, nil) {
+ t.Fatalf("an unconfigured exact relation filter should be ignored")
+ }
+
+ filter.Value.Relation.BlockIDs = []string{"row-c"}
+ filter.Operator = FilterOperatorDoesNotContainAnyItem
+ emptyValue := &Value{Type: KeyTypeRelation}
+ if !emptyValue.Filter(filter, nil, "", nil, nil) {
+ t.Fatalf("an empty relation should pass the negative exact operator")
+ }
+}
+
+func TestExactRelationFilterWithMissingCell(t *testing.T) {
+ filter := &ViewFilter{
+ Column: "relation",
+ Operator: FilterOperatorDoesNotContainAnyItem,
+ Value: &Value{
+ Type: KeyTypeRelation,
+ Relation: &ValueRelation{BlockIDs: []string{"row-a"}},
+ },
+ }
+ columnIndexes := map[string]int{"relation": 0}
+ if !evalNode(filter, []*Value{nil}, columnIndexes, nil, "", nil, nil) {
+ t.Fatalf("a missing relation cell should pass the negative exact operator")
+ }
+ if !evalNode(filter, nil, columnIndexes, nil, "", nil, nil) {
+ t.Fatalf("an absent relation value should pass the negative exact operator")
+ }
+
+ filter.Operator = FilterOperatorContainsAnyItem
+ if evalNode(filter, []*Value{nil}, columnIndexes, nil, "", nil, nil) {
+ t.Fatalf("a missing relation cell should fail the positive exact operator")
+ }
+
+ filter.Value.Relation.BlockIDs = nil
+ if !evalNode(filter, []*Value{nil}, columnIndexes, nil, "", nil, nil) {
+ t.Fatalf("an unconfigured exact filter should be ignored for a missing relation cell")
+ }
+}
+
+func TestRemoveRelationItemsFromFilters(t *testing.T) {
+ exact := func(column string, operator FilterOperator, blockIDs ...string) *ViewFilter {
+ return &ViewFilter{
+ Column: column,
+ Operator: operator,
+ Value: &Value{
+ Type: KeyTypeRelation,
+ Relation: &ValueRelation{BlockIDs: blockIDs},
+ },
+ }
+ }
+ keyword := exact("relation", FilterOperatorContains, "同名主键")
+ root := group(FilterCombinationAnd,
+ exact("relation", FilterOperatorContainsAnyItem, "row-a", "row-b"),
+ group(FilterCombinationOr, exact("relation", FilterOperatorDoesNotContainAnyItem, "row-a")),
+ keyword,
+ )
+
+ got, changed := RemoveRelationItemsFromFilters([]*ViewFilter{root}, "relation", []string{"row-a"})
+ if !changed || 1 != len(got) || 2 != len(got[0].Filters) {
+ t.Fatalf("expected the deleted row ID and emptied nested group to be pruned")
+ }
+ remaining := got[0].Filters[0].Value.Relation.BlockIDs
+ if 1 != len(remaining) || "row-b" != remaining[0] {
+ t.Fatalf("unexpected remaining exact relation IDs: %v", remaining)
+ }
+ if got[0].Filters[1] != keyword {
+ t.Fatalf("keyword relation filter should remain unchanged")
+ }
+}
+
+func TestRemoveExactRelationFiltersByColumn(t *testing.T) {
+ exact := &ViewFilter{
+ Column: "relation",
+ Operator: FilterOperatorContainsAnyItem,
+ Value: &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"row-a"}}},
+ }
+ keyword := &ViewFilter{
+ Column: "relation",
+ Operator: FilterOperatorContains,
+ Value: &Value{Type: KeyTypeRelation, Relation: &ValueRelation{BlockIDs: []string{"主键"}}},
+ }
+ got, changed := RemoveExactRelationFiltersByColumn(
+ []*ViewFilter{group(FilterCombinationAnd, exact, keyword)}, "relation")
+ if !changed || 1 != len(got) || 1 != len(got[0].Filters) || got[0].Filters[0] != keyword {
+ t.Fatalf("only exact filters for the retargeted relation column should be removed")
+ }
+}
+
+func TestAttributeViewRemoveRelationFilterItems(t *testing.T) {
+ exact := func(column string, blockIDs ...string) *ViewFilter {
+ return &ViewFilter{
+ Column: column,
+ Operator: FilterOperatorContainsAnyItem,
+ Value: &Value{
+ Type: KeyTypeRelation,
+ Relation: &ValueRelation{BlockIDs: blockIDs},
+ },
+ }
+ }
+ attrView := &AttributeView{
+ KeyValues: []*KeyValues{
+ {Key: &Key{ID: "target-relation", Type: KeyTypeRelation, Relation: &Relation{AvID: "target"}}},
+ {Key: &Key{ID: "other-relation", Type: KeyTypeRelation, Relation: &Relation{AvID: "other"}}},
+ },
+ Views: []*View{
+ {Filters: []*ViewFilter{group(FilterCombinationAnd,
+ exact("target-relation", "row-a"),
+ exact("other-relation", "row-a"),
+ )}},
+ },
+ }
+ if !attrView.RemoveRelationFilterItems("target", []string{"row-a"}) {
+ t.Fatalf("removing a selected target row should report a filter change")
+ }
+ filters := attrView.Views[0].Filters
+ if 1 != len(filters) || 1 != len(filters[0].Filters) ||
+ "other-relation" != filters[0].Filters[0].Column {
+ t.Fatalf("only filters for relation columns pointing to the target database should change")
+ }
+
+ if !attrView.RemoveRelationFilterItems("other", []string{"row-a"}) {
+ t.Fatalf("removing the final selected row should report a filter change")
+ }
+ if 1 != len(attrView.Views[0].Filters) || !attrView.Views[0].Filters[0].IsGroup() ||
+ 0 != len(attrView.Views[0].Filters[0].Filters) {
+ t.Fatalf("an emptied filter tree should retain an empty AND root group")
+ }
+}
+
func TestRenameSelectOptionInFilters(t *testing.T) {
sel := &ViewFilter{Column: "c1", Operator: FilterOperatorContains, Value: &Value{
Type: KeyTypeMSelect,
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index ec9411b52a..9f213d2237 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -1779,7 +1779,7 @@ func SetDatabaseBlockView(blockID, avID, viewID string) (err error) {
return
}
-func GetAttributeViewPrimaryKeyValues(avID, keyword string, page, pageSize int) (attributeViewName string, databaseBlockIDs []string, keyValues *av.KeyValues, err error) {
+func GetAttributeViewPrimaryKeyValues(avID, keyword string, blockIDs []string, page, pageSize int) (attributeViewName string, databaseBlockIDs []string, keyValues *av.KeyValues, err error) {
waitForSyncingStorages()
attrView, err := av.ParseAttributeView(avID)
@@ -1792,16 +1792,32 @@ func GetAttributeViewPrimaryKeyValues(avID, keyword string, page, pageSize int)
databaseBlockIDs = treenode.GetMirrorAttrViewBlockIDs(avID)
keyValues = attrView.GetBlockKeyValues()
+ if nil == keyValues {
+ keyValues = &av.KeyValues{}
+ return
+ }
var values []*av.Value
+ valuesByBlockID := map[string]*av.Value{}
for _, kv := range keyValues.Values {
if !kv.IsDetached && !treenode.ExistBlockTree(kv.Block.ID) {
continue
}
+ valuesByBlockID[kv.BlockID] = kv
if strings.Contains(strings.ToLower(kv.String(true)), strings.ToLower(keyword)) {
values = append(values, kv)
}
}
+ if 0 < len(blockIDs) {
+ values = nil
+ for _, blockID := range blockIDs {
+ if value := valuesByBlockID[blockID]; nil != value {
+ values = append(values, value)
+ }
+ }
+ keyValues.Values = values
+ return
+ }
keyValues.Values = values
sort.Slice(keyValues.Values, func(i, j int) bool {
@@ -1812,6 +1828,9 @@ func GetAttributeViewPrimaryKeyValues(avID, keyword string, page, pageSize int)
pageSize = 16
}
start := (page - 1) * pageSize
+ if len(keyValues.Values) < start {
+ start = len(keyValues.Values)
+ }
end := min(len(keyValues.Values), start+pageSize)
keyValues.Values = keyValues.Values[start:end]
return
@@ -3235,6 +3254,7 @@ func updateAttributeViewColRelation(operation *Operation) (err error) {
}
if oldDestAvID != operation.ID {
srcAv.RemoveNewItemTemplateFieldValue(operation.KeyID)
+ srcAv.RemoveExactRelationFilters(operation.KeyID)
}
destAdded := false
@@ -4531,6 +4551,7 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
}
}
attrView.RemoveNewItemTemplateRelationItems(avID, srcIDs)
+ attrView.RemoveRelationFilterItems(avID, srcIDs)
regenAttrViewGroups(attrView)
@@ -4538,7 +4559,7 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
if nil != err {
return
}
- if err = removeRelatedNewItemTemplateRelationItems(avID, srcIDs); nil != err {
+ if err = removeRelatedRelationItems(avID, srcIDs); nil != err {
return
}
@@ -4585,7 +4606,7 @@ func removeAttributeViewBlock(srcIDs []string, avID string, tx *Transaction) (er
return
}
-func removeRelatedNewItemTemplateRelationItems(avID string, itemIDs []string) (err error) {
+func removeRelatedRelationItems(avID string, itemIDs []string) (err error) {
for _, relatedAvID := range av.GetSrcAvIDs(avID) {
if relatedAvID == avID {
continue
@@ -4594,7 +4615,9 @@ func removeRelatedNewItemTemplateRelationItems(avID string, itemIDs []string) (e
if nil != parseErr || nil == relatedAv {
continue
}
- if !relatedAv.RemoveNewItemTemplateRelationItems(avID, itemIDs) {
+ templateChanged := relatedAv.RemoveNewItemTemplateRelationItems(avID, itemIDs)
+ filterChanged := relatedAv.RemoveRelationFilterItems(avID, itemIDs)
+ if !templateChanged && !filterChanged {
continue
}
if err = av.SaveAttributeView(relatedAv); nil != err {