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
14 changes: 14 additions & 0 deletions .changeset/pop-to-native-topmost-surface.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@callstack/react-native-brownfield': patch
---

Fix `popToNative()` on iOS closing every React Native screen instead of only the topmost one.

`popToNative()` is delivered as an app-wide notification, so every live React Native surface acted on it — including surfaces buried under other screens, and each surface acted twice when hosted by SwiftUI. In a stack such as RN → native → RN, a single call tore down the whole navigation stack, taking native screens with it.

A React Native surface now acts only when it is the topmost one on screen, and only once per host.

Two consequences worth knowing about:

- When no React Native surface is on screen — for example one hidden behind a full-screen native modal — `popToNative()` is now a no-op instead of popping the hidden screen. It logs when this happens.
- `popToNative()` no longer dismisses a modally presented native screen that merely *contains* a React Native surface. Only a surface that owns a navigation stack entry pops.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like an unusual place to put this and related files. Let's put this at packages/react-native-brownfield/ios/.

We can then discard the Package.swift change

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I followed the BrownfieldBundleURLResolver example. SPM can't reach outside its package root, so moving the file to ios will delete the unit tests. I can do that but just making sure we're fine with that.

For what it's worth they only cover the surface election logic, which is the simple part. The bugs I actually hit were all in the wiring and the e2e caught those, so losing them isn't a big deal.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah let's ignore this test.

Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import Foundation

/// Identifies one live React Native surface. Vended by `BrownfieldSurfaceRegistry`.
struct BrownfieldSurfaceID: Hashable, CustomStringConvertible {
fileprivate let rawValue: UInt64

var description: String { "surface#\(rawValue)" }
}

/// Decides which React Native surface may act on a `popToNative()` request.
///
/// `popToNative()` is delivered as an app-wide notification, so every live React
/// Native surface receives it — including ones buried under other screens. Acting
/// on all of them tears down the whole navigation stack
/// (https://github.com/callstack/react-native-brownfield/issues/354).
///
/// The registry resolves that to a single surface: whichever on-screen surface
/// was shown most recently.
///
/// Visibility is asked for at query time instead of being cached from lifecycle
/// callbacks. Hosts recreate view controllers — SwiftUI does it freely — and a
/// cached flag is stale exactly when the notification arrives.
///
/// Deliberately free of UIKit so it can be unit tested on macOS via `swift test`.
/// Internal, like the sibling `BrownfieldBundleSupport` target: it is an
/// implementation detail of the pod, not API for host apps.
final class BrownfieldSurfaceRegistry {
static let shared = BrownfieldSurfaceRegistry()

private struct Surface {
let isOnScreen: () -> Bool
var shownAt: UInt64
}

private let lock = NSLock()
private var nextSurfaceValue: UInt64 = 0
private var nextShownValue: UInt64 = 0
private var surfaces: [BrownfieldSurfaceID: Surface] = [:]

init() {}

/// - Parameter isOnScreen: queried on every `popTarget()`. Capture the host
/// weakly so a released surface stops winning the election.
func register(isOnScreen: @escaping () -> Bool) -> BrownfieldSurfaceID {
lock.lock()
defer { lock.unlock() }

nextSurfaceValue += 1
let id = BrownfieldSurfaceID(rawValue: nextSurfaceValue)
surfaces[id] = Surface(isOnScreen: isOnScreen, shownAt: 0)
return id
}

func unregister(_ surface: BrownfieldSurfaceID) {
lock.lock()
defer { lock.unlock() }

surfaces.removeValue(forKey: surface)
}

/// Records that a surface was just shown, ordering it ahead of other on-screen
/// surfaces. Only a tiebreaker — a surface never marked shown can still win
/// when it is the one on screen.
func markShown(_ surface: BrownfieldSurfaceID) {
lock.lock()
defer { lock.unlock() }

guard var entry = surfaces[surface] else { return }

nextShownValue += 1
entry.shownAt = nextShownValue
surfaces[surface] = entry
}

/// The single surface allowed to handle `popToNative()`, or `nil` when no
/// React Native surface is on screen.
func popTarget() -> BrownfieldSurfaceID? {
lock.lock()
let candidates = surfaces
lock.unlock()

return candidates
.filter { $0.value.isOnScreen() }
.max { lhs, rhs in
(lhs.value.shownAt, lhs.key.rawValue) < (rhs.value.shownAt, rhs.key.rawValue)
}?
.key
}

func isPopTarget(_ surface: BrownfieldSurfaceID) -> Bool {
popTarget() == surface
}
}
39 changes: 34 additions & 5 deletions packages/react-native-brownfield/ios/Views/ReactNativeView.swift
Original file line number Diff line number Diff line change
@@ -1,20 +1,38 @@
import SwiftUI

