An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Stabilize iOS text selection and native editing menus https://github.com/siyuan-note/siyuan/issues/20691
Vanessa503db35e8481
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.tsindex c45bda61bd..2c1924d1ce 100644--- a/app/src/menus/protyle.ts+++ b/app/src/menus/protyle.ts@@ -38,7 +38,8 @@ import {transaction, updateTransaction} from "../protyle/wysiwyg/transaction";import {openMenu} from "./commonMenuItem";import {fetchPost, fetchSyncPost} from "../util/fetch";import {Constants} from "../constants";-import {copyPlainText, isPhablet, readClipboard, setStorageVal, updateHotkeyTip, writeText} from "../protyle/util/compatibility";+import {copyPlainText, isIOSDevice, isPhablet, readClipboard, setStorageVal, updateHotkeyTip, writeText} from "../protyle/util/compatibility";+import {usesNativeTextMenu} from "../protyle/wysiwyg/nativeTextMenu";import {onGet} from "../protyle/util/onGet";import {getAllModels} from "../layout/getAll";import {paste, pasteAndKeepSourceFormat, pasteAsPlainText, pasteEscaped} from "../protyle/util/paste";@@ -795,6 +796,16 @@ export const refMenu = (protyle: IProtyle, element: HTMLElement) => {export const contentMenu = (protyle: IProtyle, nodeElement: Element) => {const range = getEditorRange(nodeElement);+ /// #if MOBILE+ const rangeTarget = range.startContainer.nodeType === Node.ELEMENT_NODE ?+ range.startContainer as HTMLElement : range.startContainer.parentElement;+ if (isIOSDevice() && rangeTarget && !isInEmbedBlock(rangeTarget) &&+ usesNativeTextMenu(rangeTarget, protyle.wysiwyg.element)) {+ // 所有正文菜单入口统一交给系统,避免异步菜单在选区切换后短暂覆盖文字。+ protyle.toolbar.subElement.classList.add("fn__none");+ return;+ }+ /// #endifwindow.siyuan.menus.menu.remove();window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_INLINE_CONTEXT);/// #if !MOBILEdiff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex 939b74b07c..7d1859e4ca 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -25,6 +25,7 @@ import {handleTouchSelectionChange,handleTouchStart,handleTouchUp,+ handleTouchFocusOut,} from "./util/touch";import {fetchPost} from "../util/fetch";import {initFramework} from "./util/initFramework";@@ -274,6 +275,7 @@ class App {document.addEventListener("touchend", handleTouchEnd, false);document.addEventListener("touchcancel", handleTouchCancel, false);document.addEventListener("contextmenu", handleTouchContextMenu, true);+ document.addEventListener("focusout", handleTouchFocusOut, true);document.addEventListener("selectionchange", handleTouchSelectionChange, true);window.addEventListener("nativePhysicalTouchUp", handleTouchUp, false);window.addEventListener("keyup", () => {diff --git a/app/src/mobile/util/touch.test.ts b/app/src/mobile/util/touch.test.tsindex 931a880ccc..d484c597ca 100644--- a/app/src/mobile/util/touch.test.ts+++ b/app/src/mobile/util/touch.test.ts@@ -4,6 +4,7 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";import * as touchSelection from "./touchSelection";+import * as touchGesture from "./touchGesture";const compiled = transpileModule(readFileSync("src/mobile/util/touch.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},@@ -14,6 +15,12 @@ const fixture = (text = "\u200b\n", collapsed = false, inside = true) => {let blurCount = 0;let focusCount = 0;let keyboardHidden = false;+ let now = 1000;+ let blockTouch = false;+ let nativeMenu = false;+ let multiSelectCount = 0;+ const timers = new Map<number, () => void>();+ let nextTimer = 0;const startContainer = {isConnected: true};const endContainer = {isConnected: true};let range = {@@ -44,7 +51,10 @@ const fixture = (text = "\u200b\n", collapsed = false, inside = true) => {};const mobile: any = {};const element = {tagName: "DIV", dataset: {}, contains: () => inside, closest: (): null => null};- const editor = {protyle: {wysiwyg: {element}, toolbar: {isMultiSelectMode: () => false}}};+ const editor = {protyle: {wysiwyg: {element}, options: {render: {gutter: false}}, toolbar: {+ isMultiSelectMode: () => multiSelectCount > 0,+ showMultiSelectMode: () => multiSelectCount++,+ }}};const body = {};const document: any = {body, activeElement: body, querySelector: (): null => null,getElementById: () => ({classList: {contains: () => keyboardHidden}})};@@ -60,10 +70,15 @@ const fixture = (text = "\u200b\n", collapsed = false, inside = true) => {activeBlur: () => blurCount++,},"../editor": {getCurrentEditor: () => editor},- "../../constants": {Constants: {TIMEOUT_MULTIPLE_SELECT: 1500}},- "../../protyle/util/hasClosest": {hasClosestBlock: (): null => null, hasClosestByAttribute: (): null => null,+ "../../constants": {Constants: {TIMEOUT_MULTIPLE_SELECT: 1500, TIMEOUT_LONGPRESS: 460, SIZE_DRAG_THRESHOLD: 5}},+ "../../protyle/util/hasClosest": {hasClosestBlock: () => blockTouch ? element : null, hasClosestByAttribute: (): null => null,hasClosestByClassName: (): null => null},- "../../protyle/util/compatibility": {isIPhone: () => false},+ "../../protyle/util/compatibility": {isIPhone: () => false, isIOSDevice: () => nativeMenu,+ isInAndroid: () => false, isInHarmony: () => false},+ "../../protyle/wysiwyg/nativeTextMenu": {usesNativeTextMenu: () => nativeMenu},+ "../../protyle/util/selection": {getRangeByPoint: () => range},+ "./blockSelection": {getMobileBlockSelectionElement: (value: unknown) => value},+ "./touchGesture": touchGesture,"./touchSelection": touchSelection,"../../protyle/util/inlineElementMarker": {stripSemanticMarkersFromRangeText: () => text},};@@ -71,13 +86,17 @@ const fixture = (text = "\u200b\n", collapsed = false, inside = true) => {exports,require: (name: string) => modules[name] || {},document,+ Node: {ELEMENT_NODE: 1},+ Date: {now: () => now},+ clearTimeout: (id: number) => timers.delete(id),getSelection: () => selection,- window: {innerWidth: 384, innerHeight: 808, getSelection: () => selection, siyuan: {mobile}},+ window: {innerWidth: 384, innerHeight: 808, getSelection: () => selection, siyuan: {mobile},+ setTimeout: (callback: () => void) => { timers.set(++nextTimer, callback); return nextTimer; }},});- const startBlankTouch = (target = element, count = 1) => {+ const startBlankTouch = (target = element, count = 1, timeStamp = now, clientX = 100, clientY = 100) => {document.activeElement = editable;- exports.handleTouchStart({target, touches: Array.from({length: count}, () =>- ({target, clientX: 100, clientY: 100}))});+ exports.handleTouchStart({target, timeStamp, touches: Array.from({length: count}, () =>+ ({target, clientX, clientY}))});};const contextMenu = (target = element) => {const event = {target, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }};@@ -85,9 +104,88 @@ const fixture = (text = "\u200b\n", collapsed = false, inside = true) => {return event;};return {exports, selection, range, mobile, document, editable, element, editor, startBlankTouch, contextMenu,+ startBlockTouch: (timeStamp = now, clientX = 100, clientY = 100) => {+ blockTouch = true;+ startBlankTouch(element, 1, timeStamp, clientX, clientY);+ },+ nativeMenu: () => { nativeMenu = true; },+ delay: (duration = 2000) => { now += duration; },+ flushTimers: () => { for (const callback of timers.values()) callback(); timers.clear(); },+ multiSelectCount: () => multiSelectCount,hideKeyboard: () => { keyboardHidden = true; }, focusCount: () => focusCount, blurCount: () => blurCount};};+test("release cancels pending multi-select even when processing is delayed beyond the threshold", () => {+ const f = fixture("", true);+ f.startBlockTouch();+ f.delay();+ f.exports.handleTouchUp();+ f.flushTimers();+ assert.equal(f.multiSelectCount(), 0);+});++test("iOS repeated text taps cannot enter multi-select when the native gesture omits touchend", () => {+ for (const initiallyCollapsed of [true, false]) {+ const f = fixture("word", initiallyCollapsed);+ f.nativeMenu();+ f.startBlockTouch(1000);+ f.delay();+ f.startBlockTouch(1100);+ f.range.collapsed = true;+ f.flushTimers();+ assert.equal(f.multiSelectCount(), 0);+ f.startBlockTouch(1200);+ f.flushTimers();+ assert.equal(f.multiSelectCount(), 0);+ }+});++test("separate iOS text presses and other platforms retain long-press multi-select", () => {+ for (const kind of ["later", "elsewhere", "otherPlatform"]) {+ const f = fixture("", true);+ if (kind !== "otherPlatform") f.nativeMenu();+ f.startBlockTouch(1000);+ f.exports.handleTouchUp();+ f.startBlockTouch(kind === "later" ? 1500 : 1100, kind === "elsewhere" ? 140 : 100);+ f.flushTimers();+ assert.equal(f.multiSelectCount(), 1, kind);+ }+});++test("native text menus and visible text selections permanently cancel this press's multi-select", () => {+ for (const mode of ["menu", "selection", "cancel", "focusout"]) {+ const f = fixture("text", true);+ f.startBlockTouch();+ if (mode === "menu") {+ f.nativeMenu();+ f.contextMenu();+ } else if (mode === "selection") {+ f.range.collapsed = false;+ f.exports.handleTouchSelectionChange();+ f.range.collapsed = true;+ } else if (mode === "focusout") {+ f.exports.handleTouchFocusOut({target: f.editable});+ } else {+ f.exports.handleTouchCancel();+ }+ f.flushTimers();+ assert.equal(f.multiSelectCount(), 0, mode);+ }+});++test("an uninterrupted long press still enters block multi-select", () => {+ const f = fixture("", true);+ f.startBlockTouch();+ f.flushTimers();+ assert.equal(f.multiSelectCount(), 1);+ let consumed = false;+ f.exports.handleTouchEnd({target: f.element, timeStamp: 2000,+ changedTouches: [{clientX: 100, clientY: 100}],+ stopImmediatePropagation: () => {}, preventDefault: () => { consumed = true; }});+ assert.equal(consumed, true);+ assert.equal(f.multiSelectCount(), 1);+});+test("releasing a blank editor selection preserves the caret and keyboard", () => {const f = fixture();f.exports.handleTouchUp();diff --git a/app/src/mobile/util/touch.ts b/app/src/mobile/util/touch.tsindex 5bb03843c6..a475630929 100644--- a/app/src/mobile/util/touch.ts+++ b/app/src/mobile/util/touch.ts@@ -9,7 +9,8 @@ import {} from "../../protyle/util/hasClosest";import {closeModel, closePanel, showPanelMask} from "./closePanel";import {activeBlur, resetAndroidBoundedSelectionGesture} from "./keyboardToolbar";-import {isChromeBrowser, isInAndroid, isInHarmony, isIPhone} from "../../protyle/util/compatibility";+import {isChromeBrowser, isInAndroid, isInHarmony, isIPhone, isIOSDevice} from "../../protyle/util/compatibility";+import {usesNativeTextMenu} from "../../protyle/wysiwyg/nativeTextMenu";import {getRangeByPoint} from "../../protyle/util/selection";import {getCurrentEditor} from "../editor";import {Constants} from "../../constants";@@ -51,6 +52,8 @@ let swipeStartSidebar: MobileSidebarSide;let preventSwipe = false;// 长按进入多选的定时器let longPressTimer: number;+let longPressTriggered = false;+let previousNativeTextTouch: {editorElement: HTMLElement, x: number, y: number, time: number};let longPressBlockElement: HTMLElement;let longPressTouchRange: Range;let blankTouchFocus: {editorElement: HTMLElement, editableElement: HTMLElement, range: Range};@@ -151,9 +154,7 @@ const restoreInvisibleLongPressSelection = () => {export const handleTouchUp = () => {updateSidebarSwipeState();resetAndroidBoundedSelectionGesture();- if (Date.now() - time < Constants.TIMEOUT_MULTIPLE_SELECT) {- clearLongPress();- }+ clearLongPress();if (!restoreInvisibleLongPressSelection()) {clearInvisibleEditorSelection();}@@ -163,6 +164,11 @@ export const handleTouchUp = () => {};export const handleTouchContextMenu = (event: MouseEvent) => {+ const editor = getCurrentEditor();+ if (isIOSDevice() && editor && usesNativeTextMenu(event.target as HTMLElement, editor.protyle.wysiwyg.element)) {+ // 系统接管文字菜单后,本轮触摸不再升级为块多选。+ clearLongPress();+ }const saved = blankTouchFocus;if (!saved || event.target !== saved.editorElement ||getCurrentEditor()?.protyle.wysiwyg.element !== saved.editorElement ||@@ -181,7 +187,25 @@ export const handleTouchContextMenu = (event: MouseEvent) => {window.siyuan.mobile.touchRange = saved.range.cloneRange();};+export const handleTouchFocusOut = (event: FocusEvent) => {+ if (getCurrentEditor()?.protyle.wysiwyg.element.contains(event.target as Node)) {+ // 键盘收起或原生菜单切换焦点时,结束可能缺少 touchend 的正文长按计时。+ clearLongPress();+ }+};+export const handleTouchSelectionChange = () => {+ const selection = window.getSelection();+ const editor = getCurrentEditor();+ if (selection?.rangeCount > 0 && editor) {+ const range = selection.getRangeAt(0);+ if (!range.collapsed && editor.protyle.wysiwyg.element.contains(range.startContainer) &&+ editor.protyle.wysiwyg.element.contains(range.endContainer) &&+ hasVisibleSelectionText(stripSemanticMarkersFromRangeText(range))) {+ // 选词或拖动选择手柄后,即使选区随后折叠,也不恢复这一轮的块多选计时。+ clearLongPress();+ }+ }if (longPressBlockElement && !restoreInvisibleLongPressSelection()) {clearInvisibleEditorSelection();}@@ -208,7 +232,7 @@ export const handleTouchEnd = (event: TouchEvent) => {if (Math.abs(clientX - event.changedTouches[0].clientX) < Constants.SIZE_DRAG_THRESHOLD &&Math.abs(clientY - event.changedTouches[0].clientY) < Constants.SIZE_DRAG_THRESHOLD) {if (editor && editor.protyle.toolbar.isMultiSelectMode()) {- if (longPressTimer) {+ if (longPressTriggered) {event.stopImmediatePropagation();event.preventDefault();return;@@ -359,6 +383,7 @@ export const handleTouchEnd = (event: TouchEvent) => {};const resetTouchGesture = () => {+ longPressTriggered = false;blankTouchFocus = undefined;isFirstMove = true;clientX = null;@@ -394,6 +419,8 @@ export const handleTouchCancel = () => {export const handleTouchStart = (event: TouchEvent) => {updateSidebarSwipeState();resetTouchGesture();+ const previousTextTouch = previousNativeTextTouch;+ previousNativeTextTouch = undefined;time = Date.now();touchStartTimeStamp = event.timeStamp;longPressBlockElement = undefined;@@ -426,6 +453,19 @@ export const handleTouchStart = (event: TouchEvent) => {const editor = getCurrentEditor();const activeElement = document.activeElement as HTMLElement;const selection = window.getSelection();+ let repeatedNativeTextTouch = false;+ if (event.touches.length === 1 && editor && isIOSDevice() &&+ usesNativeTextMenu(target, editor.protyle.wysiwyg.element)) {+ const point = event.touches[0];+ const touchTime = Number.isFinite(event.timeStamp) ? event.timeStamp : time;+ repeatedNativeTextTouch = previousTextTouch?.editorElement === editor.protyle.wysiwyg.element &&+ touchTime - previousTextTouch.time >= 0 &&+ touchTime - previousTextTouch.time < Constants.TIMEOUT_LONGPRESS &&+ Math.hypot(point.clientX - previousTextTouch.x, point.clientY - previousTextTouch.y) <+ Constants.SIZE_DRAG_THRESHOLD * 4;+ previousNativeTextTouch = {editorElement: editor.protyle.wysiwyg.element,+ x: point.clientX, y: point.clientY, time: touchTime};+ }if (event.touches.length === 1 && editor && !editor.protyle.disabled &&target === editor.protyle.wysiwyg.element && activeElement?.isContentEditable &&target.contains(activeElement) && selection?.rangeCount > 0 &&@@ -451,7 +491,8 @@ export const handleTouchStart = (event: TouchEvent) => {event.stopImmediatePropagation();}// 长按编辑器内块达到阈值时直接进入多选模式,无需抬手- if (clientX && clientY && editor && !editor.protyle.toolbar.isMultiSelectMode()) {+ // 系统双击选词可能不再派发第二次 touchend,连续短按不启动块多选计时。+ if (clientX && clientY && editor && !repeatedNativeTextTouch && !editor.protyle.toolbar.isMultiSelectMode()) {const blockElement = hasClosestBlock(target);if (blockElement && editor.protyle.wysiwyg.element.contains(blockElement) &&shouldStartLongPressMultiSelect(@@ -471,6 +512,7 @@ export const handleTouchStart = (event: TouchEvent) => {longPressTouchRange.collapse(true);}longPressTimer = window.setTimeout(() => {+ longPressTimer = undefined;clearInvisibleEditorSelection();const selection = window.getSelection();if (selection?.rangeCount > 0) {@@ -478,11 +520,11 @@ export const handleTouchStart = (event: TouchEvent) => {if (!range.collapsed && hasVisibleSelectionText(stripSemanticMarkersFromRangeText(range)) &&editor.protyle.wysiwyg.element.contains(range.startContainer) &&editor.protyle.wysiwyg.element.contains(range.endContainer)) {- longPressTimer = undefined;return;}}window.getSelection()?.removeAllRanges();+ longPressTriggered = true;const selectionBlockElement = getMobileBlockSelectionElement(blockElement as HTMLElement);editor.protyle.toolbar.showMultiSelectMode(editor.protyle, selectionBlockElement);if (editor.protyle.options.render.gutter) {diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 4f4df50160..0d4694c5c3 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -14,6 +14,7 @@ import {isTabTextBoundary} from "./tabsBoundary";import {captureCompositionText} from "./compositionCaret";import {isCommittedTextInput} from "./compositionInput";import {bindIOSTouchCaret} from "./touchCaret";+import {usesNativeTextMenu} from "./nativeTextMenu";import {bindListMarkerCaret} from "./listMarkerCaret";import {clearTouchBlockSelection} from "./touchBlockSelection";import {isDirectMathClick} from "../util/mathClick";@@ -3733,6 +3734,12 @@ export class WYSIWYG {const target = event.detail.target || event.target as HTMLElement;const selectElements = protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select");/// #if MOBILE+ if (isIOSDevice() && selectElements.length === 0 && !isInEmbedBlock(target) &&+ usesNativeTextMenu(target, this.element)) {+ // 不在系统选词菜单上叠加正文浮层,保留原生选区和选择手柄。+ protyle.toolbar.subElement.classList.add("fn__none");+ return;+ }if (event.isTrusted && !protyle.disabled && window.JSAndroid?.prepareWordSelection &&selectElements.length === 0 && target.closest('[contenteditable="true"]') && !isInEmbedBlock(target)) {const blockElement = hasClosestBlock(target);@@ -4737,6 +4744,13 @@ export class WYSIWYG {return;}const target = event.target as HTMLElement;+ /// #if MOBILE+ if (isIOSDevice() && usesNativeTextMenu(target, this.element)) {+ // 双击选词与长按共用系统文字菜单,避免正文浮层覆盖后续触摸位置。+ protyle.toolbar.subElement.classList.add("fn__none");+ return;+ }+ /// #endifif (!protyle.disabled && target.classList.contains("av__widthdrag")) {const blockElement = hasClosestBlock(target) as HTMLElement;const columnID = target.parentElement?.getAttribute("data-col-id");diff --git a/app/src/protyle/wysiwyg/nativeTextMenu.ts b/app/src/protyle/wysiwyg/nativeTextMenu.tsnew file mode 100644index 0000000000..0f95c9bbee--- /dev/null+++ b/app/src/protyle/wysiwyg/nativeTextMenu.ts@@ -0,0 +1,110 @@+// 正文使用系统文字菜单,块控件和语义元素仍由各自的菜单处理。+export const usesNativeTextMenu = (target: HTMLElement, editor: HTMLElement) => {+ const editable = target.closest('[contenteditable="true"]');+ return !!editable && editor.contains(editable) && !target.closest(+ "input, textarea, button, a, img, audio, video, iframe, [contenteditable='false']:not(.protyle-wysiwyg), " ++ ".protyle-action, .protyle-attr, .table, .av, .protyle-custom, [data-prevent-swipe], " ++ "[data-type~='block-ref'], [data-type~='virtual-block-ref'], [data-type~='file-annotation-ref'], " ++ "[data-type~='a'], [data-type~='tag'], [data-type~='inline-memo'], [data-type~='inline-math']",+ );+};++type NativeTextMenuState = {range: Range, timer?: number, requested?: boolean};++const nativeMenus = new WeakMap<HTMLElement, NativeTextMenuState>();++const sameRange = (current: Range, saved: Range) => current && !current.collapsed &&+ current.startContainer === saved.startContainer && current.startOffset === saved.startOffset &&+ current.endContainer === saved.endContainer && current.endOffset === saved.endOffset;++export const cancelNativeTextMenu = (editor: HTMLElement) => {+ const state = nativeMenus.get(editor);+ if (!state) {+ return;+ }+ nativeMenus.delete(editor);+ const ownerWindow = editor.ownerDocument.defaultView;+ if (state.timer !== undefined) {+ ownerWindow.clearTimeout(state.timer);+ }+ if (state.requested) {+ // 空文字只收起本次补显的系统菜单,不改变正文选区。+ void ownerWindow.webkit?.messageHandlers?.showTextMenu?.postMessage("").catch(() => {});+ }+};++export const bindNativeTextMenu = (editor: HTMLElement) => {+ const ownerDocument = editor.ownerDocument;+ const cancel = () => cancelNativeTextMenu(editor);+ const selectionChange = () => {+ const state = nativeMenus.get(editor);+ const selection = ownerDocument.getSelection();+ if (state && (!editor.contains(ownerDocument.activeElement) || !selection?.rangeCount ||+ !sameRange(selection.getRangeAt(0), state.range))) {+ cancel();+ }+ };+ const scroll = (event: Event) => {+ const target = event.target;+ if (target instanceof Node && (editor.contains(target) || target.contains(editor))) {+ cancel();+ }+ };+ const focusOut = (event: FocusEvent) => {+ if (editor.contains(event.target as Node) && !editor.contains(event.relatedTarget as Node)) {+ cancel();+ }+ };+ ownerDocument.addEventListener("selectionchange", selectionChange);+ ownerDocument.addEventListener("scroll", scroll, true);+ ownerDocument.addEventListener("focusout", focusOut, true);+ const cancelEvents = ["pointerdown", "touchstart", "beforeinput"];+ cancelEvents.forEach(type => ownerDocument.addEventListener(type, cancel, {capture: true, passive: true}));+ return () => {+ cancel();+ ownerDocument.removeEventListener("selectionchange", selectionChange);+ ownerDocument.removeEventListener("scroll", scroll, true);+ ownerDocument.removeEventListener("focusout", focusOut, true);+ cancelEvents.forEach(type => ownerDocument.removeEventListener(type, cancel, true));+ };+};++export const requestNativeTextMenu = (editor: HTMLElement, range: Range) => {+ const ownerDocument = editor.ownerDocument;+ const ownerWindow = ownerDocument.defaultView;+ const handler = ownerWindow.webkit?.messageHandlers?.showTextMenu;+ if (!handler || range.collapsed) {+ return;+ }+ const previous = nativeMenus.get(editor);+ if (previous?.requested && previous.timer === undefined && sameRange(range, previous.range)) {+ return;+ }+ if (previous?.timer !== undefined) {+ ownerWindow.clearTimeout(previous.timer);+ }+ const saved = range.cloneRange();+ const state: NativeTextMenuState = {range: saved, requested: previous?.requested};+ nativeMenus.set(editor, state);+ // 等待原生双击结束和选区同步,再恢复补选文字的系统菜单。+ state.timer = ownerWindow.setTimeout(() => {+ state.timer = undefined;+ const selection = ownerDocument.getSelection();+ const current = selection?.rangeCount > 0 ? selection.getRangeAt(0) : undefined;+ if (!saved.startContainer.isConnected || !editor.contains(ownerDocument.activeElement) ||+ !sameRange(current, saved)) {+ cancelNativeTextMenu(editor);+ return;+ }+ state.requested = true;+ void handler.postMessage(selection.toString()).then(shown => {+ if (!shown && nativeMenus.get(editor) === state) {+ cancelNativeTextMenu(editor);+ }+ }).catch(() => {+ if (nativeMenus.get(editor) === state) {+ nativeMenus.delete(editor);+ }+ });+ }, 120);+};diff --git a/app/src/protyle/wysiwyg/touchCaret.ts b/app/src/protyle/wysiwyg/touchCaret.tsindex 40e7f77998..417432bef0 100644--- a/app/src/protyle/wysiwyg/touchCaret.ts+++ b/app/src/protyle/wysiwyg/touchCaret.ts@@ -2,6 +2,7 @@ import {Constants} from "../../constants";import {focusByRange} from "../util/selectionOffsets";import {isCommittedTextInput} from "./compositionInput";import {bindTouchNavigation} from "./touchNavigation";+import {bindNativeTextMenu, cancelNativeTextMenu, requestNativeTextMenu} from "./nativeTextMenu";const TOUCH_CARET_EXCLUDED = "input, textarea, select, button, a, img, audio, video, iframe, " +".protyle-action, .protyle-attr, .table, .av, .protyle-custom, [data-prevent-swipe], " +@@ -32,10 +33,12 @@ const getTouchCharacterRange = (range: Range, point: {x: number, y: number}) =>export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => boolean) => {const ownerDocument = element.ownerDocument;const ownerWindow = ownerDocument.defaultView;+ const disposeNativeMenu = bindNativeTextMenu(element);let frame: number;let composing = false;- let touchCaret: {editable: HTMLElement, range: Range, character?: Range, startedUnfocused: boolean, time: number};- let previousTap: typeof touchCaret & {time: number, x: number, y: number, count: number, word?: Range | false};+ let touchCaret: {editable: HTMLElement, range: Range, character?: Range, startedUnfocused: boolean,+ time: number, touchTime: number, selection?: Range};+ let previousTap: typeof touchCaret & {x: number, y: number, count: number, word?: Range | false, canceled?: boolean};let pendingTap: typeof previousTap;const cancelFrame = () => {if (frame !== undefined) {@@ -45,6 +48,7 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => boo};const cancel = () => {cancelFrame();+ cancelNativeTextMenu(element);pendingTap = undefined;};const schedule = () => {@@ -55,10 +59,25 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => booframe = undefined;const selection = ownerDocument.getSelection();const activeElement = ownerDocument.activeElement;+ const range = selection?.rangeCount > 0 ? selection.getRangeAt(0) : undefined;+ // 只替换双击前未更新且不包含目标字符的旧选区,保留系统已经完成的新文字选择。+ const staleSelection = tap.count === 2 && tap.selection && range && !range.collapsed &&+ range.startContainer === tap.selection.startContainer && range.startOffset === tap.selection.startOffset &&+ range.endContainer === tap.selection.endContainer && range.endOffset === tap.selection.endOffset &&+ tap.character && !(range.isPointInRange(tap.character.startContainer, tap.character.startOffset) &&+ range.isPointInRange(tap.character.endContainer, tap.character.endOffset));+ const activeInEditable = element.contains(activeElement) &&+ (tap.editable.contains(activeElement) || activeElement.contains(tap.editable));+ if (tap.count === 2 && !composing && canPlaceCaret() && activeInEditable && range &&+ !range.collapsed && !staleSelection && tap.editable.contains(range.startContainer) &&+ tap.editable.contains(range.endContainer)) {+ requestNativeTextMenu(element, range);+ }if (composing || !canPlaceCaret() || !tap.range.startContainer.isConnected ||- !tap.editable.isContentEditable || !element.contains(activeElement) ||- (!tap.editable.contains(activeElement) && !activeElement.contains(tap.editable)) ||- !selection?.isCollapsed || selection.rangeCount === 0 ||+ !tap.editable.isContentEditable ||+ (!activeInEditable && !(tap.count === 2 &&+ (activeElement === ownerDocument.body || element.contains(activeElement)))) ||+ (!selection?.isCollapsed && !staleSelection) || selection.rangeCount === 0 ||!element.contains(selection.anchorNode)) {return;}@@ -71,8 +90,12 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => booif (tap.word === false || !tap.character?.startContainer.isConnected) {return;}+ if (!activeInEditable) {+ tap.editable.focus({preventScroll: true});+ }if (tap.word) {focusByRange(tap.word);+ requestNativeTextMenu(element, tap.word);return;}const word = tap.character.cloneRange() as Range & {expand?: (unit: string) => void};@@ -107,6 +130,7 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => boo.some(item => word.intersectsNode(item))) {tap.word = word;focusByRange(word);+ requestNativeTextMenu(element, word);} else {tap.word = false;}@@ -142,6 +166,20 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => booschedule();}};+ const doubleClick = (event: MouseEvent) => {+ const tap = previousTap;+ if (event.defaultPrevented || composing || !canPlaceCaret() || !tap || tap.count > 2 ||+ Date.now() - tap.time >= Constants.TIMEOUT_LONGPRESS ||+ Math.hypot(event.clientX - tap.x, event.clientY - tap.y) >= Constants.SIZE_DRAG_THRESHOLD * 4 ||+ !tap.range.startContainer.isConnected || !element.contains(tap.editable) ||+ (event.target as HTMLElement).closest(TOUCH_CARET_EXCLUDED)) {+ return;+ }+ // 原生双击可能取消第二次触摸或在键盘滚动后送达,沿用首次命中的正文补全选词。+ previousTap = {...tap, count: 2};+ pendingTap = previousTap;+ schedule();+ };const focusOut = (event: FocusEvent) => {if (event.relatedTarget && !element.contains(event.relatedTarget as Node)) {cancel();@@ -160,21 +198,40 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => boocomposing = false;}};+ const rememberTouchStart = (point: {x: number, y: number}) => {+ const repeated = previousTap && !previousTap.canceled && previousTap.editable === touchCaret.editable &&+ touchCaret.touchTime - previousTap.touchTime >= 0 &&+ touchCaret.touchTime - previousTap.touchTime < Constants.TIMEOUT_LONGPRESS &&+ Math.hypot(point.x - previousTap.x, point.y - previousTap.y) < Constants.SIZE_DRAG_THRESHOLD * 4;+ previousTap = {...(repeated ? previousTap : touchCaret), ...point, time: Date.now(),+ touchTime: touchCaret.touchTime, count: repeated ? previousTap.count + 1 : 1};+ // 按下时记录连续点击,原生手势缺少任一次 touchend 时仍能识别双击。+ if (previousTap.count === 2) {+ pendingTap = previousTap;+ schedule();+ }+ };const touchStart = (event: TouchEvent) => {cancel();touchCaret = undefined;const target = event.target as HTMLElement;if (event.defaultPrevented || event.touches.length !== 1 || composing || !canPlaceCaret() ||target.closest(TOUCH_CARET_EXCLUDED)) {+ if (previousTap) {+ previousTap.canceled = true;+ }return;}const point = {x: event.touches[0].clientX, y: event.touches[0].clientY};- if (previousTap?.count === 1 && previousTap.startedUnfocused &&- Date.now() - previousTap.time < Constants.TIMEOUT_LONGPRESS &&+ const touchTime = Number.isFinite(event.timeStamp) ? event.timeStamp : Date.now();+ if (previousTap?.count === 1 && !previousTap.canceled && previousTap.startedUnfocused &&+ touchTime - previousTap.touchTime >= 0 &&+ touchTime - previousTap.touchTime < Constants.TIMEOUT_LONGPRESS &&Math.hypot(point.x - previousTap.x, point.y - previousTap.y) < Constants.SIZE_DRAG_THRESHOLD * 4 &&previousTap.range.startContainer.isConnected && element.contains(previousTap.editable)) {// 键盘唤起后第二次点击可能命中正文空白,双击仍以第一次按下时的字符为目标。- touchCaret = {...previousTap, time: Date.now()};+ touchCaret = {...previousTap, time: Date.now(), touchTime};+ rememberTouchStart(point);return;}const editable = target.closest<HTMLElement>("[contenteditable]");@@ -193,9 +250,15 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => booconst activeElement = ownerDocument.activeElement;const startedUnfocused = !element.contains(activeElement) ||(!editable.contains(activeElement) && !activeElement.contains(editable));- touchCaret = {editable, range, character: getTouchCharacterRange(range, point), startedUnfocused, time: Date.now()};+ const selection = ownerDocument.getSelection();+ const savedSelection = selection?.rangeCount > 0 && !selection.isCollapsed &&+ element.contains(selection.anchorNode) && element.contains(selection.focusNode) ?+ selection.getRangeAt(0).cloneRange() : undefined;+ touchCaret = {editable, range, character: getTouchCharacterRange(range, point),+ startedUnfocused, time: Date.now(), touchTime, selection: savedSelection};+ rememberTouchStart(point);};- const disposeNavigation = bindTouchNavigation(element, (_target, point) => {+ const disposeNavigation = bindTouchNavigation(element, () => {cancel();const caret = touchCaret;touchCaret = undefined;@@ -203,11 +266,7 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => boo!element.contains(caret.editable)) {return;}- const time = Date.now();- const repeated = previousTap && previousTap.editable === caret.editable &&- caret.time - previousTap.time < Constants.TIMEOUT_LONGPRESS &&- Math.hypot(point.x - previousTap.x, point.y - previousTap.y) < Constants.SIZE_DRAG_THRESHOLD * 4;- previousTap = {...(repeated ? previousTap : caret), time, ...point, count: repeated ? previousTap.count + 1 : 1};+ previousTap.time = Date.now();// 三击及更多次连续点击保留系统的整段选择行为。if (previousTap.count > 2) {return;@@ -221,24 +280,45 @@ export const bindIOSTouchCaret = (element: HTMLElement, canPlaceCaret: () => boopendingTap = previousTap;schedule();}, () => !!touchCaret);- const cancelEvents = ["pointerdown", "touchcancel", "beforeinput", "keydown", "scroll"];- cancelEvents.forEach(type => element.addEventListener(type, cancel, {capture: true, passive: true}));+ const cancelGesture = () => {+ cancel();+ touchCaret = undefined;+ if (previousTap) {+ previousTap.canceled = true;+ }+ };+ const touchMove = (event: TouchEvent) => {+ if (event.touches.length !== 1 || (previousTap &&+ Math.hypot(event.touches[0].clientX - previousTap.x, event.touches[0].clientY - previousTap.y) >=+ Constants.SIZE_DRAG_THRESHOLD)) {+ cancelGesture();+ }+ };+ const cancelEvents = ["touchcancel", "beforeinput", "keydown", "scroll"];+ cancelEvents.forEach(type => element.addEventListener(type, cancelGesture, {capture: true, passive: true}));+ element.addEventListener("pointerdown", cancel, {capture: true, passive: true});+ element.addEventListener("touchmove", touchMove, {capture: true, passive: true});element.addEventListener("touchstart", touchStart, {capture: true, passive: true});element.addEventListener("compositionstart", compositionStart);element.addEventListener("compositionend", compositionEnd);element.addEventListener("input", input);element.addEventListener("click", click);+ element.addEventListener("dblclick", doubleClick);element.addEventListener("focusout", focusOut);ownerDocument.addEventListener("selectionchange", selectionChange);return () => {cancel();+ disposeNativeMenu();disposeNavigation();- cancelEvents.forEach(type => element.removeEventListener(type, cancel, true));+ cancelEvents.forEach(type => element.removeEventListener(type, cancelGesture, true));+ element.removeEventListener("pointerdown", cancel, true);+ element.removeEventListener("touchmove", touchMove, true);element.removeEventListener("touchstart", touchStart, true);element.removeEventListener("compositionstart", compositionStart);element.removeEventListener("compositionend", compositionEnd);element.removeEventListener("input", input);element.removeEventListener("click", click);+ element.removeEventListener("dblclick", doubleClick);element.removeEventListener("focusout", focusOut);ownerDocument.removeEventListener("selectionchange", selectionChange);};diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex fbbc3bb05c..01a111c4ae 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -165,6 +165,7 @@ interface Window {nativeCallbacks: { [key: string]: (id: number) => void },messageHandlers: {finishKeyboardComposition?: { postMessage: (data: string) => Promise<boolean> }+ showTextMenu?: { postMessage: (data: string) => Promise<boolean> }saveExportFile: { postMessage: (url: string) => void }saveExportFileV2?: { postMessage: (data: {uri: string, requestID: string}) => void }openLink: { postMessage: (url: string) => void }diff --git a/app/tests/iosTouchCaret.test.js b/app/tests/iosTouchCaret.test.jsindex 03c32a7817..7e9a7977f9 100644--- a/app/tests/iosTouchCaret.test.js+++ b/app/tests/iosTouchCaret.test.js@@ -12,12 +12,41 @@ const rendererSource = () => {assert.ok(focus);const source = "const Constants = {SIZE_DRAG_THRESHOLD: 5, TIMEOUT_LONGPRESS: 460};\n" +"const revealTabsForTarget = () => {};\n" + focus.getText(selection) + "\n" +- ["wysiwyg/compositionInput", "wysiwyg/touchNavigation", "wysiwyg/touchCaret"].map(name => {+ ["wysiwyg/compositionInput", "wysiwyg/touchNavigation", "wysiwyg/touchCaret", "wysiwyg/nativeTextMenu"].map(name => {const parsed = ts.createSourceFile(name + ".ts", read(name), ts.ScriptTarget.Latest, true);return parsed.statements.filter(statement => !ts.isImportDeclaration(statement)).map(statement => statement.getText(parsed)).join("\n");}).join("\n");- return ts.transpileModule(source, {compilerOptions: {+ const wysiwyg = ts.createSourceFile("index.ts", read("wysiwyg/index"), ts.ScriptTarget.Latest, true);+ let doubleClick;+ const visit = node => {+ if (ts.isCallExpression(node) && node.expression.getText(wysiwyg) === "this.element.addEventListener" &&+ node.arguments[0]?.getText(wysiwyg) === '"dblclick"') {+ doubleClick = node.getText(wysiwyg);+ }+ ts.forEachChild(node, visit);+ };+ visit(wysiwyg);+ assert.ok(doubleClick);+ const menus = ts.createSourceFile("protyle.ts", readFileSync(path.join(__dirname, "../src/menus/protyle.ts"), "utf8"),+ ts.ScriptTarget.Latest, true);+ const contentMenu = menus.statements.find(statement => ts.isVariableStatement(statement) &&+ statement.declarationList.declarations.some(declaration => declaration.name.getText(menus) === "contentMenu"));+ assert.ok(contentMenu);+ const integration = `exports.bindNativeDoubleClick = function(element, toolbar) {+ const protyle = {toolbar};+ const isIOSDevice = () => true;+ const getAVTemplateInteractiveElement = () => undefined;+ (function() { ${doubleClick}; }).call({element});+ };+ exports.callNativeContentMenu = function(protyle, nodeElement) {+ const getEditorRange = () => document.getSelection().getRangeAt(0);+ const isIOSDevice = () => true;+ const isInEmbedBlock = () => false;+ ${contentMenu.getText(menus).replace(/^export /u, "")}+ contentMenu(protyle, nodeElement);+ };`;+ return ts.transpileModule(source + integration, {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021,}}).outputText;};@@ -62,7 +91,7 @@ const runCases = async () => {const touch = new Touch({identifier: 1, target, ...point});const event = new TouchEvent(type, {bubbles: true, cancelable: true,touches: type === "touchend" || type === "touchcancel" ? [] : [touch], changedTouches: [touch], ...options});- Object.defineProperty(event, "timeStamp", {value: time});+ Object.defineProperty(event, "timeStamp", {value: options.timeStamp ?? time});target.dispatchEvent(event);return event;};@@ -96,6 +125,246 @@ const runCases = async () => {}};try {+ await run(async f => {+ const subElement = document.createElement("div");+ f.place(1, f.text, 6);+ window.touchCaret.callNativeContentMenu({wysiwyg: {element: f.root}, toolbar: {subElement}}, f.editable.parentElement);+ check.equal(subElement.classList.contains("fn__none"), true);+ });+ await run(async f => {+ const originalWebkit = window.webkit;+ window.webkit = {};+ try {+ f.place(1, f.text, 6);+ window.touchCaret.requestNativeTextMenu(f.root, selection.getRangeAt(0));+ } finally {+ window.webkit = originalWebkit;+ }+ });+ for (const kind of ["selected", "native", "changed", "scroll"]) {+ await run(async f => {+ let calls = 0;+ const originalWebkit = window.webkit;+ window.webkit = {messageHandlers: {showTextMenu: {postMessage: async () => { calls++; return true; }}}};+ try {+ const point = f.pointAt(4);+ f.send("touchstart", point);+ time += 100;+ f.send("touchstart", point);+ if (kind === "native") {+ f.place(2, f.text, 6);+ }+ await nextFrame();+ if (kind === "changed") {+ time += 1000;+ f.place(f.text.length);+ } else if (kind === "scroll") {+ f.root.dispatchEvent(new Event("scroll"));+ }+ await new Promise(resolve => setTimeout(resolve, 150));+ check.equal(calls, kind === "selected" || kind === "native" ? 1 : 0, kind);+ } finally {+ window.webkit = originalWebkit;+ }+ });+ }+ for (const kind of ["collapsed", "changed", "outside", "ancestorScroll", "unrelatedScroll", "input", "duplicate", "dispose"]) {+ await run(async f => {+ const originalWebkit = window.webkit;+ const messages = [];+ window.webkit = {messageHandlers: {showTextMenu: {postMessage: async text => {+ messages.push(text);+ return true;+ }}}};+ try {+ f.place(2, f.text, 6);+ const text = selection.toString();+ window.touchCaret.requestNativeTextMenu(f.root, selection.getRangeAt(0));+ await new Promise(resolve => setTimeout(resolve, 150));+ check.deepEqual(messages, [text]);+ if (kind === "collapsed" || kind === "changed") {+ f.place(1, f.text, kind === "collapsed" ? 1 : 3);+ document.dispatchEvent(new Event("selectionchange"));+ } else if (kind === "outside") {+ document.querySelector("#outside").dispatchEvent(new Event("pointerdown", {bubbles: true}));+ } else if (kind === "ancestorScroll") {+ document.body.dispatchEvent(new Event("scroll"));+ } else if (kind === "unrelatedScroll") {+ document.querySelector("#outside").dispatchEvent(new Event("scroll"));+ } else if (kind === "input") {+ f.editable.dispatchEvent(new InputEvent("beforeinput", {bubbles: true, inputType: "insertText"}));+ } else if (kind === "duplicate") {+ window.touchCaret.requestNativeTextMenu(f.root, selection.getRangeAt(0));+ } else if (kind === "dispose") {+ f.dispose();+ }+ await new Promise(resolve => setTimeout(resolve, 150));+ check.deepEqual(messages, kind === "unrelatedScroll" || kind === "duplicate" ? [text] : [text, ""], kind);+ } finally {+ window.webkit = originalWebkit;+ }+ });+ }+ await run(async f => {+ const other = f.root.querySelectorAll('[contenteditable="true"]')[1];+ const oldText = other.firstChild;+ other.focus();+ f.place(0, oldText, 2);+ const point = f.pointAt(4);+ f.send("touchstart", point);+ const staleTouch = new Touch({identifier: 2, target: other, ...point});+ f.send("touchend", point, f.editable, {touches: [staleTouch]});+ time += 100;+ f.send("touchstart", point);+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent, "double tap replaces the adjacent block's stale selection");+ check.equal(selection.anchorNode, f.text);+ check.equal(document.activeElement, f.editable);+ });+ await run(async f => {+ f.text.textContent = "alpha beta";+ f.place(0, f.text, 5);+ const point = f.pointAt(8);+ f.send("touchstart", point);+ time += 100;+ f.send("touchstart", point);+ await nextFrame();+ check.equal(selection.toString(), "beta", "double tap works when neither touch sends an end event");+ });+ await run(async f => {+ const point = f.pointAt(4);+ f.send("touchstart", point);+ time += 100;+ f.send("touchstart", point);+ f.place(2, f.text, 6);+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent.slice(2, 6));+ });+ await run(async f => {+ f.text.textContent = "alpha beta";+ const point = f.pointAt(2);+ f.send("touchstart", point);+ time += 100;+ f.send("touchstart", point);+ time += 100;+ f.send("touchstart", point);+ f.place(0, f.text, f.text.length);+ await nextFrame();+ check.equal(selection.toString(), "alpha beta");+ });+ for (const kind of ["touchcancel", "scroll", "move", "multitouch"]) {+ await run(async f => {+ const point = f.pointAt(4);+ f.send("touchstart", point);+ if (kind === "scroll") {+ f.root.dispatchEvent(new Event("scroll"));+ } else if (kind === "move") {+ f.send("touchmove", {...point, clientY: point.clientY + 10});+ } else if (kind === "multitouch") {+ const touch = new Touch({identifier: 2, target: f.editable, ...point});+ f.send("touchstart", point, f.editable, {touches: [touch, touch]});+ } else {+ f.send("touchcancel", point);+ }+ time += 100;+ f.tap(4);+ await nextFrame();+ f.caret(4);+ });+ }+ await run(async f => {+ const subElement = document.createElement("div");+ window.touchCaret.bindNativeDoubleClick(f.root, {isMultiSelectMode: () => false, subElement});+ f.place(1, f.text, 6);+ f.editable.dispatchEvent(new MouseEvent("dblclick", {bubbles: true, detail: 2, ...f.pointAt(4)}));+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent.slice(1, 6));+ check.equal(subElement.classList.contains("fn__none"), true);+ });+ await run(async f => {+ const point = f.pointAt(4);+ f.tap(4);+ await nextFrame();+ time += 100;+ f.send("touchstart", point);+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent);+ f.send("touchcancel", point);+ check.equal(selection.toString(), f.text.textContent);+ }, false);+ await run(async f => {+ const point = f.pointAt(4);+ f.tap(4);+ await nextFrame();+ time += 100;+ f.send("touchstart", point);+ f.send("touchcancel", point);+ f.place(f.text.length);+ f.editable.dispatchEvent(new MouseEvent("dblclick", {bubbles: true, detail: 2, ...point}));+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent);+ }, false);+ await run(async f => {+ const point = f.pointAt(4);+ f.tap(4);+ await nextFrame();+ time += 100;+ f.tap(4);+ f.root.dispatchEvent(new Event("scroll"));+ f.place(f.text.length);+ f.editable.dispatchEvent(new MouseEvent("dblclick", {bubbles: true, detail: 2, ...point}));+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent);+ }, false);+ await run(async f => {+ const point = f.pointAt(4);+ f.tap(4);+ await nextFrame();+ time += 100;+ f.place(1, f.text, 6);+ f.editable.dispatchEvent(new MouseEvent("dblclick", {bubbles: true, detail: 2, ...point}));+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent.slice(1, 6));+ });+ await run(async f => {+ const {usesNativeTextMenu} = window.touchCaret;+ check.equal(usesNativeTextMenu(f.editable, f.root), true);+ f.editable.innerHTML = "<b>formatted text</b>";+ check.equal(usesNativeTextMenu(f.editable.firstChild, f.root), true);+ for (const markup of ["<a href='#'>link</a>", "<span data-type='block-ref'>reference</span>",+ "<span data-type='inline-math'>math</span>", "<span contenteditable='false'>readonly</span>",+ "<button>action</button>", "<img>", "<span class='protyle-action'>1.</span>"]) {+ f.editable.innerHTML = markup;+ check.equal(usesNativeTextMenu(f.editable.firstChild, f.root), false, markup);+ }+ check.equal(usesNativeTextMenu(document.getElementById("outside"), f.root), false);+ check.equal(usesNativeTextMenu(f.root, f.root), false);+ });+ await run(async f => {+ const point = f.pointAt(4);+ const touchTime = time;+ f.send("touchstart", point, f.editable, {timeStamp: touchTime});+ f.send("touchend", point, f.editable, {timeStamp: touchTime + 30});+ await nextFrame();+ f.root.style.paddingTop = "100px";+ time += 800;+ f.send("touchstart", point, f.root, {timeStamp: touchTime + 160});+ f.send("touchend", point, f.root, {timeStamp: touchTime + 190});+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent);+ }, false);+ await run(async f => {+ const point = f.pointAt(4);+ const touchTime = time;+ f.send("touchstart", point, f.editable, {timeStamp: touchTime});+ f.send("touchend", point, f.editable, {timeStamp: touchTime + 30});+ await nextFrame();+ time += 800;+ f.send("touchstart", point, f.editable, {timeStamp: touchTime + 160});+ f.send("touchend", point, f.editable, {timeStamp: touchTime + 190});+ await nextFrame();+ check.equal(selection.toString(), f.text.textContent);+ });await run(async f => {check.equal(selection.rangeCount, 0);f.tap(4);@@ -408,7 +677,7 @@ if (process.versions.electron && process.type === "browser") {try {const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});- assert.match(stdout, /iOS touch caret: 35 DOM cases passed/);+ assert.match(stdout, /iOS touch caret: 65 DOM cases passed/);} finally {assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));assert.ok(path.basename(profile).startsWith("siyuan-ios-touch-caret-"));