From 19824fd2b33cb0cde560520781acfaab9242614e Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Wed, 2 Dec 2026 11:42:24 +0530 Subject: [PATCH 1/7] fix(ios): cancel touch pointers WebKit leaves down after a native gesture WebKit delivers pointerdown but never pointerup or pointercancel when a native gesture claims a touch, such as dragging a text selection handle or double-tapping a word, so the editor kept believing a finger was down and hid the selection menu until the next touch. WebTouchEnd now observes touches natively without preventing or delaying any gesture; when the last finger lifts, pages and their frames receive a pointercancel for the touch pointers still held, after a short settle window so a real pointerup that arrives late wins. The recognizer never fails itself, because a failed recognizer is not reset while WebKit's double-tap recognizer is pending, which made it miss the second tap. It is installed in the main and preview WebViews, and it tolerates a missed touch-end instead of silencing itself. Selection menu buttons now activate on the touch's touchend, with a 100 ms fallback, so removing the menu cannot drop touchend and let WebKit place the caret under the finger, and they accept WebKit's emulated mousedown when a tap never reports pointerup. The menu also restores the selection that WebKit's native text tap moves or clears behind a press, bounded to 1.5 s and dropped when the press is cancelled. Copying on iOS shows a confirmation toast, and the colour action only appears when the caret or selection holds a colour, using the menu's own editor state so split panes no longer disagree. --- docs/ios-port.md | 28 ++++ platforms/ios/runner/WebTouchEnd.swift | 114 +++++++++++++++ platforms/ios/runner/WebViewController.swift | 2 + .../lib/preview/PreviewViewController.swift | 2 + .../ios/runnerTests/WebTouchEndTests.swift | 67 +++++++++ src/cm/commandRegistry.js | 8 ++ src/cm/selectionMenuUtils.ts | 45 +++++- src/cm/touchSelectionMenu.js | 74 +++++++++- src/lib/selectionMenu.js | 22 +-- src/utils/color/regex.js | 11 +- tests/unit/color.test.js | 25 +++- tests/unit/iosWebTouchEnd.test.js | 134 ++++++++++++++++++ tests/unit/selectionMenuButton.test.ts | 97 ++++++++++++- tests/unit/touchSelectionMenuTapGuard.test.ts | 117 +++++++++++++++ 14 files changed, 720 insertions(+), 26 deletions(-) create mode 100644 platforms/ios/runner/WebTouchEnd.swift create mode 100644 platforms/ios/runnerTests/WebTouchEndTests.swift create mode 100644 tests/unit/iosWebTouchEnd.test.js create mode 100644 tests/unit/touchSelectionMenuTapGuard.test.ts diff --git a/docs/ios-port.md b/docs/ios-port.md index 5f4982939f..a9e03cc7d0 100644 --- a/docs/ios-port.md +++ b/docs/ios-port.md @@ -523,6 +523,34 @@ long-press/right-click menu presentation and third-party keyboard suggestions still need manual checks; calling UIKit's edit interaction programmatically did not reproduce normal menu presentation in the simulator. +When a native gesture claims a touch, such as dragging a text selection handle, +WebKit delivers `pointerdown` but never `pointerup` or `pointercancel`, which left +the editor's selection menu hidden until the next touch. `WebTouchEnd` observes +touches natively without preventing or delaying any gesture; when every finger +lifts, pages and their frames get a `pointercancel` for touch pointers still held +after 100 ms. Touches that begin after the native end are never cancelled. The +recognizer never fails itself: a failed recognizer is not reset while WebKit's +double-tap recognizer is pending, so it would miss the second tap of a double-tap +on a word, which WebKit also swallows, leaving the menu hidden. The main +and preview WebViews install it. Simulator and happy-dom tests cover stale, released, +late-released and newly started touches, Shadow DOM and frames; dragging a handle +by hand on a physical device remains a manual check. + +Selection menu buttons work around three more WebKit touch behaviours, all seen +in device logs. A touch press runs its action on that touch's `touchend`, which +normally arrives in the same millisecond as `pointerup`, so there is no visible delay. Removing +the menu on `pointerup` dropped the `touchend` and let WebKit place the caret +under the finger. If no `touchend` arrives, the action runs 100 ms after +`pointerup`. When WebKit claims a tap and sends only an emulated `mousedown`, +that `mousedown` activates the button. WebKit's native text tap can also clear or +move the selection behind a menu press with no page event, so the menu restores +the selection it saw when the press began, unless a menu action or a document +edit changed it. The restore window starts at `pointerdown`, is capped at 1.5 s, +lasts 350 ms after release, and is dropped when the press is cancelled before +release. Presses from a secondary pointer still activate buttons, because WebKit +keeps reporting taps as secondary after some double-taps on a word even with +`WebTouchEnd` installed. A second press while one is already held is ignored. + The account API uses an iOS-only fetch/XHR URL adapter because the app's custom scheme has an opaque browser origin. The native handler restricts requests to the Acode API origin, retains TLS verification, honors credential omission and diff --git a/platforms/ios/runner/WebTouchEnd.swift b/platforms/ios/runner/WebTouchEnd.swift new file mode 100644 index 0000000000..eeab4d48aa --- /dev/null +++ b/platforms/ios/runner/WebTouchEnd.swift @@ -0,0 +1,114 @@ +import UIKit +import WebKit + +/// When a native gesture (such as dragging a text selection handle) takes over a touch, +/// WebKit stops delivering its pointer events, so the page never sees pointerup or +/// pointercancel. This watches touches natively and, when the touch sequence ends, +/// cancels any touch pointer the page still believes is down. +final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate { + private weak var webView: WKWebView? + private var activeTouches = Set() + + init(webView: WKWebView) { + self.webView = webView + super.init(target: nil, action: nil) + cancelsTouchesInView = false + delaysTouchesEnded = false + delegate = self + webView.addGestureRecognizer(self) + webView.configuration.userContentController.addUserScript( + WKUserScript(source: Self.script, injectionTime: .atDocumentStart, forMainFrameOnly: false) + ) + } + + override func canBePrevented(by preventingGestureRecognizer: UIGestureRecognizer) -> Bool { false } + + override func canPrevent(_ preventedGestureRecognizer: UIGestureRecognizer) -> Bool { false } + + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, + shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { + true + } + + override func touchesBegan(_ touches: Set, with event: UIEvent) { + // This recognizer is rarely reset, so drop touches whose end callback was missed; + // one stale touch would otherwise silence it for the rest of the session. + activeTouches = activeTouches.filter { [.began, .moved, .stationary].contains($0.phase) } + activeTouches.formUnion(touches) + } + + override func touchesEnded(_ touches: Set, with event: UIEvent) { + release(touches) + } + + override func touchesCancelled(_ touches: Set, with event: UIEvent) { + release(touches) + } + + override func reset() { + super.reset() + activeTouches.removeAll() + } + + func send() { + webView?.evaluateJavaScript("window.acodeNativeTouchEnd?.()", completionHandler: nil) + } + + private func release(_ touches: Set) { + activeTouches.subtract(touches) + guard activeTouches.isEmpty else { return } + // Failing here would leave this recognizer unreset, and blind to the next tap, + // while a multi-tap recognizer such as WebKit's double-tap is still pending. + send() + } + + static let script = """ + (() => { + const messageType = 'acode-native-touchend'; + // WebKit can still deliver the real pointerup shortly after the native touch end. + const settleDelay = 100; + const active = new Map(); + const track = event => { + if (event.pointerType !== 'touch') return; + if (event.type === 'pointerdown') { + active.set(event.pointerId, { + target: event.composedPath()[0], isPrimary: event.isPrimary, + clientX: event.clientX, clientY: event.clientY + }); + return; + } + const pointer = active.get(event.pointerId); + if (!pointer) return; + pointer.clientX = event.clientX; + pointer.clientY = event.clientY; + }; + document.addEventListener('pointerdown', track, true); + document.addEventListener('pointermove', track, true); + for (const type of ['pointerup', 'pointercancel']) + document.addEventListener(type, event => active.delete(event.pointerId), true); + const cancel = stale => { + for (const [pointerId, pointer] of stale) { + if (active.get(pointerId) !== pointer) continue; + active.delete(pointerId); + const {target, isPrimary, clientX, clientY} = pointer; + (target.isConnected ? target : document).dispatchEvent(new PointerEvent('pointercancel', { + bubbles: true, composed: true, pointerId, pointerType: 'touch', isPrimary, clientX, clientY + })); + } + }; + const receive = () => { + if (active.size) { + const stale = [...active]; + setTimeout(() => cancel(stale), settleDelay); + } + for (let i = 0; i < frames.length; i++) + frames[i].postMessage({type: messageType}, '*'); + }; + window.acodeNativeTouchEnd = receive; + window.addEventListener('message', event => { + if (event.source === parent && event.data?.type === messageType) + receive(); + }); + })(); + """ +} diff --git a/platforms/ios/runner/WebViewController.swift b/platforms/ios/runner/WebViewController.swift index b22fa5a094..65268cfc70 100644 --- a/platforms/ios/runner/WebViewController.swift +++ b/platforms/ios/runner/WebViewController.swift @@ -15,6 +15,7 @@ final class WebViewController: UIViewController { var isFullscreenLayout: Bool { fullscreenLayout.first?.isActive == true } private var scrollObservation: NSKeyValueObservation? private var contextMenu: WebContextMenu? + private var touchEnd: WebTouchEnd? override func viewDidLoad() { super.viewDidLoad() @@ -38,6 +39,7 @@ final class WebViewController: UIViewController { config.allowsInlineMediaPlayback = true webView = AppWebView(frame: .zero, configuration: config) contextMenu = WebContextMenu(webView: webView) + touchEnd = WebTouchEnd(webView: webView) webView.navigationDelegate = self #if DEBUG webView.isInspectable = true diff --git a/platforms/ios/runner/lib/preview/PreviewViewController.swift b/platforms/ios/runner/lib/preview/PreviewViewController.swift index b3c252eff8..f684cc5360 100644 --- a/platforms/ios/runner/lib/preview/PreviewViewController.swift +++ b/platforms/ios/runner/lib/preview/PreviewViewController.swift @@ -32,6 +32,7 @@ final class PreviewViewController: UIViewController { private(set) var isClosed = false private var observations: [NSKeyValueObservation] = [] private var contextMenu: WebContextMenu? + private var touchEnd: WebTouchEnd? private var contentBottom: NSLayoutConstraint? private var contentFollowsKeyboard = true @@ -46,6 +47,7 @@ final class PreviewViewController: UIViewController { webView = WKWebView(frame: .zero, configuration: configuration) super.init(nibName: nil, bundle: nil) contextMenu = WebContextMenu(webView: webView) + touchEnd = WebTouchEnd(webView: webView) modalPresentationStyle = .fullScreen } diff --git a/platforms/ios/runnerTests/WebTouchEndTests.swift b/platforms/ios/runnerTests/WebTouchEndTests.swift new file mode 100644 index 0000000000..128d2ae082 --- /dev/null +++ b/platforms/ios/runnerTests/WebTouchEndTests.swift @@ -0,0 +1,67 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class WebTouchEndTests: XCTestCase { + func testNativeConfigurationNeverInterferesWithOtherGesturesAndCoversAllFrames() { + let view = WKWebView() + let touchEnd = WebTouchEnd(webView: view) + XCTAssertTrue(view.gestureRecognizers?.contains(touchEnd) == true) + XCTAssertFalse(touchEnd.cancelsTouchesInView) + XCTAssertFalse(touchEnd.delaysTouchesBegan) + XCTAssertFalse(touchEnd.delaysTouchesEnded) + XCTAssertFalse(touchEnd.canBePrevented(by: UIPanGestureRecognizer())) + XCTAssertFalse(touchEnd.canPrevent(UIPanGestureRecognizer())) + XCTAssertTrue(touchEnd.gestureRecognizer(touchEnd, shouldRecognizeSimultaneouslyWith: UILongPressGestureRecognizer())) + let script = view.configuration.userContentController.userScripts.first { $0.source == WebTouchEnd.script } + XCTAssertEqual(script?.injectionTime, .atDocumentStart) + XCTAssertEqual(script?.isForMainFrameOnly, false) + let preview = PreviewViewController(url: URL(string: "about:blank")!, theme: [:], console: false) + XCTAssertTrue(preview.webView.configuration.userContentController.userScripts.contains { $0.source == WebTouchEnd.script }) + } + + func testNativeTouchEndCancelsOnlyUnreleasedTouchPointersIncludingFrames() async throws { + let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 400, height: 600)) + let touchEnd = WebTouchEnd(webView: view) + view.loadHTMLString(""" + +
+ + + """, baseURL: nil) + try await waitFor(view, "typeof window.down==='function' && !!document.querySelector('iframe').contentWindow.acodeNativeTouchEnd") + _ = try await view.evaluateJavaScript(""" + down(document.getElementById('held'),1); + down(document.getElementById('released'),2); + down(document.getElementById('released'),2,'pointerup'); + down(document.getElementById('host').shadowRoot.getElementById('shadow-held'),3); + const frame=document.querySelector('iframe').contentWindow; + frame.cancels=[]; + frame.document.addEventListener('pointercancel',event=>frame.cancels.push(event.target.id)); + down(frame.document.getElementById('frame-held'),4,'pointerdown',frame); + true; + """) + touchEnd.send() + try await waitFor(view, "cancels.length===2 && document.querySelector('iframe').contentWindow.cancels.length===1") + let cancels = try await view.evaluateJavaScript("cancels") as? [String] + XCTAssertEqual(cancels, ["held", "shadow-held"]) + let frameCancels = try await view.evaluateJavaScript("document.querySelector('iframe').contentWindow.cancels") as? [String] + XCTAssertEqual(frameCancels, ["frame-held"]) + } + + private func waitFor(_ view: WKWebView, _ expression: String) async throws { + for _ in 0..<100 { + if (try? await view.evaluateJavaScript(expression)) as? Bool == true { return } + try await Task.sleep(for: .milliseconds(50)) + } + XCTFail("WebView did not settle: \(expression)") + throw NSError(domain: "WebTouchEndTests", code: 1) + } +} diff --git a/src/cm/commandRegistry.js b/src/cm/commandRegistry.js index 3ec24baf5b..45137a954d 100644 --- a/src/cm/commandRegistry.js +++ b/src/cm/commandRegistry.js @@ -1353,9 +1353,16 @@ function copyCommand(view) { }); const textToCopy = texts.join("\n"); Bridge.clipboard.copy(textToCopy); + notifyCopied(); return true; } +// Android shows its own clipboard confirmation; iOS shows nothing. +function notifyCopied() { + if (!platform.isIOS) return; + toast(globalThis.strings?.["copied to clipboard"] || "Copied to clipboard"); +} + function cutCommand(view) { const resolvedView = resolveView(view); if (!resolvedView) return false; @@ -1374,6 +1381,7 @@ function cutCommand(view) { changes.push({ from: range.from, to: range.to, insert: "" }); }); Bridge.clipboard.copy(segments.join("\n")); + notifyCopied(); resolvedView.dispatch({ changes, selection: EditorSelection.single( diff --git a/src/cm/selectionMenuUtils.ts b/src/cm/selectionMenuUtils.ts index 1cbc55d704..199e56105f 100644 --- a/src/cm/selectionMenuUtils.ts +++ b/src/cm/selectionMenuUtils.ts @@ -10,6 +10,7 @@ export interface SelectionMenuFilterOptions { } const POINTER_MOVE_TOLERANCE = 8; +const TOUCH_END_WAIT = 100; /** Preserve editor focus during a pointer press and activate on release. */ export function bindSelectionMenuButton( @@ -18,6 +19,9 @@ export function bindSelectionMenuButton( ): void { let activePointerId: number | null = null; let pointerStart: { x: number; y: number } | null = null; + let isTouchPress = false; + let pendingTouchRelease: PointerEvent | null = null; + let touchReleaseTimer: ReturnType | undefined; const stopEvent = (event: Event) => { event.preventDefault(); @@ -26,8 +30,17 @@ export function bindSelectionMenuButton( const clearPointer = () => { activePointerId = null; pointerStart = null; + isTouchPress = false; button.classList.remove("is-pressed"); }; + // Removing the menu on pointerup would drop the touch's touchend, letting + // iOS WebKit place the caret wherever the tap landed in the editor below. + const activateTouchRelease = () => { + clearTimeout(touchReleaseTimer); + const event = pendingTouchRelease; + pendingTouchRelease = null; + if (event) onActivate(event); + }; const pointerMoved = (event: PointerEvent) => { if (!pointerStart) return false; const xDistance = event.clientX - pointerStart.x; @@ -36,10 +49,13 @@ export function bindSelectionMenuButton( }; button.addEventListener("pointerdown", (event) => { - if (event.isPrimary === false) return; + // iOS WebKit can keep a lost double-tap touch registered, which makes every + // later tap a secondary pointer, so only a second simultaneous press is ignored. + if (event.isPrimary === false && activePointerId !== null) return; if (event.pointerType === "mouse" && event.button !== 0) return; activePointerId = event.pointerId; pointerStart = { x: event.clientX, y: event.clientY }; + isTouchPress = event.pointerType === "touch"; button.classList.add("is-pressed"); stopEvent(event); try { @@ -57,13 +73,38 @@ export function bindSelectionMenuButton( button.addEventListener("pointerup", (event) => { if (event.pointerId !== activePointerId || !pointerStart) return; const moved = pointerMoved(event); + const wasTouchPress = isTouchPress; clearPointer(); stopEvent(event); - if (!moved) onActivate(event); + if (moved) return; + if (!wasTouchPress) { + onActivate(event); + return; + } + pendingTouchRelease = event; + touchReleaseTimer = setTimeout(activateTouchRelease, TOUCH_END_WAIT); }); button.addEventListener("pointercancel", clearPointer); button.addEventListener("lostpointercapture", clearPointer); + // iOS WebKit follows a tap with emulated mouse events after the menu has + // closed, which would land on the editor underneath and move the caret. + button.addEventListener( + "touchend", + (event) => { + if (event.cancelable) event.preventDefault(); + activateTouchRelease(); + }, + { passive: false }, + ); + button.addEventListener("mousedown", (event) => { + event.preventDefault(); + // iOS WebKit sometimes claims a tap without sending pointerup, leaving + // only this emulated mousedown to mark the end of the touch press. + if (!isTouchPress) return; + clearPointer(); + onActivate(event); + }); button.addEventListener("click", (event) => { stopEvent(event); if (event.detail === 0) onActivate(event); diff --git a/src/cm/touchSelectionMenu.js b/src/cm/touchSelectionMenu.js index c31c20995f..f004d183c8 100644 --- a/src/cm/touchSelectionMenu.js +++ b/src/cm/touchSelectionMenu.js @@ -21,12 +21,16 @@ const TAP_MAX_DISTANCE = 20; const EDGE_SCROLL_GAP = 40; const MENU_MARGIN = 10; const MENU_SHOW_DELAY = 120; +const MENU_TAP_SETTLE = 350; +const MENU_TAP_PRESS_LIMIT = 1500; const MENU_CARET_GAP = 10; const MENU_SELECTION_GAP = 12; const MENU_HANDLE_CLEARANCE = 28; const OVERFLOW_GRID_THRESHOLD = 10; const TAP_MAX_COLUMN_DELTA = 2; const TAP_MAX_POS_DELTA = 2; +const MENU_TAP_END_EVENTS = ["pointerup", "touchend", "mousedown", "click"]; +const MENU_TAP_CANCEL_EVENTS = ["pointercancel", "lostpointercapture"]; /** * Classify taps into single/double/triple tap buckets. @@ -212,6 +216,9 @@ class TouchSelectionMenuController { #viewAnimations = []; #overflowExpanded = false; #canvas = false; + #menuTapState = null; + #menuTapGuardUntil = 0; + #menuTapSettled = false; constructor(view, options = {}) { this.#view = view; @@ -242,6 +249,13 @@ class TouchSelectionMenuController { document.addEventListener("pointermove", this.#onGlobalPointerMove, true); document.addEventListener("pointerup", this.#onGlobalPointerUp, true); document.addEventListener("pointercancel", this.#onGlobalPointerUp, true); + this.$menu.addEventListener("pointerdown", this.#guardMenuTap, true); + for (const type of MENU_TAP_END_EVENTS) { + this.$menu.addEventListener(type, this.#settleMenuTap, true); + } + for (const type of MENU_TAP_CANCEL_EVENTS) { + this.$menu.addEventListener(type, this.#cancelMenuTap, true); + } } this.#tooltipObserver = new MutationObserver((mutations) => { @@ -297,6 +311,7 @@ class TouchSelectionMenuController { this.#pointerSelectionSession = null; this.#readOnlyTapSession = null; this.#pendingPointerSelectionClick = null; + this.#menuTapState = null; this.#tooltipObserver?.disconnect(); this.#hideMenu(true); } @@ -304,6 +319,7 @@ class TouchSelectionMenuController { setEnabled(enabled) { this.#enabled = !!enabled; if (this.#enabled) return; + this.#menuTapState = null; this.#pointerSelectionSession = null; this.#readOnlyTapSession = null; this.#pendingPointerSelectionClick = null; @@ -375,6 +391,7 @@ class TouchSelectionMenuController { // A canvas view drops its menu itself on keyboard input and outside // selection changes. if (!this.#enabled || this.#canvas) return; + if (meta.selectionChanged && this.#restoreMenuTapSelection()) return; if (meta.selectionChanged) this.#cancelReadOnlyTap(); if ( meta.selectionChanged && @@ -402,6 +419,7 @@ class TouchSelectionMenuController { this.#readOnlyTapSession = null; this.#pendingPointerSelectionClick = null; this.#dismissedSelection = null; + this.#menuTapState = null; this.#menuRequested = false; this.#isPointerInteracting = false; this.#isScrolling = false; @@ -770,6 +788,7 @@ class TouchSelectionMenuController { selectionMenu({ codeActionsAvailable: hasCodeActionProvider(this.#view), lspActionsAvailable: hasLspActions(this.#view), + state: this.#view.state, }), { readOnly: this.#isReadOnly(), @@ -806,7 +825,7 @@ class TouchSelectionMenuController { } #renderMenu(primaryItems, overflowItems) { - for (const animation of this.#viewAnimations) animation.cancel?.(); + for (const animation of this.#viewAnimations) settleAnimation(animation); this.#viewAnimations = []; this.#overflowExpanded = false; this.$menu.style.removeProperty("width"); @@ -910,6 +929,7 @@ class TouchSelectionMenuController { this.#hideMenu(); if (this.#canvas) this.#view.touchSelection?.hideMenu(); focusEditorIfEditable(this.#view); + if (this.#menuTapState) this.#menuTapState = this.#view.state; } }; bindSelectionMenuButton($item, runAction); @@ -917,7 +937,7 @@ class TouchSelectionMenuController { } #animateMenuIn() { - this.#menuAnimation?.cancel?.(); + settleAnimation(this.#menuAnimation); if (animationsDisabled()) { this.$menu.style.opacity = "1"; this.$menu.style.transform = "none"; @@ -939,9 +959,9 @@ class TouchSelectionMenuController { #setOverflowExpanded($primary, $overflow, expanded) { if (expanded === this.#overflowExpanded) return; const initialRect = this.$menu.getBoundingClientRect(); - this.#menuAnimation?.cancel?.(); + settleAnimation(this.#menuAnimation); this.#menuAnimation = null; - for (const animation of this.#viewAnimations) animation.cancel?.(); + for (const animation of this.#viewAnimations) settleAnimation(animation); this.#viewAnimations = []; $primary.hidden = this.#overflowExpanded; $overflow.hidden = !this.#overflowExpanded; @@ -1199,8 +1219,8 @@ class TouchSelectionMenuController { #hideMenu(force = false) { if (!force && !this.#menuActive && !this.$menu.isConnected) return; - this.#menuAnimation?.cancel?.(); - for (const animation of this.#viewAnimations) animation.cancel?.(); + settleAnimation(this.#menuAnimation); + for (const animation of this.#viewAnimations) settleAnimation(animation); this.#menuAnimation = null; this.#viewAnimations = []; if (this.$menu.isConnected) { @@ -1276,6 +1296,42 @@ class TouchSelectionMenuController { return false; } + // iOS WebKit runs its native text tap on a menu press: it clears a selection + // it made itself or moves the caret under the finger, without page events. + #guardMenuTap = () => { + this.#menuTapState = this.#view.state; + this.#menuTapSettled = false; + this.#menuTapGuardUntil = performance.now() + MENU_TAP_PRESS_LIMIT; + }; + + #settleMenuTap = () => { + if (!this.#menuTapState) return; + this.#menuTapSettled = true; + this.#menuTapGuardUntil = performance.now() + MENU_TAP_SETTLE; + }; + + // A press cancelled before release (a scroll, or WebKit claiming the touch) + // ran no action, so the editor owns any selection change that follows. + #cancelMenuTap = () => { + if (!this.#menuTapSettled) this.#menuTapState = null; + }; + + #restoreMenuTapSelection() { + const tapState = this.#menuTapState; + if (!tapState) return false; + const { state } = this.#view; + if ( + performance.now() > this.#menuTapGuardUntil || + state.doc !== tapState.doc + ) { + this.#menuTapState = null; + return false; + } + if (state.selection.eq(tapState.selection)) return false; + this.#view.dispatch({ selection: tapState.selection }); + return true; + } + #hasSelection() { const selection = this.#view.state.selection.main; return selection.from !== selection.to; @@ -1287,3 +1343,9 @@ class TouchSelectionMenuController { .join("|"); } } + +// Motion keeps a cancelled animation's last transform and reapplies it on the +// element's next animation, which left the reopened menu stretched. +function settleAnimation(animation) { + animation?.complete?.(); +} diff --git a/src/lib/selectionMenu.js b/src/lib/selectionMenu.js index a3fd34237b..28a69ea97b 100644 --- a/src/lib/selectionMenu.js +++ b/src/lib/selectionMenu.js @@ -1,5 +1,6 @@ import { focusEditorIfEditable } from "cm/editorReadOnly"; import appSettings from "lib/settings"; +import { getColorRange } from "utils/color/regex"; const exec = (command) => { const { editor } = editorManager; @@ -98,7 +99,11 @@ const showLspActions = async () => { const items = []; export default function selectionMenu(options = {}) { - const { codeActionsAvailable = true, lspActionsAvailable = true } = options; + const { + codeActionsAvailable = true, + lspActionsAvailable = true, + state, + } = options; return [ item( () => exec("copy"), @@ -142,13 +147,14 @@ export default function selectionMenu(options = {}) { true, { id: "share", label: getLabel("share", "Share") }, ), - item( - (color) => acode.exec("insert-color", color), - , - "all", - false, - { id: "insert-color", label: getLabel("insert color", "Insert color") }, - ), + getColorRange(state) && + item( + (color) => acode.exec("insert-color", color), + , + "all", + false, + { id: "insert-color", label: getLabel("insert color", "Insert color") }, + ), codeActionsAvailable && item( () => showCodeActions(), diff --git a/src/utils/color/regex.js b/src/utils/color/regex.js index 5b239bceee..34662880b0 100644 --- a/src/utils/color/regex.js +++ b/src/utils/color/regex.js @@ -248,26 +248,25 @@ export const colorRegex = { /** * Select the color at current line and cursor position (CodeMirror) + * @param {import("@codemirror/state").EditorState} [state] Defaults to the active editor's state * @returns {{from:number,to:number}|null} */ -export function getColorRange() { - const { editor } = editorManager; - +export function getColorRange(state = editorManager.editor?.state) { try { - const sel = editor.state.selection.main; + const sel = state.selection.main; const from = sel.from; const to = sel.to; // If there is a selection, validate and return it if (from !== to) { - const text = editor.state.doc.sliceString(from, to); + const text = state.doc.sliceString(from, to); if (!isValidColor(text)) return null; return { from, to }; } // No selection: find color under cursor in the current line const head = sel.head; - const line = editor.state.doc.lineAt(head); + const line = state.doc.lineAt(head); const lineText = line.text; const col = head - line.from; diff --git a/tests/unit/color.test.js b/tests/unit/color.test.js index 703c6f1e14..8a4452037b 100644 --- a/tests/unit/color.test.js +++ b/tests/unit/color.test.js @@ -1,6 +1,7 @@ +import { EditorSelection, EditorState } from "@codemirror/state"; import Hex from "utils/color/hex"; import Hsl from "utils/color/hsl"; -import { isValidColor } from "utils/color/regex"; +import { getColorRange, isValidColor } from "utils/color/regex"; import Rgb from "utils/color/rgb"; import { describe, expect, it } from "vitest"; @@ -101,3 +102,25 @@ describe("isValidColor", () => { expect(isValidColor("#gg0000")).toBe(false); }); }); + +describe("getColorRange", () => { + const stateWith = (doc, selection) => EditorState.create({ doc, selection }); + + it("returns a selection only when it is a colour", () => { + expect( + getColorRange(stateWith("color: #ff0000;", EditorSelection.range(7, 14))), + ).toEqual({ from: 7, to: 14 }); + expect( + getColorRange(stateWith("function test", EditorSelection.range(0, 8))), + ).toBeNull(); + }); + + it("finds the colour under a caret in the given editor state", () => { + expect( + getColorRange(stateWith("a { color: red; }", EditorSelection.cursor(12))), + ).toEqual({ from: 11, to: 14 }); + expect( + getColorRange(stateWith("plain text", EditorSelection.cursor(3))), + ).toBeNull(); + }); +}); diff --git a/tests/unit/iosWebTouchEnd.test.js b/tests/unit/iosWebTouchEnd.test.js new file mode 100644 index 0000000000..81a951c09f --- /dev/null +++ b/tests/unit/iosWebTouchEnd.test.js @@ -0,0 +1,134 @@ +import fs from "node:fs"; +import { Window } from "happy-dom"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; + +const source = fs.readFileSync( + new URL("../../platforms/ios/runner/WebTouchEnd.swift", import.meta.url), + "utf8", +); +const script = source.match(/static let script = """\n([\s\S]*?)\n\s*"""/)[1]; +let window, target, cancels; + +beforeEach(() => { + window = new Window(); + window.eval(script); + target = window.document.createElement("div"); + window.document.body.append(target); + cancels = vi.fn(); + window.document.addEventListener("pointercancel", cancels, true); +}); +afterEach(async () => { + await window.happyDOM.close(); + vi.restoreAllMocks(); +}); + +it("cancels a touch pointer the page never saw released, at its last position", async () => { + pointer(target, "pointerdown"); + pointer(target, "pointermove", { clientX: 60, clientY: 70 }); + window.acodeNativeTouchEnd(); + expect(cancels).not.toHaveBeenCalled(); + await settle(); + expect(cancels).toHaveBeenCalledOnce(); + const event = cancels.mock.calls[0][0]; + expect(event.target).toBe(target); + expect(event).toMatchObject({ + pointerId: 1, + pointerType: "touch", + isPrimary: true, + clientX: 60, + clientY: 70, + bubbles: true, + composed: true, + }); + window.acodeNativeTouchEnd(); + await settle(); + expect(cancels).toHaveBeenCalledOnce(); +}); + +it.each([ + "pointerup", + "pointercancel", +])("leaves a touch alone once the page received %s", async (type) => { + pointer(target, "pointerdown"); + pointer(target, type); + cancels.mockClear(); + window.acodeNativeTouchEnd(); + await settle(); + expect(cancels).not.toHaveBeenCalled(); +}); + +it("leaves a touch alone when WebKit's real pointerup arrives after the native touch end", async () => { + pointer(target, "pointerdown"); + window.acodeNativeTouchEnd(); + pointer(target, "pointerup"); + await settle(); + expect(cancels).not.toHaveBeenCalled(); +}); + +it.each([ + ["a new pointer", { pointerId: 2 }], + ["a reused pointer id", { pointerId: 1 }], +])("does not cancel %s that starts while the stale touch settles", async (_, options) => { + pointer(target, "pointerdown"); + window.acodeNativeTouchEnd(); + pointer(target, "pointerup"); + pointer(target, "pointerdown", options); + await settle(); + expect(cancels).not.toHaveBeenCalled(); +}); + +it("cancels only the stale touch when another starts after the native touch end", async () => { + pointer(target, "pointerdown"); + window.acodeNativeTouchEnd(); + pointer(target, "pointerdown", { pointerId: 2 }); + await settle(); + expect(cancels.mock.calls.map(([event]) => event.pointerId)).toEqual([1]); +}); + +it("ignores mouse pointers", async () => { + pointer(target, "pointerdown", { pointerType: "mouse" }); + window.acodeNativeTouchEnd(); + await settle(); + expect(cancels).not.toHaveBeenCalled(); +}); + +it("dispatches inside Shadow DOM and falls back to the document for removed targets", async () => { + const shadow = target.attachShadow({ mode: "open" }); + shadow.innerHTML = "inside"; + const inside = vi.fn(); + shadow.firstChild.addEventListener("pointercancel", inside); + pointer(shadow.firstChild, "pointerdown"); + window.acodeNativeTouchEnd(); + await settle(); + expect(inside).toHaveBeenCalledOnce(); + + const removed = window.document.createElement("div"); + window.document.body.append(removed); + pointer(removed, "pointerdown", { pointerId: 2 }); + removed.remove(); + cancels.mockClear(); + window.acodeNativeTouchEnd(); + await settle(); + expect(cancels).toHaveBeenCalledOnce(); + expect(cancels.mock.calls[0][0].target).toBe(window.document); +}); + +function settle() { + return new Promise((resolve) => window.setTimeout(resolve, 150)); +} + +function pointer(element, type, options = {}) { + element.dispatchEvent( + new window.PointerEvent(type, { + bubbles: true, + composed: true, + cancelable: true, + pointerType: "touch", + isPrimary: true, + pointerId: 1, + clientX: 20, + clientY: 30, + ...options, + }), + ); +} diff --git a/tests/unit/selectionMenuButton.test.ts b/tests/unit/selectionMenuButton.test.ts index 47e0b26b1b..b6fb6ef5be 100644 --- a/tests/unit/selectionMenuButton.test.ts +++ b/tests/unit/selectionMenuButton.test.ts @@ -3,10 +3,15 @@ import { bindSelectionMenuButton } from "cm/selectionMenuUtils"; import { describe, expect, it, vi } from "vitest"; +function touchEnd() { + return new Event("touchend", { bubbles: true, cancelable: true }); +} + function pointerEvent( type: string, pointerId = 7, position: { x: number; y: number } = { x: 0, y: 0 }, + isPrimary = true, ) { return new PointerEvent(type, { bubbles: true, @@ -14,7 +19,7 @@ function pointerEvent( cancelable: true, clientX: position.x, clientY: position.y, - isPrimary: true, + isPrimary, pointerId, pointerType: "touch", }); @@ -33,11 +38,13 @@ describe("selection menu button interaction", () => { expect(activate).not.toHaveBeenCalled(); button.dispatchEvent(pointerEvent("pointerup")); + expect(button.classList.contains("is-pressed")).toBe(false); + expect(activate).not.toHaveBeenCalled(); + + button.dispatchEvent(touchEnd()); button.dispatchEvent( new MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }), ); - - expect(button.classList.contains("is-pressed")).toBe(false); expect(activate).toHaveBeenCalledTimes(1); }); @@ -56,6 +63,90 @@ describe("selection menu button interaction", () => { expect(activate).toHaveBeenCalledTimes(1); }); + it("activates a secondary pointer when WebKit still tracks a lost touch", () => { + const button = document.createElement("button"); + const activate = vi.fn(); + bindSelectionMenuButton(button, activate); + + const down = pointerEvent("pointerdown", 8, undefined, false); + button.dispatchEvent(down); + expect(down.defaultPrevented).toBe(true); + button.dispatchEvent(pointerEvent("pointerup", 8, undefined, false)); + button.dispatchEvent(touchEnd()); + + expect(activate).toHaveBeenCalledTimes(1); + }); + + it("ignores a second simultaneous pointer during a press", () => { + const button = document.createElement("button"); + const activate = vi.fn(); + bindSelectionMenuButton(button, activate); + + button.dispatchEvent(pointerEvent("pointerdown", 7)); + const second = pointerEvent("pointerdown", 8, undefined, false); + button.dispatchEvent(second); + button.dispatchEvent(pointerEvent("pointerup", 8, undefined, false)); + expect(second.defaultPrevented).toBe(false); + expect(activate).not.toHaveBeenCalled(); + + button.dispatchEvent(pointerEvent("pointerup", 7)); + button.dispatchEvent(touchEnd()); + expect(activate).toHaveBeenCalledTimes(1); + }); + + it("activates from WebKit's emulated mousedown when a touch never reports pointerup", () => { + const button = document.createElement("button"); + const activate = vi.fn(); + bindSelectionMenuButton(button, activate); + + button.dispatchEvent(pointerEvent("pointerdown")); + const mouseDown = new MouseEvent("mousedown", { + bubbles: true, + cancelable: true, + }); + button.dispatchEvent(mouseDown); + button.dispatchEvent(pointerEvent("pointercancel")); + + expect(mouseDown.defaultPrevented).toBe(true); + expect(activate).toHaveBeenCalledTimes(1); + }); + + it("keeps emulated mouse events from following a released touch to the editor", () => { + const button = document.createElement("button"); + const activate = vi.fn(); + bindSelectionMenuButton(button, activate); + + button.dispatchEvent(pointerEvent("pointerdown")); + button.dispatchEvent(pointerEvent("pointerup")); + const release = touchEnd(); + button.dispatchEvent(release); + button.dispatchEvent( + new MouseEvent("mousedown", { bubbles: true, cancelable: true }), + ); + + expect(release.defaultPrevented).toBe(true); + expect(activate).toHaveBeenCalledTimes(1); + }); + + it("activates a released touch even if WebKit never delivers touchend", () => { + vi.useFakeTimers(); + try { + const button = document.createElement("button"); + const activate = vi.fn(); + bindSelectionMenuButton(button, activate); + + button.dispatchEvent(pointerEvent("pointerdown")); + button.dispatchEvent(pointerEvent("pointerup")); + expect(activate).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(100); + button.dispatchEvent(touchEnd()); + expect(activate).toHaveBeenCalledTimes(1); + } finally { + vi.useRealTimers(); + } + }); + it("does not activate an action when the pointer becomes a scroll gesture", () => { const button = document.createElement("button"); const activate = vi.fn(); diff --git a/tests/unit/touchSelectionMenuTapGuard.test.ts b/tests/unit/touchSelectionMenuTapGuard.test.ts new file mode 100644 index 0000000000..ff4fb9588a --- /dev/null +++ b/tests/unit/touchSelectionMenuTapGuard.test.ts @@ -0,0 +1,117 @@ +// @vitest-environment happy-dom + +import { EditorSelection, EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import createTouchSelectionMenu from "cm/touchSelectionMenu"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("lib/selectionMenu", () => ({ default: () => [] })); +vi.mock("cm/lsp/clientLoader", () => ({ getAllLspPlugins: () => [] })); + +const views: EditorView[] = []; + +afterEach(() => { + vi.useRealTimers(); + while (views.length) views.pop()?.destroy(); + document.body.replaceChildren(); +}); + +describe("touch selection menu tap guard", () => { + it("restores a selection that WebKit's native tap changes during a menu press", () => { + const { view, menu } = createMenu(); + pressMenu(menu); + + view.dispatch({ selection: { anchor: 3 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 0, to: 5 }); + }); + + it("keeps guarding after a release that implicitly loses pointer capture", () => { + const { view, menu } = createMenu(); + pressMenu(menu, ["pointerdown", "pointerup", "lostpointercapture"]); + + view.dispatch({ selection: { anchor: 3 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 0, to: 5 }); + }); + + it.each([ + "pointercancel", + "lostpointercapture", + ])("drops the guard when a press ends with %s before release", (type) => { + const { view, menu } = createMenu(); + pressMenu(menu, ["pointerdown", type]); + + view.dispatch({ selection: { anchor: 9 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 9, to: 9 }); + }); + + it("expires a press that never reports its end", () => { + vi.useFakeTimers(); + const { view, menu } = createMenu(); + pressMenu(menu, ["pointerdown"]); + vi.advanceTimersByTime(1600); + + view.dispatch({ selection: { anchor: 9 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 9, to: 9 }); + }); + + it("leaves later selection changes alone once the tap has settled", () => { + vi.useFakeTimers(); + const { view, menu } = createMenu(); + pressMenu(menu); + vi.advanceTimersByTime(400); + + view.dispatch({ selection: { anchor: 3 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 3, to: 3 }); + }); + + it("never restores a selection after the document changed", () => { + const { view, menu } = createMenu(); + pressMenu(menu); + + view.dispatch({ + changes: { from: 0, to: 5 }, + selection: { anchor: 0 }, + }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.doc.toString()).toBe(" beta"); + expect(view.state.selection.main).toMatchObject({ from: 0, to: 0 }); + }); +}); + +function createMenu() { + const state = EditorState.create({ + doc: "alpha beta", + selection: EditorSelection.range(0, 5), + }); + const view = new EditorView({ state, parent: document.body }); + views.push(view); + const menu = createTouchSelectionMenu(view, { container: document.body }); + return { view, menu }; +} + +function pressMenu( + menu: ReturnType, + types = ["pointerdown", "pointerup"], +) { + for (const type of types) { + menu.$menu.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + cancelable: true, + pointerId: 1, + pointerType: "touch", + }), + ); + } +} From 393fc26059e09d36a8a699071edc3d5c60842159 Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Wed, 2 Dec 2026 12:11:57 +0530 Subject: [PATCH 2/7] fix(editor): end the menu tap guard on new editor input The guard that restores the selection after a menu press no longer outlives the press: any tap outside the menu and any key press in the editor clears it, so the following selection change belongs to the editor. A selection-changing menu action keeps its own selection, because the restore is skipped while an action runs. The docs now describe the guard's full lifetime, and tests cover a second press on the menu, an action that changes the selection, and the outside-tap and key-press cases. --- docs/ios-port.md | 2 +- .../runnerTests/PreviewTransferTests.swift | 28 +++++- src/cm/touchSelectionMenu.js | 15 ++- tests/unit/touchSelectionMenuTapGuard.test.ts | 99 ++++++++++++++++--- 4 files changed, 123 insertions(+), 21 deletions(-) diff --git a/docs/ios-port.md b/docs/ios-port.md index a9e03cc7d0..772c7431fc 100644 --- a/docs/ios-port.md +++ b/docs/ios-port.md @@ -547,7 +547,7 @@ move the selection behind a menu press with no page event, so the menu restores the selection it saw when the press began, unless a menu action or a document edit changed it. The restore window starts at `pointerdown`, is capped at 1.5 s, lasts 350 ms after release, and is dropped when the press is cancelled before -release. Presses from a secondary pointer still activate buttons, because WebKit +release, by any tap outside the menu, or by a key press in the editor. Presses from a secondary pointer still activate buttons, because WebKit keeps reporting taps as secondary after some double-taps on a word even with `WebTouchEnd` installed. A second press while one is already held is ignored. diff --git a/platforms/ios/runnerTests/PreviewTransferTests.swift b/platforms/ios/runnerTests/PreviewTransferTests.swift index 6ccb80f319..f4831750be 100644 --- a/platforms/ios/runnerTests/PreviewTransferTests.swift +++ b/platforms/ios/runnerTests/PreviewTransferTests.swift @@ -77,17 +77,35 @@ final class PreviewTransferTests: BridgeTestCase { while responder != nil, !(responder is WebViewController) { responder = responder?.next } let host = try XCTUnwrap(responder as? WebViewController) XCTAssertNil(host.presentedViewController) - let browser = PreviewViewController(url: try XCTUnwrap(URL(string: origin)), theme: [:], console: false, dataStore: dataStore) + let url = try XCTUnwrap(URL(string: origin)) + let browser = PreviewViewController(url: url, theme: [:], console: false, dataStore: dataStore) browser.consoleEnabled = false - let loaded = expectation(description: "Initial preview navigation finished") + var loaded = XCTestExpectation(description: "Initial preview navigation finished") + loaded.assertForOverFulfill = false browser.onPageFinished = { loaded.fulfill() } await withCheckedContinuation { continuation in host.present(browser, animated: false) { continuation.resume() } } addTeardownBlock { @MainActor in if browser.presentingViewController != nil { await self.close(browser) } } - await fulfillment(of: [loaded], timeout: 5) - browser.onPageFinished = nil - return browser + defer { browser.onPageFinished = nil } + if await XCTWaiter().fulfillment(of: [loaded], timeout: 5) == .completed { return browser } + // Hosted simulators occasionally stall a new web process's first load, which these + // tests are not about, so load once more before treating it as a failure. + let firstFailure = dismissNavigationError(browser) + loaded = XCTestExpectation(description: "Retried preview navigation finished") + loaded.assertForOverFulfill = false + browser.load(url) + if await XCTWaiter().fulfillment(of: [loaded], timeout: 10) == .completed { return browser } + let failure = dismissNavigationError(browser) ?? firstFailure ?? "no navigation error reported" + XCTFail("Preview never finished loading \(origin): \(failure)") + throw NSError(domain: "PreviewTransferTests", code: 1) + } + + private func dismissNavigationError(_ browser: PreviewViewController) -> String? { + let message = browser.activeDialog?.message + browser.pendingDialog?() + browser.activeDialog?.dismiss(animated: false) + return message } private func finishNavigation(_ browser: PreviewViewController, _ navigate: () throws -> Void) async throws { diff --git a/src/cm/touchSelectionMenu.js b/src/cm/touchSelectionMenu.js index f004d183c8..56d8e6efe0 100644 --- a/src/cm/touchSelectionMenu.js +++ b/src/cm/touchSelectionMenu.js @@ -245,6 +245,7 @@ class TouchSelectionMenuController { ); } else { root.addEventListener("contextmenu", this.#onContextMenu, true); + root.addEventListener("keydown", this.#endMenuTap, true); document.addEventListener("pointerdown", this.#onGlobalPointerDown, true); document.addEventListener("pointermove", this.#onGlobalPointerMove, true); document.addEventListener("pointerup", this.#onGlobalPointerUp, true); @@ -289,6 +290,7 @@ class TouchSelectionMenuController { true, ); root.removeEventListener("contextmenu", this.#onContextMenu, true); + root.removeEventListener("keydown", this.#endMenuTap, true); document.removeEventListener( "pointerdown", this.#onGlobalPointerDown, @@ -391,7 +393,13 @@ class TouchSelectionMenuController { // A canvas view drops its menu itself on keyboard input and outside // selection changes. if (!this.#enabled || this.#canvas) return; - if (meta.selectionChanged && this.#restoreMenuTapSelection()) return; + if ( + meta.selectionChanged && + !this.#handlingMenuAction && + this.#restoreMenuTapSelection() + ) { + return; + } if (meta.selectionChanged) this.#cancelReadOnlyTap(); if ( meta.selectionChanged && @@ -490,6 +498,7 @@ class TouchSelectionMenuController { this.#readOnlyTapSession = null; return; } + this.#menuTapState = null; if (this.#isIgnoredPointerTarget(target)) { this.#pointerSelectionSession = null; this.#readOnlyTapSession = null; @@ -1310,6 +1319,10 @@ class TouchSelectionMenuController { this.#menuTapGuardUntil = performance.now() + MENU_TAP_SETTLE; }; + #endMenuTap = () => { + this.#menuTapState = null; + }; + // A press cancelled before release (a scroll, or WebKit claiming the touch) // ran no action, so the editor owns any selection change that follows. #cancelMenuTap = () => { diff --git a/tests/unit/touchSelectionMenuTapGuard.test.ts b/tests/unit/touchSelectionMenuTapGuard.test.ts index ff4fb9588a..6c561d45fd 100644 --- a/tests/unit/touchSelectionMenuTapGuard.test.ts +++ b/tests/unit/touchSelectionMenuTapGuard.test.ts @@ -1,16 +1,23 @@ // @vitest-environment happy-dom -import { EditorSelection, EditorState } from "@codemirror/state"; +import { + EditorSelection, + EditorState, + type Extension, +} from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import createTouchSelectionMenu from "cm/touchSelectionMenu"; import { afterEach, describe, expect, it, vi } from "vitest"; -vi.mock("lib/selectionMenu", () => ({ default: () => [] })); +const menuItems = vi.hoisted(() => ({ list: [] as unknown[] })); + +vi.mock("lib/selectionMenu", () => ({ default: () => menuItems.list })); vi.mock("cm/lsp/clientLoader", () => ({ getAllLspPlugins: () => [] })); const views: EditorView[] = []; afterEach(() => { + menuItems.list = []; vi.useRealTimers(); while (views.length) views.pop()?.destroy(); document.body.replaceChildren(); @@ -19,7 +26,7 @@ afterEach(() => { describe("touch selection menu tap guard", () => { it("restores a selection that WebKit's native tap changes during a menu press", () => { const { view, menu } = createMenu(); - pressMenu(menu); + pressMenu(menu.$menu); view.dispatch({ selection: { anchor: 3 } }); menu.onStateChanged({ selectionChanged: true }); @@ -29,7 +36,7 @@ describe("touch selection menu tap guard", () => { it("keeps guarding after a release that implicitly loses pointer capture", () => { const { view, menu } = createMenu(); - pressMenu(menu, ["pointerdown", "pointerup", "lostpointercapture"]); + pressMenu(menu.$menu, ["pointerdown", "pointerup", "lostpointercapture"]); view.dispatch({ selection: { anchor: 3 } }); menu.onStateChanged({ selectionChanged: true }); @@ -42,7 +49,7 @@ describe("touch selection menu tap guard", () => { "lostpointercapture", ])("drops the guard when a press ends with %s before release", (type) => { const { view, menu } = createMenu(); - pressMenu(menu, ["pointerdown", type]); + pressMenu(menu.$menu, ["pointerdown", type]); view.dispatch({ selection: { anchor: 9 } }); menu.onStateChanged({ selectionChanged: true }); @@ -53,7 +60,7 @@ describe("touch selection menu tap guard", () => { it("expires a press that never reports its end", () => { vi.useFakeTimers(); const { view, menu } = createMenu(); - pressMenu(menu, ["pointerdown"]); + pressMenu(menu.$menu, ["pointerdown"]); vi.advanceTimersByTime(1600); view.dispatch({ selection: { anchor: 9 } }); @@ -62,10 +69,76 @@ describe("touch selection menu tap guard", () => { expect(view.state.selection.main).toMatchObject({ from: 9, to: 9 }); }); + it("keeps the selection a menu action makes while it runs", () => { + vi.useFakeTimers(); + const { view, menu } = createMenu([EditorState.readOnly.of(true)]); + menuItems.list = [ + { + id: "select-all", + mode: "all", + readOnly: true, + label: "Select all", + text: "Select all", + onclick: () => { + view.dispatch({ + selection: { anchor: 0, head: view.state.doc.length }, + }); + menu.setSelection(true); + }, + }, + ]; + vi.spyOn(view, "coordsAtPos").mockReturnValue({ + left: 0, + right: 10, + top: 0, + bottom: 10, + }); + menu.setMenu(true); + vi.advanceTimersByTime(500); + const button = menu.$menu.querySelector("button"); + expect(button).not.toBeNull(); + + pressMenu(button as HTMLElement, ["pointerdown", "pointerup", "touchend"]); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 0, to: 10 }); + }); + + it.each([ + ["pointerdown", () => new PointerEvent("pointerdown", { bubbles: true })], + [ + "keydown", + () => new KeyboardEvent("keydown", { bubbles: true, key: "ArrowLeft" }), + ], + ])("ends the guard when the editor gets a new %s", (_, createEvent) => { + const { view, menu } = createMenu(); + pressMenu(menu.$menu); + + view.contentDOM.dispatchEvent(createEvent()); + view.dispatch({ selection: { anchor: 9 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 9, to: 9 }); + }); + + it("keeps guarding through a second press on the menu", () => { + const { view, menu } = createMenu(); + document.body.append(menu.$menu); + pressMenu(menu.$menu); + menu.$menu.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, pointerType: "touch" }), + ); + + view.dispatch({ selection: { anchor: 3 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 0, to: 5 }); + }); + it("leaves later selection changes alone once the tap has settled", () => { vi.useFakeTimers(); const { view, menu } = createMenu(); - pressMenu(menu); + pressMenu(menu.$menu); vi.advanceTimersByTime(400); view.dispatch({ selection: { anchor: 3 } }); @@ -76,7 +149,7 @@ describe("touch selection menu tap guard", () => { it("never restores a selection after the document changed", () => { const { view, menu } = createMenu(); - pressMenu(menu); + pressMenu(menu.$menu); view.dispatch({ changes: { from: 0, to: 5 }, @@ -89,10 +162,11 @@ describe("touch selection menu tap guard", () => { }); }); -function createMenu() { +function createMenu(extensions: Extension[] = []) { const state = EditorState.create({ doc: "alpha beta", selection: EditorSelection.range(0, 5), + extensions, }); const view = new EditorView({ state, parent: document.body }); views.push(view); @@ -100,12 +174,9 @@ function createMenu() { return { view, menu }; } -function pressMenu( - menu: ReturnType, - types = ["pointerdown", "pointerup"], -) { +function pressMenu(target: HTMLElement, types = ["pointerdown", "pointerup"]) { for (const type of types) { - menu.$menu.dispatchEvent( + target.dispatchEvent( new PointerEvent(type, { bubbles: true, cancelable: true, From b311ce22425c63eee734765328a00d5628b8e548 Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Wed, 2 Dec 2026 16:44:13 +0530 Subject: [PATCH 3/7] chore: bump version --- package.json | 4 ++-- platforms/ios/runner.xcodeproj/project.pbxproj | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 29c2381fda..09fc528e44 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "acode-app", "displayName": "Acode", - "version": "1.13.7", - "versionCode": 1024, + "version": "1.13.8", + "versionCode": 1025, "androidPackageId": "com.foxdebug.acode", "appleAppId": "app.acode", "description": "Powerful code editor and terminal for IOS and Android", diff --git a/platforms/ios/runner.xcodeproj/project.pbxproj b/platforms/ios/runner.xcodeproj/project.pbxproj index 4837508b35..c2078e814a 100644 --- a/platforms/ios/runner.xcodeproj/project.pbxproj +++ b/platforms/ios/runner.xcodeproj/project.pbxproj @@ -375,7 +375,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1024; + CURRENT_PROJECT_VERSION = 1025; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; @@ -396,7 +396,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 18.6; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; - MARKETING_VERSION = 1.13.7; + MARKETING_VERSION = 1.13.8; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -443,7 +443,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1024; + CURRENT_PROJECT_VERSION = 1025; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; @@ -458,7 +458,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 18.6; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; - MARKETING_VERSION = 1.13.7; + MARKETING_VERSION = 1.13.8; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = iphoneos; From 5d2defc73c85898f836b5ebb1263046ecc2b8b45 Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Wed, 2 Dec 2026 16:47:49 +0530 Subject: [PATCH 4/7] chore: bump version --- package.json | 2 +- platforms/ios/runner.xcodeproj/project.pbxproj | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 09fc528e44..b972dd69b2 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "acode-app", "displayName": "Acode", "version": "1.13.8", - "versionCode": 1025, + "versionCode": 1026, "androidPackageId": "com.foxdebug.acode", "appleAppId": "app.acode", "description": "Powerful code editor and terminal for IOS and Android", diff --git a/platforms/ios/runner.xcodeproj/project.pbxproj b/platforms/ios/runner.xcodeproj/project.pbxproj index c2078e814a..88a7f2ffc5 100644 --- a/platforms/ios/runner.xcodeproj/project.pbxproj +++ b/platforms/ios/runner.xcodeproj/project.pbxproj @@ -375,7 +375,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1025; + CURRENT_PROJECT_VERSION = 1026; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; @@ -443,7 +443,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1025; + CURRENT_PROJECT_VERSION = 1026; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; From b2fefd6c1c52b23517d3228abb9c6d7180b7df14 Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Thu, 3 Dec 2026 02:20:25 +0530 Subject: [PATCH 5/7] fix(ios): harden touch selection handling and text decoding Cancel stale touch pointers after native gestures, activate menu buttons on touch end with WebKit fallbacks, and restore selections cleared by iOS native text taps. Gate the tap guard to iOS and keep touched buttons activatable after WebKit cancels the pointer. Decode malformed text like Android instead of failing and cover the behaviour with tests. Bump the build number to 1027. --- docs/ios-port.md | 4 +- package.json | 2 +- .../ios/runner.xcodeproj/project.pbxproj | 4 +- platforms/ios/runner/lib/FileContents.swift | 18 ++++++++ platforms/ios/runner/lib/SystemService.swift | 4 +- .../ios/runnerTests/FileContentsTests.swift | 8 ++++ src/cm/selectionMenuUtils.ts | 14 ++++-- src/cm/touchSelectionMenu.js | 20 ++++++--- tests/unit/selectionMenuButton.test.ts | 43 +++++++++++++++++++ tests/unit/touchSelectionMenuTapGuard.test.ts | 26 +++++++++++ 10 files changed, 126 insertions(+), 17 deletions(-) diff --git a/docs/ios-port.md b/docs/ios-port.md index 772c7431fc..111d69dc15 100644 --- a/docs/ios-port.md +++ b/docs/ios-port.md @@ -542,7 +542,9 @@ normally arrives in the same millisecond as `pointerup`, so there is no visible the menu on `pointerup` dropped the `touchend` and let WebKit place the caret under the finger. If no `touchend` arrives, the action runs 100 ms after `pointerup`. When WebKit claims a tap and sends only an emulated `mousedown`, -that `mousedown` activates the button. WebKit's native text tap can also clear or +that `mousedown` activates the button, even when it arrives after the press was +cancelled, as `WebTouchEnd` does 100 ms after the touch ends. A new press first +runs a released press that is still waiting for its `touchend`. WebKit's native text tap can also clear or move the selection behind a menu press with no page event, so the menu restores the selection it saw when the press began, unless a menu action or a document edit changed it. The restore window starts at `pointerdown`, is capped at 1.5 s, diff --git a/package.json b/package.json index b972dd69b2..7fb9bf5109 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "acode-app", "displayName": "Acode", "version": "1.13.8", - "versionCode": 1026, + "versionCode": 1027, "androidPackageId": "com.foxdebug.acode", "appleAppId": "app.acode", "description": "Powerful code editor and terminal for IOS and Android", diff --git a/platforms/ios/runner.xcodeproj/project.pbxproj b/platforms/ios/runner.xcodeproj/project.pbxproj index 88a7f2ffc5..c94fc2a62d 100644 --- a/platforms/ios/runner.xcodeproj/project.pbxproj +++ b/platforms/ios/runner.xcodeproj/project.pbxproj @@ -375,7 +375,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1026; + CURRENT_PROJECT_VERSION = 1027; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; @@ -443,7 +443,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 1026; + CURRENT_PROJECT_VERSION = 1027; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; diff --git a/platforms/ios/runner/lib/FileContents.swift b/platforms/ios/runner/lib/FileContents.swift index 56a1d1f063..b5e444fc0f 100644 --- a/platforms/ios/runner/lib/FileContents.swift +++ b/platforms/ios/runner/lib/FileContents.swift @@ -8,6 +8,24 @@ struct FileContents { return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(value)) } + /// Like Android's `new String(bytes, charset)`, malformed bytes become U+FFFD instead of failing the decode. + static func decode(_ data: Data, as name: String) throws -> String { + let target = try encoding(name) + if let text = String(data: data, encoding: target) { return text } + if target == .utf8 { + let bom: [UInt8] = [0xEF, 0xBB, 0xBF] + return String(decoding: data.starts(with: bom) ? data.dropFirst(bom.count) : data, as: UTF8.self) + } + var converted: NSString? + _ = NSString.stringEncoding(for: data, encodingOptions: [ + .suggestedEncodingsKey: [target.rawValue], + .useOnlySuggestedEncodingsKey: true, + .allowLossyKey: true, + ], convertedString: &converted, usedLossyConversion: nil) + guard let converted else { throw FileFailure(5) } + return converted as String + } + static func availableEncodings() -> [String: Any] { var result: [String: Any] = [:] for value in String.availableStringEncodings { diff --git a/platforms/ios/runner/lib/SystemService.swift b/platforms/ios/runner/lib/SystemService.swift index aadf9a72dd..1a23ae3006 100644 --- a/platforms/ios/runner/lib/SystemService.swift +++ b/platforms/ios/runner/lib/SystemService.swift @@ -30,8 +30,8 @@ final class SystemService: BaseService { guard let text = args[safe: 0] as? String, let data = text.data(using: try FileContents.encoding(args[safe: 1] as? String ?? "UTF-8")) else { throw FileFailure(5) } callback.successBinary(data) case "decode": - guard let encoded = args[safe: 0] as? String, let data = Data(base64Encoded: encoded), let text = String(data: data, encoding: try FileContents.encoding(args[safe: 1] as? String ?? "UTF-8")) else { throw FileFailure(5) } - callback.success(text) + guard let encoded = args[safe: 0] as? String, let data = Data(base64Encoded: encoded) else { throw FileFailure(5) } + callback.success(try FileContents.decode(data, as: args[safe: 1] as? String ?? "UTF-8")) case "getInstaller": callback.success("appstore") case "getRewardStatus": callback.success(try rewards.getRewardStatus()) case "get-android-version": callback.success(0) diff --git a/platforms/ios/runnerTests/FileContentsTests.swift b/platforms/ios/runnerTests/FileContentsTests.swift index 3bbcacaa83..d54f0f4ed9 100644 --- a/platforms/ios/runnerTests/FileContentsTests.swift +++ b/platforms/ios/runnerTests/FileContentsTests.swift @@ -4,6 +4,14 @@ import WebKit @MainActor final class FileContentsTests: BridgeTestCase { + func testDecodeReplacesMalformedBytesLikeAndroid() throws { + let binary = Data([0x89, 0x50, 0x4E, 0x47, 0x00, 0xFF, 0xFE, 0x41]) + XCTAssertEqual(try FileContents.decode(binary, as: "UTF-8"), "\u{FFFD}PNG\u{0}\u{FFFD}\u{FFFD}A") + XCTAssertEqual(try FileContents.decode(Data([0xEF, 0xBB, 0xBF, 0x41, 0xFF]), as: "UTF-8"), "A\u{FFFD}") + XCTAssertEqual(try FileContents.decode(Data("Acode ✓".utf8), as: "UTF-8"), "Acode ✓") + XCTAssertEqual(try FileContents.decode(Data([0x41, 0x00, 0x00, 0xD8]), as: "UTF-16LE"), "A\u{FFFD}") + } + func testNativeReadRangesAndBinaryRepresentationsMatchBytes() async throws { let app = try await editorWebView() let file = AppFiles.shared.cache.appendingPathComponent("ios-read-ranges-" + UUID().uuidString + ".bin") diff --git a/src/cm/selectionMenuUtils.ts b/src/cm/selectionMenuUtils.ts index 199e56105f..66bf822bc1 100644 --- a/src/cm/selectionMenuUtils.ts +++ b/src/cm/selectionMenuUtils.ts @@ -27,12 +27,15 @@ export function bindSelectionMenuButton( event.preventDefault(); event.stopPropagation(); }; - const clearPointer = () => { + const releasePointer = () => { activePointerId = null; pointerStart = null; - isTouchPress = false; button.classList.remove("is-pressed"); }; + const clearPointer = () => { + releasePointer(); + isTouchPress = false; + }; // Removing the menu on pointerup would drop the touch's touchend, letting // iOS WebKit place the caret wherever the tap landed in the editor below. const activateTouchRelease = () => { @@ -53,6 +56,7 @@ export function bindSelectionMenuButton( // later tap a secondary pointer, so only a second simultaneous press is ignored. if (event.isPrimary === false && activePointerId !== null) return; if (event.pointerType === "mouse" && event.button !== 0) return; + activateTouchRelease(); activePointerId = event.pointerId; pointerStart = { x: event.clientX, y: event.clientY }; isTouchPress = event.pointerType === "touch"; @@ -85,8 +89,10 @@ export function bindSelectionMenuButton( touchReleaseTimer = setTimeout(activateTouchRelease, TOUCH_END_WAIT); }); - button.addEventListener("pointercancel", clearPointer); - button.addEventListener("lostpointercapture", clearPointer); + // A cancelled touch can still be a tap WebKit claimed, which only its + // emulated mousedown reports, so the press stays a touch press until then. + button.addEventListener("pointercancel", releasePointer); + button.addEventListener("lostpointercapture", releasePointer); // iOS WebKit follows a tap with emulated mouse events after the menu has // closed, which would land on the editor underneath and move the caret. button.addEventListener( diff --git a/src/cm/touchSelectionMenu.js b/src/cm/touchSelectionMenu.js index 56d8e6efe0..307e5a473a 100644 --- a/src/cm/touchSelectionMenu.js +++ b/src/cm/touchSelectionMenu.js @@ -11,6 +11,7 @@ import { filterSelectionMenuItems, partitionSelectionMenuItems, } from "cm/selectionMenuUtils"; +import platform from "lib/platform"; import selectionMenu from "lib/selectionMenu"; import { animate } from "motion"; @@ -250,13 +251,7 @@ class TouchSelectionMenuController { document.addEventListener("pointermove", this.#onGlobalPointerMove, true); document.addEventListener("pointerup", this.#onGlobalPointerUp, true); document.addEventListener("pointercancel", this.#onGlobalPointerUp, true); - this.$menu.addEventListener("pointerdown", this.#guardMenuTap, true); - for (const type of MENU_TAP_END_EVENTS) { - this.$menu.addEventListener(type, this.#settleMenuTap, true); - } - for (const type of MENU_TAP_CANCEL_EVENTS) { - this.$menu.addEventListener(type, this.#cancelMenuTap, true); - } + if (platform.isIOS) this.#listenMenuTapGuard("addEventListener"); } this.#tooltipObserver = new MutationObserver((mutations) => { @@ -314,6 +309,7 @@ class TouchSelectionMenuController { this.#readOnlyTapSession = null; this.#pendingPointerSelectionClick = null; this.#menuTapState = null; + this.#listenMenuTapGuard("removeEventListener"); this.#tooltipObserver?.disconnect(); this.#hideMenu(true); } @@ -1329,6 +1325,16 @@ class TouchSelectionMenuController { if (!this.#menuTapSettled) this.#menuTapState = null; }; + #listenMenuTapGuard(method) { + this.$menu[method]("pointerdown", this.#guardMenuTap, true); + for (const type of MENU_TAP_END_EVENTS) { + this.$menu[method](type, this.#settleMenuTap, true); + } + for (const type of MENU_TAP_CANCEL_EVENTS) { + this.$menu[method](type, this.#cancelMenuTap, true); + } + } + #restoreMenuTapSelection() { const tapState = this.#menuTapState; if (!tapState) return false; diff --git a/tests/unit/selectionMenuButton.test.ts b/tests/unit/selectionMenuButton.test.ts index b6fb6ef5be..bf1ae57eb0 100644 --- a/tests/unit/selectionMenuButton.test.ts +++ b/tests/unit/selectionMenuButton.test.ts @@ -111,6 +111,49 @@ describe("selection menu button interaction", () => { expect(activate).toHaveBeenCalledTimes(1); }); + it("activates from an emulated mousedown that WebKit delays past a pointercancel", () => { + const button = document.createElement("button"); + const activate = vi.fn(); + bindSelectionMenuButton(button, activate); + + button.dispatchEvent(pointerEvent("pointerdown")); + button.dispatchEvent(pointerEvent("pointercancel")); + button.dispatchEvent(pointerEvent("lostpointercapture")); + expect(button.classList.contains("is-pressed")).toBe(false); + button.dispatchEvent( + new MouseEvent("mousedown", { bubbles: true, cancelable: true }), + ); + + expect(activate).toHaveBeenCalledTimes(1); + }); + + it("activates each of two quick taps when neither reports touchend", () => { + vi.useFakeTimers(); + try { + const button = document.createElement("button"); + const activate = vi.fn(); + bindSelectionMenuButton(button, activate); + const firstRelease = pointerEvent("pointerup", 7); + const secondRelease = pointerEvent("pointerup", 8); + + button.dispatchEvent(pointerEvent("pointerdown", 7)); + button.dispatchEvent(firstRelease); + vi.advanceTimersByTime(50); + button.dispatchEvent(pointerEvent("pointerdown", 8)); + expect(activate).toHaveBeenCalledTimes(1); + expect(activate).toHaveBeenLastCalledWith(firstRelease); + + button.dispatchEvent(secondRelease); + vi.advanceTimersByTime(50); + expect(activate).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(50); + expect(activate).toHaveBeenCalledTimes(2); + expect(activate).toHaveBeenLastCalledWith(secondRelease); + } finally { + vi.useRealTimers(); + } + }); + it("keeps emulated mouse events from following a released touch to the editor", () => { const button = document.createElement("button"); const activate = vi.fn(); diff --git a/tests/unit/touchSelectionMenuTapGuard.test.ts b/tests/unit/touchSelectionMenuTapGuard.test.ts index 6c561d45fd..b0e1d82372 100644 --- a/tests/unit/touchSelectionMenuTapGuard.test.ts +++ b/tests/unit/touchSelectionMenuTapGuard.test.ts @@ -10,14 +10,17 @@ import createTouchSelectionMenu from "cm/touchSelectionMenu"; import { afterEach, describe, expect, it, vi } from "vitest"; const menuItems = vi.hoisted(() => ({ list: [] as unknown[] })); +const platform = vi.hoisted(() => ({ isIOS: true })); vi.mock("lib/selectionMenu", () => ({ default: () => menuItems.list })); vi.mock("cm/lsp/clientLoader", () => ({ getAllLspPlugins: () => [] })); +vi.mock("lib/platform", () => ({ default: platform })); const views: EditorView[] = []; afterEach(() => { menuItems.list = []; + platform.isIOS = true; vi.useRealTimers(); while (views.length) views.pop()?.destroy(); document.body.replaceChildren(); @@ -34,6 +37,29 @@ describe("touch selection menu tap guard", () => { expect(view.state.selection.main).toMatchObject({ from: 0, to: 5 }); }); + it("leaves selection changes alone outside iOS, where no native tap runs", () => { + platform.isIOS = false; + const { view, menu } = createMenu(); + pressMenu(menu.$menu); + + view.dispatch({ selection: { anchor: 3 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 3, to: 3 }); + }); + + it("stops guarding menu presses once destroyed", () => { + const { view, menu } = createMenu(); + const $menu = menu.$menu; + menu.destroy(); + pressMenu($menu); + + view.dispatch({ selection: { anchor: 3 } }); + menu.onStateChanged({ selectionChanged: true }); + + expect(view.state.selection.main).toMatchObject({ from: 3, to: 3 }); + }); + it("keeps guarding after a release that implicitly loses pointer capture", () => { const { view, menu } = createMenu(); pressMenu(menu.$menu, ["pointerdown", "pointerup", "lostpointercapture"]); From a2b13a23e0243ad3787b671a41a2f9b8927f8a5d Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Thu, 3 Dec 2026 02:30:14 +0530 Subject: [PATCH 6/7] fix: Late taps lose selection protection --- docs/ios-port.md | 6 ++-- src/cm/touchSelectionMenu.js | 20 ++++++++++-- tests/unit/touchSelectionMenuTapGuard.test.ts | 32 +++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/docs/ios-port.md b/docs/ios-port.md index 111d69dc15..9ed83632ec 100644 --- a/docs/ios-port.md +++ b/docs/ios-port.md @@ -548,8 +548,10 @@ runs a released press that is still waiting for its `touchend`. WebKit's native move the selection behind a menu press with no page event, so the menu restores the selection it saw when the press began, unless a menu action or a document edit changed it. The restore window starts at `pointerdown`, is capped at 1.5 s, -lasts 350 ms after release, and is dropped when the press is cancelled before -release, by any tap outside the menu, or by a key press in the editor. Presses from a secondary pointer still activate buttons, because WebKit +lasts 350 ms after release, and is dropped by any tap outside the menu or a key +press in the editor. A press cancelled before release pauses it; a late emulated +`mousedown` within the 1.5 s cap resumes it and restores the selection, and +otherwise it ends unused. Presses from a secondary pointer still activate buttons, because WebKit keeps reporting taps as secondary after some double-taps on a word even with `WebTouchEnd` installed. A second press while one is already held is ignored. diff --git a/src/cm/touchSelectionMenu.js b/src/cm/touchSelectionMenu.js index 307e5a473a..a49b315fec 100644 --- a/src/cm/touchSelectionMenu.js +++ b/src/cm/touchSelectionMenu.js @@ -220,6 +220,7 @@ class TouchSelectionMenuController { #menuTapState = null; #menuTapGuardUntil = 0; #menuTapSettled = false; + #menuTapCancelled = false; constructor(view, options = {}) { this.#view = view; @@ -1306,13 +1307,24 @@ class TouchSelectionMenuController { #guardMenuTap = () => { this.#menuTapState = this.#view.state; this.#menuTapSettled = false; + this.#menuTapCancelled = false; this.#menuTapGuardUntil = performance.now() + MENU_TAP_PRESS_LIMIT; }; - #settleMenuTap = () => { + #settleMenuTap = (event) => { if (!this.#menuTapState) return; + const wasCancelled = this.#menuTapCancelled; + // Only the emulated mousedown of a tap WebKit claimed runs a cancelled + // press's action, so only it brings the guard back. + if (wasCancelled && event.type !== "mousedown") return; + if (wasCancelled && performance.now() > this.#menuTapGuardUntil) { + this.#menuTapState = null; + return; + } this.#menuTapSettled = true; + this.#menuTapCancelled = false; this.#menuTapGuardUntil = performance.now() + MENU_TAP_SETTLE; + if (wasCancelled) this.#restoreMenuTapSelection(); }; #endMenuTap = () => { @@ -1320,9 +1332,10 @@ class TouchSelectionMenuController { }; // A press cancelled before release (a scroll, or WebKit claiming the touch) - // ran no action, so the editor owns any selection change that follows. + // has run no action, so the editor owns selection changes until a late + // emulated mousedown shows WebKit claimed a tap after all. #cancelMenuTap = () => { - if (!this.#menuTapSettled) this.#menuTapState = null; + if (!this.#menuTapSettled) this.#menuTapCancelled = true; }; #listenMenuTapGuard(method) { @@ -1346,6 +1359,7 @@ class TouchSelectionMenuController { this.#menuTapState = null; return false; } + if (this.#menuTapCancelled) return false; if (state.selection.eq(tapState.selection)) return false; this.#view.dispatch({ selection: tapState.selection }); return true; diff --git a/tests/unit/touchSelectionMenuTapGuard.test.ts b/tests/unit/touchSelectionMenuTapGuard.test.ts index b0e1d82372..441c539318 100644 --- a/tests/unit/touchSelectionMenuTapGuard.test.ts +++ b/tests/unit/touchSelectionMenuTapGuard.test.ts @@ -83,6 +83,38 @@ describe("touch selection menu tap guard", () => { expect(view.state.selection.main).toMatchObject({ from: 9, to: 9 }); }); + it("restores the selection behind a tap WebKit reports only with a late mousedown", () => { + const { view, menu } = createMenu(); + pressMenu(menu.$menu, ["pointerdown", "pointercancel"]); + + view.dispatch({ selection: { anchor: 9 } }); + menu.onStateChanged({ selectionChanged: true }); + expect(view.state.selection.main).toMatchObject({ from: 9, to: 9 }); + + menu.$menu.dispatchEvent( + new MouseEvent("mousedown", { bubbles: true, cancelable: true }), + ); + expect(view.state.selection.main).toMatchObject({ from: 0, to: 5 }); + + view.dispatch({ selection: { anchor: 3 } }); + menu.onStateChanged({ selectionChanged: true }); + expect(view.state.selection.main).toMatchObject({ from: 0, to: 5 }); + }); + + it("leaves a cancelled press alone when a late mousedown comes after the guard expires", () => { + vi.useFakeTimers(); + const { view, menu } = createMenu(); + pressMenu(menu.$menu, ["pointerdown", "pointercancel"]); + view.dispatch({ selection: { anchor: 9 } }); + vi.advanceTimersByTime(1600); + + menu.$menu.dispatchEvent( + new MouseEvent("mousedown", { bubbles: true, cancelable: true }), + ); + + expect(view.state.selection.main).toMatchObject({ from: 9, to: 9 }); + }); + it("expires a press that never reports its end", () => { vi.useFakeTimers(); const { view, menu } = createMenu(); From 6d250c752067687a898d9ad1312e2a03cd6c3f13 Mon Sep 17 00:00:00 2001 From: Ajit Kumar Date: Thu, 3 Dec 2026 21:09:35 +0530 Subject: [PATCH 7/7] test(ios): wait for a slow cold app load in BridgeTestCase The first suite timed out after ~10s while a cold hosted simulator took about a minute to finish the initial page load. Wait up to 90s instead. Co-Authored-By: Claude Opus 5.5 --- platforms/ios/runnerTests/BridgeTestCase.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/platforms/ios/runnerTests/BridgeTestCase.swift b/platforms/ios/runnerTests/BridgeTestCase.swift index 55214909e5..35f6d926ac 100644 --- a/platforms/ios/runnerTests/BridgeTestCase.swift +++ b/platforms/ios/runnerTests/BridgeTestCase.swift @@ -14,7 +14,9 @@ class BridgeTestCase: XCTestCase { } func appWebView() async throws -> WKWebView { - for _ in 0..<100 { + // Cold hosted simulators can take close to a minute to finish the first page load. + let deadline = ContinuousClock.now + .seconds(90) + while ContinuousClock.now < deadline { for scene in UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }) { for window in scene.windows { if let webView = findWebView(window), webView.url?.scheme == "acode", !webView.isLoading,