Skip to content

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

:bug: Restore native mobile selection and keyboard behavior https://github.com/siyuan-note/siyuan/issues/19949

Daniel5ed62d31c5b3
diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scss
index 1a962da20b..7475142c1e 100644
--- a/app/src/assets/scss/main/_mobile.scss
+++ b/app/src/assets/scss/main/_mobile.scss
@@ -1342,11 +1342,6 @@ body.mobile-topbar--merged {
flex-direction: column;
z-index: 1;
- &--selection {
- width: calc(100% - 16px);
- max-width: 480px;
- }
-
&__dynamic {
overflow: auto;
display: flex;
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index f4b34ce5e9..a72415a278 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -62,7 +62,6 @@ import {correctHotkey} from "../boot/globalEvent/commonHotkey";
import {processIOSPurchaseResponse} from "../util/iOSPurchase";
import {nbsp2space} from "../protyle/util/normalizeText";
import {armKeyboardLock, callMobileAppShowKeyboard, canInput, setWebViewFocusable} from "./util/mobileAppUtil";
-import {suppressMobileSelectionFocus} from "./util/selectionKeyboard";
import {hideAllElements} from "../protyle/ui/hideElements";
import {initTouchDragBridge} from "../util/touchDragBridge";
import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";
@@ -141,7 +140,7 @@ class App {
scrollInputIntoView(editableElement);
}, Constants.TIMEOUT_TRANSITION);
}
- if (editableElement && !suppressMobileSelectionFocus(editableElement)) {
+ if (editableElement) {
hideKeyboardToolbarUtilOnEditorClick();
// 原生 App 通过桥接主动唤起键盘;移动端浏览器没有桥接,但点击可编辑区域后也会立刻触发 resize,
// 进而调用 activeBlur 关闭键盘(比如三星键盘 https://github.com/siyuan-note/siyuan/issues/18078),所以此处也需要上锁
@@ -158,7 +157,6 @@ class App {
{
const __siyuan_original_focus = HTMLElement.prototype.focus;
HTMLElement.prototype.focus = function (this: HTMLElement, ...args) {
- const selectionOnly = suppressMobileSelectionFocus(this);
try {
if (typeof __siyuan_original_focus === "function") {
__siyuan_original_focus.apply(this, args);
@@ -166,7 +164,7 @@ class App {
} catch (e) {
console.error("Error in focus event:", e);
}
- if (!selectionOnly && canInput(this)) {
+ if (canInput(this)) {
// 原生 App 通过桥接主动唤起键盘;移动端浏览器没有桥接,仅上锁以阻止 focus 后立即触发的 activeBlur 关闭键盘
if (window.JSAndroid && window.JSAndroid.showKeyboard || window.JSHarmony && window.JSHarmony.showKeyboard) {
callMobileAppShowKeyboard();
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 99f90b47c1..f8a2f99d19 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -90,7 +90,6 @@ import {insertEmptyBlock} from "../../block/util";
import {getIconByType} from "../../editor/getIcon";
import {MOBILE_TOOLBAR_ACTIONS, MOBILE_TOOLBAR_INSERTS} from "./toolbarActions";
import {pauseMobileBarsScroll} from "./mobileBars";
-import {clearMobileSelectionInput, getMobileSelectionRange, initMobileSelectionInput, isMobileSelectionMode} from "./selectionKeyboard";
const getCurrentEditor = () => getMobileToolbarProtyle()?.getInstance() || getDocumentEditor();
let toolbarProtyle: IProtyle;
@@ -103,7 +102,10 @@ const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<string
isAvailable: name => {
const protyle = getCurrentEditor()?.protyle;
if (name === "copy" || name === "cut") {
- return !!getMobileSelectionRange();
+ const selection = getSelection();
+ return !!protyle && !protyle.disabled && selection?.rangeCount > 0 && !selection.isCollapsed &&
+ protyle.wysiwyg.element.contains(selection.anchorNode) &&
+ protyle.wysiwyg.element.contains(selection.focusNode);
}
if (name === "block") {
return !!protyle?.gutter || !!protyle && !!getTableCellRichContext(protyle);
@@ -396,43 +398,12 @@ const preventKeyboardToolbarRender = () => {
};
const updateKeyboardToolbarPosition = () => {
- const toolbarElement = document.getElementById("keyboardToolbar");
- const range = getMobileSelectionRange();
- const floating = !!range && keyboardPanelTop === undefined;
- if (toolbarElement.classList.contains("keyboard--selection") && !floating) {
- toolbarElement.style.top = "";
- toolbarElement.style.left = "";
- toolbarElement.style.bottom = "";
- toolbarElement.style.visibility = "";
- }
- toolbarElement.classList.toggle("keyboard--selection", floating);
- if (floating) {
- const viewport = getVisibleViewportBounds();
- const content = hasClosestByClassName(range.startContainer, "protyle-content", true);
- if (content) {
- const contentRect = content.getBoundingClientRect();
- viewport.top = Math.max(viewport.top, contentRect.top);
- viewport.bottom = Math.min(viewport.bottom, contentRect.bottom);
- }
- const rect = Array.from(range.getClientRects()).find(item => item.bottom > viewport.top && item.top < viewport.bottom);
- toolbarElement.style.visibility = rect ? "" : "hidden";
- if (rect) {
- const width = toolbarElement.getBoundingClientRect().width;
- const height = toolbarElement.clientHeight || 48;
- toolbarElement.style.top = `${Math.max(viewport.top + 8, Math.min(viewport.bottom - height - 8,
- rect.top - height - 8 >= viewport.top ? rect.top - height - 8 : rect.bottom + 8))}px`;
- toolbarElement.style.left = `${Math.max(8, Math.min(window.innerWidth - width - 8,
- rect.left + (rect.width - width) / 2))}px`;
- }
- toolbarElement.style.bottom = "auto";
- toolbarElement.style.transform = "";
- return;
- }
updateKeyboardPanelHeight();
scrollKeyboardSelectionIntoView();
if (isInMobileApp() || !window.visualViewport) {
return;
}
+ const toolbarElement = document.getElementById("keyboardToolbar");
const viewportBottom = window.visualViewport.offsetTop + window.visualViewport.height;
const toolbarHeight = toolbarElement.getBoundingClientRect().height || 48;
toolbarElement.style.transform = "";
@@ -896,7 +867,7 @@ const hideKeyboardToolbarUtil = (restoreKeyboard = false) => {
if (keyboardPanelClosing) {
return;
}
- if (restoreKeyboard && keyboardPanelTop !== undefined && !isMobileSelectionMode()) {
+ if (restoreKeyboard && keyboardPanelTop !== undefined) {
keyboardPanelClosing = true;
showUtil = true;
resetKeyboardToolbarUtilButtons();
@@ -985,7 +956,7 @@ const renderKeyboardToolbar = () => {
// 合并同一帧内的选区变化,在浏览器更新选区后及时显示工具栏。
renderKeyboardToolbarFrame = window.requestAnimationFrame(() => {
renderKeyboardToolbarFrame = undefined;
- if (!canInput(document.activeElement) && !getMobileSelectionRange()) {
+ if (!canInput(document.activeElement)) {
hideKeyboardToolbar();
return;
}
@@ -1090,7 +1061,7 @@ const showKeyboardToolbarElement = () => {
}
const selection = getSelection();
// 空块恢复焦点时 Selection 可能暂时为空,但原生键盘已经显示,仍需隐藏普通底栏。
- notifyMobileKeyboardChange(!isMobileSelectionMode());
+ notifyMobileKeyboardChange(true);
const protyle = getCurrentEditor()?.protyle;
if (!protyle || (selection.rangeCount > 0 && (
hasClosestByClassName(selection.getRangeAt(0).startContainer, "protyle-wysiwyg", true) !== protyle.wysiwyg.element ||
@@ -1107,14 +1078,10 @@ const showKeyboardToolbarElement = () => {
toolbarProtyle = protyle;
updateMobilePluginToolbar(protyle);
}
- const selectionOnly = isMobileSelectionMode();
const done = toolbarElement.querySelector('.keyboard__action[data-type="done"]');
- done.setAttribute("aria-label", selectionOnly && keyboardPanelTop === undefined ? window.siyuan.languages.edit : window.siyuan.languages.close);
+ done.setAttribute("aria-label", window.siyuan.languages.close);
done.querySelector("use").setAttribute("xlink:href",
- keyboardPanelTop !== undefined ? "#iconCloseRound" : selectionOnly ? "#iconEdit" : "#iconKeyboardHide");
- if (selectionOnly) {
- getMobileToolbarPaddingElement(protyle).style.paddingBottom = "";
- }
+ keyboardPanelTop !== undefined ? "#iconCloseRound" : "#iconKeyboardHide");
if (!toolbarElement.classList.contains("fn__none")) {
return;
}
@@ -1124,9 +1091,6 @@ const showKeyboardToolbarElement = () => {
toolbarElement.classList.remove("fn__none");
toolbarElement.style.zIndex = (++window.siyuan.zIndex).toString();
updateKeyboardToolbarPosition();
- if (selectionOnly) {
- return;
- }
const modelElement = document.getElementById("model");
if (modelElement.style.transform === "translateX(0px)") {
modelElement.style.paddingBottom = "48px";
@@ -1155,7 +1119,7 @@ export const showKeyboardToolbar = () => {
const scrollKeyboardSelectionIntoView = () => {
const toolbarElement = document.getElementById("keyboardToolbar");
- if (!toolbarElement || toolbarElement.classList.contains("fn__none") || showUtil || isMobileSelectionMode()) {
+ if (!toolbarElement || toolbarElement.classList.contains("fn__none") || showUtil) {
return;
}
clearTimeout(scrollSelectionIntoViewTimeout);
@@ -1237,7 +1201,7 @@ export const hideKeyboardToolbar = () => {
clearTimeout(scrollSelectionIntoViewTimeout);
clearRenderGutterAfterScroll?.();
// 键盘退场时保留已展开的移动端菜单,菜单由用户操作或编辑器切换关闭。
- if (showUtil || keyboardPanelTop !== undefined || getMobileSelectionRange()) {
+ if (showUtil || keyboardPanelTop !== undefined) {
return;
}
pendingKeyboardFocus = undefined;
@@ -1263,11 +1227,6 @@ export const hideKeyboardToolbar = () => {
};
export const hideKeyboardToolbarByApp = (preserveSelection = false) => {
- if (isMobileSelectionMode()) {
- notifyMobileKeyboardChange(false);
- renderKeyboardToolbar();
- return KeyboardHideResult.PreserveSelection;
- }
inlineMathSelection.reset();
if (preserveSelection && ["INPUT", "TEXTAREA"].includes(document.activeElement?.tagName)) {
// 输入法切换安全键盘时会临时隐藏,保留普通输入框焦点,避免中断密码输入。
@@ -1305,9 +1264,6 @@ export const hideKeyboardToolbarByApp = (preserveSelection = false) => {
};
export const activeBlur = (force = false) => {
- if (!force && isMobileSelectionMode()) {
- return;
- }
const now = Date.now();
if (!force && now < keyboardLockUntil) {
console.warn(`activeBlur blocked by lock (remaining: ${keyboardLockUntil - now}ms)`);
@@ -1328,20 +1284,6 @@ export const activeBlur = (force = false) => {
};
export const initKeyboardToolbar = () => {
- initMobileSelectionInput(() => {
- const protyle = getCurrentEditor()?.protyle;
- if (protyle) {
- hideElements(["util"], protyle);
- }
- notifyMobileKeyboardChange(false);
- window.JSAndroid?.hideKeyboard?.();
- window.JSHarmony?.hideKeyboard?.();
- }, renderKeyboardToolbar);
- document.addEventListener("scroll", () => {
- if (getMobileSelectionRange()) {
- updateKeyboardToolbarPosition();
- }
- }, true);
window.addEventListener("siyuan-mobile-toolbar-focus", renderKeyboardToolbar);
window.addEventListener("siyuan-mobile-toolbar-editor", (event: CustomEvent<IProtyle>) => {
if (event.detail) {
@@ -1357,9 +1299,6 @@ export const initKeyboardToolbar = () => {
});
let composing = false;
window.addEventListener("siyuan-mobile-keyboard-hiding", () => {
- if (isMobileSelectionMode()) {
- return;
- }
// 键盘退场前先隐藏工具栏,焦点和选区由原生端在动画结束后清理。
preventKeyboardToolbarRender();
hideKeyboardToolbar();
@@ -1563,7 +1502,7 @@ export const initKeyboardToolbar = () => {
toolbarElement.addEventListener("mousedown", event => {
const buttonElement = hasClosestByTag(event.target as HTMLElement, "BUTTON");
const type = buttonElement && buttonElement.getAttribute("data-type");
- if (isMobileSelectionMode() || type === "undo" || type === "redo" || type === "block") {
+ if (type === "undo" || type === "redo" || type === "block") {
// 保持编辑器焦点,避免工具栏操作期间软键盘收起。
event.preventDefault();
}
@@ -1693,12 +1632,6 @@ export const initKeyboardToolbar = () => {
event.stopPropagation();
const selection = getSelection();
const currentRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;
- if (type === "done" && isMobileSelectionMode() && keyboardPanelTop === undefined) {
- const range = currentRange?.cloneRange() || protyle?.toolbar.range;
- clearMobileSelectionInput();
- restoreKeyboardToolbarRange(protyle, range);
- return;
- }
// 收起菜单不依赖实时选区,编辑器失焦后使用保存的选区恢复光标。
const closeAddMenu = type === "add" && buttonElement.classList.contains("protyle-toolbar__item--current");
if (type === "done" || closeAddMenu) {
diff --git a/app/src/mobile/util/mobileAppUtil.test.ts b/app/src/mobile/util/mobileAppUtil.test.ts
index 81fd0e699c..63dfc42275 100644
--- a/app/src/mobile/util/mobileAppUtil.test.ts
+++ b/app/src/mobile/util/mobileAppUtil.test.ts
@@ -128,8 +128,6 @@ describe("mobile input detection", () => {
describe("mobile app keyboard", () => {
it("notifies listeners before requesting the Android keyboard", () => {
const originalWindow = globalThis.window;
- const originalDocument = globalThis.document;
- Object.defineProperty(globalThis, "document", {configurable: true, value: {activeElement: undefined}});
const calls: string[] = [];
const testWindow = new EventTarget() as Window & typeof globalThis;
Object.assign(testWindow, {
@@ -152,7 +150,6 @@ describe("mobile app keyboard", () => {
callMobileAppShowKeyboard();
assert.deepEqual(calls, ["change", "keyboard"]);
} finally {
- Object.defineProperty(globalThis, "document", {configurable: true, value: originalDocument});
Object.defineProperty(globalThis, "window", {
configurable: true,
value: originalWindow,
diff --git a/app/src/mobile/util/mobileAppUtil.ts b/app/src/mobile/util/mobileAppUtil.ts
index 5022a4fcbb..6817a244ab 100644
--- a/app/src/mobile/util/mobileAppUtil.ts
+++ b/app/src/mobile/util/mobileAppUtil.ts
@@ -1,6 +1,5 @@
import {hasClosestByAttribute, hasClosestByClassName} from "../../protyle/util/hasClosest";
import {notifyMobileKeyboardChange} from "./mobileKeyboardChange";
-import {isMobileSelectionMode, suppressMobileSelectionFocus} from "./selectionKeyboard";
export let keyboardLockUntil = 0;
@@ -11,9 +10,6 @@ export const armKeyboardLock = () => {
};
export const callMobileAppShowKeyboard = () => {
- if (isMobileSelectionMode() || suppressMobileSelectionFocus(document.activeElement)) {
- return;
- }
armKeyboardLock();
notifyMobileKeyboardChange(true);
diff --git a/app/src/mobile/util/mobileInputFlow.test.ts b/app/src/mobile/util/mobileInputFlow.test.ts
new file mode 100644
index 0000000000..5f56480482
--- /dev/null
+++ b/app/src/mobile/util/mobileInputFlow.test.ts
@@ -0,0 +1,105 @@
+import {readFileSync} from "node:fs";
+import {join} from "node:path";
+import {runInNewContext} from "node:vm";
+import {it} from "node:test";
+import * as assert from "node:assert/strict";
+import * as ts from "typescript";
+
+const sourceFile = ts.createSourceFile("mobile/index.ts", readFileSync(join(__dirname, "../index.ts"), "utf8"),
+ ts.ScriptTarget.Latest, true);
+const appClass = sourceFile.statements.find(node => ts.isClassDeclaration(node) && node.name?.text === "App") as ts.ClassDeclaration;
+const statements = appClass.members.find(ts.isConstructorDeclaration).body.statements;
+const clickBinding = statements.find(node => node.getText(sourceFile).startsWith('window.addEventListener("click",'));
+const focusBinding = statements.find(node => ts.isBlock(node) && node.getText(sourceFile).includes("__siyuan_original_focus"));
+assert.ok(clickBinding && focusBinding);
+
+const compile = (source: string) => ts.transpileModule(source, {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+}).outputText;
+
+for (const platform of ["android", "harmony", "ios", "browser"]) {
+ it(`preserves the selection input flow on ${platform}`, () => {
+ const calls: string[] = [];
+ const listeners = new Map<string, (event: {target: TestElement}) => void>();
+ const document = {activeElement: undefined as TestElement | undefined, contains: () => true};
+ const selection = {isCollapsed: false, rangeCount: 1, toString: () => "selected text"};
+ class TestElement {
+ nodeType = 1;
+ tagName = "DIV";
+ parentElement: TestElement | null = null;
+ attributes = new Map<string, string>();
+ classes = new Set<string>();
+ classList = {contains: (name: string) => this.classes.has(name)};
+ getAttribute(name: string) { return this.attributes.get(name) ?? null; }
+ hasAttribute(name: string) { return this.attributes.has(name); }
+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }
+ focus() {
+ document.activeElement = this;
+ calls.push("focus");
+ }
+ }
+ const body = new TestElement();
+ body.tagName = "BODY";
+ const root = new TestElement();
+ root.classes.add("protyle-wysiwyg");
+ root.setAttribute("data-readonly", "false");
+ root.setAttribute("contenteditable", "false");
+ root.parentElement = body;
+ const editable = new TestElement();
+ editable.parentElement = root;
+ editable.setAttribute("contenteditable", "true");
+ editable.setAttribute("inputmode", "text");
+ const window = {
+ siyuan: {},
+ addEventListener: (type: string, callback: (event: {target: TestElement}) => void) => listeners.set(type, callback),
+ dispatchEvent: (event: CustomEvent<boolean>) => calls.push(event.detail ? "open" : "close"),
+ setTimeout,
+ clearTimeout,
+ ...(platform === "android" ? {JSAndroid: {showKeyboard: () => calls.push("show"), hideKeyboard: () => calls.push("hide")}} : {}),
+ ...(platform === "harmony" ? {JSHarmony: {showKeyboard: () => calls.push("show"), hideKeyboard: () => calls.push("hide")}} : {}),
+ };
+ const globals = {window, document, HTMLElement: TestElement, getSelection: () => selection, CustomEvent, console};
+ const closest: any = {};
+ runInNewContext(compile(readFileSync(join(__dirname, "../../protyle/util/hasClosest.ts"), "utf8")),
+ {...globals, exports: closest});
+ const notifier: any = {};
+ runInNewContext(compile(readFileSync(join(__dirname, "mobileKeyboardChange.ts"), "utf8")),
+ {...globals, exports: notifier});
+ const input: any = {};
+ runInNewContext(compile(readFileSync(join(__dirname, "mobileAppUtil.ts"), "utf8")), {
+ ...globals, exports: input,
+ require: (name: string) => name === "./mobileKeyboardChange" ? notifier : closest,
+ });
+ // 运行 App 中的实际事件绑定;选区状态不应替换输入属性或拦截 focus。
+ runInNewContext(compile(`${clickBinding.getText(sourceFile)}\n${focusBinding.getText(sourceFile)}`), {
+ ...globals, ...closest, ...input,
+ hideKeyboardToolbarUtilOnEditorClick: () => calls.push("menu"),
+ hideAllElements() {},
+ });
+ const nativeKeyboard = platform === "android" || platform === "harmony";
+ editable.focus();
+ assert.deepEqual(calls, nativeKeyboard ? ["focus", "open", "show"] : ["focus"]);
+ assert.ok(input.keyboardLockUntil > Date.now());
+ assert.equal(document.activeElement, editable);
+ assert.equal(editable.getAttribute("inputmode"), "text");
+ for (const isCollapsed of [false, true, false]) {
+ calls.length = 0;
+ selection.isCollapsed = isCollapsed;
+ listeners.get("click")({target: editable});
+ assert.deepEqual(calls, nativeKeyboard ? ["menu", "open", "show"] : ["menu"]);
+ assert.equal(editable.getAttribute("inputmode"), "text");
+ assert.equal(selection.isCollapsed, isCollapsed);
+ }
+ calls.length = 0;
+ root.setAttribute("data-readonly", "true");
+ editable.focus();
+ listeners.get("click")({target: editable});
+ assert.deepEqual(calls, ["focus"]);
+ root.setAttribute("data-readonly", "false");
+ editable.setAttribute("contenteditable", "false");
+ calls.length = 0;
+ editable.focus();
+ listeners.get("click")({target: editable});
+ assert.deepEqual(calls, ["focus"]);
+ });
+}
diff --git a/app/src/mobile/util/selectionKeyboard.ts b/app/src/mobile/util/selectionKeyboard.ts
deleted file mode 100644
index a5001dadff..0000000000
--- a/app/src/mobile/util/selectionKeyboard.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-let editor: HTMLElement;
-let selecting = false;
-let touching = false;
-let gestureUntil = 0;
-const inputModes = new Map<Element, string | null>();
-
-const suppressInput = (element: Element) => {
- if (!inputModes.has(element)) {
- inputModes.set(element, element.getAttribute("inputmode"));
- }
- element.setAttribute("inputmode", "none");
-};
-
-export const clearMobileSelectionInput = () => {
- inputModes.forEach((value, element) => {
- if (value === null) {
- element.removeAttribute("inputmode");
- } else {
- element.setAttribute("inputmode", value);
- }
- });
- inputModes.clear();
- editor = undefined;
- selecting = false;
- touching = false;
- gestureUntil = 0;
-};
-
-export const isMobileSelectionMode = () => {
- if (editor && !editor.isConnected) {
- clearMobileSelectionInput();
- }
- return selecting;
-};
-
-export const suppressMobileSelectionFocus = (element: Element) => {
- if (editor && element && !editor.contains(element) && !element.closest("#keyboardToolbar, .protyle-util, .b3-menu")) {
- clearMobileSelectionInput();
- return false;
- }
- if (!editor?.isConnected || !editor.contains(element) || (!selecting && inputModes.size === 0)) {
- return false;
- }
- // 格式操作可能替换可编辑节点,恢复焦点时继续保留选择模式。
- suppressInput(element);
- return true;
-};
-
-export const getMobileSelectionRange = () => {
- if (!isMobileSelectionMode()) {
- return;
- }
- const selection = getSelection();
- if (!selection?.rangeCount) {
- return;
- }
- const range = selection.getRangeAt(0);
- if (!range.collapsed && editor.contains(range.startContainer) && editor.contains(range.endContainer)) {
- return range;
- }
-};
-
-const refreshSelectionFocus = () => {
- const active = document.activeElement as HTMLElement;
- const selection = getSelection();
- if (window.JSAndroid || window.JSHarmony || !getMobileSelectionRange() || !editor.contains(active)) {
- return;
- }
- // 浏览器在焦点切换时应用 inputmode,保留方向及端点,避免收起键盘时丢失选区。
- const {anchorNode, anchorOffset, focusNode, focusOffset} = selection;
- suppressInput(active);
- active.blur();
- active.focus({preventScroll: true});
- selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
-};
-
-export const initMobileSelectionInput = (onSelect: () => void, onChange: () => void) => {
- const begin = (event: PointerEvent) => {
- if (event.pointerType !== "touch" && event.pointerType !== "pen") {
- return;
- }
- const target = event.target as HTMLElement;
- if (target.closest("#keyboardToolbar, .protyle-util, .b3-menu")) {
- return;
- }
- const root = target.closest<HTMLElement>('.protyle-wysiwyg[data-readonly="false"]');
- const editable = target.closest<HTMLElement>('[contenteditable="true"], [contenteditable="plaintext-only"]');
- if (!root || !editable || target.closest("input, textarea") ||
- target.closest("[contenteditable]")?.getAttribute("contenteditable") === "false" ||
- root.querySelector(".protyle-wysiwyg--select")) {
- clearMobileSelectionInput();
- return;
- }
- if (editor !== root) {
- clearMobileSelectionInput();
- }
- editor = root;
- touching = true;
- // 在浏览器处理长按之前阻止首次唤起键盘;短按会在 click 中恢复输入。
- if (selecting || !document.body.classList.contains("mobile-keyboard--open")) {
- suppressInput(editable);
- }
- };
- const end = () => {
- touching = false;
- gestureUntil = Date.now() + 600;
- refreshSelectionFocus();
- };
- const update = () => {
- if (!editor?.isConnected || (!selecting && !touching && Date.now() > gestureUntil)) {
- return;
- }
- const selection = getSelection();
- if (!selection?.rangeCount || selection.isCollapsed || !editor.contains(selection.anchorNode) ||
- !editor.contains(selection.focusNode)) {
- onChange();
- return;
- }
- const wasSelecting = selecting;
- selecting = true;
- [selection.anchorNode, selection.focusNode].forEach(node => {
- const element = (node.nodeType === Node.ELEMENT_NODE ? node as Element : node.parentElement)
- ?.closest<HTMLElement>('[contenteditable="true"], [contenteditable="plaintext-only"]');
- if (element) {
- suppressInput(element);
- }
- });
- if (!wasSelecting) {
- onSelect();
- if (!touching) {
- refreshSelectionFocus();
- }
- }
- onChange();
- };
- const click = (event: MouseEvent) => {
- const target = event.target as HTMLElement;
- if (!editor?.contains(target)) {
- return;
- }
- update();
- if (getMobileSelectionRange()) {
- return;
- }
- const editable = target.closest<HTMLElement>('[contenteditable="true"], [contenteditable="plaintext-only"]');
- const restoreInput = inputModes.size > 0;
- const selection = getSelection();
- const range = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined;
- clearMobileSelectionInput();
- if (restoreInput && editable && range) {
- editable.blur();
- editable.focus({preventScroll: true});
- selection.removeAllRanges();
- selection.addRange(range);
- }
- };
- document.addEventListener("pointerdown", begin, true);
- document.addEventListener("pointerup", end, true);
- document.addEventListener("pointercancel", end, true);
- document.addEventListener("selectionchange", update, true);
- document.addEventListener("click", click, true);
- document.addEventListener("contextmenu", event => {
- update();
- if (getMobileSelectionRange() && editor.contains(event.target as Node)) {
- event.preventDefault();
- event.stopPropagation();
- onChange();
- }
- }, true);
- document.addEventListener("focusin", event => {
- const target = event.target as HTMLElement;
- if (target.matches("input, textarea") && !target.closest("#keyboardToolbar")) {
- clearMobileSelectionInput();
- }
- }, true);
-};
diff --git a/app/tests/mobileEditingToolbar.test.js b/app/tests/mobileEditingToolbar.test.js
index aa0bac5956..b4d72df822 100644
--- a/app/tests/mobileEditingToolbar.test.js
+++ b/app/tests/mobileEditingToolbar.test.js
@@ -13,6 +13,8 @@ const runCases = async (sources, platform) => {
let inputRequests = 0;
let undoCalls = 0;
const inserts = [];
+ const commands = [];
+ const nativeKeyboard = platform === "android" || platform === "harmony";
const visible = new Set(["mobile-copy", "mobile-cut", "mobile-undo", "mobile-redo", "mobile-indent",
"mobile-outdent", "mobile-block", "mobile-add", "mobile-heading1", "strong", "em", "mobile-separator"]);
const order = ["strong", "mobile-undo", "mobile-separator", "mobile-heading1", "em", "mobile-indent", "mobile-outdent"];
@@ -24,8 +26,8 @@ const runCases = async (sources, platform) => {
"mobile/editor": {getCurrentEditor: () => current && {protyle: current}},
"protyle/lite/mobileToolbar": {getMobileToolbarProtyle: () => undefined, getMobileToolbarUndo: () => undefined,
getMobileToolbarPaddingElement: protyle => protyle.element},
- "protyle/util/compatibility": {isInAndroid: () => platform === "android", isInHarmony: () => false,
- isInMobileApp: () => platform === "android",
+ "protyle/util/compatibility": {isInAndroid: () => platform === "android", isInHarmony: () => platform === "harmony",
+ isInMobileApp: () => platform !== "browser",
isInEdge: () => false},
"mobile/util/inlineMathSelection": {createInlineMathSelection: () => ({reset() {}, update() {}, prepareInput() {}})},
"mobile/util/pluginToolbar": {getMobilePluginToolbarItems: () => []},
@@ -38,6 +40,14 @@ const runCases = async (sources, platform) => {
"protyle/util/tableCellRichContext": {getTableCellRichContext: () => undefined},
"editor/getIcon": {getIconByType: () => "iconParagraph"},
"plugin/EventBusCore": {forEachPluginSubscriber() {}},
+ "protyle/util/selection": {
+ getSelectionPosition: () => ({top: 100, left: 0}),
+ focusByRange: range => {
+ editable.focus();
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ },
+ },
"protyle/util/inlineElementMarker": {stripSemanticMarkersFromRangeText: range => range.toString()},
"protyle/util/editorFocus": {getEditorFocusRange: (_root, range, fallback) => range || fallback,
restoreEditorFocusRange: (_root, range) => {
@@ -57,7 +67,7 @@ const runCases = async (sources, platform) => {
if (!cache[name]) {
cache[name] = {};
new Function("require", "exports", sources[name])(relative =>
- load(path.posix.normalize(path.posix.join(path.posix.dirname(name), relative))), cache[name]);
+ load(relative.startsWith(".") ? path.posix.normalize(path.posix.join(path.posix.dirname(name), relative)) : relative), cache[name]);
}
return cache[name];
};
@@ -67,25 +77,23 @@ const runCases = async (sources, platform) => {
const toolbar = document.getElementById("keyboardToolbar");
const preview = document.createElement("div");
preview.className = "fn__none";
- const selectionInput = load("mobile/util/selectionKeyboard");
- const focus = HTMLElement.prototype.focus;
- HTMLElement.prototype.focus = function (...args) {
- const suppressed = selectionInput.suppressMobileSelectionFocus(this);
- focus.apply(this, args);
- if (!suppressed && this === editable) {
- load("mobile/util/mobileAppUtil").callMobileAppShowKeyboard();
- }
- };
window.siyuan = {zIndex: 1, languages: {}, mobile: {size: {}}, config: {readonly: false, editor: {fontSize: 16}},
- menus: {menu: {remove() {}}}};
- if (platform === "android") {
- window.JSAndroid = {showKeyboard: () => keyboardShows++, hideKeyboard: () => keyboardHides++};
+ menus: {menu: {element: document.createElement("div"), remove() {}}}};
+ if (nativeKeyboard) {
+ window[platform === "android" ? "JSAndroid" : "JSHarmony"] = {
+ showKeyboard: () => keyboardShows++, hideKeyboard: () => keyboardHides++,
+ };
}
window.addEventListener("siyuan-mobile-keyboard-change", event => {
+ document.body.classList.toggle("mobile-keyboard--open", event.detail);
if (event.detail) {
inputRequests++;
}
});
+ document.execCommand = command => {
+ commands.push({command, text: getSelection().toString()});
+ return true;
+ };
window.Lute = {Caret: "‸"};
current = {element: document.getElementById("editor"), editable, contentElement: root.parentElement,
wysiwyg: {element: root}, preview: {element: preview},
@@ -94,8 +102,11 @@ const runCases = async (sources, platform) => {
gutter: {}, undo: {undo: () => undoCalls++}, hint: {fill: value => inserts.push(value)}};
const keyboard = load("mobile/util/keyboardToolbar");
keyboard.initKeyboardToolbar();
+ load("mobile/inputBindings");
const settle = async () => {
document.dispatchEvent(new Event("selectionchange"));
+ // 文档编辑器和原生键盘回调会刷新工具栏,此处复用同一入口。
+ keyboard.showKeyboardToolbar();
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
};
const select = (end = 5) => {
@@ -106,34 +117,53 @@ const runCases = async (sources, platform) => {
getSelection().addRange(range);
};
const touch = type => editable.dispatchEvent(new PointerEvent(type, {bubbles: true, pointerType: "touch"}));
+ // 键盘尚未打开时选字,不覆盖输入类型,也不要求先点击独立的编辑按钮。
touch("pointerdown");
- assert.equal(editable.getAttribute("inputmode"), "none");
+ assert.equal(editable.hasAttribute("inputmode"), false);
editable.focus();
- assert.equal(keyboardShows, 0);
+ assert.equal(keyboardShows > 0, nativeKeyboard);
select();
touch("pointerup");
+ editable.click();
await settle();
- assert.equal(selectionInput.isMobileSelectionMode(), true);
- assert.equal(keyboardHides, platform === "android" ? 1 : 0);
+ assert.equal(keyboardHides, 0);
assert.equal(toolbar.classList.contains("fn__none"), false);
- assert.equal(toolbar.classList.contains("keyboard--selection"), true);
+ assert.equal(toolbar.classList.contains("keyboard--selection"), false);
+ assert.equal(toolbar.querySelector('[data-type="done"] use').getAttribute("xlink:href"), "#iconKeyboardHide");
assert.equal(getSelection().toString(), "Alpha");
+ assert.equal(document.activeElement, editable);
+ assert.ok(inputRequests > 0);
+ assert.equal(toolbar.querySelector('[data-type="copy"]').classList.contains("fn__none"), false);
+ assert.equal(toolbar.querySelector('[data-type="cut"]').classList.contains("fn__none"), false);
const contextMenu = new MouseEvent("contextmenu", {bubbles: true, cancelable: true});
editable.dispatchEvent(contextMenu);
- assert.equal(contextMenu.defaultPrevented, true);
+ assert.equal(contextMenu.defaultPrevented, false);
assert.equal(getSelection().toString(), "Alpha");
- editable.blur();
- load("mobile/util/mobileAppUtil").callMobileAppShowKeyboard();
- assert.equal(keyboardShows, 0);
- assert.equal(selectionInput.isMobileSelectionMode(), true);
- assert.equal(keyboard.hideKeyboardToolbarByApp(false), load("mobile/util/touchSelection").KeyboardHideResult.PreserveSelection);
+
+ // 正在输入时重新选字或拖动端点,选区变化不能关闭键盘。
+ assert.equal(document.body.classList.contains("mobile-keyboard--open"), true);
+ touch("pointerdown");
+ select(10);
+ touch("pointerup");
+ await settle();
+ assert.equal(getSelection().toString(), "Alpha beta");
+ assert.equal(keyboardHides, 0);
+ assert.equal(editable.hasAttribute("inputmode"), false);
+ select();
+ editable.dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));
+ await settle();
assert.equal(getSelection().toString(), "Alpha");
+ assert.equal(keyboardHides, 0);
const action = name => toolbar.querySelector(`[data-type="${name}"]`).dispatchEvent(
- new Event(platform === "android" ? "touchend" : "click", {bubbles: true, cancelable: true}));
+ new Event(nativeKeyboard ? "touchend" : "click", {bubbles: true, cancelable: true}));
+ action("copy");
+ action("cut");
+ assert.deepEqual(commands, [{command: "copy", text: "Alpha"}, {command: "cut", text: "Alpha"}]);
action("strong");
await settle();
- assert.equal(keyboardShows, 0);
- assert.equal(editable.getAttribute("inputmode"), "none");
+ assert.equal(keyboardHides, 0);
+ assert.equal(editable.hasAttribute("inputmode"), false);
+ assert.equal(document.activeElement, editable);
action("undo");
assert.equal(undoCalls, 1);
action("redo");
@@ -153,30 +183,44 @@ const runCases = async (sources, platform) => {
await settle();
assert.equal(toolbar.querySelector('[data-type="heading1"]').classList.contains("fn__none"), true);
current.lite = undefined;
+ const showsBeforeClose = keyboardShows;
action("done");
- await settle();
- assert.equal(selectionInput.isMobileSelectionMode(), false);
+ assert.equal(document.activeElement, document.body);
assert.equal(editable.hasAttribute("inputmode"), false);
- assert.ok(inputRequests > 0);
- assert.equal(keyboardShows > 0, platform === "android");
- assert.equal(toolbar.classList.contains("keyboard--selection"), false);
- // 短按折叠光标恢复输入,保留已有的 inputmode 属性。
- selectionInput.clearMobileSelectionInput();
+ assert.equal(keyboardHides, nativeKeyboard ? 1 : 0);
+ assert.equal(keyboardShows, showsBeforeClose);
+ assert.equal(toolbar.classList.contains("fn__none"), true);
+ // 短按继续输入时保留已有 inputmode,折叠选区不显示复制与剪切。
editable.setAttribute("inputmode", "text");
touch("pointerdown");
+ editable.focus();
select(0);
touch("pointerup");
editable.click();
- assert.equal(editable.getAttribute("inputmode"), "text");
- assert.equal(selectionInput.isMobileSelectionMode(), false);
- // 输入框与数据库字段弹层不会继承文档的选择模式。
- touch("pointerdown");
- select();
await settle();
+ assert.equal(editable.getAttribute("inputmode"), "text");
+ assert.equal(toolbar.querySelector('[data-type="copy"]').classList.contains("fn__none"), true);
+ assert.equal(toolbar.querySelector('[data-type="cut"]').classList.contains("fn__none"), true);
+ // 输入框不会因残留文档选区恢复文档工具栏。
const input = document.createElement("input");
document.body.append(input);
+ select();
input.focus();
- assert.equal(selectionInput.isMobileSelectionMode(), false);
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ assert.equal(toolbar.classList.contains("fn__none"), true);
+ assert.equal(editable.getAttribute("inputmode"), "text");
+ assert.equal(document.activeElement, input);
+ // 只读编辑器不通过全局点击与焦点逻辑请求输入。
+ keyboard.hideKeyboardToolbar();
+ root.setAttribute("data-readonly", "true");
+ current.disabled = true;
+ const showsBeforeReadonly = keyboardShows;
+ touch("pointerdown");
+ editable.focus();
+ select();
+ touch("pointerup");
+ editable.click();
+ assert.equal(keyboardShows, showsBeforeReadonly);
assert.equal(editable.getAttribute("inputmode"), "text");
};
@@ -190,15 +234,33 @@ const runElectron = async () => {
let exitCode = 0;
try {
const ts = require("typescript");
- const modules = ["mobile/util/selectionKeyboard", "mobile/util/keyboardToolbar", "mobile/util/toolbarActions",
+ const modules = ["mobile/util/keyboardToolbar", "mobile/util/toolbarActions",
"mobile/util/toolbarEntries", "mobile/util/mobileAppUtil", "mobile/util/mobileKeyboardChange",
"mobile/util/touchSelection", "mobile/util/visibleViewport", "protyle/util/hasClosest",
"protyle/toolbar/defaults", "protyle/toolbar/entryVisibility", "config/entryVisibility/order"];
const sources = Object.fromEntries(modules.map(name => [name, ts.transpileModule(
readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"),
{compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText]));
+ // 直接使用移动端 App 的点击与 focus 绑定,避免测试替身漏掉输入抑制逻辑。
+ const appSource = ts.createSourceFile("mobile/index.ts",
+ readFileSync(path.join(__dirname, "../src/mobile/index.ts"), "utf8"), ts.ScriptTarget.Latest, true);
+ const appClass = appSource.statements.find(node => ts.isClassDeclaration(node) && node.name.text === "App");
+ const statements = appClass.members.find(ts.isConstructorDeclaration).body.statements;
+ const clickBinding = statements.find(node => node.getText(appSource).startsWith('window.addEventListener("click",'));
+ const focusBinding = statements.find(node => ts.isBlock(node) && node.getText(appSource).includes("__siyuan_original_focus"));
+ assert.ok(clickBinding && focusBinding);
+ sources["mobile/inputBindings"] = ts.transpileModule(`
+ const {canInput, armKeyboardLock, callMobileAppShowKeyboard} = require("mobile/util/mobileAppUtil");
+ const {hideKeyboardToolbarUtilOnEditorClick} = require("mobile/util/keyboardToolbar");
+ const {hasClosestByClassName, hasClosestByAttribute, hasTopClosestByClassName} = require("protyle/util/hasClosest");
+ const {Constants} = require("constants");
+ const scrollInputIntoView = () => {};
+ const hideAllElements = () => {};
+ ${clickBinding.getText(appSource)}
+ ${focusBinding.getText(appSource)}
+ `, {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText;
const css = require("sass").compile(path.join(__dirname, "../src/assets/scss/mobile.scss"), {logger: {warn() {}}}).css;
- for (const platform of ["android", "browser"]) {
+ for (const platform of ["android", "harmony", "ios", "browser"]) {
await win.loadURL("data:text/html,<html><body></body></html>");
await win.webContents.insertCSS(css);
await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(sources)}, ${JSON.stringify(platform)})`);
@@ -216,7 +278,7 @@ const runElectron = async () => {
if (process.versions.electron && process.type === "browser") {
runElectron().catch(error => {console.error(error); require("electron").app.exit(1);});
} else {
- require("node:test").it("keeps touch selections editable without opening the keyboard and shares toolbar configuration", {
+ require("node:test").it("keeps touch selections in the input flow and shares toolbar configuration", {
skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
timeout: 45000,
}, async () => {