Skip to content

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

:bug: Keep keyboard focus inside open dialogs https://github.com/siyuan-note/siyuan/issues/19510

Daniel5f4f8b6dca34
diff --git a/app/src/dialog/index.ts b/app/src/dialog/index.ts
index d699db9926..67753a142b 100644
--- a/app/src/dialog/index.ts
+++ b/app/src/dialog/index.ts
@@ -17,6 +17,30 @@ export class Dialog {
private previousFocus: HTMLElement;
private previousRange: Range;
private destroying = false;
+ private trapFocus = (event: KeyboardEvent) => {
+ if (event.key !== "Tab" || this.destroying ||
+ window.siyuan.dialogs[window.siyuan.dialogs.length - 1] !== this) {
+ return;
+ }
+ // 对话框上方的菜单也需要约束 Tab,避免从菜单末尾进入背景。
+ const menu = window.siyuan.menus.menu.element;
+ const container = menu.contains(document.activeElement) && isAbove(menu, this.element.querySelector(".b3-dialog")) ?
+ menu : 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"))) &&
+ !element.matches(":disabled") &&
+ !element.closest("[inert]") && element.getClientRects().length &&
+ getComputedStyle(element).visibility === "visible");
+ 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 ||
+ (event.shiftKey ? active === elements[0] : active === elements[elements.length - 1])) {
+ event.preventDefault();
+ event.stopPropagation();
+ (elements.length ? elements[event.shiftKey ? elements.length - 1 : 0] : container).focus({preventScroll: true});
+ }
+ };
constructor(options: {
positionId?: string,
@@ -63,10 +87,10 @@ export class Dialog {
}
this.element.innerHTML = `<div class="b3-dialog" style="z-index: ${++window.siyuan.zIndex};${typeof left === "string" ? "display:block" : ""}">
<div class="b3-dialog__scrim"${options.transparent ? ' style="background-color:transparent"' : ""}></div>
-<div class="b3-dialog__container ${options.containerClassName || ""}" style="width:${options.width || "auto"};height:${options.height || "auto"};
+<div role="dialog" aria-modal="true" ${options.title ? `aria-labelledby="dialog-title-${this.id}" ` : ""}tabindex="-1" class="b3-dialog__container ${options.containerClassName || ""}" style="width:${options.width || "auto"};height:${options.height || "auto"};
left:${left || "auto"};top:${top || "auto"}">
<svg class="b3-dialog__close${(!isMobile() || this.disableClose || options.hideCloseIcon) ? " fn__none" : ""}"><use xlink:href="#iconCloseRound"></use></svg>
- <div class="resize__move b3-dialog__header${options.title ? "" : " fn__none"}" ${(isMobile() &&options.title) ? 'style="padding-right: 38px;"' : ""} onselectstart="return false;">${options.title || ""}</div>
+ <div id="dialog-title-${this.id}" class="resize__move b3-dialog__header${options.title ? "" : " fn__none"}" ${(isMobile() &&options.title) ? 'style="padding-right: 38px;"' : ""} onselectstart="return false;">${options.title || ""}</div>
<div class="b3-dialog__body">${options.content}</div>
<div class="resize__rd"></div><div class="resize__ld"></div><div class="resize__lt"></div><div class="resize__rt"></div><div class="resize__r"></div><div class="resize__d"></div><div class="resize__t"></div><div class="resize__l"></div>
</div></div>`;
@@ -86,6 +110,8 @@ left:${left || "auto"};top:${top || "auto"}">
});
}
document.body.append(this.element);
+ document.addEventListener("keydown", this.trapFocus, true);
+ (this.element.querySelector(".b3-dialog__container") as HTMLElement).focus({preventScroll: true});
if (options.disableAnimation) {
this.element.classList.add("b3-dialog--open");
} else {
@@ -110,6 +136,7 @@ left:${left || "auto"};top:${top || "auto"}">
return;
}
this.destroying = true;
+ document.removeEventListener("keydown", this.trapFocus, true);
this.element.classList.remove("b3-dialog--open");
setTimeout(() => {
// av 修改列头emoji后点击关闭emoji图标
diff --git a/app/tests/dialogFocus.test.js b/app/tests/dialogFocus.test.js
index caa73f78ae..6fad3092e2 100644
--- a/app/tests/dialogFocus.test.js
+++ b/app/tests/dialogFocus.test.js
@@ -106,10 +106,41 @@ const runCases = async (source) => {
assert.equal(document.activeElement, editor);
assert.equal(window.getSelection().anchorOffset, 3);
assert.equal(window.siyuan.dialogs.length, 0);
+
+ dialog = new Dialog({content: '<button id="first">First</button><input disabled><button hidden>Hidden</button><button id="last">Last</button>'});
+ const container = dialog.element.querySelector(".b3-dialog__container");
+ assert.equal(document.activeElement, container);
+ const tab = (shiftKey = false) => document.activeElement.dispatchEvent(new KeyboardEvent("keydown", {
+ key: "Tab", shiftKey, bubbles: true, cancelable: true,
+ }));
+ tab();
+ assert.equal(document.activeElement.id, "first");
+ tab(true);
+ assert.equal(document.activeElement.id, "last");
+ tab();
+ assert.equal(document.activeElement.id, "first");
+ editor.focus();
+ tab();
+ assert.equal(document.activeElement.id, "first");
+ for (const shift of [false, true]) {
+ for (let i = 0; i < 6; i++) {
+ await require("electron").ipcRenderer.invoke("dialog-test-tab", shift);
+ assert.ok(container.contains(document.activeElement));
+ }
+ }
+ assert.equal(editor.textContent, "Editor content");
+ const empty = new Dialog({content: "No controls"});
+ tab(true);
+ assert.equal(document.activeElement, empty.element.querySelector(".b3-dialog__container"));
+ empty.destroy();
+ await tick();
+ assert.equal(document.activeElement.id, "first");
+ dialog.destroy();
+ await tick();
};
if (process.versions.electron && process.type === "browser") {
- const {app, BrowserWindow} = require("electron");
+ const {app, BrowserWindow, ipcMain} = require("electron");
app.setPath("userData", process.argv[2]);
app.whenReady().then(async () => {
const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});
@@ -118,6 +149,13 @@ if (process.versions.electron && process.type === "browser") {
await win.loadURL("data:text/html,<html><body></body></html>");
win.webContents.debugger.attach("1.3");
await win.webContents.debugger.sendCommand("Emulation.setFocusEmulationEnabled", {enabled: true});
+ ipcMain.handle("dialog-test-tab", async (_event, shift) => {
+ for (const type of ["keyDown", "keyUp"]) {
+ await win.webContents.debugger.sendCommand("Input.dispatchKeyEvent", {
+ type, key: "Tab", code: "Tab", windowsVirtualKeyCode: 9, modifiers: shift ? 8 : 0,
+ });
+ }
+ });
const ts = require("typescript");
const source = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src/dialog/index.ts"), "utf8"), {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},