Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions platforms/ios/ads/AMBBannerLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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 }
Expand Down
36 changes: 30 additions & 6 deletions platforms/ios/runner/WebTouchEnd.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
Expand All @@ -38,9 +41,6 @@ final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate, WKScr
}

override func touchesBegan(_ touches: Set<UITouch>, 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)
}

Expand Down Expand Up @@ -73,9 +73,14 @@ final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate, WKScr
private func release(_ touches: Set<UITouch>) {
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 = """
Expand Down Expand Up @@ -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)
}
}
67 changes: 55 additions & 12 deletions platforms/ios/runner/WebViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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 = [
Expand All @@ -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)
Expand Down Expand Up @@ -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)
}
Expand All @@ -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 : [] }
Expand 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) {
Expand Down
1 change: 0 additions & 1 deletion platforms/ios/runner/lib/PlatformServices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions platforms/ios/runnerTests/AdsBannerLifecycleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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 {
Expand All @@ -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)
}
Expand Down
18 changes: 11 additions & 7 deletions platforms/ios/runnerTests/AdsBridgeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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))
}

Expand All @@ -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 {
Expand Down
15 changes: 12 additions & 3 deletions platforms/ios/runnerTests/AppBridgeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
6 changes: 6 additions & 0 deletions platforms/ios/runnerTests/BridgeTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading