Skip to content

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

:bug: Keep recent document controls inside narrow dialogs https://github.com/siyuan-note/siyuan/issues/20799

Daniel629d5906f8cc
diff --git a/app/src/assets/scss/main/_main.scss b/app/src/assets/scss/main/_main.scss
index b41271f46b..5135376de9 100644
--- a/app/src/assets/scss/main/_main.scss
+++ b/app/src/assets/scss/main/_main.scss
@@ -475,7 +475,37 @@ body.body--harmony {
.switch-doc {
max-height: 70vh;
max-width: 100%;
- min-width: 426px;
+ min-width: 0;
+
+ &__header {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ }
+
+ &__title {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow-wrap: anywhere;
+ }
+
+ &__search {
+ flex: 0 1 200px;
+ min-width: 0;
+ max-width: 100%;
+ }
+
+ &__actions {
+ display: flex;
+ align-items: center;
+ max-width: 100%;
+
+ .b3-select {
+ flex: 1;
+ min-width: 0;
+ }
+ }
.b3-list {
padding: 8px 0;
diff --git a/app/src/business/openRecentDocs.layout.test.ts b/app/src/business/openRecentDocs.layout.test.ts
new file mode 100644
index 0000000000..dd0378fdf0
--- /dev/null
+++ b/app/src/business/openRecentDocs.layout.test.ts
@@ -0,0 +1,149 @@
+import * as assert from "node:assert/strict";
+import {execFile} from "node:child_process";
+import {mkdtempSync, readFileSync, realpathSync, 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 {compile} from "sass";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (sources: string[], css: string, languages: Record<string, string>[], themes: Record<string, string>) => {
+ const check: typeof assert = require("node:assert/strict");
+ document.head.innerHTML = `<style id="theme"></style><style>${css}</style>`;
+ document.body.className = "body--windows";
+ const constants = {DIALOG_RECENTDOCS: "recent-docs", LOCAL_DIALOGPOSITION: "dialog-position", TIMEOUT_OPENDIALOG: 0};
+ const load = (source: string, dependencies: Record<string, unknown>) => {
+ const exports: any = {};
+ new Function("exports", "require", source)(exports, (id: string) => {
+ check.ok(id in dependencies, "missing dependency: " + id);
+ return dependencies[id];
+ });
+ return exports;
+ };
+ const closest = {hasClosestByClassName: (element: Element, name: string) => element.closest("." + name)};
+ const resize = load(sources[0], {
+ "../protyle/util/hasClosest": closest, "../constants": {Constants: constants},
+ "../protyle/ui/hideElements": {hideAllElements() {}},
+ "../protyle/util/compatibility": {setStorageVal() {}}, "../layout/getTopBarHeight": {getTopBarHeight: () => 0},
+ });
+ const panels = {destroyDialogBlockPanels() {}, getDialogBlockPanel() {}};
+ const dialog = load(sources[1], {
+ "../util/genID": {genUUID: () => "test-dialog"}, "../util/zIndex": {isAbove: () => false}, "./moveResize": resize,
+ "../util/functions": {isMobile: () => false}, "../protyle/util/compatibility": {},
+ "../protyle": {}, "../constants": {Constants: constants}, "../block/panelOwnership": panels,
+ "./anchoredInput": {},
+ });
+ const clear = load(sources[2], {
+ "../dialog/confirmDialog": {}, "../dialog/message": {}, "../util/fetch": {},
+ "../util/escape": {escapeHtmlTextAndAttr: (value: string) => value},
+ });
+ let detached = false;
+ const api = load(sources[3], {
+ "../config/tabs/fileRuntime": {},
+ "../util/fetch": {fetchPost: (_url: string, _data: unknown, callback: (data: unknown) => void) => callback({data: []})},
+ "../emoji/fileTreeIcon": {}, "../constants": {Constants: constants}, "../util/escape": {},
+ "../util/functions": {isWindow: () => detached}, "../protyle/util/compatibility": {updateHotkeyTip: () => ""},
+ "../layout/getAll": {getAllDocks: (): unknown[] => []}, "../layout/dock/hotkey": {}, "../dialog": dialog,
+ "../protyle/util/hasClosest": closest, "../protyle/ui/hideElements": {},
+ "../block/panelOwnership": panels, "./clearRecentDocs": clear,
+ });
+ let cases = 0;
+ for (const theme of ["daylight", "midnight"]) {
+ document.getElementById("theme").textContent = themes[theme];
+ document.documentElement.dataset.themeMode = theme === "daylight" ? "light" : "dark";
+ for (const lang of languages) {
+ for (const fontSize of [16, 28]) {
+ document.documentElement.style.setProperty("--b3-font-size", fontSize + "px");
+ for (const isDetached of [false, true]) {
+ detached = isDetached;
+ window.siyuan = {zIndex: 1, languages: lang, dialogs: [], storage: {[constants.LOCAL_DIALOGPOSITION]: {}},
+ menus: {menu: {element: document.createElement("div")}},
+ config: {fileTree: {recentDocsSort: "viewedAt"}, keymap: {general: {riffCard: {custom: ""}}}},
+ } as unknown as typeof window.siyuan;
+ api.openRecentDocs();
+ await new Promise(resolve => setTimeout(resolve, 10));
+ const root = window.siyuan.dialogs[0].element;
+ const container = root.querySelector<HTMLElement>(".b3-dialog__container");
+ container.style.transition = "none";
+ container.parentElement.style.display = "block";
+ for (const direction of ["r", "l", "rd", "lt"]) {
+ for (const width of [201, 320, 680]) {
+ Object.assign(container.style, {left: "20px", top: "20px", width: "700px", height: "560px"});
+ const bounds = container.getBoundingClientRect();
+ const x = direction.includes("l") ? bounds.left : bounds.right;
+ const y = direction.includes("t") ? bounds.top : bounds.bottom;
+ const delta = container.clientWidth - width;
+ container.querySelector(".resize__" + direction).dispatchEvent(new MouseEvent("mousedown", {
+ bubbles: true, clientX: x, clientY: y,
+ }));
+ document.dispatchEvent(new MouseEvent("mousemove", {
+ clientX: x + (direction.includes("l") ? 1 : -1) * delta, clientY: y,
+ }));
+ document.dispatchEvent(new MouseEvent("mouseup"));
+ const rect = container.getBoundingClientRect();
+ check.ok(Math.abs(rect.width - width) <= 2, `${direction}: requested ${width}, got ${rect.width}`);
+ const label = `${theme}/${lang.recentDocs}/${fontSize}/${isDetached}/${direction}/${width}`;
+ for (const control of root.querySelectorAll<HTMLElement>(".b3-dialog__header input, .b3-dialog__header select, .b3-dialog__header button")) {
+ const controlRect = control.getBoundingClientRect();
+ check.ok(controlRect.width > 0 && controlRect.left >= rect.left && controlRect.right <= rect.right &&
+ controlRect.top >= rect.top && controlRect.bottom <= rect.bottom, label);
+ }
+ const header = root.querySelector(".b3-dialog__header");
+ check.ok(header.scrollWidth <= header.clientWidth + 1, "header overflow: " + label);
+ const content = root.querySelector(".switch-doc").getBoundingClientRect();
+ check.ok(content.left >= rect.left && content.right <= rect.right, "content overflow: " + label);
+ cases++;
+ }
+ }
+ window.siyuan.dialogs[0].destroy();
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ }
+ }
+ }
+ return cases;
+};
+
+test("recent documents controls stay inside resized main and detached dialogs across languages", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 30000,
+}, async () => {
+ const sources = ["src/dialog/moveResize.ts", "src/dialog/index.ts", "src/business/clearRecentDocs.ts", "src/business/openRecentDocs.ts"]
+ .map(file => transpileModule(readFileSync(file, "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText);
+ const css = compile("src/assets/scss/base.scss", {logger: {warn() {}, debug() {}}}).css;
+ const languages = ["en", "zh-CN", "zh-TW", "ja"].map(lang => JSON.parse(readFileSync(`appearance/langs/${lang}.json`, "utf8")));
+ const themes = Object.fromEntries(["daylight", "midnight"].map(theme => [theme, readFileSync(`appearance/themes/${theme}/theme.css`, "utf8")]));
+ const temporaryRoot = realpathSync(tmpdir());
+ const temporary = mkdtempSync(path.join(temporaryRoot, "siyuan-recent-docs-layout-"));
+ const script = path.join(temporary, "run.cjs");
+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");
+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
+app.disableHardwareAcceleration();
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({show: false, width: 1000, height: 800,
+ webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false}});
+ try {
+ await win.loadURL("about:blank");
+ const result = await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" + browserCases.toString() + ")(" +
+ JSON.stringify(sources) + "," + JSON.stringify(css) + "," + JSON.stringify(languages) + "," + JSON.stringify(themes) + ")")});
+ console.log(JSON.stringify({cases: result}));
+ app.exit(0);
+ } catch (error) {
+ console.error(error);
+ app.exit(1);
+ }
+});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const result = await promisify(execFile)(require("electron"), [script], {env, windowsHide: true, timeout: 25000});
+ assert.deepEqual(JSON.parse(result.stdout.trim().split("\n").at(-1)), {cases: 384});
+ } finally {
+ assert.equal(path.dirname(path.resolve(temporary)), temporaryRoot);
+ assert.ok(path.basename(temporary).startsWith("siyuan-recent-docs-layout-"));
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
diff --git a/app/src/business/openRecentDocs.ts b/app/src/business/openRecentDocs.ts
index a1cb8b104c..b2616ec181 100644
--- a/app/src/business/openRecentDocs.ts
+++ b/app/src/business/openRecentDocs.ts
@@ -110,12 +110,10 @@ export const openRecentDocs = (openOnly = false) => {
fetchPost("/api/storage/getRecentDocs", {sortBy}, (response) => {
const dialog = new Dialog({
positionId: Constants.DIALOG_RECENTDOCS,
- title: `<div class="fn__flex">
-<div class="fn__flex-center">${window.siyuan.languages.recentDocs}</div>
-<div class="fn__flex-1"></div>
-<input spellcheck="false" placeholder="${window.siyuan.languages.searchPlaceholder}" class="b3-text-field fn__size200">
-<span class="fn__space"></span>
-<div class="fn__flex fn__flex-center">
+ title: `<div class="switch-doc__header">
+<div class="switch-doc__title">${window.siyuan.languages.recentDocs}</div>
+<input spellcheck="false" placeholder="${window.siyuan.languages.searchPlaceholder}" class="b3-text-field switch-doc__search">
+<div class="switch-doc__actions">
<select class="b3-select" id="recentDocsSort">
<option value="viewedAt">${window.siyuan.languages.recentViewed}</option>
<option value="created">${window.siyuan.languages.recentCreated}</option>