expo-modules-core 58.0.30 → 58.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/ExpoModulesCore.podspec +6 -8
  3. package/android/build.gradle +3 -3
  4. package/android/prebuilt/metadata.json +1 -1
  5. package/android/prebuilt/native-libs.tar.xz +0 -0
  6. package/android/src/main/java/expo/modules/adapters/react/apploader/RNHeadlessAppLoader.kt +2 -3
  7. package/android/src/main/java/expo/modules/kotlin/AppContext.kt +4 -2
  8. package/android/src/main/java/expo/modules/kotlin/sharedobjects/SharedObjectRegistry.kt +6 -2
  9. package/android/src/main/java/expo/modules/v2/AppExpoContext.kt +35 -0
  10. package/android/src/main/java/expo/modules/v2/ExpoModulesV2Host.kt +31 -14
  11. package/expo-module-gradle-plugin/build.gradle.kts +1 -1
  12. package/ios/Core/AppContext.swift +46 -4
  13. package/ios/Core/Arguments/Convertibles.swift +1 -24
  14. package/ios/Core/Coding/JavaScriptCodable+Color.swift +887 -0
  15. package/ios/Core/Coding/JavaScriptCodable+URL.swift +55 -0
  16. package/ios/Core/Convertibles/Convertibles+Color.swift +10 -686
  17. package/ios/Core/Events/EventEmitter.swift +194 -1
  18. package/ios/Core/ExpoModulesMacros.swift +32 -1
  19. package/ios/Core/ExpoPackage.swift +29 -0
  20. package/ios/Core/ModulesProvider.swift +19 -0
  21. package/ios/Core/SharedObjects/SharedObjectRegistry.swift +28 -16
  22. package/ios/Core/Views/SwiftUI/Convertibles+SwiftUI.swift +2 -67
  23. package/ios/Core/Views/SwiftUI/SwiftUIHostingView.swift +5 -1
  24. package/ios/Core/Views/SwiftUI/SwiftUIViewHost.swift +100 -39
  25. package/ios/Core/Views/SwiftUI/SwiftUIVirtualView.swift +1 -0
  26. package/package.json +3 -3
  27. package/prebuilds/output/debug/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  28. package/prebuilds/output/debug/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  29. package/prebuilds/output/headers/xcframeworks/ExpoModulesCoreHeaders.tar.gz +0 -0
  30. package/prebuilds/output/headers/xcframeworks/ExpoModulesWorkletsHeaders.tar.gz +0 -0
  31. package/prebuilds/output/release/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  32. package/prebuilds/output/release/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  33. package/spm.config.json +5 -1
@@ -172,6 +172,184 @@ public extension EventEmitter {
172
172
  }
173
173
  }
174
174
 
