An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support document previews in recent documents dialog https://github.com/siyuan-note/siyuan/issues/20117
Daniele51083bcb0eb
diff --git a/app/src/block/Panel.ts b/app/src/block/Panel.tsindex bf7c20940f..f3d90a7905 100644--- a/app/src/block/Panel.ts+++ b/app/src/block/Panel.ts@@ -27,6 +27,7 @@ import {} from "./panelRemoval";import {getBlockPanelLoadPlan} from "./panelLoad";import {positionBlockPanel} from "./panelPosition";+import {isBlockPanelTargetAvailable, registerBlockPanelOwner} from "./panelOwnership";const BLOCK_PANEL_EDITOR_MIN_HEIGHT = 155;@@ -73,6 +74,7 @@ export class BlockPanel {this.element = document.createElement("div");this.element.classList.add("block__popover");+ registerBlockPanelOwner(this.element, this.targetElement);const parentElement = hasClosestByClassName(this.targetElement, "block__popover", true);let level = 1;@@ -595,7 +597,9 @@ export class BlockPanel {if (!document.contains(this.element)) {return;}- if (this.canShow && !this.canShow()) {+ if ((this.canShow && !this.canShow()) ||+ (!this.element.classList.contains("block__popover--open") && this.targetElement &&+ !isBlockPanelTargetAvailable(this.targetElement))) {// 尚未展示的浮窗不能关闭其他浮窗上的菜单。this.destroy(false);return;diff --git a/app/src/block/panelOwnership.test.ts b/app/src/block/panelOwnership.test.tsnew file mode 100644index 0000000000..14649b741f--- /dev/null+++ b/app/src/block/panelOwnership.test.ts@@ -0,0 +1,500 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isClassDeclaration, ModuleKind, ScriptTarget, transpileModule} from "typescript";++const loadSource = (source: string, globals: Record<string, unknown>) => {+ const compiled = transpileModule(source, {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ const exports: any = {};+ runInNewContext(compiled, {exports, ...globals});+ return exports;+};++const loadDialogMethods = (globals: Record<string, unknown>) => {+ const path = "src/dialog/index.ts";+ const source = createSourceFile(path, readFileSync(path, "utf8"), ScriptTarget.ES2021, true);+ const declaration = source.statements.find(statement => isClassDeclaration(statement) &&+ statement.name?.text === "Dialog");+ assert.ok(declaration && isClassDeclaration(declaration));+ const names = ["destroying", "trapFocus", "destroy"];+ const members = declaration.members.filter(member => names.includes(member.name?.getText(source)));+ assert.equal(members.length, names.length);+ return loadSource(`export class Dialog {${members.map(member => member.getText(source)).join("\n")}}`, globals).Dialog;+};++class TestElement {+ public parentElement: TestElement | null = null;+ public children: TestElement[] = [];+ public dataset: Record<string, string> = {};+ public style = {zIndex: "0", visibility: "visible"};+ public tabIndex = -1;+ public isContentEditable = false;+ public disabled = false;+ public hidden = false;+ public inert = false;+ private attributes = new Set<string>();+ private classes = new Set<string>();+ public classList = {+ add: (value: string) => this.classes.add(value),+ remove: (value: string) => this.classes.delete(value),+ contains: (value: string) => this.classes.has(value),+ };++ constructor(private document: any, public tagName = "div", className = "") {+ className.split(" ").filter(Boolean).forEach(value => this.classes.add(value));+ if (["button", "input", "select", "textarea"].includes(tagName)) {+ this.tabIndex = 0;+ }+ }++ get isConnected(): boolean {+ return this === this.document.body || !!this.parentElement?.isConnected;+ }++ public append(child: TestElement) {+ child.remove();+ child.parentElement = this;+ this.children.push(child);+ return child;+ }++ public remove() {+ if (this.contains(this.document.activeElement)) {+ this.document.activeElement = this.document.body;+ }+ if (this.parentElement) {+ this.parentElement.children = this.parentElement.children.filter(child => child !== this);+ this.parentElement = null;+ }+ }++ public contains(element: TestElement): boolean {+ return !!element && (element === this || this.children.some(child => child.contains(element)));+ }++ public matches(selector: string): boolean {+ if (selector.includes(",")) {+ return selector.split(",").some(value => this.matches(value.trim()));+ }+ if (selector.startsWith(".")) {+ return this.classes.has(selector.slice(1));+ }+ if (selector === ":disabled") {+ return this.disabled;+ }+ if (selector === "[inert]") {+ return this.inert;+ }+ if (selector === '[data-dialog-closing="true"]') {+ return this.dataset.dialogClosing === "true";+ }+ if (selector === "[contenteditable]") {+ return this.hasAttribute("contenteditable") || this.isContentEditable;+ }+ if (selector === "[tabindex]") {+ return this.hasAttribute("tabindex");+ }+ return this.tagName === selector;+ }++ public closest(selector: string): TestElement | null {+ return this.matches(selector) ? this : this.parentElement?.closest(selector) || null;+ }++ public querySelectorAll(selector: string): TestElement[] {+ return this.children.flatMap(child => [+ ...(child.matches(selector) ? [child] : []), ...child.querySelectorAll(selector),+ ]);+ }++ public querySelector(selector: string) {+ return this.querySelectorAll(selector)[0] || null;+ }++ public hasAttribute(name: string) {+ return this.attributes.has(name);+ }++ public setAttribute(name: string, value: string) {+ this.attributes.add(name);+ if (name === "tabindex") {+ this.tabIndex = Number(value);+ }+ }++ public getClientRects() {+ return this.isConnected && !this.hidden ? [{}] : [];+ }++ public focus() {+ this.document.activeElement = this;+ }+}++const keyboardEvent = (shiftKey = false, key = "Tab") => ({+ key,+ shiftKey,+ defaultPrevented: false,+ propagationStopped: false,+ preventDefault() { this.defaultPrevented = true; },+ stopPropagation() { this.propagationStopped = true; },+});++const fixture = () => {+ const timers: Array<() => void> = [];+ const removedListeners: unknown[][] = [];+ const document: any = {+ removeEventListener: (...args: unknown[]) => removedListeners.push(args),+ getElementById: (): null => null,+ };+ const element = (tagName = "div", className = "") => new TestElement(document, tagName, className);+ document.body = element("body");+ document.activeElement = document.body;+ const menu = {element: document.body.append(element()), remove: (): void => undefined};+ const window = {siyuan: {blockPanels: [] as any[], dialogs: [] as any[], menus: {menu}}};+ const globals = {window, document};+ const ownership = loadSource(readFileSync("src/block/panelOwnership.ts", "utf8"), globals);+ const zIndex = loadSource(readFileSync("src/util/zIndex.ts", "utf8"), globals);+ const Dialog = loadDialogMethods({+ ...globals, ...ownership, ...zIndex,+ Constants: {TIMEOUT_DBLCLICK: 200},+ setTimeout: (callback: () => void) => timers.push(callback),+ getComputedStyle: (node: TestElement) => node.style,+ });+ const dialog = () => {+ const instance = new Dialog();+ instance.id = `dialog-${window.siyuan.dialogs.length}`;+ instance.element = document.body.append(element());+ instance.element.classList.add("b3-dialog--open");+ const overlay = instance.element.append(element("div", "b3-dialog"));+ overlay.style.zIndex = String(10 + window.siyuan.dialogs.length * 10);+ const container = overlay.append(element("div", "b3-dialog__container"));+ const first = container.append(element("button"));+ const last = container.append(element("input"));+ window.siyuan.dialogs.push(instance);+ return {instance, wrapper: instance.element as TestElement, overlay, container, first, last};+ };+ const destroyed: string[] = [];+ const panel = (name: string, anchor?: TestElement, pinned = false) => {+ const node = document.body.append(element("div", "block__popover")) as TestElement;+ node.dataset.pin = String(pinned);+ node.style.zIndex = "100";+ ownership.registerBlockPanelOwner(node, anchor);+ const first = node.append(element("button"));+ const last = node.append(element("button"));+ const item = {element: node, destroy: () => {+ destroyed.push(name);+ node.remove();+ window.siyuan.blockPanels = window.siyuan.blockPanels.filter(value => value !== item);+ }};+ window.siyuan.blockPanels.push(item);+ return {item, element: node, first, last};+ };+ return {document, window, element, ownership, dialog, panel, destroyed, timers, removedListeners};+};++test("panel ownership survives detached and moved recent-document anchors", () => {+ const f = fixture();+ const owner = f.dialog();+ const other = f.dialog();+ const preview = f.panel("preview", owner.first);+ owner.first.remove();+ assert.equal(f.ownership.getDialogBlockPanel(owner.wrapper, preview.last), preview.element);+ other.container.append(owner.first);+ assert.equal(f.ownership.getDialogBlockPanel(owner.wrapper, preview.last), preview.element);+ assert.equal(f.ownership.getDialogBlockPanel(other.wrapper, preview.last), undefined);+ assert.equal(f.ownership.getDialogBlockPanel(owner.wrapper, other.first), undefined);+ assert.equal(f.ownership.getDialogBlockPanel(owner.wrapper, null), undefined);+});++test("nested panels inherit their original dialog even after ancestor anchors detach", () => {+ const f = fixture();+ const owner = f.dialog();+ const parent = f.panel("parent", owner.first);+ owner.first.remove();+ const child = f.panel("child", parent.last);+ parent.element.remove();+ const grandchild = f.panel("grandchild", child.last);+ for (const preview of [parent, child, grandchild]) {+ assert.equal(f.ownership.getDialogBlockPanel(owner.wrapper, preview.last), preview.element);+ }+});++test("dialog cleanup snapshots nested panels and destroys children before parents", () => {+ const f = fixture();+ const owner = f.dialog();+ const parent = f.panel("parent", owner.first);+ const child = f.panel("child", parent.last);+ f.panel("grandchild", child.last);+ f.ownership.destroyDialogBlockPanels(owner.wrapper);+ assert.deepEqual(f.destroyed, ["grandchild", "child", "parent"]);+ assert.equal(f.window.siyuan.blockPanels.length, 0);+ f.ownership.destroyDialogBlockPanels(owner.wrapper);+ assert.deepEqual(f.destroyed, ["grandchild", "child", "parent"]);+});++test("dialog cleanup preserves pinned panels and unrelated panels without changing ownership", () => {+ const f = fixture();+ const owner = f.dialog();+ const other = f.dialog();+ const parent = f.panel("parent", owner.first);+ const pinned = f.panel("pinned", parent.last, true);+ f.panel("child", pinned.last);+ const unrelated = f.panel("unrelated", other.first);+ const unowned = f.panel("unowned");+ f.ownership.destroyDialogBlockPanels(owner.wrapper);+ owner.wrapper.remove();+ assert.deepEqual(f.destroyed, ["child", "parent"]);+ assert.deepEqual(f.window.siyuan.blockPanels, [pinned.item, unrelated.item, unowned.item]);+ assert.equal(f.ownership.getDialogBlockPanel(owner.wrapper, pinned.last), pinned.element);+ assert.equal(f.ownership.getDialogBlockPanel(other.wrapper, pinned.last), undefined);+ pinned.element.dataset.pin = "false";+ f.ownership.destroyDialogBlockPanels(owner.wrapper);+ assert.deepEqual(f.destroyed, ["child", "parent", "pinned"]);+ assert.equal(unrelated.element.isConnected, true);+ assert.equal(unowned.element.isConnected, true);+});++test("preview targets must remain connected and outside a closing dialog", () => {+ const f = fixture();+ const owner = f.dialog();+ assert.equal(f.ownership.isBlockPanelTargetAvailable(owner.first), true);+ owner.wrapper.dataset.dialogClosing = "true";+ assert.equal(owner.first.isConnected, true);+ assert.equal(f.ownership.isBlockPanelTargetAvailable(owner.first), false);+ delete owner.wrapper.dataset.dialogClosing;+ assert.equal(f.ownership.isBlockPanelTargetAvailable(owner.first), true);+ owner.first.remove();+ assert.equal(f.ownership.isBlockPanelTargetAvailable(owner.first), false);+});++test("Dialog.destroy marks closing and clears owned previews synchronously and only once", () => {+ const f = fixture();+ const owner = f.dialog();+ const preview = f.panel("preview", owner.first);+ const pinned = f.panel("pinned", owner.last, true);+ const unrelated = f.panel("unrelated");+ const destroyPanel = preview.item.destroy;+ preview.item.destroy = () => {+ assert.equal(owner.wrapper.dataset.dialogClosing, "true");+ assert.equal(f.ownership.isBlockPanelTargetAvailable(owner.first), false);+ assert.equal(owner.instance.destroying, true);+ assert.equal(f.removedListeners.length, 1);+ destroyPanel();+ };+ let callbacks = 0;+ const options = {reason: "close"};+ owner.instance.destroyCallback = (value: unknown) => {+ assert.equal(value, options);+ callbacks++;+ };+ owner.instance.destroy(options);+ owner.instance.destroy(options);+ assert.equal(owner.wrapper.isConnected, true);+ assert.equal(owner.wrapper.classList.contains("b3-dialog--open"), false);+ assert.deepEqual(f.destroyed, ["preview"]);+ assert.deepEqual(f.removedListeners, [["keydown", owner.instance.trapFocus, true]]);+ assert.equal(callbacks, 0);+ assert.equal(f.timers.length, 1);+ f.timers.shift()();+ assert.equal(owner.wrapper.isConnected, false);+ assert.equal(f.window.siyuan.dialogs.length, 0);+ assert.equal(callbacks, 1);+ assert.deepEqual(f.window.siyuan.blockPanels, [pinned.item, unrelated.item]);+});++test("Tab in an owned Protyle body remains editor-owned in both directions", () => {+ const f = fixture();+ const owner = f.dialog();+ const preview = f.panel("preview", owner.first);+ const body = preview.element.append(f.element("div", "protyle-wysiwyg"));+ body.isContentEditable = true;+ const block = body.append(f.element());+ block.isContentEditable = true;+ for (const active of [body, block]) {+ for (const shiftKey of [false, true]) {+ active.focus();+ const event = keyboardEvent(shiftKey);+ owner.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, false);+ assert.equal(event.propagationStopped, false);+ assert.equal(f.document.activeElement, active);+ }+ }+});++test("Tab in a readonly Protyle body or embedded input remains panel-trapped", () => {+ for (const mode of ["readonly", "input"]) {+ const f = fixture();+ const owner = f.dialog();+ const preview = f.panel("preview", owner.first);+ const body = preview.element.append(f.element("div", "protyle-wysiwyg"));+ body.isContentEditable = mode !== "readonly";+ body.setAttribute("tabindex", "0");+ const active = mode === "readonly" ? body : body.append(f.element("input"));+ active.focus();+ const event = keyboardEvent();+ owner.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, true, mode);+ assert.equal(event.propagationStopped, true, mode);+ assert.equal(f.document.activeElement, preview.first, mode);+ }+});++test("Tab from a non-tabbable readonly body returns to the owned panel controls", () => {+ const f = fixture();+ const owner = f.dialog();+ const preview = f.panel("preview", owner.first);+ const body = preview.element.append(f.element("div", "protyle-wysiwyg"));+ body.setAttribute("contenteditable", "false");+ assert.equal(body.tabIndex, -1);+ for (const shiftKey of [false, true]) {+ body.focus();+ const event = keyboardEvent(shiftKey);+ owner.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, true);+ assert.equal(event.propagationStopped, true);+ assert.equal(f.document.activeElement, shiftKey ? preview.last : preview.first);+ }+});++test("Tab wraps within owned panel controls, including nested panels", () => {+ const f = fixture();+ const owner = f.dialog();+ const parent = f.panel("parent", owner.first);+ const child = f.panel("child", parent.last);+ owner.first.remove();+ for (const preview of [parent, child]) {+ for (const shiftKey of [false, true]) {+ (shiftKey ? preview.first : preview.last).focus();+ const event = keyboardEvent(shiftKey);+ owner.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, true);+ assert.equal(event.propagationStopped, true);+ assert.equal(f.document.activeElement, shiftKey ? preview.last : preview.first);+ }+ preview.first.focus();+ const event = keyboardEvent();+ owner.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, false);+ assert.equal(event.propagationStopped, false);+ }+});++test("unrelated panels and panels behind the dialog cannot escape modal focus", () => {+ for (const mode of ["unowned", "other-dialog", "behind"]) {+ const f = fixture();+ const other = f.dialog();+ const owner = f.dialog();+ const preview = f.panel("preview", mode === "unowned" ? undefined :+ mode === "other-dialog" ? other.first : owner.first);+ if (mode === "behind") {+ preview.element.style.zIndex = "0";+ }+ const body = preview.element.append(f.element("div", "protyle-wysiwyg"));+ body.isContentEditable = true;+ for (const active of [preview.last, body]) {+ for (const shiftKey of [false, true]) {+ active.focus();+ const event = keyboardEvent(shiftKey);+ owner.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, true, mode);+ assert.equal(event.propagationStopped, true, mode);+ assert.equal(f.document.activeElement, shiftKey ? owner.last : owner.first, mode);+ }+ }+ }+});++test("an upper Dialog controls focus while a lower dialog owns the preview", () => {+ const f = fixture();+ const lower = f.dialog();+ const preview = f.panel("preview", lower.first);+ const upper = f.dialog();+ for (const shiftKey of [false, true]) {+ preview.last.focus();+ const event = keyboardEvent(shiftKey);+ lower.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, false);+ assert.equal(f.document.activeElement, preview.last);+ upper.instance.trapFocus(event);+ assert.equal(event.defaultPrevented, true);+ assert.equal(event.propagationStopped, true);+ assert.equal(f.document.activeElement, shiftKey ? upper.last : upper.first);+ }+});++test("closing a child Dialog restores focus to its parent dialog's owned preview", () => {+ const f = fixture();+ const owner = f.dialog();+ const preview = f.panel("preview", owner.first);+ preview.last.focus();+ const child = f.dialog();+ child.instance.previousFocus = preview.last;+ child.first.focus();+ child.instance.destroy();+ assert.equal(f.document.activeElement, child.first);+ f.timers.shift()();+ assert.equal(f.document.activeElement, preview.last);+ assert.deepEqual(f.window.siyuan.dialogs, [owner.instance]);+ assert.equal(preview.element.isConnected, true);+});++test("closing a child Dialog does not restore focus to unrelated or covered previews", () => {+ for (const mode of ["unowned", "other-dialog", "behind"]) {+ const f = fixture();+ const other = f.dialog();+ const owner = f.dialog();+ const preview = f.panel("preview", mode === "unowned" ? undefined :+ mode === "other-dialog" ? other.first : owner.first);+ if (mode === "behind") {+ preview.element.style.zIndex = "0";+ }+ const child = f.dialog();+ child.instance.previousFocus = preview.last;+ child.first.focus();+ child.instance.destroy();+ f.timers.shift()();+ assert.equal(f.document.activeElement, f.document.body, mode);+ assert.equal(preview.element.isConnected, true, mode);+ }+});++test("child Dialog cleanup preserves focus taken by another control or its close callback", () => {+ for (const fromCallback of [false, true]) {+ const f = fixture();+ const owner = f.dialog();+ const preview = f.panel("preview", owner.first);+ const child = f.dialog();+ child.instance.previousFocus = preview.last;+ child.first.focus();+ if (fromCallback) {+ child.instance.destroyCallback = () => owner.last.focus();+ }+ child.instance.destroy();+ if (!fromCallback) {+ owner.last.focus();+ }+ f.timers.shift()();+ assert.equal(f.document.activeElement, owner.last);+ }+});++test("closing dialogs and non-Tab keys do not intercept panel focus", () => {+ const f = fixture();+ const owner = f.dialog();+ const preview = f.panel("pinned", owner.first, true);+ preview.last.focus();+ const escape = keyboardEvent(false, "Escape");+ owner.instance.trapFocus(escape);+ assert.equal(escape.defaultPrevented, false);+ owner.instance.destroy();+ const tab = keyboardEvent();+ owner.instance.trapFocus(tab);+ assert.equal(tab.defaultPrevented, false);+ assert.equal(tab.propagationStopped, false);+ assert.equal(f.document.activeElement, preview.last);+});diff --git a/app/src/block/panelOwnership.ts b/app/src/block/panelOwnership.tsnew file mode 100644index 0000000000..13df93f76f--- /dev/null+++ b/app/src/block/panelOwnership.ts@@ -0,0 +1,25 @@+const dialogOwners = new WeakMap<HTMLElement, HTMLElement>();++export const registerBlockPanelOwner = (element: HTMLElement, target?: HTMLElement) => {+ const dialog = target?.closest<HTMLElement>(".b3-dialog")?.parentElement;+ const parentPanel = target?.closest<HTMLElement>(".block__popover");+ const owner = dialog || (parentPanel && dialogOwners.get(parentPanel));+ if (owner) {+ dialogOwners.set(element, owner);+ }+};++export const getDialogBlockPanel = (dialog: HTMLElement, target: Element) => {+ const panel = target?.closest<HTMLElement>(".block__popover");+ return panel && dialogOwners.get(panel) === dialog ? panel : undefined;+};++export const destroyDialogBlockPanels = (dialog: HTMLElement) => {+ // 先收集再逆序销毁,避免父浮窗清理后丢失嵌套浮窗;固定浮窗保留原来的归属。+ const panels = (window.siyuan.blockPanels || []).filter(item =>+ dialogOwners.get(item.element) === dialog && item.element.dataset.pin !== "true");+ panels.reverse().forEach(item => item.destroy());+};++export const isBlockPanelTargetAvailable = (target: HTMLElement) =>+ target.isConnected && !target.closest('[data-dialog-closing="true"]');diff --git a/app/src/block/popover.test.ts b/app/src/block/popover.test.tsindex 2a344e0790..e13107332e 100644--- a/app/src/block/popover.test.ts+++ b/app/src/block/popover.test.ts@@ -199,7 +199,7 @@ test("mindmap interaction cancels pending popovers and preserves hover preferencskip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,timeout: 20000,}, async () => {- const source = ["../protyle/util/hasClosest.ts", "../util/escape.ts", "../protyle/render/imageTooltip.ts", "popoverLifecycle.ts", "popover.ts"].map(file => transpileModule(+ const source = ["../protyle/util/hasClosest.ts", "../util/escape.ts", "../protyle/render/imageTooltip.ts", "panelOwnership.ts", "popoverLifecycle.ts", "popover.ts"].map(file => transpileModule(readFileSync(path.join(__dirname, file), "utf8").replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""),{compilerOptions: {target: ScriptTarget.ES2021}},).outputText).join("\n");diff --git a/app/src/block/popover.ts b/app/src/block/popover.tsindex 42623e473f..e53f676446 100644--- a/app/src/block/popover.ts+++ b/app/src/block/popover.ts@@ -21,6 +21,7 @@ import {isPopoverMenuBlocked,setPopoverCancellationHandler,} from "./popoverLifecycle";+import {isBlockPanelTargetAvailable} from "./panelOwnership";/// #if !MOBILEimport {getInstanceById} from "../layout/util";import {Editor} from "../editor";@@ -664,7 +665,7 @@ const getTarget = (event: MouseEvent & { target: HTMLElement }, aElement: false}}}- if (!popoverTargetElement || window.siyuan.altIsPressed ||+ if (!popoverTargetElement || !isBlockPanelTargetAvailable(popoverTargetElement) || window.siyuan.altIsPressed ||(window.siyuan.isPublish && popoverTargetElement.dataset.popoverUrl === "/api/av/getMirrorDatabaseBlocks") ||(window.siyuan.config.editor.floatWindowMode === 0 && window.siyuan.ctrlIsPressed) ||(popoverTargetElement && popoverTargetElement.getAttribute("prevent-popover") === "true")) {@@ -781,7 +782,7 @@ export const showPopover = async (app: App, showRef = false, automatic = false)if (interactionGeneration !== popoverGeneration || (automatic && generation !== getPopoverGeneration()) ||targetElement !== popoverTargetElement ||(automatic && isPopoverMenuBlocked(targetElement)) ||- !targetElement.isConnected || isPopoverSuspended() || refDefs.length === 0) {+ !isBlockPanelTargetAvailable(targetElement) || isPopoverSuspended() || refDefs.length === 0) {return;}@@ -802,7 +803,7 @@ export const showPopover = async (app: App, showRef = false, automatic = false)isBacklink: showRef || popoverTargetElement.classList.contains("protyle-attr--refcount") || popoverTargetElement.classList.contains("counter"),refDefs,originalRefBlockIDs,- canShow: automatic ? () => generation === getPopoverGeneration() && targetElement.isConnected &&+ canShow: automatic ? () => generation === getPopoverGeneration() && isBlockPanelTargetAvailable(targetElement) &&!isPopoverSuspended() && !isPopoverMenuBlocked(targetElement) : undefined,}));}diff --git a/app/src/block/popoverInteraction.test.ts b/app/src/block/popoverInteraction.test.tsindex 6a8632eedc..a662401758 100644--- a/app/src/block/popoverInteraction.test.ts+++ b/app/src/block/popoverInteraction.test.ts@@ -31,6 +31,9 @@ class TestElement {if (selector.startsWith(".") && this.classes.has(selector.substring(1))) {return this;}+ if (selector === '[data-dialog-closing="true"]' && this.dataset.dialogClosing === "true") {+ return this;+ }return this.parentElement?.closest(selector) || null;}querySelector(selector: string): TestElement {@@ -108,6 +111,7 @@ const createHarness = (android = false) => {typeof import("./popoverLifecycle");const api = loadModule("src/block/popover.ts", globals, {"./popoverLifecycle": lifecycle,+ "./panelOwnership": loadModule("src/block/panelOwnership.ts", globals, {}),"./Panel": {BlockPanel: class {element = element({"data-pin": "false"});editors: unknown[] = [];@@ -196,9 +200,9 @@ test("crossing a child before pointermove still resumes after a click", async ()});test("document icons, block references and both SiYuan link forms share cancellation and recovery", async () => {- for (const kind of ["reference", "tree", "breadcrumb", "database", "search", "bookmark", "gutter", "hint", "link", "url"]) {+ for (const kind of ["reference", "tree", "breadcrumb", "database", "search", "recent", "bookmark", "gutter", "hint", "link", "url"]) {const h = createHarness();- if (["tree", "breadcrumb", "search", "bookmark", "gutter", "hint"].includes(kind)) {+ if (["tree", "breadcrumb", "search", "recent", "bookmark", "gutter", "hint"].includes(kind)) {h.ref.attributes = {"data-id": kind};h.ref.classes.add("popover__block");} else if (kind === "link") {@@ -224,6 +228,47 @@ test("document icons, block references and both SiYuan link forms share cancella}});+test("recent-document hover cannot start or finish after its dialog closes or its icon is replaced", async () => {+ for (const state of ["closing", "detached"]) {+ for (const phase of ["timer", "panel"]) {+ const h = createHarness();+ const dialog = h.element();+ const icon = h.element({"data-id": "recent-document"}, ["popover__block"], dialog);+ h.fire("mouseover", icon);+ if (phase === "panel") {+ await h.advance();+ assert.equal(h.panels.length, 1);+ assert.equal(h.panels[0].refDefs[0].refID, "recent-document");+ assert.equal(h.panels[0].canShow(), true);+ }+ if (state === "closing") {+ dialog.dataset.dialogClosing = "true";+ } else {+ icon.isConnected = false;+ }+ await h.advance();+ if (phase === "timer") {+ assert.equal(h.panels.length, 0);+ } else {+ assert.equal(h.panels[0].canShow(), false);+ }+ }+ }+});++test("closing dialog anchors reject late explicit backlink queries without changing modifier semantics", async () => {+ const h = createHarness();+ const dialog = h.element();+ const icon = h.element({"data-id": "recent-document"}, ["popover__block"], dialog);+ h.siyuan.shiftIsPressed = true;+ h.fire("mouseover", icon);+ assert.equal(h.requests.length, 1);+ dialog.dataset.dialogClosing = "true";+ h.requests[0].resolve({code: 0, data: {refDefs: [{refID: "backlink"}]}});+ await h.advance();+ assert.equal(h.panels.length, 0);+});+test("contextmenu capture and menu lifecycle cancel timers without pointer events", async () => {for (const cancel of [(h: ReturnType<typeof createHarness>) => h.fire("contextmenu"),(h: ReturnType<typeof createHarness>) => h.open()]) {@@ -417,7 +462,7 @@ test("hover preferences, excluded targets and mindmap suspension remain effectiv}});-test("the real Panel first-load callback discards canceled hover and leaves explicit or opened panels alone", () => {+test("the real Panel first-load callback rejects canceled hover and unavailable anchors without closing menus", () => {const globals = {window: {siyuan: {zIndex: 5, languages: {}, config: {keymap: {general: {closeTab: {custom: ""}}, editor: {general: {openInNewTab: {custom: ""}}},@@ -426,12 +471,13 @@ test("the real Panel first-load callback discards canceled hover and leaves explResizeObserver: class { observe() {} }, IntersectionObserver: class { observe() {} },};const module = loadModule("src/block/Panel.ts", globals, {+ "./panelOwnership": loadModule("src/block/panelOwnership.ts", globals, {}),"../protyle/util/compatibility": {updateHotkeyAfterTip: () => ""},"../layout/getTopBarHeight": {getTopBarHeight: () => 0},"./panelPosition": {positionBlockPanel() {}},}) as unknown as {BlockPanel: {prototype: {render: () => void}}};for (const automatic of [false, true]) {- for (const cancelled of [false, true]) {+ for (const state of ["available", "cancelled", "closing", "detached"]) {const element = new TestElement();const editorElement = new TestElement();const content = new TestElement();@@ -453,12 +499,19 @@ test("the real Panel first-load callback discards canceled hover and leaves expl},};module.BlockPanel.prototype.render.call(panel);- valid = !cancelled;+ valid = state !== "cancelled";+ if (state === "closing") {+ panel.targetElement.dataset.dialogClosing = "true";+ } else if (state === "detached") {+ panel.targetElement.isConnected = false;+ }after();- assert.equal(destroyed, automatic && cancelled);- assert.equal(element.classes.has("block__popover--open"), !(automatic && cancelled));+ const unavailable = (automatic && state === "cancelled") || ["closing", "detached"].includes(state);+ assert.equal(destroyed, unavailable);+ assert.equal(element.classes.has("block__popover--open"), !unavailable);if (!destroyed) {valid = false;+ panel.targetElement.isConnected = false;after();assert.equal(destroyed, false, "already displayed panels are not canceled later");}diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.tsindex 02e90625ec..62b0fcac4b 100644--- a/app/src/boot/globalEvent/keydown.ts+++ b/app/src/boot/globalEvent/keydown.ts@@ -1465,7 +1465,8 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {return true;}});- if (openRecentDocsDialog) {+ if (openRecentDocsDialog && openRecentDocsDialog.element.contains(event.target as Node) &&+ !openRecentDocsDialog.element.hasAttribute("data-dialog-closing")) {if ((event.target as HTMLElement).closest("select")) {return;}diff --git a/app/src/business/openRecentDocs.test.ts b/app/src/business/openRecentDocs.test.tsnew file mode 100644index 0000000000..e1ff78d0e2--- /dev/null+++ b/app/src/business/openRecentDocs.test.ts@@ -0,0 +1,208 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isArrowFunction, isBlock, isIfStatement, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";++const loadModule = (filename: string, globals: Record<string, unknown>, dependencies: Record<string, unknown> = {}, tail = "") => {+ const exports: any = {};+ runInNewContext(transpileModule(readFileSync(filename, "utf8") + tail, {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText, {exports, require: (name: string) => dependencies[name] || {}, ...globals});+ return exports;+};++const createHarness = () => {+ const callbacks = new Map<string, (...args: any[]) => void>();+ const input = {value: "", focus() {}, addEventListener: (name: string, callback: (...args: any[]) => void) =>+ callbacks.set("input:" + name, callback)};+ const select = {value: "", addEventListener: (name: string, callback: (...args: any[]) => void) =>+ callbacks.set("select:" + name, callback)};+ const host = {innerHTML: ""};+ const path = {innerHTML: "", previousElementSibling: host};+ let icons: Array<{tagName: string, classes: Set<string>, classList: {add: (name: string) => void},+ dataset: Record<string, string>, parentElement: {dataset: {nodeId: string}}}> = [];+ const attributes = new Map<string, string>();+ const root = {+ isConnected: true,+ hasAttribute: (name: string) => attributes.has(name),+ getAttribute: (name: string) => attributes.get(name),+ setAttribute: (name: string, value: string) => attributes.set(name, value),+ querySelector: (selector: string) => {+ if (selector === ".switch-doc__path") {+ return path;+ }+ return selector === "input" ? input : select;+ },+ querySelectorAll: (selector: string) => {+ assert.equal(selector, "li[data-node-id] > .b3-list-item__graphic");+ icons = [...host.innerHTML.matchAll(/<li[^>]*data-node-id="([^"]+)"[^>]*>\s*<(svg|span|img) class="([^"]*)"/g)]+ .map(([, id, tag, classes]) => {+ const names = new Set(classes.split(" "));+ return {tagName: tag.toUpperCase(), classes: names, classList: {add: (name: string) => names.add(name)},+ dataset: {}, parentElement: {dataset: {nodeId: id}}};+ });+ return icons;+ },+ addEventListener: (name: string, callback: (...args: any[]) => void) => callbacks.set(name, callback),+ };+ const pathRequests: Array<{id: string, resolve: (response: unknown) => void}> = [];+ const requests: Array<{url: string, data: any, receive: (response: unknown) => void}> = [];+ const cleanups: string[] = [];+ let dialogOptions: any;+ const constants = {LOCAL_IMAGES: "images", LOCAL_RECENT_DOCS: "recent", DIALOG_RECENTDOCS: "recent-dialog"};+ const siyuan = {+ config: {fileTree: {useSVGDefaultIcon: true}, keymap: {general: {riffCard: {custom: ""}}}},+ storage: {images: {file: "1f4c4"}, recent: {type: "viewedAt"}},+ languages: {riffCard: "Cards", recentDocs: "Recent documents"},+ dialogs: [] as Array<{element: typeof root}>,+ };+ const globals = {window: {siyuan}, URL, URLSearchParams, Lute: {Sanitize: (html: string) => html}};+ const escape = loadModule("src/util/escape.ts", globals);+ const iconValue = loadModule("src/emoji/iconValue.ts", globals, {"../util/escape": escape});+ const icon = loadModule("src/emoji/fileTreeIcon.ts", globals, {+ "../constants": {Constants: constants}, "../util/escape": escape, "./iconValue": iconValue,+ });+ const api = loadModule("src/business/openRecentDocs.ts", globals, {+ "../util/fetch": {+ fetchSyncPost: (_url: string, data: {id: string}) => new Promise(resolve => pathRequests.push({id: data.id, resolve})),+ fetchPost: (url: string, data: unknown, receive: (response: unknown) => void) => requests.push({url, data, receive}),+ },+ "../emoji/fileTreeIcon": icon,+ "../constants": {Constants: constants},+ "../util/escape": escape,+ "../util/functions": {isWindow: () => false},+ "../protyle/util/compatibility": {updateHotkeyTip: (value: string) => value, setStorageVal() {}},+ "../layout/getAll": {getAllDocks: () => [{title: "Documents", type: "files", icon: "iconFiles"}]},+ "../layout/dock/hotkey": {getDockHotkey: () => ""},+ "../block/panelOwnership": {destroyDialogBlockPanels: (element: typeof root) => {+ assert.equal(element, root);+ cleanups.push(host.innerHTML);+ }},+ "../dialog": {Dialog: class {+ element = root;+ constructor(options: any) {+ dialogOptions = options;+ siyuan.dialogs.push(this);+ }+ }},+ }, "\nexports.render = renderRecentDocsContent;");+ const settle = async () => { await new Promise(resolve => setImmediate(resolve)); };+ return {api, root, host, path, input, select, siyuan, pathRequests, requests, callbacks, cleanups, settle,+ icons: () => icons, dialogOptions: () => dialogOptions};+};++test("recent document SVG, Unicode and image icons receive the shared document preview target", async () => {+ const h = createHarness();+ const data = [{rootID: "svg", title: "SVG"}, {rootID: "emoji", title: "Emoji", icon: "1f600"},+ {rootID: "image", title: "Image", icon: "custom.png"}];+ const pending = h.api.render(data, h.root);+ assert.equal(h.cleanups.length, 0);+ h.pathRequests[0].resolve({code: 0, data: "/SVG"});+ await pending;+ assert.deepEqual(h.icons().map(item => item.tagName), ["SVG", "SPAN", "IMG"]);+ assert.deepEqual(h.icons().map(item => item.dataset.id), data.map(item => item.rootID));+ assert.ok(h.icons().every(item => item.classes.has("popover__block")));+ assert.equal(h.cleanups.length, 1);+ assert.match(h.host.innerHTML, /data-type="files"/);+ assert.doesNotMatch(h.host.innerHTML, /b3-list-item__text[^>]*popover__block/);+ assert.equal(h.requests.length, 0, "rendering a preview entry does not write recent history");+});++test("filtering previews the matching root and accepts only the latest asynchronous render", async () => {+ const h = createHarness();+ const data = [{rootID: "alpha", title: "Alpha"}, {rootID: "beta", title: "Beta"}];+ const first = h.api.render(data, h.root, "alpha");+ const latest = h.api.render(data, h.root, "beta");+ assert.deepEqual(h.pathRequests.map(item => item.id), ["alpha", "beta"]);+ h.pathRequests[1].resolve({code: 0, data: "/Beta"});+ await latest;+ h.pathRequests[0].resolve({code: 0, data: "/Alpha"});+ await first;+ assert.equal(h.path.innerHTML, "/Beta");+ assert.deepEqual(h.icons().map(item => item.dataset.id), ["beta"]);+ assert.equal(h.cleanups.length, 1, "stale requests do not close the current preview");+});++test("closing or removing the recent dialog prevents a late render from replacing its content", async () => {+ for (const closing of [true, false]) {+ const h = createHarness();+ h.host.innerHTML = "previous content";+ const pending = h.api.render([{rootID: "document", title: "Document"}], h.root);+ if (closing) {+ h.root.setAttribute("data-dialog-closing", "true");+ } else {+ h.root.isConnected = false;+ }+ h.pathRequests[0].resolve({code: 0, data: "/Document"});+ await pending;+ assert.equal(h.host.innerHTML, "previous content");+ assert.equal(h.cleanups.length, 0);+ }+});++test("empty filters synchronously invalidate older document renders and do not mark dock icons", async () => {+ const h = createHarness();+ const old = h.api.render([{rootID: "document", title: "Document"}], h.root);+ await h.api.render([], h.root, "Cards");+ assert.deepEqual(h.icons(), []);+ assert.match(h.host.innerHTML, /data-type="riffCard"/);+ h.pathRequests[0].resolve({code: 0, data: "/Document"});+ await old;+ assert.equal(h.path.innerHTML, "Cards");+ assert.doesNotMatch(h.host.innerHTML, /data-node-id/);+});++test("sort responses cannot restore older preview anchors or update a closing dialog", async () => {+ const h = createHarness();+ h.api.openRecentDocs();+ assert.equal(h.requests[0].url, "/api/storage/getRecentDocs");+ h.requests[0].receive({data: []});+ assert.equal(h.dialogOptions().destroyCallback, undefined, "Dialog owns guarded focus restoration");+ h.select.value = "created";+ h.callbacks.get("select:change")();+ h.select.value = "closedAt";+ h.callbacks.get("select:change")();+ h.requests[2].receive({data: [{rootID: "latest", title: "Latest"}]});+ h.requests[1].receive({data: [{rootID: "old", title: "Old"}]});+ assert.deepEqual(h.pathRequests.map(item => item.id), ["latest"]);+ h.pathRequests[0].resolve({code: 0, data: "/Latest"});+ await h.settle();+ assert.deepEqual(h.icons().map(item => item.dataset.id), ["latest"]);+ h.select.value = "viewedAt";+ h.callbacks.get("select:change")();+ h.root.setAttribute("data-dialog-closing", "true");+ h.requests[3].receive({data: [{rootID: "late", title: "Late"}]});+ assert.equal(h.pathRequests.length, 1);+});++test("recent Arrow and Enter handlers ignore popover editors and closing dialog controls", () => {+ const filename = "src/boot/globalEvent/keydown.ts";+ const source = createSourceFile(filename, readFileSync(filename, "utf8"), ScriptTarget.ES2021, true);+ const declaration = source.statements.find(item => isVariableStatement(item) &&+ item.declarationList.declarations.some(variable => variable.name.getText(source) === "windowKeyDown"));+ assert.ok(declaration && isVariableStatement(declaration));+ const initializer = declaration.declarationList.declarations[0].initializer;+ assert.ok(initializer && isArrowFunction(initializer) && isBlock(initializer.body));+ const statement = initializer.body.statements.find(item => isIfStatement(item) && item.getText(source).includes("DIALOG_RECENTDOCS"));+ assert.ok(statement, "load the actual recent-document branch");+ const input = {closest: (): null => null};+ const editor = {closest: (): null => null};+ let closing = false;+ let calls = 0;+ const element = {getAttribute: () => "recent", hasAttribute: () => closing, contains: (target: unknown) => target === input};+ const exports: any = {};+ runInNewContext(transpileModule(`exports.keydown = (event, app) => { ${statement.getText(source)} };`, {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText, {exports, isNotCtrl: () => true, Constants: {DIALOG_RECENTDOCS: "recent"},+ window: {siyuan: {dialogs: [{element}]}}, dialogArrow: () => calls++});+ for (const key of ["ArrowDown", "ArrowLeft", "Enter"]) {+ const event = {key, target: input, preventDefault() {}};+ exports.keydown(event, {});+ exports.keydown({...event, target: editor}, {});+ }+ assert.equal(calls, 3);+ closing = true;+ exports.keydown({key: "Enter", target: input, preventDefault() {}}, {});+ assert.equal(calls, 3);+});diff --git a/app/src/business/openRecentDocs.ts b/app/src/business/openRecentDocs.tsindex 94cf0c723c..f809cd50b1 100644--- a/app/src/business/openRecentDocs.ts+++ b/app/src/business/openRecentDocs.ts@@ -7,9 +7,11 @@ import {setStorageVal, updateHotkeyTip} from "../protyle/util/compatibility";import {getAllDocks} from "../layout/getAll";import {getDockHotkey} from "../layout/dock/hotkey";import {Dialog} from "../dialog";-import {focusByRange} from "../protyle/util/selection";import {hasClosestByClassName} from "../protyle/util/hasClosest";import {hideElements} from "../protyle/ui/hideElements";+import {destroyDialogBlockPanels} from "../block/panelOwnership";++const recentDocsRenderVersions = new WeakMap<Element, number>();const renderRecentDocsContent = async (data: {rootID: string,@@ -19,10 +21,14 @@ const renderRecentDocsContent = async (data: {closedAt?: number,openAt?: number,}[], element: Element, key?: string) => {+ const version = (recentDocsRenderVersions.get(element) || 0) + 1;+ recentDocsRenderVersions.set(element, version);let tabHtml = "";let index = 0;+ let firstRootID: string;data.forEach((item) => {if (!key || (item.title || "").toLowerCase().includes(key.toLowerCase())) {+ firstRootID = firstRootID || item.rootID;tabHtml += `<li data-index="${index}" data-node-id="${item.rootID}" class="b3-list-item${index === 0 ? " b3-list-item--focus" : ""}">${getFileTreeIconHTML(item.icon, "file", "b3-list-item__graphic", true)}<span class="b3-list-item__text">${escapeHtml(item.title || "")}</span>@@ -33,7 +39,7 @@ const renderRecentDocsContent = async (data: {let switchPath = "";if (tabHtml) {const pathResponse = await fetchSyncPost("/api/filetree/getFullHPathByID", {- id: data[0].rootID // 过滤后的第一个文档 ID+ id: firstRootID});if (pathResponse.code === 0 && typeof pathResponse.data === "string") {switchPath = escapeHtml(pathResponse.data);@@ -69,12 +75,21 @@ const renderRecentDocsContent = async (data: {dockHtml = '<ul class="b3-list b3-list--background" style="overflow: auto;width: 200px;">' + dockHtml + "</ul>";}+ if (!element.isConnected || element.hasAttribute("data-dialog-closing") ||+ recentDocsRenderVersions.get(element) !== version) {+ return;+ }+ destroyDialogBlockPanels(element as HTMLElement);const pathElement = element.querySelector(".switch-doc__path");pathElement.innerHTML = switchPath;pathElement.previousElementSibling.innerHTML = `<div class="fn__flex fn__flex-1" style="overflow: auto;">${dockHtml}<ul style="${isWindow() ? "border-left: 0;" : ""}min-width: 360px;" class="b3-list b3-list--background fn__flex-1">${tabHtml}</ul></div>`;+ element.querySelectorAll<HTMLElement>("li[data-node-id] > .b3-list-item__graphic").forEach(icon => {+ icon.classList.add("popover__block");+ icon.dataset.id = icon.parentElement.dataset.nodeId;+ });};export const openRecentDocs = (openOnly = false) => {@@ -91,10 +106,6 @@ export const openRecentDocs = (openOnly = false) => {}const sortBy = window.siyuan.storage[Constants.LOCAL_RECENT_DOCS].type as TRecentDocsSort;fetchPost("/api/storage/getRecentDocs", {sortBy}, (response) => {- let range: Range;- if (getSelection().rangeCount > 0) {- range = getSelection().getRangeAt(0);- }const dialog = new Dialog({positionId: Constants.DIALOG_RECENTDOCS,title: `<div class="fn__flex">@@ -117,11 +128,6 @@ export const openRecentDocs = (openOnly = false) => {<div class="switch-doc__path"></div></div>`,height: "80vh",- destroyCallback: () => {- if (range && range.getBoundingClientRect().height !== 0) {- focusByRange(range);- }- }});const sortSelect = dialog.element.querySelector("#recentDocsSort") as HTMLSelectElement;sortSelect.value = sortBy;@@ -149,9 +155,15 @@ export const openRecentDocs = (openOnly = false) => {});// 添加排序下拉框事件监听+ let sortRequestId = 0;sortSelect.addEventListener("change", () => {+ const requestId = ++sortRequestId;// 重新调用 API 获取排序后的数据fetchPost("/api/storage/getRecentDocs", {sortBy: sortSelect.value}, (newResponse) => {+ if (requestId !== sortRequestId || !dialog.element.isConnected ||+ dialog.element.hasAttribute("data-dialog-closing")) {+ return;+ }response = newResponse;renderRecentDocsContent(newResponse.data, dialog.element, searchElement.value);});diff --git a/app/src/dialog/index.ts b/app/src/dialog/index.tsindex 4de47aab77..df9c37d386 100644--- a/app/src/dialog/index.ts+++ b/app/src/dialog/index.ts@@ -5,6 +5,7 @@ import {isMobile} from "../util/functions";import {isNotCtrl} from "../protyle/util/compatibility";import {Protyle} from "../protyle";import {Constants} from "../constants";+import {destroyDialogBlockPanels, getDialogBlockPanel} from "../block/panelOwnership";export class Dialog {private destroyCallback: (options?: IObject) => void;@@ -24,8 +25,16 @@ export class Dialog {}// 对话框上方的菜单也需要约束 Tab,避免从菜单末尾进入背景。const menu = window.siyuan.menus.menu.element;+ const dialog = this.element.querySelector(".b3-dialog") as HTMLElement;+ const popover = getDialogBlockPanel(this.element, document.activeElement);+ const activePopover = popover && isAbove(popover, dialog) ? popover : undefined;+ // 浮窗正文中的 Tab 由编辑器处理,保留列表、表格和代码块的缩进操作。+ if (activePopover && (document.activeElement as HTMLElement).isContentEditable &&+ document.activeElement.closest(".protyle-wysiwyg")) {+ return;+ }const container = menu.contains(document.activeElement) && isAbove(menu, this.element.querySelector(".b3-dialog")) ?- menu : this.element.querySelector(".b3-dialog__container") as HTMLElement;+ menu : activePopover || this.element.querySelector(".b3-dialog__container") as HTMLElement;const elements = Array.from(container.querySelectorAll<HTMLElement>("a[href], button, input, select, textarea, [tabindex], [contenteditable]")).filter(element => (element.tabIndex >= 0 || (element.isContentEditable && !element.hasAttribute("tabindex"))) &&@@ -35,6 +44,7 @@ export class Dialog {elements.sort((a, b) => (a.tabIndex > 0 ? a.tabIndex : Infinity) - (b.tabIndex > 0 ? b.tabIndex : Infinity));const active = document.activeElement;if (!elements.length || !container.contains(active) || active === container ||+ (activePopover && container === activePopover && !elements.includes(active as HTMLElement)) ||(event.shiftKey ? active === elements[0] : active === elements[elements.length - 1])) {event.preventDefault();event.stopPropagation();@@ -136,6 +146,7 @@ left:${left || "auto"};top:${top || "auto"}">return;}this.destroying = true;+ this.element.dataset.dialogClosing = "true";document.removeEventListener("keydown", this.trapFocus, true);this.element.classList.remove("b3-dialog--open");const menu = window.siyuan.menus.menu;@@ -161,9 +172,11 @@ left:${left || "auto"};top:${top || "auto"}">// 调用方和上层对话框已接管焦点时,不覆盖其焦点;失效或隐藏的触发元素不再恢复。const target = this.previousFocus;const topDialog = window.siyuan.dialogs[window.siyuan.dialogs.length - 1];+ const targetPopover = topDialog && getDialogBlockPanel(topDialog.element, target);if (restoreFocus && document.activeElement === document.body && target?.isConnected &&target.getClientRects().length && getComputedStyle(target).visibility === "visible" &&- !target.closest("[inert]") && (!topDialog || topDialog.element.contains(target))) {+ !target.closest("[inert]") && (!topDialog || topDialog.element.contains(target) ||+ (targetPopover && isAbove(targetPopover, topDialog.element.querySelector(".b3-dialog"))))) {target.focus({preventScroll: true});if (document.activeElement === target && this.previousRange?.startContainer.isConnected &&this.previousRange.endContainer.isConnected && target.contains(this.previousRange.commonAncestorContainer)) {@@ -176,6 +189,7 @@ left:${left || "auto"};top:${top || "auto"}">document.getElementById("drag")?.classList.remove("fn__hidden");}}, Constants.TIMEOUT_DBLCLICK);+ destroyDialogBlockPanels(this.element);}public bindInput(inputElement: HTMLInputElement | HTMLTextAreaElement, enterEvent?: () => void, bindEnter = true) {diff --git a/app/tests/commandPaletteClose.test.js b/app/tests/commandPaletteClose.test.jsindex 59d55fcf0f..3ddad7f59f 100644--- a/app/tests/commandPaletteClose.test.js+++ b/app/tests/commandPaletteClose.test.js@@ -105,6 +105,7 @@ function fixture(delay, mobile = false) {"../util/genID": { genUUID: () => "palette" }, "../util/zIndex": zIndex,"./moveResize": { moveResize() { } }, "../util/functions": { isMobile: () => false },"../constants": { Constants },+ "../block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},});const lifecycle = load("command/paletteCore.ts");const command = { id: "core.insert.assets", label: () => "Assets" };diff --git a/app/tests/dialogFocus.test.js b/app/tests/dialogFocus.test.jsindex d71f140058..89720554d3 100644--- a/app/tests/dialogFocus.test.js+++ b/app/tests/dialogFocus.test.js@@ -15,6 +15,7 @@ const runCases = async (source) => {"../util/functions": {isMobile: () => false},"../protyle/util/compatibility": {isNotCtrl: () => true},"../constants": {Constants: {TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0}},+ "../block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},};const exports = {};new Function("require", "exports", source)(name => {@@ -197,6 +198,7 @@ const runFlashcardCases = async (dialogSource, cardSource, mobile) => {"./moveResize": {moveResize() {}},"../util/functions": {isMobile: () => mobile},"../constants": {Constants: constants},+ "../block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},"../protyle/util/selection": {focusByRange: range => {window.getSelection().removeAllRanges();window.getSelection().addRange(range);diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.jsindex 931e2ed5fe..40c756b1d7 100644--- a/app/tests/settingsWindow.test.js+++ b/app/tests/settingsWindow.test.js@@ -21,6 +21,7 @@ const rendererModules = (sources) => {menus: {menu: {element: document.createElement("div"), remove() {}}}, ws: {app: {plugins: [], appId: "test"}}};const genUUID = () => "test-" + Date.now() + "-" + (++sequence);const {Dialog} = loadRendererModule(sources.dialog, {+ "../block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},"../util/genID": {genUUID}, "../util/zIndex": {isAbove: () => false}, "./moveResize": {moveResize() {}},"../util/functions": {isMobile: () => false}, "../protyle/util/compatibility": {isNotCtrl: () => true},"../constants": {Constants: {TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0}},