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: Keep automation settings stationary when conditions expand https://github.com/siyuan-note/siyuan/issues/20547
Daniel59d679a91c5b
diff --git a/app/src/assets/scss/business/_av.scss b/app/src/assets/scss/business/_av.scssindex 2cdfd2956d..8655cac6ad 100644--- a/app/src/assets/scss/business/_av.scss+++ b/app/src/assets/scss/business/_av.scss@@ -2075,6 +2075,14 @@width: 520px;min-width: min(340px, calc(100vw - 32px));max-width: calc(100vw - 32px);+ max-height: var(--av-automation-max-height, calc(100vh - 60px));+ display: flex;+ flex-direction: column;++ > .b3-menu__items {+ min-height: 0;+ max-height: none;+ }}&__items {diff --git a/app/src/protyle/render/av/automationPosition.ts b/app/src/protyle/render/av/automationPosition.tsnew file mode 100644index 0000000000..071cba4a36--- /dev/null+++ b/app/src/protyle/render/av/automationPosition.ts@@ -0,0 +1,11 @@+import {getTopBarHeight} from "../../../layout/getTopBarHeight";+import {setPosition} from "../../../util/setPosition";++export const setAutomationMenuPosition = (menuElement: HTMLElement, anchor: DOMRect) => {+ const margin = 8;+ const topBarHeight = getTopBarHeight();+ // 为靠近窗口底部的入口预留可操作区域,位置只随锚点和窗口变化,不随表单内容变化。+ const top = Math.max(topBarHeight, Math.min(anchor.bottom, window.innerHeight - 320 - margin));+ menuElement.style.setProperty("--av-automation-max-height", Math.max(0, window.innerHeight - top - margin) + "px");+ setPosition(menuElement, anchor.right - menuElement.clientWidth, top);+};diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.tsindex f8ee065714..eef130601e 100644--- a/app/src/protyle/render/av/openMenuPanel.ts+++ b/app/src/protyle/render/av/openMenuPanel.ts@@ -6,6 +6,7 @@ import {isTableLikeView} from "./viewType";import {transaction} from "../../wysiwyg/transaction";import {fetchPost} from "../../../util/fetch";import {setPosition} from "../../../util/setPosition";+import {setAutomationMenuPosition} from "./automationPosition";import {setColOption} from "./select";import {prepareFilterColumns} from "./filter";import {Constants} from "../../../constants";@@ -156,7 +157,11 @@ export const openMenuPanel = (options: IOpenAVPanelOptions) => {delete menuElement.dataset.positionTop;delete menuElement.dataset.positionBottom;delete menuElement.dataset.positionX;- setPosition(menuElement, tabRect.right - menuElement.clientWidth, tabRect.bottom, tabRect.height, 0, true);+ if (menuElement.classList.contains("av__automation-panel")) {+ setAutomationMenuPosition(menuElement, tabRect);+ } else {+ setPosition(menuElement, tabRect.right - menuElement.clientWidth, tabRect.bottom, tabRect.height, 0, true);+ }} : undefined;if (resizeMenu) {window.addEventListener("resize", resizeMenu);diff --git a/app/src/protyle/render/av/panels/config.ts b/app/src/protyle/render/av/panels/config.tsindex bc8ae8e61a..05d84be6e5 100644--- a/app/src/protyle/render/av/panels/config.ts+++ b/app/src/protyle/render/av/panels/config.ts@@ -1,5 +1,6 @@import { getViewHTML, bindViewEvent, getFieldsByData } from "../view";import { openAutomationMenu } from "../automation";+import { setAutomationMenuPosition } from "../automationPosition";import { isMobile } from "../../../../util/functions";import { setPosition } from "../../../../util/setPosition";import { getLayoutHTML, bindLayoutEvent, updateLayout } from "../layout";@@ -28,8 +29,10 @@ export const configPanel: IAVPanelDescriptor = {menuElement: context.menuElement,onResize: () => {if (!isMobile()) {- delete context.menuElement.dataset.positionX;- setPosition(context.menuElement, context.tabRect.right - context.menuElement.clientWidth, context.tabRect.bottom, context.tabRect.height, 0, true);+ const anchor = context.options.blockElement.querySelector(".av__views")?.getBoundingClientRect();+ if (anchor) {+ setAutomationMenuPosition(context.menuElement, anchor);+ }}},});diff --git a/app/src/protyle/render/av/panels/lifecycle.test.ts b/app/src/protyle/render/av/panels/lifecycle.test.tsindex b144000134..270e3afda9 100644--- a/app/src/protyle/render/av/panels/lifecycle.test.ts+++ b/app/src/protyle/render/av/panels/lifecycle.test.ts@@ -12,7 +12,9 @@ const createPanel = (mobile = false) => {const observers: Array<() => void> = [];let context: IAVPanelContext;let existing = false;- const menu = {isConnected: true, clientWidth: 100, dataset: {}, querySelector: (): null => null};+ const menuClasses = new Set<string>();+ const menu = {isConnected: true, clientWidth: 100, dataset: {}, querySelector: (): null => null,+ classList: {contains: (name: string) => menuClasses.has(name)}};const panel = {isConnected: true, lastElementChild: menu, parentElement: {},remove: () => { existing = false; panel.isConnected = false; calls.push("remove"); },addEventListener: (name: string, callback: (event: unknown) => unknown) => events.set(name, callback)};@@ -36,15 +38,32 @@ const createPanel = (mobile = false) => {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}}}},- addEventListener: () => calls.push("resize.bind"), removeEventListener: () => calls.push("resize.unbind")},+ addEventListener: (name: string, callback: (event: unknown) => unknown) => {+ calls.push("resize.bind");+ events.set(name, callback);+ }, removeEventListener: () => calls.push("resize.unbind")},MutationObserver: class { constructor(callback: () => void) { observers.push(callback); } observe() {} disconnect() {} },setTimeout: (callback: () => void) => callback(),});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, get context() { return context; }, setExisting: () => { existing = true; }};+ return {open, options, calls, click, observers, menuClasses, resize: () => events.get("resize")({}),+ get context() { return context; }, setExisting: () => { existing = true; }};};+test("window resizing uses the automation height constraint only while its panel is open", () => {+ const h = createPanel();+ h.open(h.options);+ h.calls.length = 0;+ h.menuClasses.add("av__automation-panel");+ h.resize();+ assert.deepEqual(h.calls, ["setAutomationMenuPosition"]);+ h.calls.length = 0;+ h.menuClasses.delete("av__automation-panel");+ h.resize();+ assert.deepEqual(h.calls, ["setPosition"]);+});+test("opening an existing panel destroys it without fetching or binding another panel", () => {const h = createPanel();h.setExisting();diff --git a/app/tests/avAutomationPosition.test.js b/app/tests/avAutomationPosition.test.jsnew file mode 100644index 0000000000..082ed27679--- /dev/null+++ b/app/tests/avAutomationPosition.test.js@@ -0,0 +1,116 @@+const assert = require("node:assert/strict");+const {mkdtempSync, readFileSync, rmSync} = require("node:fs");+const path = require("node:path");+const os = require("node:os");+const {test} = require("node:test");+const sass = require("sass");+const ts = require("typescript");++const compile = file => ts.transpileModule(readFileSync(path.join(__dirname, "../src", file), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022},+}).outputText;++const browserCases = (css, positionCode, automationCode, mobile) => {+ const check = require("node:assert/strict");+ document.head.innerHTML = "<style></style>";+ document.querySelector("style").textContent = css;+ const modules = {"../layout/getTopBarHeight": {getTopBarHeight: () => 32},+ "../../../layout/getTopBarHeight": {getTopBarHeight: () => 32}};+ const load = code => {+ const result = {};+ new Function("exports", "require", code)(result, name => modules[name]);+ return result;+ };+ modules["../../../util/setPosition"] = load(positionCode);+ const {setAutomationMenuPosition} = load(automationCode);+ document.body.innerHTML = `<div class="av__panel"><div class="b3-menu av__automation-panel${mobile ? " b3-menu--fullscreen b3-menu--sheet" : ""}">+<div class="b3-menu__items"><button class="b3-menu__item">Automation</button><div class="av__automation"><div class="av__automation-body"><select class="b3-select"><option>Added</option><option>Block</option></select><div data-content></div><button data-last>Preview</button></div></div></div></div></div>`;+ const menu = document.querySelector(".b3-menu");+ const items = menu.querySelector(".b3-menu__items");+ const content = menu.querySelector("[data-content]");+ if (mobile) {+ menu.style.height = "400px";+ content.style.height = "1200px";+ const maxHeight = getComputedStyle(menu).maxHeight;+ menu.classList.remove("av__automation-panel");+ check.equal(getComputedStyle(menu).maxHeight, maxHeight, "desktop height cap must not affect mobile sheets");+ check.equal(menu.getBoundingClientRect().height, 400);+ return;+ }+ for (const bottom of [200, window.innerHeight - 30]) {+ const anchor = {right: window.innerWidth - 20, bottom};+ content.style.height = "100px";+ setAutomationMenuPosition(menu, anchor);+ const initialTop = menu.getBoundingClientRect().top;+ const initialLeft = menu.getBoundingClientRect().left;+ for (const height of [1400, 2200, 100]) {+ content.style.height = height + "px";+ setAutomationMenuPosition(menu, anchor);+ const rect = menu.getBoundingClientRect();+ check.equal(rect.top, initialTop, "growing and shrinking conditions must not move the panel");+ check.equal(rect.left, initialLeft);+ check.ok(rect.bottom <= window.innerHeight - 7, "panel stays inside the viewport");+ check.ok(rect.left >= 0 && rect.right <= window.innerWidth);+ if (height > 100) {+ check.ok(items.scrollHeight > items.clientHeight, "long conditions scroll inside the menu");+ items.scrollTop = items.scrollHeight;+ const last = menu.querySelector("[data-last]").getBoundingClientRect();+ check.ok(last.bottom <= rect.bottom && last.top >= rect.top, "last action is reachable");+ const scrollTop = items.scrollTop;+ setAutomationMenuPosition(menu, anchor);+ check.equal(items.scrollTop, scrollTop, "repositioning preserves the scroll offset");+ }+ }+ }+ menu.classList.remove("av__automation-panel");+ check.equal(getComputedStyle(menu).maxHeight, "none", "returning to settings removes the automation height cap");+};++if (process.versions.electron && process.type === "browser") {+ const {app, BrowserWindow} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.whenReady().then(async () => {+ console.log("Automation renderer ready");+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ win.webContents.on("console-message", event => console.error(event.message));+ try {+ for (const [name, theme, width, height, fontSize] of [+ ["base", "daylight", 1280, 900, 16], ["base", "midnight", 420, 600, 24],+ ["base", "daylight", 800, 360, 32], ["mobile", "daylight", 420, 800, 16],+ ]) {+ win.setSize(width, height);+ console.log(`Checking ${name}/${theme}/${width}/${height}`);+ await win.loadURL("data:text/html,<html><body></body></html>");+ const css = readFileSync(path.join(__dirname, `../appearance/themes/${theme}/theme.css`), "utf8") ++ sass.compile(path.join(__dirname, `../src/assets/scss/${name}.scss`), {logger: sass.Logger.silent}).css ++ `body {font-size:${fontSize}px; --b3-font-size:${fontSize}px;}`;+ await win.webContents.executeJavaScript(`try { (${browserCases.toString()})(${[+ css, compile("util/setPosition.ts"), compile("protyle/render/av/automationPosition.ts"), name === "mobile",+ ].map(value => JSON.stringify(value)).join(",")}) } catch (error) { console.error(error.stack); throw error; }`);+ }+ console.log("Automation position cases passed");+ app.exit(0);+ } catch (error) {+ console.error(error);+ app.exit(1);+ }+ });+} else {+ test("automation panels keep their position and scroll in desktop layouts without changing mobile sheets", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 120000,+ }, async () => {+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-automation-position-"));+ try {+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 115000});+ assert.match(stdout, /Automation position cases passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));+ assert.ok(path.basename(profile).startsWith("siyuan-automation-position-"));+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}