Skip to content

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

:bug: Preserve WebView focus during mobile block dragging https://github.com/siyuan-note/siyuan/issues/20709

Daniel6f8b4696eedb
diff --git a/app/src/mobile/util/keyboardToolbar.test.ts b/app/src/mobile/util/keyboardToolbar.test.ts
new file mode 100644
index 0000000000..9a4121b851
--- /dev/null
+++ b/app/src/mobile/util/keyboardToolbar.test.ts
@@ -0,0 +1,85 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+import * as gutterVisibility from "../../protyle/ui/gutterVisibility";
+import * as touchSelection from "./touchSelection";
+
+const {setGutterTouchDragging} = gutterVisibility;
+const source = createSourceFile("keyboardToolbar.ts", readFileSync("src/mobile/util/keyboardToolbar.ts", "utf8"),
+ ScriptTarget.Latest, true);
+const declaration = source.statements.find(node => isVariableStatement(node) &&
+ node.declarationList.declarations.some(item => item.name.getText(source) === "hideKeyboardToolbarByApp"));
+assert.ok(declaration);
+const compiled = transpileModule(`${declaration.getText(source).replace(/^export /, "")}\nhideKeyboardToolbarByApp;`, {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = () => {
+ const gutter = {} as HTMLElement;
+ const calls: string[] = [];
+ let editor: unknown = {protyle: {gutter: {element: gutter}, wysiwyg: {element: {contains: () => true}}}};
+ let text = "";
+ let tableSelection = false;
+ const selection = {rangeCount: 1, getRangeAt: () => ({collapsed: !text, startContainer: {}, endContainer: {}}),
+ removeAllRanges: () => calls.push("clear-selection")};
+ const hide = runInNewContext(compiled, {
+ ...touchSelection, ...gutterVisibility,
+ inlineMathSelection: {reset: () => calls.push("reset-math")},
+ preventKeyboardToolbarRender: () => calls.push("prevent-render"),
+ hideKeyboardToolbar: () => calls.push("hide-toolbar"),
+ restoreRecentAndroidTableCellSelectAll: () => { calls.push("restore-table"); return tableSelection; },
+ getCurrentEditor: () => editor, getSelection: () => selection,
+ hideElements: () => calls.push("hide-utils"), stripSemanticMarkersFromRangeText: () => text,
+ keyboardPanelTop: undefined,
+ document: {activeElement: {tagName: "DIV", blur: () => calls.push("blur")}},
+ });
+ return {gutter, calls, selection, hide,
+ setText: (value: string) => text = value,
+ setTableSelection: () => tableSelection = true,
+ removeEditor: (): void => { editor = undefined; }};
+};
+
+for (const preserveSelection of [true, false]) {
+ for (const range of ["caret", "cleared", "text"]) {
+ test(`keyboard hide preserves the touched gutter's focus (${preserveSelection}, ${range})`, () => {
+ const f = fixture();
+ if (range === "cleared") f.selection.rangeCount = 0;
+ if (range === "text") f.setText("selected text");
+ setGutterTouchDragging(f.gutter, true);
+ assert.equal(f.hide(preserveSelection), touchSelection.KeyboardHideResult.PreserveSelection);
+ assert.ok(f.calls.includes("hide-toolbar"), "the keyboard toolbar still closes");
+ assert.ok(f.calls.includes("prevent-render"));
+ assert.ok(!f.calls.includes("blur"));
+ assert.ok(!f.calls.includes("clear-selection"));
+ setGutterTouchDragging(f.gutter, false);
+ });
+ }
+}
+
+test("gutter dragging does not reopen the keyboard from a recent table selection", () => {
+ const f = fixture();
+ f.setTableSelection();
+ setGutterTouchDragging(f.gutter, true);
+ assert.equal(f.hide(true), touchSelection.KeyboardHideResult.PreserveSelection);
+ assert.ok(!f.calls.includes("restore-table"));
+ setGutterTouchDragging(f.gutter, false);
+ assert.equal(f.hide(true), touchSelection.KeyboardHideResult.RestoreTableCellSelection);
+});
+
+test("keyboard cleanup resumes after the gutter gesture and leaves other editors alone", () => {
+ const f = fixture();
+ setGutterTouchDragging({} as HTMLElement, true);
+ assert.equal(f.hide(true), touchSelection.KeyboardHideResult.Cleanup);
+ setGutterTouchDragging(f.gutter, true);
+ setGutterTouchDragging(f.gutter, false);
+ assert.equal(f.hide(true), touchSelection.KeyboardHideResult.Cleanup);
+ f.setText("selected text");
+ assert.equal(f.hide(true), touchSelection.KeyboardHideResult.PreserveSelection);
+ assert.equal(f.hide(false), touchSelection.KeyboardHideResult.Cleanup);
+ assert.ok(f.calls.includes("blur"));
+ assert.ok(f.calls.includes("clear-selection"));
+ f.removeEditor();
+ assert.equal(f.hide(true), touchSelection.KeyboardHideResult.Cleanup);
+});
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 91542cd6a9..c161664833 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -87,6 +87,7 @@ import {MOBILE_TOOLBAR_NAMES} from "../../protyle/toolbar/defaults";
import {getKeyboardPanelHeight} from "./keyboardPanelHeight";
import {isMobileLandscape} from "./orientation";
import {restoreGutterBySelection} from "../../protyle/gutter/restore";
+import {isGutterTouchDragging} from "../../protyle/ui/gutterVisibility";
import {getFrequentSlashButtons, mountLiteSlashMenu, prependFrequentSlashButtons} from "./liteSlashMenu";
import {getPluginSlashEntryKey, SLASH_MENU_ROOT_PATH} from "../../config/entryVisibility/catalog";
import {hintSlash} from "../../protyle/hint/extend";
@@ -1365,6 +1366,13 @@ export const hideKeyboardToolbar = (keyboardClosed = true) => {
export const hideKeyboardToolbarByApp = (preserveSelection = false) => {
inlineMathSelection.reset();
+ const gutterElement = getCurrentEditor()?.protyle.gutter?.element;
+ if (gutterElement && isGutterTouchDragging(gutterElement)) {
+ // 键盘收起时保留块标手势所需的 WebView 焦点,避免原生端取消后续触摸。
+ preventKeyboardToolbarRender();
+ hideKeyboardToolbar();
+ return KeyboardHideResult.PreserveSelection;
+ }
if (preserveSelection && ["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName)) {
// 输入法切换安全键盘时会临时隐藏,保留普通输入框焦点,避免中断密码输入。
preventKeyboardToolbarRender();
diff --git a/app/src/util/touchDragSelection.test.ts b/app/src/util/touchDragSelection.test.ts
index 530af308a0..79a5c42512 100644
--- a/app/src/util/touchDragSelection.test.ts
+++ b/app/src/util/touchDragSelection.test.ts
@@ -5,9 +5,10 @@ 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";
+import {createSourceFile, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";
-const browserFixture = (bridgeSource: string, coreSource: string, gutterVisibilitySource: string) => {
+const browserFixture = (bridgeSource: string, coreSource: string, gutterVisibilitySource: string,
+ keyboardSource: string, touchSelectionSource: string) => {
document.body.innerHTML = `<style>
body{margin:0}.protyle-wysiwyg{padding-left:50px}.block{height:100px;padding:12px;box-sizing:border-box}
.protyle-gutters{position:fixed;left:0;top:20px;width:32px;user-select:none}
@@ -29,6 +30,20 @@ body{margin:0}.protyle-wysiwyg{padding-left:50px}.block{height:100px;padding:12p
new Function("exports", coreSource)(core);
const visibility = {} as typeof import("../protyle/ui/gutterVisibility");
new Function("exports", gutterVisibilitySource)(visibility);
+ const touchSelection = {} as typeof import("../mobile/util/touchSelection");
+ new Function("exports", touchSelectionSource)(touchSelection);
+ const keyboardDependencies = {
+ ...visibility, ...touchSelection,
+ inlineMathSelection: {reset() {}}, preventKeyboardToolbarRender() {}, hideKeyboardToolbar() {},
+ restoreRecentAndroidTableCellSelectAll: () => false,
+ getCurrentEditor: () => ({protyle: {gutter: {element: gutter},
+ wysiwyg: {element: document.querySelector(".protyle-wysiwyg")}}}),
+ getSelection: () => document.getSelection(), hideElements() {},
+ stripSemanticMarkersFromRangeText: (range: Range) => range.toString(),
+ keyboardPanelTop: undefined as number | undefined,
+ };
+ const hideKeyboard = new Function(...Object.keys(keyboardDependencies),
+ `${keyboardSource}\nreturn hideKeyboardToolbarByApp;`)(...Object.values(keyboardDependencies));
const bridge = {} as typeof import("./touchDragBridge");
new Function("exports", "require", bridgeSource)(bridge, (id: string) => {
if (id === "./touchDragBridgeCore") {
@@ -68,6 +83,16 @@ body{margin:0}.protyle-wysiwyg{padding-left:50px}.block{height:100px;padding:12p
document.getSelection().selectAllChildren(editable);
},
selectStart: () => source.dispatchEvent(new Event("selectstart", {bubbles: true, cancelable: true})),
+ setCaret: () => document.getSelection().collapseToStart(),
+ hideKeyboard: (preserveSelection = true) => {
+ const result = hideKeyboard(preserveSelection);
+ if (result === touchSelection.KeyboardHideResult.Cleanup) {
+ // 原生端收到清理结果后会清除 WebView 焦点,触发桥接的失焦取消。
+ (document.activeElement as HTMLElement)?.blur();
+ window.dispatchEvent(new Event("blur"));
+ }
+ return result;
+ },
keyboardLayout: () => {
(document.activeElement as HTMLElement)?.blur();
visibility.hideGutterElements([gutter], true);
@@ -99,6 +124,15 @@ test("native mobile gutter gestures preserve taps and scrolling while excluding
const bridge = compile("src/util/touchDragBridge.ts");
const core = compile("src/util/touchDragBridgeCore.ts");
const visibility = compile("src/protyle/ui/gutterVisibility.ts");
+ const touchSelection = compile("src/mobile/util/touchSelection.ts");
+ const keyboardFile = createSourceFile("keyboardToolbar.ts", readFileSync("src/mobile/util/keyboardToolbar.ts", "utf8"),
+ ScriptTarget.Latest, true);
+ const keyboardDeclaration = keyboardFile.statements.find(node => isVariableStatement(node) &&
+ node.declarationList.declarations.some(item => item.name.getText(keyboardFile) === "hideKeyboardToolbarByApp"));
+ assert.ok(keyboardDeclaration);
+ const keyboard = transpileModule(keyboardDeclaration.getText(keyboardFile).replace(/^export /, ""), {
+ compilerOptions: {target: ScriptTarget.ES2021},
+ }).outputText;
const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-touch-drag-selection-"));
const script = path.join(temporary, "run.cjs");
writeFileSync(script, `const assert = require("node:assert/strict");
@@ -114,7 +148,8 @@ app.whenReady().then(async () => {
win.webContents.debugger.attach("1.3");
await win.webContents.debugger.sendCommand("Emulation.setTouchEmulationEnabled", {enabled: true});
const evaluate = code => win.webContents.executeJavaScript(code);
- await evaluate(${JSON.stringify("const __name = value => value; (" + browserFixture.toString() + ")(" + JSON.stringify(bridge) + "," + JSON.stringify(core) + "," + JSON.stringify(visibility) + ");")});
+ await evaluate(${JSON.stringify("const __name = value => value; (" + browserFixture.toString() + ")(" +
+ [bridge, core, visibility, keyboard, touchSelection].map(value => JSON.stringify(value)).join(",") + ");")});
const touch = (type, x = 15, y = 45) => win.webContents.debugger.sendCommand("Input.dispatchTouchEvent", {
type, touchPoints: ["touchEnd", "touchCancel"].includes(type) ? [] : [{x, y, id: 1}],
});
@@ -150,6 +185,27 @@ app.whenReady().then(async () => {
assert.equal(state.ghost, false);
assert.equal(await evaluate("nativeDrag.selectStart()"), true);
}
+ await evaluate("nativeDrag.selectText(); nativeDrag.setCaret()");
+ await touch("touchStart");
+ await delay(100);
+ assert.equal(await evaluate("nativeDrag.hideKeyboard()"), 1,
+ "native keyboard dismissal preserves WebView focus while the gutter long press is pending");
+ await delay(450);
+ assert.equal((await evaluate("nativeDrag.state()")).active, true);
+ assert.equal(await evaluate("nativeDrag.hideKeyboard(false)"), 1,
+ "explicit keyboard dismissal preserves focus after block dragging clears the text range");
+ await touch("touchMove", 80, 90);
+ await touch("touchMove", 80, 150);
+ await touch("touchEnd");
+ await delay(100);
+ const keyboardDrag = await evaluate("nativeDrag.state()");
+ assert.equal(keyboardDrag.starts, 3);
+ assert.equal(keyboardDrag.drops, 3);
+ assert.equal(keyboardDrag.ends, 3);
+ assert.equal(keyboardDrag.active, false);
+ assert.equal(keyboardDrag.ghost, false);
+ assert.equal(await evaluate("nativeDrag.hideKeyboard()"), 0,
+ "the keyboard callback resumes ordinary focus cleanup after release");
await touch("touchStart");
await delay(50);
await touch("touchEnd");
@@ -165,7 +221,7 @@ app.whenReady().then(async () => {
await delay(150);
const scrolled = await evaluate("nativeDrag.state()");
assert.ok(scrolled.scroll > 0, "full gutter swipes still scroll natively");
- assert.equal(scrolled.starts, 2);
+ assert.equal(scrolled.starts, 3);
assert.equal(await evaluate("nativeDrag.selectStart()"), true);
console.log("Native gutter selection exclusion passed");
win.destroy();