175
+ public extension EventEmitter {
176
+ /// Emits an event with the given name to the associated JavaScript object. On the JavaScript thread,
177
+ /// the listeners run before this function returns; on any other thread, the event is scheduled, the
178
+ /// same as with `emit`. It never blocks. The `@Event(.inline)` macro calls it.
179
+ @inlinable
180
+ func emitInline(event: String) {
181
+ emitInline(event: event, payload: JavaScriptUndefined())
182
+ }
183
+
184
+ /// Emits an event with the given name and payload to the associated JavaScript object. On the
185
+ /// JavaScript thread, the payload is converted and the listeners run before this function returns; on
186
+ /// any other thread, the event is scheduled, the same as with `emit`. It never blocks.
187
+ ///
188
+ /// Listeners that run inline can call back into the emitter before this function returns, so emit
189
+ /// after the emitter's state is up to date. On the JavaScript thread, the event can reach the
190
+ /// listeners before events that `emit` scheduled earlier. An event emitted before the emitter is paired
191
+ /// with its JavaScript object, for example from a shared object's initializer, is dropped.
192
+ @inlinable
193
+ func emitInline<P: JavaScriptEncodable & ~Copyable>(event: String, payload: consuming sending P) {
194
+ emitInline(event: event, payload: payload) { payload, slot, runtime in
195
+ try P.encode(payload, into: slot, in: runtime)
196
+ }
197
+ }
198
+
199
+ /// Emits an event like `emitInline(event:payload:)`, converting the payload with `encode`. The
200
+ /// `@Event(.inline)` macro uses it for payload types that can't conform to `JavaScriptEncodable`, such
201
+ /// as tuples.
202
+ @inlinable
203
+ func emitInline<P: ~Copyable>(
204
+ event: String,
205
+ payload: consuming sending P,
206
+ encode: @escaping @JavaScriptActor @Sendable (consuming P, borrowing JavaScriptValue.Slot, borrowing JavaScriptRuntime)
207
+ throws -> Void
208
+ ) {
209
+ guard let runtime = eventRuntime(forEvent: event) else {
210
+ return
211
+ }
212
+ // See the note in `emit(event:payload:)` above.
213
+ let emitter = WeakEventEmitterReference(value: self)
214
+ var payload: P? = payload
215
+ if runtime.isOnJavaScriptThread() {
216
+ // Emits right away, without the closure and the box that scheduling needs.
217
+ JavaScriptActor.assumeIsolated {
218
+ guard let emitter = emitter.value else {
219
+ return
220
+ }
221
+ emitEventNow(event: event, payload: &payload, encode: encode, from: emitter, in: runtime)
222
+ }
223
+ return
224
+ }
225
+ // An escaping closure can't consume a captured non-copyable value, so the payload moves into a box.
226
+ let box = EventPayloadBox(payload)
227
+
228
+ runtime.schedule {
229
+ guard let emitter = emitter.value else {
230
+ return
231
+ }
232
+ emitEventNow(event: event, payload: &box.value, encode: encode, from: emitter, in: runtime)
233
+ }
234
+ }
235
+
236
+ /// Emits an event with the given name to the associated JavaScript object. The listeners run before
237
+ /// this function returns, on any thread: a call from another thread blocks until the JavaScript thread
238
+ /// runs them. The `@Event(.blocking)` macro calls it.
239
+ @available(*, noasync)
240
+ @inlinable
241
+ func emitBlocking(event: String) {
242
+ emitBlocking(event: event, payload: JavaScriptUndefined())
243
+ }
244
+
245
+ /// Emits an event with the given name and payload to the associated JavaScript object. The payload is
246
+ /// converted and the listeners run before this function returns, on any thread: on the JavaScript
247
+ /// thread they run inline, and a call from another thread blocks until the JavaScript thread runs them.
248
+ ///
249
+ /// A call from another thread waits for the task that the JavaScript thread is running, so a call from
250
+ /// the main thread freezes the UI while the JavaScript thread is busy, for example while it loads the
251
+ /// bundle. It deadlocks when the JavaScript thread is waiting for the calling thread, for example when
252
+ /// a synchronous function waits for the main thread with `DispatchQueue.main.sync` while the main
253
+ /// thread emits. The event is scheduled with immediate priority, so it can reach the listeners before
254
+ /// events that `emit` scheduled earlier. Use `emitInline(event:payload:)` when the caller doesn't need
255
+ /// to wait.
256
+ ///
257
+ /// `noasync` covers direct calls only. An `@Event(.blocking)` property calls this method from the
258
+ /// closure it returns, so calling the property from an `async` function compiles and blocks a thread
259
+ /// of the cooperative pool.
260
+ @available(*, noasync)
261
+ @inlinable
262
+ func emitBlocking<P: JavaScriptEncodable & ~Copyable>(event: String, payload: consuming sending P) {
263
+ emitBlocking(event: event, payload: payload) { payload, slot, runtime in
264
+ try P.encode(payload, into: slot, in: runtime)
265
+ }
266
+ }
267
+
268
+ /// Emits an event like `emitBlocking(event:payload:)`, converting the payload with `encode`. The
269
+ /// `@Event(.blocking)` macro uses it for payload types that can't conform to `JavaScriptEncodable`,
270
+ /// such as tuples.
271
+ @available(*, noasync)
272
+ @inlinable
273
+ func emitBlocking<P: ~Copyable>(
274
+ event: String,
275
+ payload: consuming sending P,
276
+ encode: @escaping @JavaScriptActor @Sendable (consuming P, borrowing JavaScriptValue.Slot, borrowing JavaScriptRuntime)
277
+ throws -> Void
278
+ ) {
279
+ guard let runtime = eventRuntime(forEvent: event) else {
280
+ return
281
+ }
282
+ // See the note in `emit(event:payload:)` above.
283
+ let emitter = WeakEventEmitterReference(value: self)
284
+ var payload: P? = payload
285
+ if runtime.isOnJavaScriptThread() {
286
+ // See the note in `emitInline(event:payload:encode:)` above.
287
+ JavaScriptActor.assumeIsolated {
288
+ guard let emitter = emitter.value else {
289
+ return
290
+ }
291
+ emitEventNow(event: event, payload: &payload, encode: encode, from: emitter, in: runtime)
292
+ }
293
+ return
294
+ }
295
+ // See the note in `emitInline(event:payload:encode:)` above.
296
+ let box = EventPayloadBox(payload)
297
+
298
+ do {
299
+ try runtime.execute {
300
+ guard let emitter = emitter.value else {
301
+ return
302
+ }
303
+ emitEventNow(event: event, payload: &box.value, encode: encode, from: emitter, in: runtime)
304
+ }
305
+ } catch {
306
+ warnRuntimeLost(event: event, emitterType: type(of: self))
307
+ }
308
+ }
309
+ }
310
+
311
+ /// Holds an event payload until the JavaScript thread takes it, so a closure that escapes can carry a
312
+ /// non-copyable payload. The payload is taken once, on the JavaScript thread.
313
+ @usableFromInline
314
+ internal final class EventPayloadBox<P: ~Copyable>: @unchecked Sendable {
315
+ @usableFromInline
316
+ var value: P?
317
+
318
+ // Not `@inlinable`: with library evolution, an inlinable initializer of a class must delegate to
319
+ // another initializer.
320
+ @usableFromInline
321
+ init(_ value: consuming P?) {
322
+ self.value = consume value
323
+ }
324
+ }
325
+
326
+ /// Takes the payload out of `payload`, converts it with `encode` and sends it to the JavaScript object of
327
+ /// the emitter. Logs a warning when the conversion fails.
328
+ @JavaScriptActor
329
+ @inlinable
330
+ internal func emitEventNow<P: ~Copyable>(
331
+ event: String,
332
+ payload: inout P?,
333
+ encode: (consuming P, borrowing JavaScriptValue.Slot, borrowing JavaScriptRuntime) throws -> Void,
334
+ from emitter: any EventEmitter,
335
+ in runtime: JavaScriptRuntime
336
+ ) {
337
+ guard payload != nil else {
338
+ return
339
+ }
340
+ let jsPayload: JavaScriptValue
341
+ do {
342
+ // A closure can't consume a captured non-copyable value, but it can take it out of an optional.
343
+ jsPayload = try JavaScriptValue.encoding(in: runtime) { slot in
344
+ try encode(payload.take()!, slot, runtime)
345
+ }
346
+ } catch {
347
+ warnNonCopyablePayloadNotEncoded(event: event, payloadType: P.self, error: error)
348
+ return
349
+ }
350
+ dispatchEvent(event: event, payload: jsPayload, from: emitter, in: runtime)
351
+ }
352
+
175
353
  /// A weak reference to an event emitter that the scheduled `emit` closures capture by value, so it is stored
