Skip to content

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

:lipstick: Improve conditional color menus and drag sorting https://github.com/siyuan-note/siyuan/issues/19889

Daniel2a1645426ce9
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
index c8e186cfff..ba8c22f43c 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20240208172514-9dsv6na.sy
@@ -7,7 +7,7 @@
"id": "20240208172514-9dsv6na",
"title": "Database",
"type": "doc",
- "updated": "20260927113016"
+ "updated": "20260927123058"
},
"Children": [
{
@@ -1417,7 +1417,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260927112821-dmce6cp",
- "updated": "20260927112821"
+ "updated": "20260927121828"
},
"Children": [
{
@@ -1468,12 +1468,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260927112821-7hfkus2",
- "updated": "20260927112821"
+ "updated": "20260927123058"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Each rule evaluates its own single-field condition; rules are not combined with AND. Use the up and down buttons to change priority. The first matching rule for each property wins. A matching entry rule colors the remaining area and stops evaluation; earlier property colors are retained. Default background also counts as a match."
+ "Data": "Each rule evaluates its own single-field condition; rules are not combined with AND. Drag a rule by its handle to change priority, including on touch screens. The first matching rule for each property wins. A matching entry rule colors the remaining area and stops evaluation; earlier property colors are retained. Default background also counts as a match."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
index b757a840f7..61509b5c48 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20240208113259-nykkvaq.sy
@@ -7,7 +7,7 @@
"id": "20240208113259-nykkvaq",
"title": "数据库",
"type": "doc",
- "updated": "20260927112821"
+ "updated": "20260927123058"
},
"Children": [
{
@@ -1417,7 +1417,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260927112821-o4rnb9h",
- "updated": "20260927112821"
+ "updated": "20260927121828"
},
"Children": [
{
@@ -1468,12 +1468,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260927112821-zrasje3",
- "updated": "20260927112821"
+ "updated": "20260927123058"
},
"Children": [
{
"Type": "NodeText",
- "Data": "每条规则独立判断一个字段的条件,多条规则不是“并且”关系。使用向上、向下按钮调整优先级,每个属性采用首个命中规则的颜色。整条目规则命中后为剩余区域着色,并停止后续判断;此前已命中的属性颜色会保留。默认背景也会占据匹配优先级。"
+ "Data": "每条规则独立判断一个字段的条件,多条规则不是“并且”关系。拖动规则左侧的抓手调整优先级,触屏设备也可使用,每个属性采用首个命中规则的颜色。整条目规则命中后为剩余区域着色,并停止后续判断;此前已命中的属性颜色会保留。默认背景也会占据匹配优先级。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
index 4286c1053f..b9e8144905 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20240208171522-y7dxcno.sy
@@ -7,7 +7,7 @@
"id": "20240208171522-y7dxcno",
"title": "資料庫",
"type": "doc",
- "updated": "20260927112821"
+ "updated": "20260927123058"
},
"Children": [
{
@@ -1417,7 +1417,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260927112821-431ln3h",
- "updated": "20260927112821"
+ "updated": "20260927121828"
},
"Children": [
{
@@ -1468,12 +1468,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260927112821-er6zp67",
- "updated": "20260927112821"
+ "updated": "20260927123058"
},
"Children": [
{
"Type": "NodeText",
- "Data": "每條規則獨立判斷一個欄位的條件,多條規則不是「且」的關係。使用向上、向下按鈕調整優先順序,每個屬性採用首個符合規則的顏色。整個項目的規則符合後會為其餘區域著色,並停止後續判斷;先前已符合的屬性顏色會保留。預設背景也會占據符合條件的優先順序。"
+ "Data": "每條規則獨立判斷一個欄位的條件,多條規則不是「且」的關係。拖曳規則左側的把手調整優先順序,觸控裝置也可使用,每個屬性採用首個符合規則的顏色。整個項目的規則符合後會為其餘區域著色,並停止後續判斷;先前已符合的屬性顏色會保留。預設背景也會占據符合條件的優先順序。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
index 8f13308e36..0df4d6c11e 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-3eaevtp.sy
@@ -8,7 +8,7 @@
"id": "20240530101000-3eaevtp",
"title": "データベース",
"type": "doc",
- "updated": "20260927112821"
+ "updated": "20260927123058"
},
"Children": [
{
@@ -1418,7 +1418,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260927112821-jd0d1rb",
- "updated": "20260927112821"
+ "updated": "20260927121828"
},
"Children": [
{
@@ -1469,12 +1469,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260927112821-sxrmvva",
- "updated": "20260927112821"
+ "updated": "20260927123058"
},
"Children": [
{
"Type": "NodeText",
- "Data": "各ルールは1つのフィールドの条件を独立して判定し、複数のルールを AND で結合しません。上下のボタンで優先順位を変更できます。各プロパティには最初に一致した色を適用します。エントリ全体のルールが一致すると残りの領域に色を付け、その後の判定を終了します。それ以前のプロパティの色は保持されます。デフォルトの背景も一致として扱います。"
+ "Data": "各ルールは1つのフィールドの条件を独立して判定し、複数のルールを AND で結合しません。ルール左側のハンドルをドラッグして優先順位を変更できます。タッチ画面でも使用できます。各プロパティには最初に一致した色を適用します。エントリ全体のルールが一致すると残りの領域に色を付け、その後の判定を終了します。それ以前のプロパティの色は保持されます。デフォルトの背景も一致として扱います。"
}
]
},
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scss
index ae7dde0ad8..4478f04808 100644
--- a/app/src/assets/scss/business/_av.scss
+++ b/app/src/assets/scss/business/_av.scss
@@ -1,4 +1,4 @@
-// 单字段条件编辑器供筛选菜单和条件颜色对话框共用。
+// 单字段条件编辑器供筛选和条件颜色菜单共用。
@mixin av-filter-editor {
.b3-menu__item.av__filter-row {
margin: 6px 0;
@@ -2038,6 +2038,12 @@
min-width: 290px;
max-width: 290px;
+ &.av__conditional-panel:not(.b3-menu--fullscreen) {
+ width: fit-content;
+ min-width: min(340px, 90vw);
+ max-width: 80vw;
+ }
+
&__items {
max-height: calc(100vh - 60px);
}
@@ -2090,7 +2096,10 @@
opacity: .38;
cursor: not-allowed;
}
+ }
+ &__item,
+ .av__conditional-rule {
&.dragover__top::after,
&.dragover__bottom::after {
content: '';
@@ -2835,24 +2844,37 @@ img.av__cellassetimg {
}
}
-.av__conditional-colors {
- @include av-filter-editor;
-
- max-height: 70vh;
- overflow: auto;
+.av__panel .av__conditional-colors {
+ padding: 8px;
[data-rules] {
display: grid;
- gap: 16px;
- margin-bottom: 16px;
+ gap: 12px;
+ margin-bottom: 8px;
}
.av__conditional-rule {
+ position: relative;
display: grid;
- gap: 8px;
+ gap: 6px;
min-width: 0;
}
+ .av__conditional-condition {
+ display: flex;
+ align-items: flex-start;
+ gap: 6px;
+
+ [data-filter] {
+ flex: 1;
+ min-width: 0;
+ }
+
+ > .fn__flex {
+ flex-shrink: 0;
+ }
+ }
+
.av__filter-rowinner,
.av__filter-date-controls,
.av__filter-date-config,
@@ -2861,7 +2883,7 @@ img.av__cellassetimg {
display: flex;
flex-wrap: wrap;
align-items: center;
- gap: 8px;
+ gap: 6px;
min-width: 0;
}
diff --git a/app/src/assets/scss/component/_menu.scss b/app/src/assets/scss/component/_menu.scss
index 587e8b1f38..e8e6f1b5c6 100644
--- a/app/src/assets/scss/component/_menu.scss
+++ b/app/src/assets/scss/component/_menu.scss
@@ -501,6 +501,11 @@
background-color: transparent;
}
+ &--warning:hover,
+ &--warning:focus-visible {
+ color: var(--b3-theme-error);
+ }
+
&--hint:hover {
color: var(--b3-theme-on-surface-light);
background-color: transparent;
diff --git a/app/src/protyle/render/av/conditionalColor.test.ts b/app/src/protyle/render/av/conditionalColor.test.ts
index 9b4e7ab19c..a43b4f9a3a 100644
--- a/app/src/protyle/render/av/conditionalColor.test.ts
+++ b/app/src/protyle/render/av/conditionalColor.test.ts
@@ -1,6 +1,6 @@
import {test} from "node:test";
import * as assert from "node:assert/strict";
-import {getConditionalBackground, getConditionalCellStyle, getConditionalItemStyle} from "./conditionalColor";
+import {getConditionalBackground, getConditionalCellStyle, getConditionalItemStyle, moveConditionalColorRule} from "./conditionalColor";
test("conditional backgrounds preserve explicit defaults and independent property colors", () => {
assert.equal(getConditionalBackground(null), "");
@@ -12,3 +12,18 @@ test("conditional backgrounds preserve explicit defaults and independent propert
assert.equal(getConditionalCellStyle(row, "other"), "");
assert.equal(getConditionalItemStyle({} as IAVRow), "");
});
+
+test("conditional rule drops preserve values and handle both directions and unchanged positions", () => {
+ const rules: IAVConditionalColorRule[] = ["a", "b", "c"].map(id => ({id, target: "item", color: null,
+ matchOption: false, filter: {column: "text", operator: "Is not empty"}}));
+ const ids = (items: IAVConditionalColorRule[]) => items.map(item => item.id);
+ assert.deepEqual(ids(moveConditionalColorRule(rules, "a", "c", false)), ["b", "c", "a"]);
+ assert.deepEqual(ids(moveConditionalColorRule(rules, "c", "a", true)), ["c", "a", "b"]);
+ assert.deepEqual(ids(moveConditionalColorRule(rules, "a", "c", true)), ["b", "a", "c"]);
+ assert.deepEqual(ids(moveConditionalColorRule(rules, "c", "a", false)), ["a", "c", "b"]);
+ assert.equal(moveConditionalColorRule(rules, "a", "b", true), rules);
+ assert.equal(moveConditionalColorRule(rules, "b", "a", false), rules);
+ assert.equal(moveConditionalColorRule(rules, "a", "a", false), rules);
+ assert.equal(moveConditionalColorRule(rules, "missing", "a", false), rules);
+ assert.deepEqual(ids(rules), ["a", "b", "c"]);
+});
diff --git a/app/src/protyle/render/av/conditionalColor.ts b/app/src/protyle/render/av/conditionalColor.ts
index 6c7ac66e61..73a19f35b6 100644
--- a/app/src/protyle/render/av/conditionalColor.ts
+++ b/app/src/protyle/render/av/conditionalColor.ts
@@ -1,5 +1,20 @@
import {getAVBackgroundColor} from "./color";
+// 按目标条目的前后位置移动规则,未改变顺序时保留原数组。
+export const moveConditionalColorRule = (rules: IAVConditionalColorRule[], sourceID: string,
+ targetID: string, before: boolean) => {
+ const sourceIndex = rules.findIndex(rule => rule.id === sourceID);
+ const targetIndex = rules.findIndex(rule => rule.id === targetID);
+ if (sourceIndex < 0 || targetIndex < 0 || sourceIndex === targetIndex) {
+ return rules;
+ }
+ const next = rules.slice();
+ const [source] = next.splice(sourceIndex, 1);
+ const insertIndex = next.findIndex(rule => rule.id === targetID) + (before ? 0 : 1);
+ next.splice(insertIndex, 0, source);
+ return next.every((rule, index) => rule === rules[index]) ? rules : next;
+};
+
export const getConditionalBackground = (color: IAVCellSelectValue) =>
color ? (color.color ? getAVBackgroundColor(color) : "var(--b3-theme-background)") : "";
diff --git a/app/src/protyle/render/av/conditionalColorMenu.test.ts b/app/src/protyle/render/av/conditionalColorMenu.test.ts
new file mode 100644
index 0000000000..95d189f073
--- /dev/null
+++ b/app/src/protyle/render/av/conditionalColorMenu.test.ts
@@ -0,0 +1,103 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {moveConditionalColorRule} from "./conditionalColor";
+
+test("returning from the color menu during field loading does not restore or bind a detached panel", async () => {
+ let finishLoading: () => void;
+ const loading = new Promise<void>(resolve => { finishLoading = resolve; });
+ const methods = {} as typeof import("./conditionalColorMenu");
+ const content = {
+ isConnected: true,
+ querySelector: () => ({}),
+ addEventListener: () => assert.fail("must not bind a closed panel"),
+ };
+ const menu = {
+ innerHTML: "view settings", classList: {add() {}, remove() {}},
+ querySelector: () => content,
+ };
+ let resized = 0;
+ runInNewContext(transpileModule(readFileSync("src/protyle/render/av/conditionalColorMenu.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+ }).outputText, {
+ exports: methods,
+ window: {siyuan: {config: {}, languages: {conditionalColors: "Colors"}}},
+ require: (name: string) => name === "./filter" ? {prepareFilterColumns: () => loading} : {},
+ });
+ const pending = methods.openConditionalColorsMenu({
+ protyle: {options: {}} as IProtyle,
+ blockElement: {} as HTMLElement,
+ data: {view: {conditionalColors: []}} as IAV,
+ menuElement: menu as unknown as HTMLElement,
+ onResize: () => { resized++; },
+ });
+ assert.match(menu.innerHTML, /data-type="go-config"/);
+ content.isConnected = false;
+ menu.innerHTML = "view settings";
+ finishLoading();
+ await pending;
+ assert.equal(menu.innerHTML, "view settings");
+ assert.equal(resized, 1);
+});
+
+test("dropping a rule saves the new priority with an undo snapshot and SVG deletion remains clickable", async () => {
+ const methods = {} as typeof import("./conditionalColorMenu");
+ const listeners = new Map<string, (event: unknown) => void>();
+ const transactions: Array<{perform: IOperation[], undo: IOperation[]}> = [];
+ const source = {dataset: {ruleId: "a"}, style: {opacity: ".38"}};
+ const target = {dataset: {ruleId: "c"}, getBoundingClientRect: () => ({top: 100, height: 40})};
+ const root = {
+ innerHTML: "", contains: (element: unknown) => element === source || element === target,
+ querySelectorAll: (): HTMLElement[] => [],
+ addEventListener: (type: string, callback: (event: unknown) => void) => listeners.set(type, callback),
+ };
+ const content = {
+ isConnected: true,
+ querySelector: (selector: string) => selector === "[data-rules]" ? root : {disabled: false},
+ addEventListener: (type: string, callback: (event: unknown) => void) => listeners.set(type, callback),
+ };
+ const window = {siyuan: {config: {}, languages: {}, dragElement: source}};
+ runInNewContext(transpileModule(readFileSync("src/protyle/render/av/conditionalColorMenu.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+ }).outputText, {
+ exports: methods, window,
+ require: (name: string) => ({
+ "./filter": {prepareFilterColumns: async () => {}},
+ "./view": {getFieldsByData: () => [{id: "text", type: "text"}]},
+ "../../../util/escape": {escapeAttr: String},
+ "./conditionalColor": {getConditionalBackground: () => "", moveConditionalColorRule},
+ "../../wysiwyg/transaction": {transaction: (_protyle: IProtyle, perform: IOperation[], undo: IOperation[]) => {
+ transactions.push({perform, undo});
+ }},
+ })[name] || {},
+ });
+ const rules: IAVConditionalColorRule[] = ["a", "b", "c"].map(id => ({id, target: "item", color: null,
+ matchOption: false, filter: {column: "text", operator: "Is not empty"}}));
+ await methods.openConditionalColorsMenu({
+ protyle: {options: {}} as IProtyle,
+ blockElement: {dataset: {nodeId: "carrier"}} as unknown as HTMLElement,
+ data: {id: "database", viewID: "view", view: {conditionalColors: rules}} as IAV,
+ menuElement: {classList: {add() {}, remove() {}}, querySelector: () => content} as unknown as HTMLElement,
+ onResize() {},
+ });
+ assert.match(root.innerHTML, /draggable="true" data-conditional-drag/);
+ assert.match(root.innerHTML, /b3-menu__action b3-menu__action--show/);
+ assert.match(root.innerHTML, /b3-menu__action--warning/);
+ assert.doesNotMatch(root.innerHTML, /data-action="(?:up|down)"/);
+ const event = {target: {closest: () => target}, clientY: 139, preventDefault() {}, stopPropagation() {}};
+ listeners.get("drop")(event);
+ const ids = (operation: IOperation) => {
+ assert.equal(operation.action, "setAttrViewConditionalColors");
+ return Array.from(operation.data as IAVConditionalColorRule[], item => item.id);
+ };
+ assert.deepEqual(ids(transactions[0].perform[0]), ["b", "c", "a"]);
+ assert.deepEqual(ids(transactions[0].undo[0]), ["a", "b", "c"]);
+ assert.equal(source.style.opacity, "");
+ assert.equal(window.siyuan.dragElement, undefined);
+ const remove = {dataset: {action: "remove"}, tagName: "svg", closest: () => source};
+ listeners.get("click")({...event, target: {closest: () => remove}});
+ assert.deepEqual(ids(transactions[1].perform[0]), ["b", "c"]);
+ assert.deepEqual(ids(transactions[1].undo[0]), ["b", "c", "a"]);
+});
diff --git a/app/src/protyle/render/av/conditionalColorDialog.ts b/app/src/protyle/render/av/conditionalColorMenu.ts
similarity index 65%
rename from app/src/protyle/render/av/conditionalColorDialog.ts
rename to app/src/protyle/render/av/conditionalColorMenu.ts
index f8de34b269..8c21957f24 100644
--- a/app/src/protyle/render/av/conditionalColorDialog.ts
+++ b/app/src/protyle/render/av/conditionalColorMenu.ts
@@ -1,37 +1,51 @@
-import {Dialog} from "../../../dialog";
import {Menu} from "../../../plugin/Menu";
import {escapeAttr, escapeHtml} from "../../../util/escape";
-import {isMobile} from "../../../util/functions";
import {transaction} from "../../wysiwyg/transaction";
import {getFieldsByData} from "./view";
import {bindInlineFilterEvents, genEmptyFilterValue, getFiltersHTML, prepareFilterColumns} from "./filter";
import {AV_MANAGE_CUSTOM_COLORS_TYPE, getAVColorGridHTML, getAVColorOrder, getAVCustomColors} from "./color";
-import {getConditionalBackground} from "./conditionalColor";
+import {getConditionalBackground, moveConditionalColorRule} from "./conditionalColor";
import {openAVCustomColorDialog} from "./colorDialog";
+import {openViewSettingMenu} from "./viewSettingMenu";
const cloneRules = (rules: IAVConditionalColorRule[]) => JSON.parse(JSON.stringify(rules || [])) as IAVConditionalColorRule[];
-export const openConditionalColors = async (protyle: IProtyle, blockElement: HTMLElement, data: IAV) => {
+export const openConditionalColorsMenu = async (options: {
+ protyle: IProtyle,
+ blockElement: HTMLElement,
+ data: IAV,
+ menuElement: HTMLElement,
+ onResize: () => void,
+}) => {
+ const {protyle, blockElement, data, menuElement, onResize} = options;
if (protyle.disabled || window.siyuan.isPublish || window.siyuan.config.readonly ||
protyle.options.history?.created || protyle.options.history?.snapshot) {
return;
}
- await prepareFilterColumns(data);
- const fields = getFieldsByData(data).filter(field => field.type !== "lineNumber");
let rules = cloneRules(data.view.conditionalColors);
const lang = window.siyuan.languages;
- const dialog = new Dialog({
- title: lang.conditionalColors,
- width: isMobile() ? "92vw" : "760px",
- content: `<div class="b3-dialog__content av__conditional-colors">
+ menuElement.classList.remove("av__filter-panel");
+ menuElement.classList.add("av__conditional-panel");
+ menuElement.innerHTML = `<div class="b3-menu__items">
+<button class="b3-menu__item" data-type="nobg">
+ <span class="block__icon" data-type="go-config"><svg><use xlink:href="#iconLeft"></use></svg></span>
+ <span class="b3-menu__label ft__center">${lang.conditionalColors}</span>
+</button>
+<button class="b3-menu__separator"></button>
+<div class="av__conditional-colors">
<div class="ft__on-surface">${lang.conditionalColorsTip}</div>
<div class="fn__hr"></div><div data-rules></div>
-<button type="button" class="b3-button b3-button--outline" data-action="add"><svg><use xlink:href="#iconAdd"></use></svg>${lang.new}</button>
-</div>`,
- });
- const root = dialog.element.querySelector<HTMLElement>("[data-rules]");
- const icon = (action: string, name: string, label: string, disabled = false) =>
- `<button type="button" class="block__icon block__icon--show ariaLabel" data-action="${action}" aria-label="${escapeAttr(label)}"${disabled ? " disabled" : ""}><svg><use xlink:href="#${name}"></use></svg></button>`;
+<button type="button" class="b3-menu__item" data-action="add" disabled><svg class="b3-menu__icon"><use xlink:href="#iconAdd"></use></svg><span class="b3-menu__label">${lang.new}</span></button>
+</div></div>`;
+ const panelElement = menuElement.querySelector<HTMLElement>(".av__conditional-colors");
+ const root = panelElement.querySelector<HTMLElement>("[data-rules]");
+ onResize();
+ await prepareFilterColumns(data);
+ // 返回上级或关闭菜单后,不再更新已经移除的面板。
+ if (!panelElement.isConnected) {
+ return;
+ }
+ const fields = getFieldsByData(data).filter(field => field.type !== "lineNumber");
const save = (next: IAVConditionalColorRule[], redraw = true) => {
const previous = cloneRules(rules);
rules = cloneRules(next);
@@ -47,11 +61,12 @@ export const openConditionalColors = async (protyle: IProtyle, blockElement: HTM
save(rules.map(rule => rule.id === id ? {...rule, ...patch} : rule), redraw);
};
const render = () => {
- root.innerHTML = rules.map((rule, index) => `<div class="av__conditional-rule" data-rule-id="${escapeAttr(rule.id)}">
-<div class="fn__flex"><span class="fn__flex-1">${index + 1}</span>
-${icon("up", "iconUp", lang.moveToUp, index === 0)}${icon("down", "iconDown", lang.moveToDown, index === rules.length - 1)}
-${icon("remove", "iconTrashcan", lang.delete)}</div>
+ root.innerHTML = rules.map(rule => `<div class="av__conditional-rule" data-rule-id="${escapeAttr(rule.id)}">
+<div class="av__conditional-condition">
+<span class="block__icon block__icon--show fn__grab ariaLabel" draggable="true" data-conditional-drag aria-label="${lang.move}"><svg><use xlink:href="#iconDrag"></use></svg></span>
<div data-filter></div>
+<div class="fn__flex">
+<svg class="b3-menu__action b3-menu__action--show b3-menu__action--warning ariaLabel" data-action="remove" role="button" tabindex="0" aria-label="${lang.delete}"><use xlink:href="#iconTrashcan"></use></svg></div></div>
<div class="av__conditional-controls">
<select class="b3-select" data-action="target" aria-label="${lang.conditionalColorTarget}">
<option value="item"${rule.target === "item" ? " selected" : ""}>${lang.conditionalColorItem}</option>
@@ -80,33 +95,60 @@ ${data.viewType === "table" || rule.target === "property" ? `<option value="prop
},
});
});
- dialog.element.querySelector<HTMLButtonElement>('[data-action="add"]').disabled = rules.length >= 100 || fields.length === 0;
+ panelElement.querySelector<HTMLButtonElement>('[data-action="add"]').disabled = rules.length >= 100 || fields.length === 0;
+ onResize();
};
- dialog.element.addEventListener("change", event => {
+ panelElement.addEventListener("change", event => {
const target = event.target as HTMLSelectElement;
if (target.dataset.action === "target") {
update(target.closest<HTMLElement>("[data-rule-id]").dataset.ruleId,
{target: target.value === "property" ? "property" : "item"});
}
});
- dialog.element.addEventListener("click", event => {
+ root.addEventListener("drop", (event: DragEvent) => {
+ const source = window.siyuan.dragElement;
+ if (!source?.dataset.ruleId || !root.contains(source)) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ const target = (event.target as HTMLElement).closest<HTMLElement>("[data-rule-id]");
+ source.style.opacity = "";
+ window.siyuan.dragElement = undefined;
+ root.querySelectorAll(".dragover__top, .dragover__bottom").forEach(element => {
+ element.classList.remove("dragover__top", "dragover__bottom");
+ });
+ if (!target || !root.contains(target)) {
+ return;
+ }
+ const rect = target.getBoundingClientRect();
+ const next = moveConditionalColorRule(rules, source.dataset.ruleId, target.dataset.ruleId,
+ event.clientY <= rect.top + rect.height / 2);
+ if (next !== rules) {
+ save(next);
+ }
+ });
+ panelElement.addEventListener("keydown", event => {
+ const target = (event.target as HTMLElement).closest<HTMLElement>('[data-action="remove"]');
+ if (target && (event.key === "Enter" || event.key === " ")) {
+ event.preventDefault();
+ event.stopPropagation();
+ target.dispatchEvent(new MouseEvent("click", {bubbles: true}));
+ }
+ });
+ panelElement.addEventListener("click", event => {
const target = (event.target as HTMLElement).closest<HTMLElement>("[data-action]");
- if (!target || target.tagName !== "BUTTON") {
+ if (!target || (target.tagName !== "BUTTON" && target.dataset.action !== "remove")) {
return;
}
+ event.preventDefault();
+ event.stopPropagation();
const action = target.dataset.action;
const id = target.closest<HTMLElement>("[data-rule-id]")?.dataset.ruleId;
const index = rules.findIndex(rule => rule.id === id);
const rule = rules[index];
if (action === "remove") {
save(rules.filter(rule => rule.id !== id));
- } else if (action === "up" || action === "down") {
- const next = cloneRules(rules);
- const to = index + (action === "up" ? -1 : 1);
- if (index >= 0 && to >= 0 && to < next.length) {
- next.splice(to, 0, next.splice(index, 1)[0]);
- save(next);
- }
} else if (action === "add") {
const menu = new Menu();
fields.forEach(field => menu.addItem({label: escapeHtml(field.name), click: () => {
@@ -115,8 +157,7 @@ ${data.viewType === "table" || rule.target === "property" ? `<option value="prop
matchOption: ["select", "mSelect"].includes(field.type),
filter: {column: field.id, operator: field.type === "checkbox" ? operator : "Is not empty", value}}]);
}}));
- const rect = target.getBoundingClientRect();
- menu.open({x: rect.left, y: rect.bottom, h: rect.height});
+ openViewSettingMenu(menu, target);
} else if (action === "color" && rule) {
const menu = new Menu();
menu.addItem({label: lang.default, checked: !rule.matchOption && !rule.color?.color,
@@ -142,8 +183,7 @@ ${data.viewType === "table" || rule.target === "property" ? `<option value="prop
});
},
});
- const rect = target.getBoundingClientRect();
- menu.open({x: rect.left, y: rect.bottom, h: rect.height});
+ openViewSettingMenu(menu, target);
}
});
render();
diff --git a/app/src/protyle/render/av/filter.ts b/app/src/protyle/render/av/filter.ts
index 999fb1d855..912ae7eea5 100644
--- a/app/src/protyle/render/av/filter.ts
+++ b/app/src/protyle/render/av/filter.ts
@@ -307,7 +307,7 @@ export const getFiltersHTML = (data: IAV, single = false) => {
: "";
const inlineHTML = genInlineFilterHTML(node, colData, path);
const leafAndOrHTML = 0 === index ? genWhenLabel() : 1 === index ? genAndOrSelect(groupPath, groupCombination) : genAndOrLabel(groupCombination);
- return `<div class="${single ? "" : "b3-menu__item "}av__filter-row" data-path="${path}" data-column="${node.column}">${single ? "" : leafAndOrHTML}<div class="fn__flex-1 av__filter-rowinner">${fieldWrapper}${valueSourceSelect}${inlineHTML}</div>${single ? "" : `<svg class="b3-menu__action ariaLabel" data-position="4west" data-type="moreFilter" data-path="${path}" aria-label="${window.siyuan.languages.more}"><use xlink:href="#iconMore"></use></svg>`}</div>`;
+ return `<div class="${single ? "" : "b3-menu__item "}av__filter-row" data-path="${path}" data-column="${node.column}">${single ? "" : leafAndOrHTML}<div class="${single ? "" : "fn__flex-1 "}av__filter-rowinner">${fieldWrapper}${valueSourceSelect}${inlineHTML}</div>${single ? "" : `<svg class="b3-menu__action ariaLabel" data-position="4west" data-type="moreFilter" data-path="${path}" aria-label="${window.siyuan.languages.more}"><use xlink:href="#iconMore"></use></svg>`}</div>`;
};
const isRootGroup = data.view.filters.length === 1 && (data.view.filters[0].filters || data.view.filters[0].combination);
@@ -934,7 +934,8 @@ export const commitFilter = (data: IAV, path: string, newFilter: IAVFilter, prot
// bindInlineFilterEvents 绑定内联筛选编辑的事件(事件委托到面板)。即时保存。
export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, protyle: IProtyle, blockID: string,
avID: string, filterOperation?: FilterEditorOptions) => {
- // 防重复绑定:事件委托绑在 panelElement 上,同一面板实例只需绑一次
+ // 事件由最近的已绑定编辑器处理,避免嵌套条件修改外层视图筛选。
+ // 同一面板实例只绑定一次。
if (panelElement.dataset.filterEventsBound === "true") {
return;
}
@@ -1091,6 +1092,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// operator change:切换操作符,可能需要重渲染(结构变化如 Is between/Is empty)
panelElement.addEventListener("change", (event: Event) => {
const target = event.target as HTMLElement;
+ if (target.closest('[data-filter-events-bound="true"]') !== panelElement) {
+ return;
+ }
const type = target.dataset.type;
if (!type) return;
const path = target.dataset.path;
@@ -1159,6 +1163,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// 值输入 blur / Enter 保存
panelElement.addEventListener("blur", (event: Event) => {
const target = event.target as HTMLElement;
+ if (target.closest('[data-filter-events-bound="true"]') !== panelElement) {
+ return;
+ }
if (target.dataset.type === "filterValue" || target.dataset.type?.startsWith("absDate") || target.dataset.type?.startsWith("relCount")) {
const path = target.dataset.path;
const row = getRow(target);
@@ -1168,6 +1175,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
panelElement.addEventListener("keydown", (event: KeyboardEvent) => {
const target = event.target as HTMLElement;
+ if (target.closest('[data-filter-events-bound="true"]') !== panelElement) {
+ return;
+ }
if (event.key !== "Enter" || event.isComposing) return;
if (target.dataset.type === "filterValue") {
const path = target.dataset.path;
@@ -1182,6 +1192,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// select 下拉触发:点击展开/收起选项面板
panelElement.addEventListener("click", (event: MouseEvent) => {
const target = event.target as HTMLElement;
+ if (target.closest('[data-filter-events-bound="true"]') !== panelElement) {
+ return;
+ }
// 先处理 selectTrigger(展开/收起下拉)
const trigger = target.closest('[data-type="selectTrigger"]') as HTMLElement;
if (trigger) {
@@ -1269,6 +1282,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// 精确关联筛选:打开远程搜索下拉,并在下拉内增删选中的关联行。
panelElement.addEventListener("click", (event: MouseEvent) => {
const target = event.target as HTMLElement;
+ if (target.closest('[data-filter-events-bound="true"]') !== panelElement) {
+ return;
+ }
const trigger = target.closest('[data-type="relationFilterTrigger"]') as HTMLElement;
if (trigger) {
const path = trigger.dataset.path;
@@ -1329,6 +1345,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// 点击面板空白处收起所有 select 下拉
panelElement.addEventListener("click", (event: MouseEvent) => {
const target = event.target as HTMLElement;
+ if (target.closest('[data-filter-events-bound="true"]') !== panelElement) {
+ return;
+ }
if (!target.closest('[data-type="selectTrigger"]') && !target.closest('[data-type="selectDropdown"]')) {
menuElement.querySelectorAll('[data-type="selectDropdown"]').forEach((el: HTMLElement) => {
el.style.display = "none";
@@ -1350,6 +1369,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// select 搜索过滤
panelElement.addEventListener("input", (event: InputEvent) => {
const target = event.target as HTMLElement;
+ if (target.closest('[data-filter-events-bound="true"]') !== panelElement) {
+ return;
+ }
if (target.dataset.type === "relationFilterSearch") {
const dropdown = target.closest('[data-type="relationFilterDropdown"]') as HTMLElement;
if (dropdown) {
@@ -1418,6 +1440,9 @@ export const bindInlineFilterEvents = (panelElement: HTMLElement, data: IAV, pro
// relation 候选点击填值
panelElement.addEventListener("click", (event: MouseEvent) => {
const target = event.target as HTMLElement;
+ if (target.closest('[data-filter-events-bound="true"]') !== panelElement) {
+ return;
+ }
const item = target.closest('[data-type="relList"] .b3-list-item') as HTMLElement;
if (!item) return;
const listEl = item.closest('[data-type="relList"]') as HTMLElement;
diff --git a/app/src/protyle/render/av/filterEditor.test.ts b/app/src/protyle/render/av/filterEditor.test.ts
new file mode 100644
index 0000000000..4b5e2862c6
--- /dev/null
+++ b/app/src/protyle/render/av/filterEditor.test.ts
@@ -0,0 +1,48 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+test("nested color conditions do not change the parent view filter, including capture events", () => {
+ const methods = {} as typeof import("./filter");
+ const fields = [{id: "text", type: "text"}];
+ runInNewContext(transpileModule(readFileSync("src/protyle/render/av/filter.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},
+ }).outputText, {
+ exports: methods,
+ require: (name: string) => name === "./view" ? {getFieldsByData: () => fields} : {},
+ });
+ const createEditor = () => {
+ const listeners = new Map<string, Array<(event: unknown) => void>>();
+ const panel = {
+ dataset: {}, innerHTML: "", querySelector: () => ({}),
+ addEventListener: (type: string, listener: (event: unknown) => void) => {
+ listeners.set(type, [...listeners.get(type) || [], listener]);
+ },
+ };
+ const data = {view: {filters: [{column: "text", operator: "Is not empty", value: {type: "text"}}]}} as IAV;
+ let saves = 0;
+ methods.bindInlineFilterEvents(panel as unknown as HTMLElement, data, {} as IProtyle, "block", "database", {
+ root: panel as unknown as HTMLElement,
+ render: () => "updated condition",
+ save: () => { saves++; },
+ });
+ return {panel, data, listeners, get saves() { return saves; }};
+ };
+ const outer = createEditor();
+ const inner = createEditor();
+ const target = {
+ dataset: {type: "fieldSelect", path: "0"}, value: "text",
+ closest: () => inner.panel,
+ };
+ for (const listeners of outer.listeners.values()) {
+ listeners.forEach(listener => listener({target, key: "Enter"}));
+ }
+ assert.equal(outer.saves, 0);
+ assert.equal(outer.data.view.filters[0].operator, "Is not empty");
+ inner.listeners.get("change").forEach(listener => listener({target}));
+ assert.equal(inner.saves, 1);
+ assert.equal(inner.data.view.filters[0].operator, "Contains");
+ assert.equal(inner.panel.innerHTML, "updated condition");
+});
diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.ts
index 1720b3a093..4f303685c8 100644
--- a/app/src/protyle/render/av/openMenuPanel.ts
+++ b/app/src/protyle/render/av/openMenuPanel.ts
@@ -1,4 +1,4 @@
-import {openConditionalColors} from "./conditionalColorDialog";
+import {openConditionalColorsMenu} from "./conditionalColorMenu";
import {isTableLikeView} from "./viewType";
import {transaction} from "../../wysiwyg/transaction";
import {fetchPost} from "../../../util/fetch";
@@ -347,7 +347,12 @@ export const openMenuPanel = (options: {
let counter = 0;
avPanelElement.addEventListener("dragstart", (event: DragEvent) => {
const sourceElement = event.target as HTMLElement;
- window.siyuan.dragElement = sourceElement.closest<HTMLElement>('[data-option-row="true"]') || sourceElement;
+ counter = 0;
+ const conditionalRule = sourceElement.closest("[data-conditional-drag]")?.closest<HTMLElement>("[data-rule-id]");
+ window.siyuan.dragElement = conditionalRule || sourceElement.closest<HTMLElement>('[data-option-row="true"]') || sourceElement;
+ if (conditionalRule) {
+ event.dataTransfer.setDragImage(conditionalRule, 16, 14);
+ }
if (window.siyuan.dragElement.dataset.relationType === "selected") {
const primaryElement = window.siyuan.dragElement.querySelector(".av__relation-table-primary");
if (primaryElement) {
@@ -660,11 +665,11 @@ export const openMenuPanel = (options: {
return;
}
const target = event.target as HTMLElement;
- let targetElement = target.closest<HTMLElement>('[data-option-row="true"]') ||
+ let targetElement = target.closest<HTMLElement>(".av__conditional-rule") || target.closest<HTMLElement>('[data-option-row="true"]') ||
hasClosestByAttribute(target, "draggable", "true");
if (!targetElement) {
const nearbyElement = document.elementFromPoint(event.clientX, event.clientY - 1);
- targetElement = nearbyElement?.closest<HTMLElement>('[data-option-row="true"]') ||
+ targetElement = nearbyElement?.closest<HTMLElement>(".av__conditional-rule") || nearbyElement?.closest<HTMLElement>('[data-option-row="true"]') ||
hasClosestByAttribute(nearbyElement, "draggable", "true");
}
if (!targetElement || targetElement === window.siyuan.dragElement) {
@@ -698,6 +703,11 @@ export const openMenuPanel = (options: {
counter++;
});
avPanelElement.addEventListener("dragend", () => {
+ counter = 0;
+ dragoverElement = undefined;
+ avPanelElement.querySelectorAll(".dragover__bottom, .dragover__top").forEach(element => {
+ element.classList.remove("dragover__bottom", "dragover__top");
+ });
if (window.siyuan.dragElement) {
window.siyuan.dragElement.style.opacity = "";
window.siyuan.dragElement = undefined;
@@ -859,6 +869,10 @@ export const openMenuPanel = (options: {
event.stopPropagation();
break;
} else if (type === "go-config") {
+ if (menuElement.classList.contains("av__conditional-panel")) {
+ delete menuElement.dataset.positionX;
+ }
+ menuElement.classList.remove("av__conditional-panel");
if (options.filterOperation) {
avPanelElement.remove();
openMenuPanel({
@@ -911,8 +925,19 @@ export const openMenuPanel = (options: {
event.stopPropagation();
break;
} else if (type === "goConditionalColors") {
- avPanelElement.remove();
- openConditionalColors(options.protyle, options.blockElement as HTMLElement, data);
+ window.siyuan.menus.menu.remove();
+ openConditionalColorsMenu({
+ protyle: options.protyle,
+ blockElement: options.blockElement as HTMLElement,
+ data,
+ menuElement,
+ onResize: () => {
+ if (!isMobile()) {
+ delete menuElement.dataset.positionX;
+ setPosition(menuElement, tabRect.right - menuElement.clientWidth, tabRect.bottom, tabRect.height, 0, true);
+ }
+ },
+ });
event.preventDefault();
event.stopPropagation();
break;