diff --git a/package-lock.json b/package-lock.json index 18f8c24e62..e33613fba4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "acode-app", - "version": "1.13.7", + "version": "1.13.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acode-app", - "version": "1.13.7", + "version": "1.13.8", "license": "MIT", "dependencies": { "@acode.app/canvas-view": "^0.0.14", diff --git a/platforms/ios/ads/AMBBannerLayout.swift b/platforms/ios/ads/AMBBannerLayout.swift index 4811b117e2..d0d33b75ee 100644 --- a/platforms/ios/ads/AMBBannerLayout.swift +++ b/platforms/ios/ads/AMBBannerLayout.swift @@ -45,7 +45,8 @@ final class AMBBannerLayout { } let root = controller.view! let safe = root.safeAreaLayoutGuide.layoutFrame - let bottom = min(safe.maxY, root.keyboardLayoutGuide.layoutFrame.minY) + let top = controller.systemTopInset + let bottom = min(safe.maxY, controller.keyboardAvoidingGuide.layoutFrame.maxY) var topHeight: CGFloat = 0 var bottomHeight: CGFloat = 0 for banner in banners where banner.visible && banner.isActive && banner.isLoaded() { @@ -59,7 +60,7 @@ final class AMBBannerLayout { y = banner.position == "top" ? offset : root.bounds.height - offset - size.height } else if banner.position == "top" { if topHeight == 0 { topHeight = marginTop } - y = safe.minY + topHeight + y = top + topHeight topHeight += size.height } else { if bottomHeight == 0 { bottomHeight = marginBottom } diff --git a/platforms/ios/runner/WebTouchEnd.swift b/platforms/ios/runner/WebTouchEnd.swift index 831dfc7494..893cb73fe1 100644 --- a/platforms/ios/runner/WebTouchEnd.swift +++ b/platforms/ios/runner/WebTouchEnd.swift @@ -6,6 +6,9 @@ import WebKit /// pointercancel. This watches touches natively and, when the touch sequence ends, /// cancels any touch pointer the page still believes is down. /// The script runs in its own content world so user pages in Preview never see it. +/// It watches from the web view's window: a recognizer inside the web view joins +/// WebKit's gesture group, which stays unreset while a double-tap is pending, so the +/// second tap of a double-tap would go unseen. final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate, WKScriptMessageHandler { static let world = WKContentWorld.world(name: "AcodeTouchEnd") static let frameHandler = "acodeTouchFrame" @@ -20,7 +23,7 @@ final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate, WKScr cancelsTouchesInView = false delaysTouchesEnded = false delegate = self - webView.addGestureRecognizer(self) + webView.addSubview(WindowFollower { [weak self] window in self?.attach(to: window) }) let scripts = webView.configuration.userContentController scripts.addUserScript( WKUserScript(source: Self.script, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: Self.world) @@ -38,9 +41,6 @@ final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate, WKScr } 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) } @@ -73,9 +73,14 @@ final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate, WKScr 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() + state = .failed + } + + private func attach(to window: UIWindow?) { + guard view !== window else { return } + view?.removeGestureRecognizer(self) + window?.addGestureRecognizer(self) } static let script = """ @@ -120,3 +125,22 @@ final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate, WKScr })(); """ } + +/// Reports the window its web view moves to, including WebKit's own fullscreen window. +private final class WindowFollower: UIView { + private let moved: (UIWindow?) -> Void + + init(moved: @escaping (UIWindow?) -> Void) { + self.moved = moved + super.init(frame: .zero) + isHidden = true + isUserInteractionEnabled = false + } + + required init?(coder: NSCoder) { nil } + + override func didMoveToWindow() { + super.didMoveToWindow() + moved(window) + } +} diff --git a/platforms/ios/runner/WebViewController.swift b/platforms/ios/runner/WebViewController.swift index 65268cfc70..93eae6ae3c 100644 --- a/platforms/ios/runner/WebViewController.swift +++ b/platforms/ios/runner/WebViewController.swift @@ -10,6 +10,14 @@ final class WebViewController: UIViewController { private(set) var fullscreen: WebFullscreen! private var contentTop: NSLayoutConstraint! private var contentBottom: NSLayoutConstraint! + private var contentAboveKeyboard: NSLayoutConstraint! + private(set) var bannerInsets = UIEdgeInsets.zero + let keyboardAvoidingGuide = UILayoutGuide() + var systemTopInset: CGFloat { + let safeTop = view.safeAreaInsets.top + let statusBar = view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0 + return prefersStatusBarHidden || statusBar == 0 ? safeTop : min(safeTop, statusBar) + } private var normalLayout: [NSLayoutConstraint] = [] private var fullscreenLayout: [NSLayoutConstraint] = [] var isFullscreenLayout: Bool { fullscreenLayout.first?.isActive == true } @@ -55,15 +63,26 @@ final class WebViewController: UIViewController { content.addSubview(webView) content.translatesAutoresizingMaskIntoConstraints = false webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] - contentTop = content.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) + view.keyboardLayoutGuide.usesBottomSafeArea = false + view.addLayoutGuide(keyboardAvoidingGuide) // iPad apps on Mac report a keyboard guide inset with no on-screen keyboard. - let bottomAnchor = ProcessInfo.processInfo.isiOSAppOnMac + let keyboardTop = ProcessInfo.processInfo.isiOSAppOnMac ? view.safeAreaLayoutGuide.bottomAnchor : view.keyboardLayoutGuide.topAnchor - contentBottom = content.bottomAnchor.constraint(equalTo: bottomAnchor) + NSLayoutConstraint.activate([ + keyboardAvoidingGuide.topAnchor.constraint(equalTo: view.topAnchor), + keyboardAvoidingGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor), + keyboardAvoidingGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor), + keyboardAvoidingGuide.bottomAnchor.constraint(equalTo: keyboardTop), + ]) + contentTop = content.topAnchor.constraint(equalTo: view.topAnchor) + contentAboveKeyboard = content.bottomAnchor.constraint(lessThanOrEqualTo: keyboardAvoidingGuide.bottomAnchor) + contentBottom = content.bottomAnchor.constraint(equalTo: view.bottomAnchor) + contentBottom.priority = .defaultHigh normalLayout = [ contentTop, - content.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), - content.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), + content.leadingAnchor.constraint(equalTo: view.leadingAnchor), + content.trailingAnchor.constraint(equalTo: view.trailingAnchor), + contentAboveKeyboard, contentBottom, ] fullscreenLayout = [ @@ -90,18 +109,31 @@ final class WebViewController: UIViewController { NotificationCenter.default.addObserver(self, selector: #selector(appCameToForeground), name: UIApplication.willEnterForegroundNotification, object: nil) } + override func viewWillLayoutSubviews() { + super.viewWillLayoutSubviews() + updateContentInsets() + } + override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() bridge.adsService?.banners.layout() } func setContentInsets(top: CGFloat, bottom: CGFloat) { - guard contentTop.constant != top || contentBottom.constant != -bottom else { return } - contentTop.constant = top - contentBottom.constant = -bottom + guard bannerInsets.top != top || bannerInsets.bottom != bottom else { return } + bannerInsets.top = top + bannerInsets.bottom = bottom + updateContentInsets() view.layoutIfNeeded() } + private func updateContentInsets() { + contentTop.constant = systemTopInset + bannerInsets.top + contentAboveKeyboard.constant = -bannerInsets.bottom + // The home indicator overlays content, but not bottom banners, which stay tappable above it. + contentBottom.constant = bannerInsets.bottom > 0 ? -(bannerInsets.bottom + view.safeAreaInsets.bottom) : 0 + } + func setFullscreenLayout(_ active: Bool) { NSLayoutConstraint.deactivate(active ? normalLayout : fullscreenLayout) NSLayoutConstraint.activate(active ? fullscreenLayout : normalLayout) @@ -136,9 +168,12 @@ final class WebViewController: UIViewController { @objc private func keyboardWillShow(_ notification: Notification) { guard let info = notification.userInfo, - let frame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } - let localFrame = view.convert(frame, from: nil) - keyboardHeight = max(0, view.bounds.intersection(localFrame).height - view.safeAreaInsets.bottom) + let frame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect, + let screen = view.window?.screen else { return } + let localFrame = view.convert(frame, from: screen.coordinateSpace) + // Content only stops above the home indicator when a bottom banner is shown. + let homeIndicator = bannerInsets.bottom > 0 ? view.safeAreaInsets.bottom : 0 + keyboardHeight = max(0, view.bounds.intersection(localFrame).height - homeIndicator) isKeyboardVisible = keyboardHeight > 0 webView.evaluateJavaScript("window.dispatchEvent(new CustomEvent('keyboardshow', { detail: { height: \(keyboardHeight) } }))", completionHandler: nil) } @@ -155,7 +190,9 @@ final class WebViewController: UIViewController { themeType == "light" ? .darkContent : .lightContent } - var statusBarHidden = false + var statusBarHidden = false { + didSet { updateStatusBar() } + } override var prefersStatusBarHidden: Bool { statusBarHidden || isFullscreenLayout } override var prefersHomeIndicatorAutoHidden: Bool { isFullscreenLayout } override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge { isFullscreenLayout ? .all : [] } @@ -173,12 +210,18 @@ final class WebViewController: UIViewController { func setThemeType(_ type: String) { themeType = type fullscreen?.updateControls() + updateStatusBar() + } + + /// The status bar frame only settles after the appearance update, so the top inset is laid out again once it has. + private func updateStatusBar() { setNeedsStatusBarAppearanceUpdate() var vc: UIViewController? = parent while let current = vc { current.setNeedsStatusBarAppearanceUpdate() vc = current.parent } + DispatchQueue.main.async { [weak self] in self?.viewIfLoaded?.setNeedsLayout() } } func setSystemBarColor(_ color: UIColor) { diff --git a/platforms/ios/runner/lib/PlatformServices.swift b/platforms/ios/runner/lib/PlatformServices.swift index b7021973be..02098940e3 100644 --- a/platforms/ios/runner/lib/PlatformServices.swift +++ b/platforms/ios/runner/lib/PlatformServices.swift @@ -57,7 +57,6 @@ final class SystemBarService: BaseService { switch action { case "setStatusBarVisible": controller.statusBarHidden = !(args[safe: 0] as? Bool ?? true) - controller.setNeedsStatusBarAppearanceUpdate() case "setStatusBarBackgroundColor": if args.count >= 3 { let color = UIColor(red: (args[0] as? Double ?? 0) / 255, green: (args[1] as? Double ?? 0) / 255, blue: (args[2] as? Double ?? 0) / 255, alpha: args[safe: 3] as? Double ?? 1) diff --git a/platforms/ios/runnerTests/AdsBannerLifecycleTests.swift b/platforms/ios/runnerTests/AdsBannerLifecycleTests.swift index 7dadebb924..d19bfbf729 100644 --- a/platforms/ios/runnerTests/AdsBannerLifecycleTests.swift +++ b/platforms/ios/runnerTests/AdsBannerLifecycleTests.swift @@ -19,7 +19,7 @@ extension AdsBridgeTests { ad.bannerViewDidReceiveAd(view) XCTAssertTrue(ad.isLoaded()) XCTAssertNotNil(view.superview) - XCTAssertEqual(controller.webView.frame.height, initial - 50, accuracy: 1) + XCTAssertEqual(controller.webView.frame.height, editorHeight(controller, bottom: 50), accuracy: 1) ad.bannerView(view, didFailToReceiveAdWithError: NSError(domain: "AdMob", code: 1)) XCTAssertFalse(ad.isLoaded()) @@ -35,7 +35,7 @@ extension AdsBridgeTests { ad.show(context(plugin, id: ad.id)) XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) ad.bannerViewDidReceiveAd(view) - XCTAssertEqual(controller.webView.frame.height, initial - 50, accuracy: 1) + XCTAssertEqual(controller.webView.frame.height, editorHeight(controller, bottom: 50), accuracy: 1) } func testHidingPendingBannerPreventsLateLoadFromRestoringSpace() async throws { @@ -56,7 +56,7 @@ extension AdsBridgeTests { XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) ad.show(context(plugin, id: ad.id)) - XCTAssertEqual(controller.webView.frame.height, initial - 50, accuracy: 1) + XCTAssertEqual(controller.webView.frame.height, editorHeight(controller, bottom: 50), accuracy: 1) ad.hide(context(plugin, id: ad.id)) XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) } diff --git a/platforms/ios/runnerTests/AdsBridgeTests.swift b/platforms/ios/runnerTests/AdsBridgeTests.swift index 10bc21c157..0508c430b9 100644 --- a/platforms/ios/runnerTests/AdsBridgeTests.swift +++ b/platforms/ios/runnerTests/AdsBridgeTests.swift @@ -95,14 +95,14 @@ final class AdsBridgeTests: BridgeTestCase { } top.show(context(plugin, id: top.id)) bottom.show(context(plugin, id: bottom.id)) - XCTAssertEqual(controller.webView.frame.height, initial - 100, accuracy: 1) + XCTAssertEqual(controller.webView.frame.height, editorHeight(controller, top: 50, bottom: 50), accuracy: 1) let topView = try XCTUnwrap(top.bannerView) let bottomView = try XCTUnwrap(bottom.bannerView) XCTAssertLessThan(topView.frame.minY, bottomView.frame.minY) top.show(context(plugin, id: top.id)) - XCTAssertEqual(controller.webView.frame.height, initial - 100, accuracy: 1) + XCTAssertEqual(controller.webView.frame.height, editorHeight(controller, top: 50, bottom: 50), accuracy: 1) top.hide(context(plugin, id: top.id)) - XCTAssertEqual(controller.webView.frame.height, initial - 50, accuracy: 1) + XCTAssertEqual(controller.webView.frame.height, editorHeight(controller, bottom: 50), accuracy: 1) bottom.destroy() XCTAssertNil(bottomView.superview) XCTAssertEqual(controller.webView.frame.height, initial, accuracy: 1) @@ -177,10 +177,7 @@ final class AdsBridgeTests: BridgeTestCase { } func host() async throws -> (WebViewController, AMBPlugin) { - let webView = try await appWebView() - var responder: UIResponder? = webView - while responder != nil, !(responder is WebViewController) { responder = responder?.next } - let controller = try XCTUnwrap(responder as? WebViewController) + let controller = try webViewController(for: try await appWebView()) return (controller, try XCTUnwrap(controller.bridge.adsService)) } @@ -199,6 +196,13 @@ final class AdsBridgeTests: BridgeTestCase { if loaded { ad.bannerViewDidReceiveAd(try XCTUnwrap(ad.bannerView)) } return ad } + + func editorHeight(_ controller: WebViewController, top: CGFloat = 0, bottom: CGFloat = 0) -> CGFloat { + let view: UIView = controller.view + let resting = view.bounds.maxY - (bottom > 0 ? bottom + view.safeAreaInsets.bottom : 0) + let keyboard = controller.keyboardAvoidingGuide.layoutFrame.maxY - bottom + return min(resting, keyboard) - controller.systemTopInset - top + } } private final class FixtureAdValue: AdValue { diff --git a/platforms/ios/runnerTests/AppBridgeTests.swift b/platforms/ios/runnerTests/AppBridgeTests.swift index a827135833..acbfb1ba2d 100644 --- a/platforms/ios/runnerTests/AppBridgeTests.swift +++ b/platforms/ios/runnerTests/AppBridgeTests.swift @@ -83,13 +83,22 @@ final class AppBridgeTests: BridgeTestCase { XCTAssertEqual(opened, true) } - func testEditorAvoidsSystemSafeAreas() async throws { + func testEditorUsesSpaceAroundSystemBars() async throws { let webView = try await appWebView() + let controller = try webViewController(for: webView) let window = try XCTUnwrap(webView.window) window.layoutIfNeeded() let frame = webView.convert(webView.bounds, to: window) - XCTAssertGreaterThanOrEqual(frame.minY, window.safeAreaInsets.top) - XCTAssertLessThanOrEqual(frame.maxY, window.bounds.height - window.safeAreaInsets.bottom) + let safe = window.safeAreaInsets + XCTAssertLessThanOrEqual(frame.minY - 1, safe.top + controller.bannerInsets.top) + let statusBar = window.windowScene?.statusBarManager?.statusBarFrame.height ?? 0 + let systemTop = statusBar > 0 ? min(safe.top, statusBar) : safe.top + XCTAssertEqual(frame.minY, systemTop + controller.bannerInsets.top, accuracy: 1) + + let banner = controller.bannerInsets.bottom + let keyboard = controller.view.convert(controller.keyboardAvoidingGuide.layoutFrame, to: window).maxY + let resting = window.bounds.height - (banner > 0 ? banner + safe.bottom : 0) + XCTAssertEqual(frame.maxY, min(resting, keyboard - banner), accuracy: 1) } func testEditorReadsEditsAndSavesAFile() async throws { let webView = try await appWebView() diff --git a/platforms/ios/runnerTests/BridgeTestCase.swift b/platforms/ios/runnerTests/BridgeTestCase.swift index 35f6d926ac..fb38db06f1 100644 --- a/platforms/ios/runnerTests/BridgeTestCase.swift +++ b/platforms/ios/runnerTests/BridgeTestCase.swift @@ -28,6 +28,12 @@ class BridgeTestCase: XCTestCase { throw NSError(domain: "AcodeTests", code: 1, userInfo: [NSLocalizedDescriptionKey: "App WebView not mounted"]) } + func webViewController(for webView: WKWebView) throws -> WebViewController { + var responder: UIResponder? = webView + while responder != nil, !(responder is WebViewController) { responder = responder?.next } + return try XCTUnwrap(responder as? WebViewController) + } + func editorWebView() async throws -> WKWebView { let webView = try await appWebView() for _ in 0..<150 { diff --git a/platforms/ios/runnerTests/SafeAreaLayoutTests.swift b/platforms/ios/runnerTests/SafeAreaLayoutTests.swift new file mode 100644 index 0000000000..444cc2ce43 --- /dev/null +++ b/platforms/ios/runnerTests/SafeAreaLayoutTests.swift @@ -0,0 +1,66 @@ +import XCTest +import WebKit +@testable import runner + +@MainActor +final class SafeAreaLayoutTests: BridgeTestCase { + func testLandscapeBandsClearTheSideInsets() async throws { + let webView = try await editorWebView() + let scene = try XCTUnwrap(webView.window?.windowScene) + _ = try await webView.callAsyncJavaScript(""" + window.safeAreaFile = new (acode.require('EditorFile'))('Safe area.txt', { text: 'safe area' }); + safeAreaFile.makeActive(); + """, arguments: [:], in: nil, contentWorld: .page) + addTeardownBlock { @MainActor in + _ = try? await webView.callAsyncJavaScript("await window.safeAreaFile.remove(true)", arguments: [:], in: nil, contentWorld: .page) + } + let original = scene.effectiveGeometry.interfaceOrientation + addTeardownBlock { @MainActor in + guard scene.effectiveGeometry.interfaceOrientation != original else { return } + _ = try? await self.rotate(webView, scene, to: UIInterfaceOrientationMask(rawValue: 1 << original.rawValue)) + } + let rotated = try await rotate(webView, scene, to: .landscapeRight) + try XCTSkipUnless(rotated, "The scene did not rotate, as a resizable iPad window does not") + let inset = try XCTUnwrap(webView.window).safeAreaInsets.right + try XCTSkipIf(inset == 0, "This device has no side safe area in landscape") + + let result = try await webView.callAsyncJavaScript(""" + const probe = document.createElement('div'); + probe.style.paddingRight = 'env(safe-area-inset-right)'; + document.body.append(probe); + const env = parseFloat(getComputedStyle(probe).paddingRight); + probe.remove(); + const page = acode.require('page')('Safe area'); + app.append(page); + const header = page.querySelector(':scope > header'); + const pageHeader = { left: header.offsetLeft, extra: header.offsetWidth - page.offsetWidth }; + page.remove(); + const paddingRight = (selector) => parseFloat(getComputedStyle(document.querySelector(selector)).paddingRight); + return { + env, + rootHeader: paddingRight('#root > header'), + editor: paddingRight('#root .cm-editor'), + tabsOverflow: document.querySelector('#root .editor-pane-tabs').getBoundingClientRect().right - innerWidth, + pageHeaderLeft: pageHeader.left, + pageHeaderExtra: pageHeader.extra, + }; + """, arguments: [:], in: nil, contentWorld: .page) + let layout = try XCTUnwrap(result as? [String: Double]) + XCTAssertEqual(layout["env"] ?? 0, inset, accuracy: 1, "viewport-fit=cover is missing from index.html") + XCTAssertEqual(layout["rootHeader"] ?? 0, inset, accuracy: 1) + XCTAssertEqual(layout["editor"] ?? 0, inset, accuracy: 1) + XCTAssertLessThanOrEqual(layout["tabsOverflow"] ?? .infinity, 1) + XCTAssertEqual(layout["pageHeaderLeft"] ?? -1, 0, accuracy: 1) + XCTAssertEqual(layout["pageHeaderExtra"] ?? -1, 0, accuracy: 1) + } + + private func rotate(_ webView: WKWebView, _ scene: UIWindowScene, to orientation: UIInterfaceOrientationMask) async throws -> Bool { + scene.requestGeometryUpdate(.iOS(interfaceOrientations: orientation)) + let landscape = !orientation.isDisjoint(with: .landscape) + for _ in 0..<100 { + if (try? await webView.evaluateJavaScript("innerWidth > innerHeight")) as? Bool == landscape { return true } + try await Task.sleep(for: .milliseconds(50)) + } + return false + } +} diff --git a/platforms/ios/runnerTests/SystemUITests.swift b/platforms/ios/runnerTests/SystemUITests.swift index 616eff79e1..e2bb7a801e 100644 --- a/platforms/ios/runnerTests/SystemUITests.swift +++ b/platforms/ios/runnerTests/SystemUITests.swift @@ -63,9 +63,7 @@ final class SystemUITests: BridgeTestCase { let webView = try await editorWebView() let scene = try XCTUnwrap(webView.window?.windowScene) XCTAssertTrue(webView.configuration.preferences.isElementFullscreenEnabled) - var responder: UIResponder? = webView - while responder != nil, !(responder is WebViewController) { responder = responder?.next } - let controller = try XCTUnwrap(responder as? WebViewController) + let controller = try webViewController(for: webView) let rejected = try await webView.callAsyncJavaScript(""" const orientation=acode.require('orientation'); try {await orientation.lock('landscape');return false;}catch{return true;} @@ -97,8 +95,8 @@ final class SystemUITests: BridgeTestCase { XCTAssertNil(controller.fullscreen.requestedOrientation) controller.view.layoutIfNeeded() let frame = webView.convert(webView.bounds, to: controller.view) - XCTAssertEqual(frame.minX, controller.view.safeAreaInsets.left, accuracy: 1) - XCTAssertEqual(webView.frame.width, controller.view.safeAreaLayoutGuide.layoutFrame.width, accuracy: 1) + XCTAssertEqual(frame.minX, 0, accuracy: 1) + XCTAssertEqual(webView.frame.width, controller.view.bounds.width, accuracy: 1) XCTAssertGreaterThan(webView.frame.height, 300) } catch { controller.fullscreen.reset() @@ -115,9 +113,7 @@ final class SystemUITests: BridgeTestCase { func testThemeAppliesSystemBarBackgroundColor() async throws { let webView = try await editorWebView() - var responder: UIResponder? = webView - while responder != nil, !(responder is WebViewController) { responder = responder?.next } - let controller = try XCTUnwrap(responder as? WebViewController) + let controller = try webViewController(for: webView) let color = controller.view.backgroundColor let type = controller.themeType // The startup theme timer must not overwrite direct bridge color checks. @@ -151,7 +147,6 @@ final class SystemUITests: BridgeTestCase { """, arguments: [:], in: nil, contentWorld: .page) as? String let error = try XCTUnwrap(result) if !error.isEmpty { - XCTAssertEqual(UIDevice.current.userInterfaceIdiom, .pad) XCTAssertTrue(error.contains("windowing mode"), error) XCTAssertNil(AppDelegate.shared?.fullscreenOrientation) XCTAssertNil(controller.fullscreen.requestedOrientation) diff --git a/platforms/ios/runnerTests/WebFullscreenTests.swift b/platforms/ios/runnerTests/WebFullscreenTests.swift index 18c7597c94..3e0d8b5db6 100644 --- a/platforms/ios/runnerTests/WebFullscreenTests.swift +++ b/platforms/ios/runnerTests/WebFullscreenTests.swift @@ -55,16 +55,16 @@ final class WebFullscreenTests: BridgeTestCase { """, arguments: [:], in: nil, contentWorld: .page) as? Bool XCTAssertEqual(result, true) XCTAssertTrue(webView.superview === parent) - let controller = try controller(for: webView) + let controller = try webViewController(for: webView) XCTAssertFalse(controller.fullscreen.isFullscreen) XCTAssertNil(controller.fullscreen.requestedOrientation) XCTAssertEqual(webView.fullscreenState, .notInFullscreen) - XCTAssertEqual(webView.frame.width, controller.view.safeAreaLayoutGuide.layoutFrame.width, accuracy: 1) + XCTAssertEqual(webView.frame.width, controller.view.bounds.width, accuracy: 1) } func testNavigationRestoresNativeFullscreenAndStatusBarPreference() async throws { let webView = try await editorWebView() - let controller = try controller(for: webView) + let controller = try webViewController(for: webView) let hidden = controller.statusBarHidden controller.statusBarHidden = true defer { controller.statusBarHidden = hidden; controller.setThemeType(controller.themeType) } @@ -85,7 +85,7 @@ final class WebFullscreenTests: BridgeTestCase { func testBackControlsRouteToHandlerAndRestoreDefaultExitAfterRelease() async throws { let webView = try await editorWebView() - let controller = try controller(for: webView) + let controller = try webViewController(for: webView) let button = try XCTUnwrap(controller.view.subviews.compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == "fullscreen-back" }) let gesture = try XCTUnwrap(controller.view.gestureRecognizers?.compactMap { $0 as? UIScreenEdgePanGestureRecognizer }.first) XCTAssertTrue(button.isHidden) @@ -134,7 +134,7 @@ final class WebFullscreenTests: BridgeTestCase { func testBackFailureCannotExitANewerFullscreenOwner() async throws { let webView = try await editorWebView() - let controller = try controller(for: webView) + let controller = try webViewController(for: webView) _ = try await webView.callAsyncJavaScript(""" await document.body.requestFullscreen(); await acode.require('fullscreen').setBackHandler(()=>{throw Error('fixture');}); @@ -194,10 +194,4 @@ final class WebFullscreenTests: BridgeTestCase { } XCTFail("Fullscreen did not reach: " + expression) } - - private func controller(for webView: WKWebView) throws -> WebViewController { - var responder: UIResponder? = webView - while responder != nil, !(responder is WebViewController) { responder = responder?.next } - return try XCTUnwrap(responder as? WebViewController) - } } diff --git a/platforms/ios/runnerTests/WebTouchEndTests.swift b/platforms/ios/runnerTests/WebTouchEndTests.swift index 57a902a885..6c43305ee4 100644 --- a/platforms/ios/runnerTests/WebTouchEndTests.swift +++ b/platforms/ios/runnerTests/WebTouchEndTests.swift @@ -7,7 +7,16 @@ final class WebTouchEndTests: XCTestCase { func testNativeConfigurationNeverInterferesWithOtherGesturesAndCoversAllFrames() { let view = WKWebView() let touchEnd = WebTouchEnd(webView: view) - XCTAssertTrue(view.gestureRecognizers?.contains(touchEnd) == true) + let window = UIWindow() + let fullscreenWindow = UIWindow() + window.addSubview(view) + XCTAssertTrue(touchEnd.view === window) + XCTAssertFalse(view.gestureRecognizers?.contains(touchEnd) == true) + fullscreenWindow.addSubview(view) + XCTAssertTrue(touchEnd.view === fullscreenWindow) + XCTAssertFalse(window.gestureRecognizers?.contains(touchEnd) == true) + view.removeFromSuperview() + XCTAssertNil(touchEnd.view) XCTAssertFalse(touchEnd.cancelsTouchesInView) XCTAssertFalse(touchEnd.delaysTouchesBegan) XCTAssertFalse(touchEnd.delaysTouchesEnded) diff --git a/rspack.config.js b/rspack.config.js index cdd0591393..4f0f896217 100644 --- a/rspack.config.js +++ b/rspack.config.js @@ -205,7 +205,19 @@ module.exports = (env, options) => { new StripSourceMapCommentsPlugin(), new rspack.CopyRspackPlugin({ patterns: [ - { from: 'src/index.html', to: 'index.html' }, + { + from: 'src/index.html', + to: 'index.html', + // iOS lets the home indicator overlay the web view; env(safe-area-inset-*) is 0 without cover. + ...(platform === 'ios' && { + transform: (content) => { + const html = content.toString(); + const viewport = /( { const rect = view.dom.getBoundingClientRect(); + const { paddingLeft, paddingRight } = getComputedStyle(view.dom); return { top: rect.top, - left: rect.left, + left: rect.left + (Number.parseFloat(paddingLeft) || 0), bottom: window.innerHeight, - right: window.innerWidth, + right: window.innerWidth - (Number.parseFloat(paddingRight) || 0), }; }, }), diff --git a/src/cm/touchSelectionMenu.js b/src/cm/touchSelectionMenu.js index 1613a2092d..197f1e440f 100644 --- a/src/cm/touchSelectionMenu.js +++ b/src/cm/touchSelectionMenu.js @@ -1139,6 +1139,9 @@ class TouchSelectionMenuController { const fitsAbove = topAbove >= minTop; const fitsBelow = topBelow <= maxTop; const placedAbove = fitsAbove || !fitsBelow; + const { paddingLeft, paddingRight } = getComputedStyle(this.#view.dom); + const safeLeft = Number.parseFloat(paddingLeft) || 0; + const safeRight = Number.parseFloat(paddingRight) || 0; const clamped = clampMenuPosition( { left: preferredLeft, @@ -1147,9 +1150,9 @@ class TouchSelectionMenuController { height: menuRect.height, }, { - left: containerRect.left, + left: containerRect.left + safeLeft, top: containerRect.top, - width: containerRect.width, + width: containerRect.width - safeLeft - safeRight, height: containerRect.height, }, ); diff --git a/src/components/contextmenu/index.js b/src/components/contextmenu/index.js index c3e6131925..f773e3d180 100644 --- a/src/components/contextmenu/index.js +++ b/src/components/contextmenu/index.js @@ -1,5 +1,8 @@ import "./style.scss"; import actionStack from "lib/actionStack"; +import platform from "lib/platform"; + +const EDGE_MARGIN = "8px"; /** * @typedef {object} ContextMenuObj @@ -54,8 +57,8 @@ export default function Contextmenu(content, options) { }, style: { top: options.top || "auto", - left: options.left || "auto", - right: options.right || "auto", + left: options.left ? insetOffset(options.left, "left") : "auto", + right: options.right ? insetOffset(options.right, "right") : "auto", bottom: options.bottom || "auto", transformOrigin: options.transformOrigin, }, @@ -310,3 +313,19 @@ export default function Contextmenu(content, options) { return $el; } + +/** + * Keeps an edge-anchored menu clear of the safe area on that side. A small + * margin from the screen edge moves inside the safe area, while a position + * measured from the viewport, which already clears it, stays where it is. + * Only iOS has side safe areas, and older Android WebViews drop the whole + * position when they meet max(). + * @param {string|number} offset + * @param {"left"|"right"} side + * @returns {string} + */ +function insetOffset(offset, side) { + if (!platform.isIOS) return offset; + const length = Number(offset) === 0 ? "0px" : offset; + return `max(${length}, calc(var(--safe-area-${side}) + min(${length}, ${EDGE_MARGIN})))`; +} diff --git a/src/components/cursorController/knob.js b/src/components/cursorController/knob.js index 55181dacf9..a16a285070 100644 --- a/src/components/cursorController/knob.js +++ b/src/components/cursorController/knob.js @@ -2,12 +2,12 @@ import quickTools from "components/quickTools"; const MAX_LEAN_PX = 3; const LEAN_REACH_PX = 20; -const KNOB_RADIUS_PX = 10; const BUMP_MS = 220; /** - * The cursor knob dot, centered on the seam between the Quick Tools - * rows. It floats over the rows, so the Quick Tools layout is untouched. + * The cursor knob dot, centered on the seam between the Quick Tools rows, + * or on the top edge of a single row. It floats over the rows, so the + * Quick Tools layout is untouched. */ export default class CursorKnob { #element = ; @@ -21,7 +21,6 @@ export default class CursorKnob { mount($footer) { this.#footer = $footer; - root.appendOuter(this.#element); } place(visible) { @@ -74,24 +73,29 @@ export default class CursorKnob { if (!rows.length) return null; const rootRect = root.getBoundingClientRect(); - const footerRect = $footer.getBoundingClientRect(); const firstRect = rows[0].getBoundingClientRect(); - const y = - rows.length > 1 ? firstRect.bottom : firstRect.top + KNOB_RADIUS_PX; + const y = rows.length > 1 ? firstRect.bottom : firstRect.top; return { - x: footerRect.left + footerRect.width / 2 - rootRect.left, + x: firstRect.left + firstRect.width / 2 - rootRect.left, bottom: rootRect.bottom - y, rows: rows.length, }; } #apply(layout) { - this.#element.classList.toggle("hidden", !layout); - if (!layout) return; - const { style, dataset } = this.#element; - style.left = `${layout.x}px`; - style.bottom = `${layout.bottom}px`; - dataset.rows = String(layout.rows); + const $knob = this.#element; + if (layout) { + const { style, dataset } = $knob; + style.left = `${layout.x}px`; + style.bottom = `${layout.bottom}px`; + dataset.rows = String(layout.rows); + // Unplaced, the knob hangs below #root and makes it scroll under the Quick Tools. + if (!$knob.isConnected) { + root.appendOuter($knob); + void $knob.offsetWidth; + } + } + $knob.classList.toggle("hidden", !layout); } } diff --git a/src/components/cursorController/style.scss b/src/components/cursorController/style.scss index 722be434cc..b78e4d1351 100644 --- a/src/components/cursorController/style.scss +++ b/src/components/cursorController/style.scss @@ -51,8 +51,15 @@ border-radius: 50%; } - &[data-rows="1"]::after { - top: 0; + // A single row's knob straddles the row's top edge; only its lower half takes touches, + // so taps on the editor just above the Quick Tools still reach it. + &[data-rows="1"] { + pointer-events: none; + + &::after { + top: 50%; + pointer-events: auto; + } } &.hidden { @@ -62,6 +69,10 @@ transition: opacity 140ms ease, scale 140ms ease-in; + + &::after { + pointer-events: none; + } } &.active { diff --git a/src/components/searchbar/index.js b/src/components/searchbar/index.js index aa92ae5100..20b22b1c5d 100644 --- a/src/components/searchbar/index.js +++ b/src/components/searchbar/index.js @@ -21,6 +21,7 @@ function searchBar( let hideOnBlur = true; let timeout = null; let closed = false; + const searchClones = new Map(); const $searchInput = Ref(); /**@type {HTMLDivElement} */ const $container = ( @@ -72,6 +73,7 @@ function searchBar( console.error("Search close callback failed:", error); } + releaseSearchClones(); $list.content = children; $container.classList.add("hide"); setTimeout(() => { @@ -138,6 +140,7 @@ function searchBar( * @returns {HTMLElement[]} */ function buildSearchContent(result, val) { + releaseSearchClones(); if (!val || !result.length) return result; const groupedSections = []; @@ -206,6 +209,10 @@ function searchBar( */ function cloneSearchItem($item) { const $clone = $item.cloneNode(true); + $item.addEventListener("settings-item-state-change", syncState); + searchClones.set($clone, () => + $item.removeEventListener("settings-item-state-change", syncState), + ); syncCheckboxState($clone, $item); $clone.addEventListener("click", (event) => { // The clone is only a proxy for the backing settings item. In @@ -225,6 +232,22 @@ function searchBar( $item.click(); }); return $clone; + + function syncState() { + $clone.className = $item.className; + $clone.hidden = $item.hidden; + for (const name of ["aria-hidden", "aria-disabled"]) { + $clone.setAttribute(name, $item.getAttribute(name)); + } + } + } + + /** + * Stop following the backing items of the previous results. + */ + function releaseSearchClones() { + for (const release of searchClones.values()) release(); + searchClones.clear(); } /** diff --git a/src/components/settingsPage.js b/src/components/settingsPage.js index 3357206c6e..977d6a4e31 100644 --- a/src/components/settingsPage.js +++ b/src/components/settingsPage.js @@ -194,11 +194,24 @@ export default function settingsPage( $item.hidden = !visible; $item.setAttribute("aria-hidden", String(!visible)); + $item.dispatchEvent(new CustomEvent("settings-item-state-change")); if ($item.hidden && document.activeElement === $item) { $list.focus(); } return true; }, + /** + * Enable or disable one setting without rebuilding the page. + * @param {string} key + * @param {boolean} disabled + */ + setItemDisabled(key, disabled) { + const $item = state.itemElements.get(key); + if (!$item) return false; + + setDisabled($item, disabled === true); + return true; + }, /** * Register cleanup that runs only when this settings page closes. * @param {()=>void} callback @@ -227,6 +240,7 @@ export default function settingsPage( * @property {boolean} [checkbox] * @property {boolean} [chevron] * @property {boolean} [hidden] + * @property {boolean} [disabled] * @property {string} [prompt] * @property {string} [promptType] * @property {import('dialogs/prompt').PromptOptions} [promptOptions] @@ -279,7 +293,11 @@ function listItems($list, items, callback, options = {}) { */ async function onclick(e) { const $target = e.currentTarget; - if ($target.hidden) return; + if ($target.hidden || $target.classList.contains("disabled")) { + e.preventDefault(); + dispatchItemInteractionEnd($target, false); + return; + } const { key } = $target.dataset; const item = itemByKey.get(key); @@ -429,6 +447,7 @@ function createListItemElement(item, options, useInfoAsDescription) { item.searchGroup || item.category || options.defaultSearchGroup; $item.hidden = item.hidden === true; $item.setAttribute("aria-hidden", String($item.hidden)); + setDisabled($item, item.disabled === true); if (searchGroup) { $item.dataset.searchGroup = searchGroup; @@ -841,6 +860,12 @@ function getSubtitleText(item, useInfoAsDescription) { return item.value ?? item.info; } +function setDisabled($item, disabled) { + $item.classList.toggle("disabled", disabled); + $item.setAttribute("aria-disabled", String(disabled)); + $item.dispatchEvent(new CustomEvent("settings-item-state-change")); +} + /** * Sets color decoration of a setting * @param {HTMLDivElement} $setting diff --git a/src/components/settingsPage.scss b/src/components/settingsPage.scss index 9ae7b8fd2e..1ea4b8df2a 100644 --- a/src/components/settingsPage.scss +++ b/src/components/settingsPage.scss @@ -53,6 +53,11 @@ } } +.settings-section-card>.list-item.disabled { + opacity: 0.5; + pointer-events: none; +} + wc-page.main-settings-page { background: var(--secondary-color); @include settings-page-shell(".main-settings-list"); @@ -417,6 +422,11 @@ wc-page.detail-settings-page { .detail-settings-list>.list-item, .settings-section-card>.list-item { display: flex; + + &[hidden] { + display: none; + } + width: 100%; margin: 0; padding: 0.75rem 1rem; diff --git a/src/components/sidebar/index.js b/src/components/sidebar/index.js index 4e7f8754b1..d4cca6ffb3 100644 --- a/src/components/sidebar/index.js +++ b/src/components/sidebar/index.js @@ -10,6 +10,7 @@ import config from "lib/config"; import customTab from "lib/customTab"; import platform from "lib/platform"; import helpers from "utils/helpers"; +import safeAreaInsets from "utils/safeAreaInsets"; import Url from "utils/Url"; /** @@ -47,7 +48,7 @@ function create($container, $toggler) { const userContextMenu = Ref(); $container = $container || app; - let mode = innerWidth > 750 ? "tab" : "phone"; + let mode = sidebarMode(innerWidth); let width = +(localStorage.sideBarWidth || MIN_WIDTH); const eventOptions = { passive: false }; @@ -365,7 +366,7 @@ function create($container, $toggler) { innerWidth = currentWidth; $el.classList.remove(mode); - mode = innerWidth > 750 ? "tab" : "phone"; + mode = sidebarMode(innerWidth); $el.classList.add(mode); let shouldShow = false; @@ -786,3 +787,13 @@ export default Sidebar; export function preventSlide(test) { preventSlideTests.push(test); } + +/** + * Docks the sidebar only when the width beside the side cutouts allows it. + * @param {number} width + * @returns {"tab"|"phone"} + */ +function sidebarMode(width) { + const { left, right } = safeAreaInsets(); + return width - left - right > 750 ? "tab" : "phone"; +} diff --git a/src/main.scss b/src/main.scss index b0649b1e37..4aebf3844c 100644 --- a/src/main.scss +++ b/src/main.scss @@ -6,6 +6,7 @@ @use "./styles/markdown.scss"; @use "./styles/codemirror.scss"; @use "./styles/notification.scss"; +@use "./styles/safeArea.scss"; :root { --scrollbar-width: 4px; @@ -845,8 +846,8 @@ input[type="search"]::-webkit-search-results-decoration { .tab-page-content { position: absolute; top: 0; - left: 0; - right: 0; + left: var(--safe-area-left); + right: var(--safe-area-right); bottom: 0; overflow: auto; } diff --git a/src/settings/appSettings.js b/src/settings/appSettings.js index f962095615..76d40fd75c 100644 --- a/src/settings/appSettings.js +++ b/src/settings/appSettings.js @@ -20,6 +20,11 @@ import helpers from "utils/helpers"; import { isPlayStoreInstall } from "utils/installSource"; import Url from "utils/Url"; +const CURSOR_CONTROLLER_SETTINGS = [ + "cursorController", + "cursorControllerHaptics", +]; + export default function otherSettings() { const values = appSettings.value; const title = strings["app settings"].capitalize(); @@ -394,7 +399,13 @@ export default function otherSettings() { }, ]; - return settingsPage( + for (const item of items) { + if (CURSOR_CONTROLLER_SETTINGS.includes(item.key)) { + item.disabled = !isCursorControllerSettingEnabled(item.key); + } + } + + const page = settingsPage( title, items.filter((item) => platform.appExit || item.key !== "confirmOnExit"), callback, @@ -408,6 +419,20 @@ export default function otherSettings() { }, ); + return page; + + function isCursorControllerSettingEnabled(key) { + const { quickTools, cursorController } = appSettings.value; + if (!Number(quickTools)) return false; + return key !== "cursorControllerHaptics" || !!cursorController; + } + + function updateCursorControllerSettings() { + for (const key of CURSOR_CONTROLLER_SETTINGS) { + page.setItemDisabled(key, !isCursorControllerSettingEnabled(key)); + } + } + async function callback(key, value) { switch (key) { case "keybindings": { @@ -507,6 +532,7 @@ export default function otherSettings() { helpers.error(error); loader.destroy(); } + break; } case "rememberFiles": @@ -573,5 +599,9 @@ export default function otherSettings() { await appSettings.update({ [key]: value, }); + // The cursor knob sits on the Quick Tools rows, so it has nothing to show without them. + if (key === "quickTools" || key === "cursorController") { + updateCursorControllerSettings(); + } } } diff --git a/src/styles/page.scss b/src/styles/page.scss index 0a4a0a1c20..79084b7fd7 100644 --- a/src/styles/page.scss +++ b/src/styles/page.scss @@ -383,7 +383,7 @@ wc-page { z-index: 98; background-color: rgb(153, 153, 255); background-color: var(--primary-color); - padding: 0 1px; + padding: 0 calc(1px + var(--safe-area-right)) 0 calc(1px + var(--safe-area-left)); box-sizing: border-box; box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.2); box-shadow: 0 -2px 4px var(--box-shadow-color); diff --git a/src/styles/safeArea.scss b/src/styles/safeArea.scss new file mode 100644 index 0000000000..7df9d86b5f --- /dev/null +++ b/src/styles/safeArea.scss @@ -0,0 +1,92 @@ +// The iOS web view spans the full width in landscape: bands keep their +// background to the screen edges while their content clears the camera cutout. +:root { + --safe-area-left: 0px; + --safe-area-right: 0px; +} + +// Inside a custom property, env() loses its fallback where it is unsupported. +@supports (left: env(safe-area-inset-left)) { + :root { + --safe-area-left: env(safe-area-inset-left, 0px); + --safe-area-right: env(safe-area-inset-right, 0px); + } +} + +// A docked sidebar covers the left edge. +body:has(> #sidebar.tab) > #root { + --safe-area-left: 0px; +} + +// Side-by-side panes only reach the screen edges on their outer sides; narrower +// screens show the active pane alone at full width. +@media (min-width: 721px) { + .editor-pane-split[data-direction="horizontal"] > :not(:first-child) { + --safe-area-left: 0px; + } + + .editor-pane-split[data-direction="horizontal"] > :not(:last-child) { + --safe-area-right: 0px; + } +} + +wc-page:not(#root) { + padding-left: var(--safe-area-left); + padding-right: var(--safe-area-right); + + // A sticky `left: 0` would hold the header inside the page padding. + > header.tile { + left: auto; + width: auto; + margin-left: calc(-1 * var(--safe-area-left)); + margin-right: calc(-1 * var(--safe-area-right)); + } +} + +wc-page > header.tile, +#root .editor-pane-tabs, +#root .cm-editor, +#search-bar, +.symbols-panel, +.references-panel { + padding-left: var(--safe-area-left); + padding-right: var(--safe-area-right); +} + +#root .editor-pane-tabs { + width: auto; + scroll-padding-inline: var(--safe-area-left) var(--safe-area-right); +} + +#root .scrollbar-container.right { + right: var(--safe-area-right); +} + +#search-bar { + box-sizing: border-box; +} + +body.fullscreen-mode #root > header.tile { + padding-left: 0; + padding-right: 0; + margin-right: var(--safe-area-right); +} + +#sidebar { + padding-left: var(--safe-area-left); + + > .file-selection-bar, + > .user-menu { + margin-left: var(--safe-area-left); + } +} + +.floating.icon, +.notification-item-container { + margin-right: var(--safe-area-right); +} + +#sidebar-toggler, +.notification-item-container { + margin-left: var(--safe-area-left); +} diff --git a/src/utils/safeAreaInsets.js b/src/utils/safeAreaInsets.js new file mode 100644 index 0000000000..47c28983ab --- /dev/null +++ b/src/utils/safeAreaInsets.js @@ -0,0 +1,17 @@ +/** + * Measures the side safe-area insets in pixels; a custom property + * holding env() only resolves once something uses it as a length. + * @returns {{left: number, right: number}} + */ +export default function safeAreaInsets() { + const $probe = document.createElement("div"); + $probe.style.cssText = + "position:fixed;visibility:hidden;pointer-events:none;padding:0 var(--safe-area-right) 0 var(--safe-area-left)"; + document.body.append($probe); + const { paddingLeft, paddingRight } = getComputedStyle($probe); + $probe.remove(); + return { + left: Number.parseFloat(paddingLeft) || 0, + right: Number.parseFloat(paddingRight) || 0, + }; +}