176
354
  /// in the closure context without an allocation of its own. Frozen, because with library evolution the
177
355
  /// inlinable initializer can't assign the stored property of a struct whose layout isn't fixed.
@@ -192,13 +370,19 @@ extension EventEmitter {
192
370
  @usableFromInline
193
371
  internal func eventRuntime(forEvent event: String) -> JavaScriptRuntime? {
194
372
  guard let appContext, let runtime = try? appContext.runtime else {
195
- log.warn("Trying to send event '\(event)' to \(type(of: self)), but the JS runtime has been lost")
373
+ warnRuntimeLost(event: event, emitterType: type(of: self))
196
374
  return nil
197
375
  }
198
376
  return runtime
199
377
  }
200
378
  }
201
379
 
380
+ /// Logs that the runtime was lost before an event could be emitted.
381
+ @usableFromInline
382
+ internal func warnRuntimeLost(event: String, emitterType: Any.Type) {
383
+ log.warn("Trying to send event '\(event)' to \(emitterType), but the JS runtime has been lost")
384
+ }
385
+
202
386
  /// Logs that the payload of an event couldn't be converted, so the event is not emitted.
203
387
  @usableFromInline
204
388
  internal func warnPayloadNotEncoded(event: String, payloadType: Any.Type, error: any Error) {
@@ -207,6 +391,15 @@ internal func warnPayloadNotEncoded(event: String, payloadType: Any.Type, error:
207
391
  )
208
392
  }