/**
Links a SwiftUI `ReactNativeView` to the view controller it hosts, so the
SwiftUI layer can ask whether this surface may act on `popToNative()`.
*/
final class BrownfieldSurfaceHost {
weak var controller: ReactNativeViewController?

var isPopTarget: Bool { controller?.isPopTarget ?? false }
}

/**
A UIViewControllerRepresentable that bridges ReactNativeViewController to SwiftUI.
*/
struct ReactNativeViewRepresentable: UIViewControllerRepresentable {
var moduleName: String
var initialProperties: [String: Any] = [:]
var host: BrownfieldSurfaceHost

func makeUIViewController(context: Context) -> UIViewController {
return ReactNativeViewController(
let controller = ReactNativeViewController(
moduleName: moduleName,
initialProperties: initialProperties
)
controller.isHostedBySwiftUI = true
host.controller = controller
return controller
}

func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
if let controller = uiViewController as? ReactNativeViewController {
host.controller = controller
}
}
}

/**
Expand All @@ -24,6 +42,7 @@ struct ReactNativeViewRepresentable: UIViewControllerRepresentable {
@available(iOS 15.0, *)
public struct ReactNativeView: View {
@Environment(\.dismiss) var dismiss
@State private var host = BrownfieldSurfaceHost()
var moduleName: String
var initialProperties: [String: Any] = [:]

Expand All @@ -35,11 +54,21 @@ public struct ReactNativeView: View {
public var body: some View {
ReactNativeViewRepresentable(
moduleName: moduleName,
initialProperties: initialProperties
initialProperties: initialProperties,
host: host
)
.ignoresSafeArea(.all)
.onReceive(NotificationCenter.default.publisher(for: NSNotification.Name.popToNative))
{ notification in
// `.popToNative` is public API and may be posted from any thread, while
// `host.isPopTarget` reads UIKit state — so deliver on main.
.onReceive(
NotificationCenter.default
.publisher(for: NSNotification.Name.popToNative)
.receive(on: DispatchQueue.main)
) { _ in
// Every live surface receives this app-wide notification; only the
// topmost on-screen one may dismiss.
// https://github.com/callstack/react-native-brownfield/issues/354
guard host.isPopTarget else { return }
dismiss()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,25 @@ internal import EXUpdates
@objc public class ReactNativeViewController: UIViewController {
private var moduleName: String
private var initialProperties: [String: Any]?
/// Identifies this surface in `BrownfieldSurfaceRegistry`, which decides
/// which single surface may act on `popToNative()`.
private var surfaceID: BrownfieldSurfaceID?

/// Set by `ReactNativeView`. SwiftUI owns its navigation state, so an
/// imperative `popViewController` is reverted; the SwiftUI host dismisses
/// instead and this controller stands down.
internal var isHostedBySwiftUI = false

/// True from the start of a disappearance transition until the surface next
/// appears. `view.window` stays non-nil for the whole animation, so this is
/// what distinguishes "the host already dismissed us" from "nothing happened".
private var isDisappearing = false

/// Whether this surface is the one allowed to act on `popToNative()`.
internal var isPopTarget: Bool {
guard let surfaceID else { return false }
return BrownfieldSurfaceRegistry.shared.isPopTarget(surfaceID)
}

#if canImport(EXUpdates)
private let expoUpdatesDelegate = ReactNativeExpoUpdatesDelegate()
Expand Down Expand Up @@ -39,6 +58,12 @@ internal import EXUpdates
#if !canImport(EXUpdates)
renderReactNativeView()
#endif

// Visibility is resolved live: SwiftUI recreates hosted controllers, so a
// cached lifecycle flag is stale when the notification arrives.
surfaceID = BrownfieldSurfaceRegistry.shared.register { [weak self] in
self?.viewIfLoaded?.window != nil
}

NotificationCenter.default.addObserver(
self,
Expand All @@ -56,8 +81,31 @@ internal import EXUpdates
}
}

public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

isDisappearing = false

// Ordered here rather than in `viewDidAppear`: during a modal presentation
// the covered surface is still in a window, so waiting for `viewDidAppear`
// would let it out-rank the surface being presented over it.
if let surfaceID {
BrownfieldSurfaceRegistry.shared.markShown(surfaceID)
}
}

public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)

isDisappearing = true
}

deinit {
NotificationCenter.default.removeObserver(self)

if let surfaceID {
BrownfieldSurfaceRegistry.shared.unregister(surfaceID)
}
}

@objc private func togglePopGestureRecognizer(_ notification: Notification) {
Expand All @@ -73,11 +121,82 @@ internal import EXUpdates
guard let userInfo = notification.userInfo,
let animated = userInfo["animated"] as? Bool else { return }

// `.popToNative` is public API, so a host may post it from any thread.
// Everything below reads UIKit state — including the registry's visibility
// check — so hop to main first.
DispatchQueue.main.async { [weak self] in
self?.navigationController?.popViewController(animated: animated)
guard let self else { return }

// The notification is app-wide, so every live surface receives it. Only
// the topmost visible one may act, otherwise surfaces buried under other
// screens tear down the whole navigation stack.
// https://github.com/callstack/react-native-brownfield/issues/354
let target = BrownfieldSurfaceRegistry.shared.popTarget()

guard let surfaceID = self.surfaceID, target == surfaceID else {
if target == nil {
NSLog("[ReactBrownfield] popToNative(): no React Native surface is on screen; ignoring.")
}
return
}

guard self.isHostedBySwiftUI else {
self.popFromNativeNavigationStack(animated: animated)
return
}

// SwiftUI owns its navigation state and reverts an imperative pop, so the
// SwiftUI host dismisses instead. It cannot always succeed though — a
// `ReactNativeView` inside a `UIHostingController` pushed onto a UIKit
// navigation stack has nothing for `dismiss()` to act on. Give the host a
// moment, then fall back, so `popToNative()` is never silently inert.
//
// `isDisappearing` — not the delay — is what makes this safe: a dismiss
// that is merely slow has already begun its transition by the time this
// runs, so a late timer stands down instead of popping a second entry.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
guard let self,
!self.isDisappearing,
self.viewIfLoaded?.window != nil,
// Re-established: the entitlement was resolved before the wait.
self.isPopTarget else { return }

self.popFromNativeNavigationStack(animated: animated)
}
}
}

/// Pops this surface off the host's `UINavigationController`.
///
/// Deliberately does not fall back to `dismiss()` when there is no navigation
/// stack: `presentingViewController` is inherited, so an inline surface hosted
/// inside a presented native screen would tear down that whole screen — the
/// same over-dismissal this fix exists to prevent.
private func popFromNativeNavigationStack(animated: Bool) {
guard let navigationController else { return }

// This controller is usually a child of a host controller (SwiftUI wraps it
// in one), so find the stack entry containing it rather than assuming it is
// itself on the stack — and pop to the entry below that, so a screen pushed
// while we were waiting is not the one that gets popped.
let stack = navigationController.viewControllers
guard let index = stack.firstIndex(where: { $0 === self || self.isDescendant(of: $0) }),
index > 0 else { return }

navigationController.popToViewController(stack[index - 1], animated: animated)
}

private func isDescendant(of controller: UIViewController) -> Bool {
var ancestor = parent

while let current = ancestor {
if current === controller { return true }
ancestor = current.parent
}

return false
}

private func renderReactNativeView() {
guard !moduleName.isEmpty else { return }

Expand Down
Loading