An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Preserve backlink database filter panel position https://github.com/siyuan-note/siyuan/issues/20802
Danielac99e80264ab
diff --git a/app/src/layout/dock/backlinkDatabaseFilter.test.ts b/app/src/layout/dock/backlinkDatabaseFilter.test.tsindex dc9e064828..d7b33347c5 100644--- a/app/src/layout/dock/backlinkDatabaseFilter.test.ts+++ b/app/src/layout/dock/backlinkDatabaseFilter.test.ts@@ -12,6 +12,7 @@ const setup = () => {let opened: IOpenAVPanelOptions;let resolve: (value: unknown) => void;const requests: unknown[] = [];+ let targetRect = {right: 1500, bottom: 460, width: 24, height: 24} as DOMRect;const methods = {} as typeof import("./backlinkDatabaseFilter");runInNewContext(transpileModule(readFileSync("src/layout/dock/backlinkDatabaseFilter.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},@@ -29,12 +30,13 @@ const setup = () => {});const options = {id: "topic", notebook: "", keyword: "", filter: {dailyNote: "all", excludeSelf: false, excludedNotebookIDs: []} as IBacklinkSourceFilter,- target: {} as HTMLElement,+ target: {getBoundingClientRect: () => targetRect} as HTMLElement,isCurrent: () => current,getSelected: () => selected,apply: (value?: IBacklinkSourceFilter["database"]) => { selected = value; },};return {methods, options, requests, respond: (value: unknown) => resolve(value),+ hideTarget: () => { targetRect = {right: 0, bottom: 0, width: 0, height: 0} as DOMRect; },stale: () => { current = false; }, get selected() { return selected; }, get opened() { return opened; }};};@@ -69,3 +71,14 @@ test("database candidates arriving after the target changes do not reopen a filtassert.equal((await pending).length, 0);assert.equal(h.opened, undefined);});++test("database filtering retains the toolbar position across candidate loading and source refresh", async () => {+ const h = setup();+ const pending = h.methods.loadBacklinkDatabaseFilterMenu(h.options);+ h.hideTarget();+ h.respond({code: 0, data: [{id: "tasks", name: "Tasks", keys: []}]});+ const menu = await pending;+ menu[2].click(null, null);+ assert.equal(h.opened.anchorRect.right, 1500);+ assert.equal(h.opened.anchorRect.bottom, 460);+});diff --git a/app/src/layout/dock/backlinkDatabaseFilter.ts b/app/src/layout/dock/backlinkDatabaseFilter.tsindex 0c52b8e264..625182b559 100644--- a/app/src/layout/dock/backlinkDatabaseFilter.ts+++ b/app/src/layout/dock/backlinkDatabaseFilter.ts@@ -32,6 +32,7 @@ export const loadBacklinkDatabaseFilterMenu = async (options: {getSelected: () => IBacklinkSourceFilter["database"];apply: (database?: IBacklinkSourceFilter["database"]) => void;}): Promise<IMenu[]> => {+ const anchorRect = options.target.getBoundingClientRect();const response = await fetchSyncPost("/api/ref/getBacklinkDatabases", {id: options.id,notebook: options.notebook,@@ -70,6 +71,7 @@ export const loadBacklinkDatabaseFilterMenu = async (options: {protyle: options.protyle,blockElement: options.target,anchorElement: options.target,+ anchorRect,type: "filters",data: getBacklinkDatabaseFilterData(database, filters),filterOperation: {diff --git a/app/src/layout/dock/backlinkDatabaseFilterPosition.test.ts b/app/src/layout/dock/backlinkDatabaseFilterPosition.test.tsnew file mode 100644index 0000000000..c7c71de404--- /dev/null+++ b/app/src/layout/dock/backlinkDatabaseFilterPosition.test.ts@@ -0,0 +1,128 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {compileString} from "sass";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import type {BacklinkDatabase} from "../../types/api";++const browserCases = async (sources: string[], css: string) => {+ const check: typeof assert = require("node:assert/strict");+ const load = (source: string, dependencies: object) => {+ const exports: Record<string, any> = {};+ new Function("exports", "require", source)(exports, () => dependencies);+ return exports;+ };+ const style = document.createElement("style");+ style.textContent = css;+ document.head.append(style);+ const toolbar = document.createElement("div");+ toolbar.innerHTML = '<button style="position:fixed;left:1420px;top:430px;width:24px;height:24px">Filter</button>';+ document.body.append(toolbar);+ const target = toolbar.firstElementChild as HTMLElement;+ const originalRect = target.getBoundingClientRect();+ let selected: {avID: string, filters: IAVFilter[]};+ let finishFields: () => void;+ let context: {menuElement: HTMLElement};+ const fieldsReady = new Promise<void>(resolve => { finishFields = resolve; });+ window.siyuan = {zIndex: 0, config: {editor: {backlinkContainChildren: true}},+ languages: {reset: "Reset"}, menus: {menu: {remove() {}}}} as unknown as typeof window.siyuan;+ const position = load(sources[0], {getTopBarHeight: () => 42});+ const panel = load(sources[1], new Proxy({+ ...position, getPageSize: () => ({}), isMobile: () => false,+ getFieldsByData: (data: IAV) => { check.ok("columns" in data.view); return data.view.columns; },+ escapeAttr: (value: string) => value,+ prepareFilterColumns: () => fieldsReady,+ getAVPanelDescriptor: () => ({render: (value: typeof context & {html: string}) => {+ context = value;+ value.html = '<div style="height:80px">Filter conditions</div>';+ return true;+ }}),+ }, {get: (object, key) => key in object ? Reflect.get(object, key) : () => {}}));+ const databases: BacklinkDatabase[] = [{id: "tasks", name: "Tasks", keys: []}];+ const databaseFilter = load(sources[2], {+ ...panel, escapeHtml: (value: string) => value,+ fetchSyncPost: async () => ({code: 0, data: databases}),+ });+ const items: IMenu[] = await databaseFilter.loadBacklinkDatabaseFilterMenu({+ id: "topic", notebook: "", keyword: "", filter: {}, target,+ isCurrent: () => true, getSelected: () => selected,+ apply: (value: typeof selected) => {+ selected = value;+ target.replaceWith(target.cloneNode(true));+ },+ });+ items[2].click(null, null);+ check.equal(target.isConnected, false);+ finishFields();+ await new Promise(requestAnimationFrame);+ const menu = document.querySelector<HTMLElement>(".av__panel > .b3-menu");+ check.ok(menu);+ let rect = menu.getBoundingClientRect();+ check.ok(Math.abs(rect.right - originalRect.right) <= 1, "the filter panel stays beside the clicked backlink toolbar");+ check.equal(rect.top, originalRect.bottom);+ window.dispatchEvent(new Event("resize"));+ check.equal(menu.getBoundingClientRect().top, originalRect.bottom, "a detached button cannot reset the anchor to the origin");+ toolbar.replaceChildren(target);+ target.style.left = "760px";+ target.style.top = "300px";+ window.dispatchEvent(new Event("resize"));+ rect = menu.getBoundingClientRect();+ check.equal(rect.right, target.getBoundingClientRect().right);+ check.equal(rect.top, target.getBoundingClientRect().bottom);+ context.menuElement.style.height = "600px";+ window.dispatchEvent(new Event("resize"));+ rect = menu.getBoundingClientRect();+ check.ok(rect.top >= 42 && rect.bottom <= window.innerHeight, "growing conditions remain inside the viewport");+ document.querySelector(".av__panel").remove();+ toolbar.remove();+ style.remove();+ return "Backlink database filter positioning passed";+};++test("backlink database filters stay anchored during source refresh, field loading and window resizing", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const sources = ["../../util/setPosition.ts", "../../protyle/render/av/openMenuPanel.ts", "backlinkDatabaseFilter.ts"].map(file =>+ transpileModule(readFileSync(path.join(__dirname, file), "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText);+ const css = compileString('@use "component/menu"; @use "business/av";', {+ loadPaths: [path.join(__dirname, "../../assets/scss")], logger: {warn: () => {}},+ }).css;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-backlink-filter-position-"));+ const script = path.join(temporary, "run.cjs");+ const expression = "const __name = value => value; (" + browserCases.toString() + ")(" + JSON.stringify(sources) + "," + JSON.stringify(css) + ")";+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, width: 1800, height: 760, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(expression)}));+ win.destroy();+ app.exit(0);+ } catch (error) {+ console.error(error);+ win.destroy();+ app.exit(1);+ }+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 25000, windowsHide: true});+ assert.match(result.stdout, /Backlink database filter positioning passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-backlink-filter-position-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex 3ffc1feae3..ef566fa375 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -29,6 +29,16 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {options.destroyCallback?.();return;}+ let anchorRect = options.anchorRect;+ const getAnchorRect = () => {+ const rect = options.anchorElement?.getBoundingClientRect();+ if (rect?.width > 0 && rect.height > 0) {+ anchorRect = rect;+ }+ return anchorRect;+ };+ // 在菜单关闭和字段异步加载前保留锚点,按钮被隐藏或替换时继续使用有效坐标。+ getAnchorRect();const avID = options.data?.id || options.blockElement.getAttribute("data-av-id");const avPageSize = getPageSize(options.blockElement);// config/properties/sorts/filters/contextFilter/switcher 菜单只需要字段/视图元数据,不需要行数据,@@ -148,13 +158,13 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {inputElement.dispatchEvent(new Event("input"));}};- let tabRect = options.anchorElement?.getBoundingClientRect() ||+ let tabRect = getAnchorRect() ||options.blockElement.querySelector(`.av__views, .av__row[data-col-id="${options.colId}"] > .block__logo`)?.getBoundingClientRect();const resizeMenu = ignoreRows && !isMobile() ? () => {if (!menuElement.isConnected) {return;}- tabRect = options.anchorElement?.getBoundingClientRect() || options.blockElement.querySelector(".av__views")?.getBoundingClientRect();+ tabRect = getAnchorRect() || options.blockElement.querySelector(".av__views")?.getBoundingClientRect();if (!tabRect) {return;}diff --git a/app/src/protyle/render/av/panels/lifecycle.test.ts b/app/src/protyle/render/av/panels/lifecycle.test.tsindex caa838844d..3978f72f78 100644--- a/app/src/protyle/render/av/panels/lifecycle.test.ts+++ b/app/src/protyle/render/av/panels/lifecycle.test.ts@@ -10,6 +10,8 @@ const createPanel = (mobile = false) => {const calls: string[] = [];const events = new Map<string, (event: unknown) => unknown>();const observers: Array<() => void> = [];+ const positions: Array<{left: number, top: number}> = [];+ let onMenuRemove = () => {};let context: IAVPanelContext;let existing = false;let backTarget: HTMLElement;@@ -33,13 +35,17 @@ const createPanel = (mobile = false) => {bind: (value: IAVPanelContext) => { value.closeCB = () => calls.push("closeCB"); }}),dispatchAVPanelAction: (value: IAVPanelContext) => { assert.equal(value, context); calls.push("action"); return "handled"; },Constants: {TIMEOUT_TRANSITION: 0},+ setPosition: (_element: HTMLElement, left: number, top: number) => {+ calls.push("setPosition");+ positions.push({left, top});+ },}, {get: (target, key) => key in target ? Reflect.get(target, key) : () => calls.push(String(key))});const exports: Record<string, unknown> = {};const source = readFileSync(path.join(__dirname, "../openMenuPanel.ts"), "utf8");runInNewContext(transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021}}).outputText, {exports, require: () => dependencies,document: {querySelector: () => existing ? panel : null, body: {insertAdjacentHTML: () => { existing = true; calls.push("insert"); }}},- window: {siyuan: {zIndex: 0, menus: {menu: {remove: () => calls.push("menu.remove"), element: {classList: classes}}}},+ window: {siyuan: {zIndex: 0, menus: {menu: {remove: () => { calls.push("menu.remove"); onMenuRemove(); }, element: {classList: classes}}}},addEventListener: (name: string, callback: (event: unknown) => unknown) => {calls.push("resize.bind");events.set(name, callback);@@ -49,7 +55,8 @@ const createPanel = (mobile = false) => {});const open = exports.openMenuPanel as typeof import("../openMenuPanel").openMenuPanel;const click = (detail: unknown) => events.get("click")({detail, target: {dataset: {}, closest: (): null => null}, preventDefault: () => {}, stopPropagation: () => {}});- return {open, options, calls, click, observers, menuClasses, resize: () => events.get("resize")({}),+ return {open, options, calls, click, observers, menuClasses, positions, resize: () => events.get("resize")({}),+ onMenuRemove: (callback: () => void) => { onMenuRemove = callback; },setBackTarget: () => {backTarget = {dataset: {type: "go-properties"}, closest: (): null => null} as unknown as HTMLElement;},@@ -75,7 +82,7 @@ for (const mobile of [false, true]) {const saved: IAVFilter[][] = [];h.options.type = "filters";h.options.protyle = undefined;- h.options.anchorElement = {getBoundingClientRect: () => ({right: 400, bottom: 50, height: 20})} as HTMLElement;+ h.options.anchorElement = {getBoundingClientRect: () => ({right: 400, bottom: 50, width: 24, height: 20})} as HTMLElement;h.options.filterOperation = {save: filters => saved.push(filters)};h.open(h.options);await Promise.resolve();@@ -91,6 +98,32 @@ for (const mobile of [false, true]) {});}+test("query panels retain their anchor while loading and use a visible anchor again on resize", async () => {+ const h = createPanel();+ h.options.type = "filters";+ let rect = {right: 1500, bottom: 460, width: 24, height: 24} as DOMRect;+ h.options.anchorElement = {getBoundingClientRect: () => rect} as HTMLElement;+ h.onMenuRemove(() => { rect = {right: 0, bottom: 0, width: 0, height: 0} as DOMRect; });+ h.open(h.options);+ await Promise.resolve();+ assert.deepEqual(h.positions.at(-1), {left: 1400, top: 460});+ h.resize();+ assert.deepEqual(h.positions.at(-1), {left: 1400, top: 460});+ rect = {right: 800, bottom: 300, width: 24, height: 24} as DOMRect;+ h.resize();+ assert.deepEqual(h.positions.at(-1), {left: 700, top: 300});+});++test("query panels use the caller's captured position when a source refresh replaced the button", async () => {+ const h = createPanel();+ h.options.type = "filters";+ h.options.anchorElement = {getBoundingClientRect: () => ({right: 0, bottom: 0, width: 0, height: 0})} as HTMLElement;+ h.options.anchorRect = {right: 1500, bottom: 460, width: 24, height: 24} as DOMRect;+ h.open(h.options);+ await Promise.resolve();+ assert.deepEqual(h.positions.at(-1), {left: 1400, top: 460});+});+test("mobile back returns within a database panel and closes the root through its save callback", async () => {const h = createPanel(true);h.options.keepMenuOpen = true;diff --git a/app/src/protyle/render/av/panels/types.ts b/app/src/protyle/render/av/panels/types.tsindex b548d79378..fb611af3d9 100644--- a/app/src/protyle/render/av/panels/types.ts+++ b/app/src/protyle/render/av/panels/types.ts@@ -14,6 +14,7 @@ export interface IOpenAVPanelOptions {keepMenuOpen?: boolean;filterOperation?: FilterEditorOptions;anchorElement?: HTMLElement;+ anchorRect?: DOMRect;requireExplicitChange?: boolean;}