209
393
 
394
+ /// Logs that the payload of an event couldn't be converted, like `warnPayloadNotEncoded`, for a payload
395
+ /// type that may be non-copyable: such a metatype doesn't convert to `Any.Type`.
396
+ @usableFromInline
397
+ internal func warnNonCopyablePayloadNotEncoded(event: String, payloadType: any (~Copyable).Type, error: any Error) {
398
+ log.warn(
399
+ "Failed to convert payload for event '\(event)' on \(payloadType); the event will not be emitted: \(error)"
400
+ )
401
+ }
402
+
210
403
  /// Sends a pre-converted event payload to the JavaScript object of the given emitter. Logs a warning
211
404
  /// when the emitter is no longer associated with a JavaScript object.
212
405
  @JavaScriptActor
@@ -87,6 +87,29 @@ public macro JS(_ jsName: String? = nil, _ options: JSOptions...) =
87
87
  public macro JS(_ options: JSOptions...) =
88
88
  #externalMacro(module: "ExpoModulesMacros", type: "JSMacro")
89
89
 
90
+ /// Options passed to `@Event` after the optional JS name, e.g. `@Event(.inline)` or
91
+ /// `@Event("tick", .blocking)`. The macro reads them from the source, so spell them as `.option`
92
+ /// literals rather than constants. Without an option, the event is scheduled on the JavaScript thread
93
+ /// and the listeners run later. An event property is callable from any thread with each option.
94
+ public enum EventOptions {
95
+ /// Runs the listeners before the call returns when it is made on the JavaScript thread, for example
96
+ /// from a synchronous function. On any other thread, the event is scheduled, the same as without an
97
+ /// option. It never blocks. The listeners can call back into the module or shared object before the
98
+ /// call returns, so emit after its state is up to date. On the JavaScript thread, the event can reach
99
+ /// the listeners before events emitted earlier without an option. An event emitted before the shared
100
+ /// object is paired with its JavaScript object, for example from its initializer, is dropped.
101
+ case inline
102
+
103
+ /// Runs the listeners before the call returns, on any thread. A call from another thread blocks until
104
+ /// the JavaScript thread runs them: from the main thread it freezes the UI while the JavaScript thread
105
+ /// is busy, and it deadlocks when the JavaScript thread is waiting for the calling thread, for example
106
+ /// in `DispatchQueue.main.sync` while the main thread emits. The event can reach the listeners before
107
+ /// events emitted earlier without an option. Don't call the property from an `async` function: it
108
+ /// would block a thread of the cooperative pool, and the compiler doesn't report it. Prefer `.inline`
109
+ /// unless the caller must wait for the listeners.
110
+ case blocking
111
+ }
112
+
90
113
  /// Turns a function-typed `var` on a module or shared object into a typed JavaScript event.
91
114
  /// Calling the property emits the event to JavaScript, with the closure's parameter as the payload.
