diff --git a/docs/ios-port.md b/docs/ios-port.md index 5f4982939..9ed83632e 100644 --- a/docs/ios-port.md +++ b/docs/ios-port.md @@ -523,6 +523,38 @@ 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, 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, +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. + 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/package.json b/package.json index 29c2381fd..7fb9bf510 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": 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 4837508b3..c94fc2a62 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 = 1027; 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 = 1027; 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; diff --git a/platforms/ios/runner/WebTouchEnd.swift b/platforms/ios/runner/WebTouchEnd.swift new file mode 100644 index 000000000..eeab4d48a --- /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 b22fa5a09..65268cfc7 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/FileContents.swift b/platforms/ios/runner/lib/FileContents.swift index 56a1d1f06..b5e444fc0 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 aadf9a72d..1a23ae300 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/runner/lib/preview/PreviewViewController.swift b/platforms/ios/runner/lib/preview/PreviewViewController.swift index b3c252eff..f684cc536 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/BridgeTestCase.swift b/platforms/ios/runnerTests/BridgeTestCase.swift index 55214909e..35f6d926a 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, diff --git a/platforms/ios/runnerTests/FileContentsTests.swift b/platforms/ios/runnerTests/FileContentsTests.swift index 3bbcacaa8..d54f0f4ed 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/platforms/ios/runnerTests/PreviewTransferTests.swift b/platforms/ios/runnerTests/PreviewTransferTests.swift index 6ccb80f31..f4831750b 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/platforms/ios/runnerTests/WebTouchEndTests.swift b/platforms/ios/runnerTests/WebTouchEndTests.swift new file mode 100644 index 000000000..128d2ae08 --- /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 3ec24baf5..45137a954 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 1cbc55d70..66bf822bc 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,16 +19,31 @@ 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(); event.stopPropagation(); }; - const clearPointer = () => { + const releasePointer = () => { activePointerId = null; pointerStart = null; 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 = () => { + 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 +52,14 @@ 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; + activateTouchRelease(); activePointerId = event.pointerId; pointerStart = { x: event.clientX, y: event.clientY }; + isTouchPress = event.pointerType === "touch"; button.classList.add("is-pressed"); stopEvent(event); try { @@ -57,13 +77,40 @@ 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); + // 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( + "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 3b430abc8..2b911a1a0 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"; @@ -21,12 +22,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 +217,10 @@ class TouchSelectionMenuController { #viewAnimations = []; #overflowExpanded = false; #canvas = false; + #menuTapState = null; + #menuTapGuardUntil = 0; + #menuTapSettled = false; + #menuTapCancelled = false; constructor(view, options = {}) { this.#view = view; @@ -238,10 +247,12 @@ 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); document.addEventListener("pointercancel", this.#onGlobalPointerUp, true); + if (platform.isIOS) this.#listenMenuTapGuard("addEventListener"); } this.#tooltipObserver = new MutationObserver((mutations) => { @@ -275,6 +286,7 @@ class TouchSelectionMenuController { true, ); root.removeEventListener("contextmenu", this.#onContextMenu, true); + root.removeEventListener("keydown", this.#endMenuTap, true); document.removeEventListener( "pointerdown", this.#onGlobalPointerDown, @@ -297,6 +309,8 @@ class TouchSelectionMenuController { this.#pointerSelectionSession = null; this.#readOnlyTapSession = null; this.#pendingPointerSelectionClick = null; + this.#menuTapState = null; + this.#listenMenuTapGuard("removeEventListener"); this.#tooltipObserver?.disconnect(); this.#hideMenu(true); } @@ -304,6 +318,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 +390,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.#handlingMenuAction && + this.#restoreMenuTapSelection() + ) { + return; + } if (meta.selectionChanged) this.#cancelReadOnlyTap(); if ( meta.selectionChanged && @@ -402,6 +424,7 @@ class TouchSelectionMenuController { this.#readOnlyTapSession = null; this.#pendingPointerSelectionClick = null; this.#dismissedSelection = null; + this.#menuTapState = null; this.#menuRequested = false; this.#isPointerInteracting = false; this.#isScrolling = false; @@ -472,6 +495,7 @@ class TouchSelectionMenuController { this.#readOnlyTapSession = null; return; } + this.#menuTapState = null; if (this.#isIgnoredPointerTarget(target)) { this.#pointerSelectionSession = null; this.#readOnlyTapSession = null; @@ -807,7 +831,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"); @@ -911,6 +935,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); @@ -918,7 +943,7 @@ class TouchSelectionMenuController { } #animateMenuIn() { - this.#menuAnimation?.cancel?.(); + settleAnimation(this.#menuAnimation); if (animationsDisabled()) { this.$menu.style.opacity = "1"; this.$menu.style.transform = "none"; @@ -940,9 +965,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; @@ -1200,8 +1225,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) { @@ -1277,6 +1302,69 @@ 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.#menuTapCancelled = false; + this.#menuTapGuardUntil = performance.now() + MENU_TAP_PRESS_LIMIT; + }; + + #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 = () => { + this.#menuTapState = null; + }; + + // A press cancelled before release (a scroll, or WebKit claiming the touch) + // 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.#menuTapCancelled = true; + }; + + #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; + const { state } = this.#view; + if ( + performance.now() > this.#menuTapGuardUntil || + state.doc !== tapState.doc + ) { + 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; + } + #hasSelection() { const selection = this.#view.state.selection.main; return selection.from !== selection.to; @@ -1288,3 +1376,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/commands.js b/src/lib/commands.js index 3cc7d3401..7f8d439db 100644 --- a/src/lib/commands.js +++ b/src/lib/commands.js @@ -718,7 +718,7 @@ const commands = { }, async "insert-color"(view) { const editor = view || editorManager.editor; - const range = getColorRange(editor); + const range = getColorRange(editor.state); let defaultColor = ""; if (range) { diff --git a/src/lib/selectionMenu.js b/src/lib/selectionMenu.js index 43574db25..64b2d0d68 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; @@ -146,13 +147,14 @@ export default function selectionMenu(options = {}) { true, { id: "share", label: getLabel("share", "Share") }, ), - item( - () => acode.exec("insert-color", view), - , - "all", - false, - { id: "insert-color", label: getLabel("insert color", "Insert color") }, - ), + getColorRange(view?.state) && + item( + () => acode.exec("insert-color", view), + , + "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 c42e08a8a..34662880b 100644 --- a/src/utils/color/regex.js +++ b/src/utils/color/regex.js @@ -248,25 +248,25 @@ export const colorRegex = { /** * Select the color at current line and cursor position (CodeMirror) - * @param {import("@codemirror/view").EditorView} [view] + * @param {import("@codemirror/state").EditorState} [state] Defaults to the active editor's state * @returns {{from:number,to:number}|null} */ -export function getColorRange(view = editorManager.editor) { +export function getColorRange(state = editorManager.editor?.state) { try { - const sel = view.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 = view.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 = view.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 703c6f1e1..8a4452037 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/insertColorCommand.test.js b/tests/unit/insertColorCommand.test.js index 6b75d9d8c..9bbe33fed 100644 --- a/tests/unit/insertColorCommand.test.js +++ b/tests/unit/insertColorCommand.test.js @@ -27,13 +27,14 @@ it("uses the active editor when no view is given", async () => { }); it("passes the menu's view to insert-color", () => { - const view = pane("", 0); + const view = pane("a { color: red; }", 12); const exec = vi.fn(); const { default: selectionMenu } = loadSourceModule( "src/lib/selectionMenu.js", { "cm/editorReadOnly": {}, "lib/settings": { __esModule: true, default: { get() {} } }, + "utils/color/regex": colorRegex, }, { acode: { exec }, tag: () => ({}) }, ); diff --git a/tests/unit/iosWebTouchEnd.test.js b/tests/unit/iosWebTouchEnd.test.js new file mode 100644 index 000000000..81a951c09 --- /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 47e0b26b1..bf1ae57eb 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,133 @@ 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("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(); + 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 000000000..441c53931 --- /dev/null +++ b/tests/unit/touchSelectionMenuTapGuard.test.ts @@ -0,0 +1,246 @@ +// @vitest-environment happy-dom + +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"; + +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(); +}); + +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.$menu); + + view.dispatch({ selection: { anchor: 3 } }); + menu.onStateChanged({ selectionChanged: true }); + + 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"]); + + 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.$menu, ["pointerdown", type]); + + view.dispatch({ selection: { anchor: 9 } }); + menu.onStateChanged({ selectionChanged: true }); + + 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(); + pressMenu(menu.$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("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.$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.$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(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); + const menu = createTouchSelectionMenu(view, { container: document.body }); + return { view, menu }; +} + +function pressMenu(target: HTMLElement, types = ["pointerdown", "pointerup"]) { + for (const type of types) { + target.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + cancelable: true, + pointerId: 1, + pointerType: "touch", + }), + ); + } +}