Skip to content

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

:bug: Keep mobile database inputs focused during keyboard resizing https://github.com/siyuan-note/siyuan/issues/20836

Danielc442131d95ec
diff --git a/app/src/dialog/anchoredInputPosition.dom.test.ts b/app/src/dialog/anchoredInputPosition.dom.test.ts
new file mode 100644
index 0000000000..cd78bc63cf
--- /dev/null
+++ b/app/src/dialog/anchoredInputPosition.dom.test.ts
@@ -0,0 +1,118 @@
+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 {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = async (source: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ const api = {} as typeof import("./anchoredInputPosition");
+ new Function("exports", "require", source)(api, () => ({isMobile: () => true}));
+ const viewport = Object.assign(new EventTarget(), {offsetLeft: 0, offsetTop: 0, width: 384, height: 808});
+ Object.defineProperty(window, "visualViewport", {configurable: true, value: viewport});
+ // 隐藏测试窗口不依赖系统绘制帧率;定位回调仍异步执行,焦点及选区使用真实 DOM。
+ window.requestAnimationFrame = callback => window.setTimeout(() => callback(performance.now()), 0);
+ window.cancelAnimationFrame = id => window.clearTimeout(id);
+ const settle = () => new Promise(resolve => setTimeout(resolve, 30));
+ for (const type of ["block", "url", "number"]) {
+ document.body.innerHTML = `<div id="content" style="position:fixed;inset:0">
+<div id="anchor" style="position:absolute;left:55px;top:167px;width:141px;height:33px"></div></div>
+<div id="mask" style="position:fixed;inset:0"></div>`;
+ const anchor = document.getElementById("anchor");
+ const mask = document.getElementById("mask");
+ const input = document.createElement(type === "number" ? "input" : "textarea");
+ if (input instanceof HTMLInputElement) {
+ input.type = "number";
+ }
+ input.style.cssText = "position:absolute;box-sizing:border-box";
+ input.value = type === "number" ? "" : "draft";
+ mask.append(input);
+ let focusouts = 0;
+ input.addEventListener("focusout", () => focusouts++);
+ const dispose = api.bindAnchoredInputPosition(input, () => anchor, document.getElementById("content"));
+ input.focus();
+ if (type !== "number") {
+ input.setSelectionRange(2, 4);
+ input.dispatchEvent(new CompositionEvent("compositionstart", {bubbles: true}));
+ }
+ await settle();
+ // 真机键盘打开时先报告 145px,随后恢复到稳定的 476px;输入框不能在过渡帧中失焦。
+ for (const height of [145, 476, 0, 476]) {
+ viewport.height = height;
+ viewport.dispatchEvent(new Event("resize"));
+ await settle();
+ check.equal(document.activeElement, input, `${type}: keyboard resize retains focus`);
+ check.equal(focusouts, 0);
+ check.equal(getComputedStyle(input).visibility, "visible");
+ if (height > 0) {
+ const bounds = input.getBoundingClientRect();
+ check.ok(bounds.top >= 0 && bounds.bottom <= height, `${type}: input stays above the keyboard`);
+ }
+ if (type !== "number") {
+ check.equal(input.value, "draft");
+ check.equal(input.selectionStart, 2);
+ check.equal(input.selectionEnd, 4);
+ }
+ }
+ if (type !== "number") {
+ input.dispatchEvent(new CompositionEvent("compositionend", {bubbles: true, data: "X"}));
+ }
+ check.equal(document.execCommand("insertText", false, type === "number" ? "12" : "X"), true);
+ check.equal(input.value, type === "number" ? "12" : "drXt");
+ viewport.height = 808;
+ viewport.dispatchEvent(new Event("resize"));
+ await settle();
+ check.equal(input.getBoundingClientRect().top, 167);
+ check.equal(document.activeElement, input);
+ // 真正移除锚点仍应隐藏编辑框,而不是把失效草稿留在屏幕上。
+ anchor.remove();
+ await settle();
+ check.equal(getComputedStyle(input).visibility, "hidden");
+ dispose();
+ mask.remove();
+ }
+ return "Anchored input DOM cases passed";
+};
+
+test("mobile primary, URL and number inputs retain real DOM focus, selection and edits during keyboard resizing", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 45000,
+}, async () => {
+ const source = transpileModule(readFileSync(path.join(__dirname, "anchoredInputPosition.ts"), "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},
+ }).outputText;
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-anchored-input-test-"));
+ const script = path.join(temporary, "run.cjs");
+ 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: 384, height: 808,
+ webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false}});
+ try {
+ await win.loadURL("about:blank");
+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(
+ `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(source)})`)}));
+ 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 {stdout} = await promisify(execFile)(require("electron") as unknown as string, [script],
+ {env, timeout: 40000, windowsHide: true});
+ assert.match(stdout, /Anchored input DOM cases passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(temporary)), path.resolve(tmpdir()));
+ assert.ok(path.basename(temporary).startsWith("siyuan-anchored-input-test-"));
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
diff --git a/app/src/dialog/anchoredInputPosition.ts b/app/src/dialog/anchoredInputPosition.ts
index e7d9e0c12c..f5c5c3d92c 100644
--- a/app/src/dialog/anchoredInputPosition.ts
+++ b/app/src/dialog/anchoredInputPosition.ts
@@ -1,3 +1,5 @@
+import {isMobile} from "../util/functions";
+
export const bindAnchoredInputPosition = (inputElement: HTMLElement, getAnchor: () => HTMLElement,
contentElement?: HTMLElement, fitContent = false) => {
const maskElement = inputElement.parentElement;
@@ -67,6 +69,22 @@ export const bindAnchoredInputPosition = (inputElement: HTMLElement, getAnchor:
inputElement.style.visibility = "";
return;
}
+ if (isMobile() && document.activeElement === inputElement) {
+ // 键盘动画期间视觉视口可能先缩小再恢复;隐藏聚焦控件会使 WebView 失焦并收起键盘。
+ // 保留同一个输入框和草稿,将其移入可见视口,空间恢复后重新对齐单元格。
+ if (viewportWidth <= 0 || viewportHeight <= 0) {
+ return;
+ }
+ const width = Math.min(preferredSize?.width ?? Math.max(cellRect.width, 25), viewportWidth);
+ const height = Math.min(preferredSize?.height ?? cellRect.height, viewportHeight);
+ const left = Math.max(viewportLeft, Math.min(cellRect.left, viewportLeft + viewportWidth - width));
+ const top = Math.max(viewportTop, Math.min(cellRect.top, viewportTop + viewportHeight - height));
+ inputElement.style.left = `${left - maskRect.left}px`;
+ inputElement.style.top = `${top - maskRect.top}px`;
+ applySize(width, height);
+ inputElement.style.visibility = "";
+ return;
+ }
const visibleLeft = Math.max(viewportLeft, contentRect?.left ?? viewportLeft);
const visibleTop = Math.max(viewportTop, contentRect?.top ?? viewportTop);
const visibleRight = Math.min(viewportLeft + viewportWidth, contentRect?.right ?? viewportLeft + viewportWidth);
diff --git a/app/src/protyle/render/av/cellInputPosition.test.ts b/app/src/protyle/render/av/cellInputPosition.test.ts
index 90b7e08760..6fcb0ccdae 100644
--- a/app/src/protyle/render/av/cellInputPosition.test.ts
+++ b/app/src/protyle/render/av/cellInputPosition.test.ts
@@ -13,7 +13,7 @@ const rect = (left: number, top: number, width: number, height: number) => ({
left, top, width, height, right: left + width, bottom: top + height,
});
-const setup = (fitContent = false) => {
+const setup = (fitContent = false, mobile = false) => {
const frames = new Map<number, FrameRequestCallback>();
let nextFrame = 0;
class TestWindow extends EventTarget {
@@ -56,10 +56,12 @@ const setup = (fitContent = false) => {
const content = {rect: rect(16, 90, 328, 710), getBoundingClientRect() {return this.rect;}};
const input = Object.assign(new EventTarget(), {parentElement: mask, style: {} as Record<string, string>,
value: "draft", scrollHeight: 400});
+ const document = {body: {}, activeElement: input as unknown};
const exports: {bindAnchoredInputPosition?: (input: unknown, anchor: () => unknown, content?: unknown,
fitContent?: boolean) => () => void} = {};
runInNewContext(compiled, {
- exports, window, document: {body: {}}, MutationObserver: TestObserver, ResizeObserver: TestObserver,
+ exports, window, document, MutationObserver: TestObserver, ResizeObserver: TestObserver,
+ require: () => ({isMobile: () => mobile}),
});
const dispose = exports.bindAnchoredInputPosition(input, () => anchor, content, fitContent);
const flush = () => {
@@ -67,7 +69,7 @@ const setup = (fitContent = false) => {
frames.clear();
pending.forEach(callback => callback(0));
};
- return {window, observers, mask, content, input, frames, dispose, flush,
+ return {window, document, observers, mask, content, input, frames, dispose, flush,
get anchor() {return anchor;}, set anchor(value) {anchor = value;}};
};
@@ -119,6 +121,59 @@ test("cell input follows native keyboard opening and closing without replacing t
fixture.dispose();
});
+test("focused mobile cell stays visible throughout keyboard viewport transitions", () => {
+ const f = setup(false, true);
+ f.anchor.rect = rect(55, 167, 141, 33);
+ f.window.innerHeight = 476;
+ for (const height of [145, 476]) {
+ f.window.visualViewport.height = height;
+ f.window.visualViewport.dispatchEvent(new Event("resize"));
+ f.flush();
+ assert.equal(f.input.style.visibility, "");
+ assert.equal(f.input.style.height, "33px");
+ assert.ok(parseFloat(f.input.style.top) + 33 <= height);
+ assert.equal(f.input.value, "draft");
+ }
+ assert.equal(f.input.style.top, "167px");
+ f.dispose();
+});
+
+test("focused mobile cell fits above the keyboard and restores manually requested dimensions", () => {
+ const f = setup(false, true);
+ f.input.style.width = "300px";
+ f.input.style.height = "120px";
+ Object.assign(f.window.visualViewport, {offsetLeft: 20, offsetTop: 100, width: 240, height: 80});
+ f.mask.rect = rect(8, 120, 360, 800);
+ f.window.visualViewport.dispatchEvent(new Event("resize"));
+ f.flush();
+ assert.equal(f.input.style.visibility, "");
+ assert.equal(f.input.style.left, "12px");
+ assert.equal(f.input.style.top, "-20px");
+ assert.equal(f.input.style.width, "240px");
+ assert.equal(f.input.style.height, "80px");
+ f.observers[0].notify();
+ f.flush();
+ Object.assign(f.window.visualViewport, {offsetLeft: 0, offsetTop: 0, width: 360, height: 800});
+ f.mask.rect = rect(0, 0, 360, 800);
+ f.window.visualViewport.dispatchEvent(new Event("resize"));
+ f.flush();
+ assert.equal(f.input.style.width, "300px");
+ assert.equal(f.input.style.height, "120px");
+ assert.equal(f.input.style.top, "500px");
+ // 失去焦点或锚点被移除时仍沿用裁剪/隐藏规则,不能保留失效的编辑入口。
+ f.document.activeElement = f.document.body;
+ f.anchor.rect = rect(40, 810, 220, 36);
+ f.window.dispatchEvent(new Event("scroll"));
+ f.flush();
+ assert.equal(f.input.style.visibility, "hidden");
+ f.document.activeElement = f.input;
+ f.anchor.isConnected = false;
+ f.observers[1].notify();
+ f.flush();
+ assert.equal(f.input.style.visibility, "hidden");
+ f.dispose();
+});
+
test("visual viewport changes keep the input aligned when the fixed mask origin moves", () => {
const fixture = setup();
fixture.flush();