92
115
  ///
@@ -101,9 +124,17 @@ public macro JS(_ options: JSOptions...) =
101
124
  ///
102
125
  /// // Emit it from anywhere:
103
126
  /// onProgress(ProgressEvent(percent: 50))
127
+ ///
128
+ /// Trailing `EventOptions` tune the event. The options-only overload exists because an option can't
129
+ /// fill the unlabeled `name` slot.
130
+ @attached(accessor)
131
+ @attached(peer, names: arbitrary)
132
+ public macro Event(_ name: String? = nil, _ options: EventOptions...) =
133
+ #externalMacro(module: "ExpoModulesMacros", type: "EventMacro")
134
+
104
135
  @attached(accessor)
105
136
  @attached(peer, names: arbitrary)
106
- public macro Event(_ name: String? = nil, sync: Bool = false) =
137
+ public macro Event(_ options: EventOptions...) =
107
138
  #externalMacro(module: "ExpoModulesMacros", type: "EventMacro")
108
139
 
109
140
  /// Member macro applied to a `Module` subclass. Scans the class body for declarations
@@ -0,0 +1,29 @@
1
+ // Copyright 2026-present 650 Industries. All rights reserved.
2
+
3
+ /**
4
+ The native exports of one npm package that are declared with the Expo Modules API 2.0 macros: its modules
5
+ and shared object classes. A modules provider returns the packages keyed by the npm package name, and that name
6
+ is the JS name of the package.
7
+ Local and inline modules are in the `$local` package.
8
+ */
9
+ public struct ExpoPackage {
10
+ /**
11
+ Name of the package of local and inline modules. It can't be the name of an npm package.
12
+ */
13
+ public static let localPackageName = "$local"
14
+
15
+ /**
16
+ Module classes of the package.
17
+ */
18
+ public let modules: [AnyModule.Type]
19
+
20
+ /**
21
+ Shared object classes of the package. They are exported next to the modules, not as members of a module.
22
+ */
23
+ public let sharedObjects: [SharedObject.Type]
24
+
25
+ public init(modules: [AnyModule.Type] = [], sharedObjects: [SharedObject.Type] = []) {
26
+ self.modules = modules
27
+ self.sharedObjects = sharedObjects
28
+ }
29
+ }
@@ -6,6 +6,12 @@ import Foundation
6
6
  public protocol ModulesProviderProtocol {
7
7
  typealias ExpoModuleTupleType = (module: AnyModule.Type, name: String?)
8
8
 
9
+ /**
10
+ The packages that provide modules declared with the Expo Modules API 2.0 macros, keyed by the npm package name.
11
+ Their modules are also in `getModuleClasses()`, which is the list that the module registry registers.
12
+ */
13
+ var packages: [String: ExpoPackage] { get }
14
+
9
15
  func getModuleClasses() -> [ExpoModuleTupleType]
10
16
 
11
17
  /**
@@ -22,6 +28,15 @@ public protocol ModulesProviderProtocol {
22
28
  func getAppCodeSignEntitlements() -> AppCodeSignEntitlements
23
29
  }
24
30
 
31
+ public extension ModulesProviderProtocol {
32
+ /**
33
+ Providers that conform to the protocol directly, without inheriting from `ModulesProvider`, have no packages by default.
34
+ */
35
+ var packages: [String: ExpoPackage] {
36
+ return [:]
37
+ }
38
+ }
39
+
25
40
  /**
26
41
  The default implementation for modules provider.
27
42
  The proper implementation is generated by autolinking as part of `pod install` command.
@@ -30,6 +45,10 @@ public protocol ModulesProviderProtocol {
30
45
  open class ModulesProvider: NSObject, ModulesProviderProtocol {
31
46
  public override required init() {}
32
47
 
48
+ open var packages: [String: ExpoPackage] {
49
+ return [:]
50
+ }
51
+
33
52
  open func getModuleClasses() -> [ExpoModuleTupleType] {
34
53
  return []
35
54
  }
@@ -180,25 +180,37 @@ public final class SharedObjectRegistry: Sendable {
180
180
  Deletes the shared objects pair with a given ID.
181
181
  */
182
182
  internal func delete(_ id: SharedObjectId) {
183
- state.withLock { state in
184
- if let nativeState = state.pairs[id] {
185
- let native = nativeState.native
186
- nativeState.markReleased()
187
-
188
- // Delete the entry from the dictionary.
189
- state.pairs[id] = nil
190
-
191
- // A native object that was paired again after its JS object died has a new native state and ID,
192
- // and stays paired.
193
- guard native.nativeState === nativeState else {
194
- return
195
- }
196
- native.sharedObjectWillRelease()
197
- // Reset an ID on the object.
183
+ let released: (native: SharedObject, nativeState: SharedObjectNativeState)? = state.withLock { state in
184
+ guard let nativeState = state.pairs[id] else {
185
+ return nil
186
+ }
187
+ let native = nativeState.native
188
+ nativeState.markReleased()
189
+
190
+ // Delete the entry from the dictionary.
191
+ state.pairs[id] = nil
192
+
193
+ // A native object that was paired again after its JS object died has a new native state and ID,
194
+ // and stays paired.
195
+ guard native.nativeState === nativeState else {
196
+ return nil
197
+ }
198
+ return (native, nativeState)
199
+ }
200
+ guard let released else {
201
+ return
202
+ }
203
+ let native = released.native
204
+ // The hooks run without the lock: they can emit events whose listeners run inline on the JavaScript
205
+ // thread and use the registry again, and the lock isn't reentrant.
206
+ native.sharedObjectWillRelease()
207
+ // Reset an ID on the object, unless the hook paired it again.
208
+ state.withLock { _ in
209
+ if native.nativeState === released.nativeState {
198
210
  native.sharedObjectId = 0
199
- native.sharedObjectDidRelease()
200
211
  }
201
212
  }
213
+ native.sharedObjectDidRelease()
202
214
  }
203
215
 
204
216
  /**
@@ -4,77 +4,12 @@ import SwiftUI
4
4
 
5
5
  extension Color: Convertible {
6
6
  public static func convert(from value: Any?) throws -> Color {
7
- // Simply reuse the logic from UIColor
8
- if let uiColor = try? UIColor.convert(from: value) {
9
- return Color(uiColor)
10
- }
11
- // Context-dependent colors
12
- if let stringValue = value as? String, let color = colorFromName(stringValue) {
13
- return color
14
- }
15
- throw Conversions.ConvertingException<Color>(value)
7
+ return try swiftUIColorFromAny(value)
16
8
  }
9
+
17
10
  public static func convert(from value: Any?, appContext: AppContext) throws -> Color {
18
11
  return try convert(from: value)
19
12
  }
20
-
21
- private static func colorFromName(_ name: String) -> Color? {
22
- switch name {
23
- case "primary":
24
- return .primary
25
- case "secondary":
26
- return .secondary
27
- case "red":
28
- return .red
29
- case "orange":
30
- return .orange
31
- case "yellow":
32
- return .yellow
33
- case "green":
34
- return .green
35
- case "blue":
36
- return .blue
37
- case "purple":
38
- return .purple
39
- case "pink":
40
- return .pink
41
- case "white":
42
- return .white
43
- case "gray":
44
- return .gray
45
- case "black":
46
- return .black
47
- case "clear":
48
- return .clear
49
- case "mint":
50
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
51
- return .mint
52
- }
53
- return nil
54
- case "teal":
55
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
56
- return .teal
57
- }
58
- return nil
59
- case "cyan":
60
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
61
- return .cyan
62
- }
63
- return nil
64
- case "indigo":
65
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
66
- return .indigo
67
- }
68
- return nil
69
- case "brown":
70
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
71
- return .brown
72
- }
73
- return nil
74
- default:
75
- return nil
76
- }
77
- }
78
13
  }
79
14
 
80
15
  extension UnitPoint: Convertible {
@@ -189,6 +189,7 @@ extension ExpoSwiftUI {
189
189
  }
190
190
 
191
191
  if let children = props.children {
192
+ (children.first(where: { $0.id == childViewId }) as? UIViewHost)?.didUnmount()
192
193
  props.children = children.filter({ $0.id != childViewId })
193
194
  #if DEBUG
194
195
  assert(props.children?.count == children.count - 1, "Failed to remove child view")
@@ -240,8 +241,11 @@ extension ExpoSwiftUI {
240
241
  parentController?.addChild(hostingController)
241
242
  #else
242
243
  guard let parentController else {
243
- hostingController.view.removeFromSuperview()
244
+ // Mounted on the window with no view controller, as `FullWindowOverlay` does.
245
+ // Render without containment.
244
246
  hostingController.removeFromParent()
247
+ addSubview(hostingController.view)
248
+ setupHostingViewConstraints()
245
249
  return
246
250
  }
247
251
  // `reactViewController()` walks the responder chain, which may not match the view hierarchy:
@@ -6,51 +6,24 @@ extension ExpoSwiftUI {
6
6
  /**
7
7
  SwiftUI view that embeds a UIKit-based view.
8
8
  */
9
- struct UIViewHost: UIViewRepresentable, AnyChild {
9
+ struct UIViewHost: SwiftUI.View, AnyChild {
10
10
  let view: UIView
11
11
  // Fabric can mount a recycled view again; a new identity per mount gives it a new container.
12
12
  private let mountToken = MountToken()
13
13
 
14
- // MARK: - UIViewRepresentable implementations
15
-
16
- #if os(macOS)
17
- func makeNSView(context: Context) -> NSView {
18
- return view
19
- }
20
-
21
- func updateNSView(_ nsView: NSView, context: Context) {
22
- // Nothing to do here
23
- }
24
- #endif
25
-
26
- func makeUIView(context: Context) -> UIView {
14
+ var body: some SwiftUI.View {
27
15
  #if os(macOS)
28
- return view
16
+ HostedViewRepresentable(view: view)
29
17
  #else
30
- // SwiftUI mutates the view it hosts (autoresizingMask, frame, visibility), sometimes
31
- // asynchronously after teardown, corrupting unmounted or recycled React views.
32
- // Hand it a disposable container instead. Fixes expo/expo#47706; supersedes the #40604 mitigation.
33
- let container = ReactViewIsolationContainer()
34
- container.hostedView = view
35
- container.addSubview(view)
36
- return container
18
+ HostedView(view: view, mountToken: mountToken)
37
19
  #endif
38
20
  }
39
21
 
40
- func updateUIView(_ uiView: UIView, context: Context) {
41
- // Nothing to do here
42
- }
43
-
44
- static func dismantleUIView(_ uiView: UIView, coordinator: Coordinator) {
45
- // Nothing to restore — SwiftUI only ever touched the container.
46
- }
47
-
48
- func makeCoordinator() -> Coordinator {
49
- Coordinator()
50
- }
51
-
52
- class Coordinator {
53
- init() {}
22
+ /**
23
+ Call when Fabric unmounts the view. Fabric can recycle it, so containers of this mount must not take it back.
24
+ */
25
+ func didUnmount() {
26
+ mountToken.isMounted = false
54
27
  }
55
28
 
56
29
  // MARK: - AnyChild implementations
@@ -72,15 +45,103 @@ extension ExpoSwiftUI {
72
45
  }
73
46
  }
74
47
 
75
- private final class MountToken {}
48
+ private final class MountToken {
49
+ var isMounted = true
50
+ }
51
+
52
+ #if os(macOS)
53
+ private struct HostedViewRepresentable: NSViewRepresentable {
54
+ let view: NSView
55
+
56
+ func makeNSView(context: Context) -> NSView {
57
+ return view
58
+ }
59
+
60
+ func updateNSView(_ nsView: NSView, context: Context) {
61
+ // Nothing to do here
62
+ }
63
+ }
64
+ #else
65
+ // SwiftUI can show one child in more than one place, such as a `List` cell it only measures.
66
+ // The view can be in only one container, so the instance that appears in a window takes it.
67
+ private struct HostedView: SwiftUI.View {
68
+ let view: UIView
69
+ let mountToken: MountToken
70
+ @State private var appearance = Appearance()
71
+
72
+ var body: some SwiftUI.View {
73
+ HostedViewRepresentable(view: view, mountToken: mountToken, appearance: appearance)
74
+ .onAppear { appearance.isAppeared = true }
75
+ .onDisappear { appearance.isAppeared = false }
76
+ }
77
+ }
78
+
79
+ @MainActor
80
+ private final class Appearance {
81
+ weak var container: ReactViewIsolationContainer?
82
+ var isAppeared = false {
83
+ didSet { container?.takeViewIfShown() }
84
+ }
85
+ }
86
+
87
+ private struct HostedViewRepresentable: UIViewRepresentable {
88
+ let view: UIView
89
+ let mountToken: MountToken
90
+ let appearance: Appearance
91
+
92
+ func makeUIView(context: Context) -> ReactViewIsolationContainer {
93
+ // SwiftUI mutates the view it hosts (autoresizingMask, frame, visibility), sometimes
94
+ // asynchronously after teardown, corrupting unmounted or recycled React views.
95
+ // Hand it a disposable container instead. Fixes expo/expo#47706; supersedes the #40604 mitigation.
96
+ let container = ReactViewIsolationContainer(hostedView: view, mountToken: mountToken, appearance: appearance)
97
+ appearance.container = container
98
+ if view.superview == nil {
99
+ container.addSubview(view)
100
+ }
101
+ return container
102
+ }
103
+
104
+ func updateUIView(_ container: ReactViewIsolationContainer, context: Context) {
105
+ // Nothing to do here
106
+ }
107
+ }
76
108
 
77
- #if !os(macOS)
78
109
  /**
79
110
  Disposable UIView handed to SwiftUI in place of the React-managed view —
80
- see `UIViewHost.makeUIView`.
111
+ see `HostedViewRepresentable.makeUIView`.
81
112
  */
82
113
  private final class ReactViewIsolationContainer: UIView {
83
114
  weak var hostedView: UIView?
115
+ let mountToken: MountToken
116
+ let appearance: Appearance
117
+
118
+ init(hostedView: UIView, mountToken: MountToken, appearance: Appearance) {
119
+ self.hostedView = hostedView
120
+ self.mountToken = mountToken
121
+ self.appearance = appearance
122
+ super.init(frame: .zero)
123
+ }
124
+
125
+ @available(*, unavailable)
126
+ required init?(coder: NSCoder) {
127
+ fatalError("init(coder:) has not been implemented")
128
+ }
129
+
130
+ override func didMoveToWindow() {
131
+ super.didMoveToWindow()
132
+ takeViewIfShown()
133
+ }
134
+
135
+ func takeViewIfShown() {
136
+ guard mountToken.isMounted, let hostedView, window != nil, hostedView.superview !== self,
137
+ appearance.isAppeared || hostedView.superview == nil else {
138
+ return
139
+ }
140
+ addSubview(hostedView)
141
+ if !bounds.isEmpty {
142
+ hostedView.frame = bounds
143
+ }
144
+ }
84
145
 
85
146
  override func layoutSubviews() {
86
147
  super.layoutSubviews()
@@ -391,6 +391,7 @@ private func virtualViewUnmountChild<Props: ExpoSwiftUI.ViewProps>(_ childCompon
391
391
  }
392
392
 
393
393
  if let children = props.children {
394
+ (children.first(where: { $0.id == childViewId }) as? ExpoSwiftUI.UIViewHost)?.didUnmount()
394
395
  props.children = children.filter({ $0.id != childViewId })
395
396
  #if DEBUG
396
397
  assert(props.children?.count == children.count - 1, "Failed to remove child view")