@onekeyfe/react-native-native-overlay 6.7.0-23 → 6.7.0-24

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.
package/docs/SPEC.md CHANGED
@@ -129,8 +129,9 @@ come only from props.
129
129
  - `reopen(id)` restores a closing entry to active, cancels its fallback timer,
130
130
  and keeps its ordering, content and removal handler. A declarative
131
131
  false-to-true change before exit completion uses this path; it does not
132
- report a completed close. Hosts retarget the in-flight animation, including
133
- cancelling the host-requested UIKit sheet dismissal when still running.
132
+ report a completed close. Hosts retarget the in-flight animation except iOS
133
+ global system sheets, which complete their own native exit before reconciling
134
+ desired visibility with a new controller and the same React child.
134
135
  - Removing a queued entry detaches its removal handler before notifying store
135
136
  subscribers or scheduling its callback. Same-tick reuse of that ID owns a
136
137
  separate handler; the old removal cannot invoke or delete the new handler.
@@ -252,7 +253,9 @@ request ─► queued ─► active ─► (enter anim) presented
252
253
  finalized, so exit and enter never overlap. `replace` is the exception: the
253
254
  new entry enters while the replaced one exits.
254
255
  - Reopening an entry that is still closing retargets the running animation from
255
- its current value. It does not restart.
256
+ its current value without restarting, except iOS global system sheets: those
257
+ finish their own exit, then re-present if still desired visible. The entry and
258
+ React content survive without a terminal event; its own controller may change.
256
259
  - `onRemoved` fires exactly once per entry, even when a finalize and the
257
260
  timeout race.
258
261
  - **Android exit ownership (Implemented; blocking page/global touch and global
@@ -284,6 +287,70 @@ request ─► queued ─► active ─► (enter anim) presented
284
287
  - Threads: store mutations happen on the JS thread. Native animation and layout
285
288
  run on the UI thread. Events are delivered as direct events.
286
289
 
290
+ ### Independent iOS global windows
291
+
292
+ Implemented; the final v3 independently passed core OneKey/Fabric Gallery
293
+ verification on iOS 27.0. See [IOS_OVERLAY_ACCEPTANCE.md](../../../IOS_OVERLAY_ACCEPTANCE.md)
294
+ for covered paths and unverified boundaries; the full runtime matrix below is
295
+ not marked complete. iOS
296
+ `main` owns the React store/content; `bg` has an independent JS heap and does
297
+ not own these resources. The native manager is process-shared and confined to
298
+ the main thread. Each scene owns one passthrough UIWindow/root presenter per
299
+ active global entry, for every presentation kind. A system sheet presents only
300
+ from its own root, so closing any other global entry MUST NOT dismiss,
301
+ reconstruct, reparent, or emit terminal events for the surviving entries.
302
+ Independent transparent roots do not apply UIKit presentation-chain push-back
303
+ scaling to lower entries. Each sheet retains its own system geometry and motion.
304
+ React parent unmounting can still unmount a child overlay; native isolation does
305
+ not change React ownership. Public APIs, Android/Web, and page scope are unchanged.
306
+
307
+ - Preserve the real UISheetPresentationController, custom detent, existing
308
+ transition animator/dimming, content width, Fabric touch/staging/measurement,
309
+ contentSize, status/orientation and React Native dimension correction paths.
310
+ - Order windows by level then stackOrder, using a stable native entry sequence
311
+ only to break ties. Recompute a bounded fractional rank in [0, 1) above each
312
+ existing level base; raw/unbounded stackOrder MUST NOT increase the level band.
313
+ Live stackOrder updates reorder the same windows without making them key.
314
+ Level/strategy changes apply only to the next open cycle, matching the JS
315
+ store. Keep the initial effective global level through this entry's own
316
+ non-terminal re-presentation; clear it on terminal close or invalidation.
317
+ - Preserve existing touch-driven input activation. Removing a non-key window
318
+ MUST NOT change the key window or a surviving first responder. Removing the
319
+ key window restores the highest-ranked desired-visible, attached, non-closing eligible
320
+ entry in the same scene, otherwise the app window. Eligible entries are
321
+ effectively blocking (system sheets always block), or actually contain a
322
+ first responder; passive toast/debug entries do not win solely by level.
323
+ Keyboard restoration may finish after dismissal completion; callers/tests
324
+ requiring keyboard geometry must observe the new keyboard readiness event.
325
+ - Every presentation lifetime has a generation. Asynchronous present, dismiss,
326
+ and animation completions must match the generation, controller/entry
327
+ identity and applicable phase before changing state or emitting callbacks.
328
+ Close during enter waits for that entry's presentation completion. Reopening
329
+ an exiting global system sheet records the latest desired visibility and
330
+ waits for its own native dismissal completion. If still desired visible, it
331
+ stages the same React child and presents a new owned window/controller without
332
+ emitting a terminal event. Its draft/mount survive; its own controller may
333
+ change. Only an entry that was key when dismissal began may weakly retain its
334
+ original first responder. After re-presentation completes, restore that input
335
+ once only if it still belongs to the same child, the entry remains highest
336
+ eligible in an active scene, no newer input in that window replaced it, and
337
+ the current key belongs to the app or this manager without a higher entry
338
+ owning key. Foreign/system key ownership prevents restoration. A non-key
339
+ lower entry never captures focus for its reopen. Non-sheet reversal is
340
+ unchanged. No timer/retry, cross-entry polling, business queue or scene-wide
341
+ transition lock is introduced.
342
+ - Invalidate, owner detachment and scene-disconnect invalidate obsolete work,
343
+ detach only the owned touch handler, stage the owned child and release only
344
+ the owned window/root. Scene disconnect callbacks identify their original
345
+ window lifetime: an owner already cleaned up by nested detachment, or now
346
+ owning another window, must ignore a stale callback. An entry cannot register
347
+ in a scene while that scene's disconnect callbacks run. Scene disconnect
348
+ actively releases its resources; cleanup does not depend on another entry
349
+ opening. A terminal native event is emitted at most once per close; timer
350
+ expiry is not native completion.
351
+ - An entry with a presenter that is not ready remains owned by its current
352
+ generation; stale deferred work cannot reopen or release a later generation.
353
+
287
354
  ### Web presentation updates (OK-50653)
288
355
 
289
356
  For an open Web overlay that keeps its portal host, changing `presentation`
@@ -472,15 +539,15 @@ a non-blocking entry remains pointer-transparent.
472
539
 
473
540
  | Concern | iOS | Android | Web |
474
541
  | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
475
- | Global level host | One passthrough `UIWindow` per active level per `UIWindowScene`, ordered by `windowLevel`. `lock` sits above RN Alert (2001). | One `OverlayHost` FrameLayout in `android.R.id.content` above the ReactRootView, with one child container per level. | Sibling `div[data-onekey-layer]` roots under `body`, one z-index band per level (`OVERLAY_WEB_Z_INDEX_BASE`). |
476
- | Order within a level | The window's presentation chain (sheet) and subview order (other presentations). | Child order. | DOM order. |
477
- | Global sheet | `UISheetPresentationController`, presented from the level window's root VC (reuses native-sheet). | View sheet: CoordinatorLayout + BottomSheetBehavior + dimming view (native-sheet reworked off `BottomSheetDialog`). | Custom sheet: pointer drag, snap by velocity, `visualViewport` keyboard. |
542
+ | Global level host | One passthrough `UIWindow`/root per active global entry per `UIWindowScene`; bounded ranks preserve level bands. `lock` sits above RN Alert (2001). | One `OverlayHost` FrameLayout in `android.R.id.content` above the ReactRootView, with one child container per level. | Sibling `div[data-onekey-layer]` roots under `body`, one z-index band per level (`OVERLAY_WEB_Z_INDEX_BASE`). |
543
+ | Order within a level | Entry window rank by stackOrder, with stable native tie-breaking across all presentations. | Child order. | DOM order. |
544
+ | Global sheet | `UISheetPresentationController`, presented only from the entry window's own root VC (reuses native-sheet). | View sheet: CoordinatorLayout + BottomSheetBehavior + dimming view (native-sheet reworked off `BottomSheetDialog`). | Custom sheet: pointer drag, snap by velocity, `visualViewport` keyboard. |
478
545
  | Page host | Fabric `PageOverlayHost` as the last child of the root-route screen. Custom-drawn sheet, because UIKit sheets cannot be page-scoped. | The same host inside the root-route screen. The ReactRootView already dispatches touches, so no nested RootView. | `position: absolute` host inside the root-route card. |
479
546
  | Header / tab bar coverage (page) | Covered: the host is above the tab controller and navigation bars. | Covered. | Covered. |
480
547
  | Touch passthrough (toast, debug, box-none) | `hitTest` returns nil on the window or root view. | A non-blocking entry hit-tests its React content with `TouchTargetHelper` (honoring `box-none`) and falls through to the FrameLayout sibling on a miss. | `pointer-events: none` root, `auto` per entry. |
481
548
  | Back / Escape | Escape via `accessibilityPerformEscape`. The interactive pop gesture is disabled while a blocking page overlay is shown. | A `Window.Callback` wrapper consumes `KEYCODE_BACK` for the topmost input-ready blocking or dismissible overlay. `ReactActivity.onBackPressed` hands back to JS BackHandler (react-navigation) before the `OnBackPressedDispatcher`, and the app opts out of predictive back, so a dispatcher callback alone never runs first. The dispatcher callback is kept for the predictive-back path. The IME still gets back first to close the keyboard. | Capture-phase `keydown` that ignores IME composition. |
482
- | Modality / accessibility | `accessibilityViewIsModal` on the blocking level window; `.screenChanged` posted on present. | `IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS` on the content below. | `inert` on the app root and lower layers, `role=dialog`, `aria-modal`, focus trap and restore. |
483
- | Keyboard | System sheet avoidance; `keyboardLayoutGuide` for custom presentations. The main window regains key status on dismiss. | `WindowInsetsAnimationCompat` per sheet (the app uses `adjustPan`). | `visualViewport`. |
549
+ | Modality / accessibility | `accessibilityViewIsModal` on blocking EntryViews; sheets retain UIKit modality. `.screenChanged` on present; cross-window VoiceOver remains pending. | `IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS` on the content below. | `inert` on the app root and lower layers, `role=dialog`, `aria-modal`, focus trap and restore. |
550
+ | Keyboard | System sheet avoidance and custom keyboard layer. Only key-entry removal restores an eligible same-scene entry or app window. | `WindowInsetsAnimationCompat` per sheet (the app uses `adjustPan`). | `visualViewport`. |
484
551
  | Animation engine | `UIViewPropertyAnimator` + `UISpringTimingParameters(mass:stiffness:damping:)`, which maps 1:1 and supports damping ratio > 1. | `SpringAnimation` with `stiffness = k/m` and `dampingRatio`; `PathInterpolator` for timing curves. | WAAPI `element.animate`. Timing presets use `cubic-bezier`; custom springs use `linear()`. |
485
552
  | Content hosting | `RCTSurfaceTouchHandler` on the host root. A state-driven shadow node sizes Yoga, which replaces native-sheet's forced `frame`. A nested `SafeAreaProvider`. | A `RootView` + `JSTouchDispatcher` container for global levels. A state-driven shadow node, like RN Modal. | `createPortal`. The Tamagui theme class is set on the layer root, and React event bubbling stops at the entry root. |
486
553
 
@@ -534,8 +601,11 @@ of these UIKit resources. Native logger persistence is owned by the logger.
534
601
 
535
602
  ## 5.8 Performance and resource budget
536
603
 
537
- - iOS level windows are created lazily per active level and hidden when empty.
538
- There are at most 6 per scene.
604
+ - iOS entry windows are created lazily and released after their entry detaches.
605
+ Window count is O(active global entries) per scene, rather than a six-window
606
+ level cache. No new public limit/configuration is introduced; page entries
607
+ remain views. Re-ranking is O(n log n) for the affected scene and creates no
608
+ per-frame bridge work.
539
609
  - Android layers are views, not windows: no extra surfaces or WindowManager IPC.
540
610
  - Store operations are O(n) in the number of live entries. Snapshots are
541
611
  rebuilt once per mutation.
@@ -569,6 +639,16 @@ navigation remains a separate runtime acceptance item.
569
639
 
570
640
  Automated (P0):
571
641
 
642
+ - `tests/ios/run.sh` compiles the production WindowManager, SheetController and
643
+ Animation into an isolated UIKit test app. Its seven checks cover bounded/live
644
+ ordering, key restoration eligibility, owning-entry release, injected scene
645
+ disconnect/reuse with original-window identity and reentrant-registration
646
+ rejection, conditional original-input focus restoration (including
647
+ higher/foreign/new-input guards), and a native sheet surviving another
648
+ entry's dismissal.
649
+ Sheet checks use `animated: false`; they do not compile the React/Fabric
650
+ Container or replace Gallery coverage of animated reversal/generation races,
651
+ real multi-scene/disconnect, keyboard geometry or accessibility.
572
652
  - `src/__tests__/focusTrap.web.test.ts` mounts real Web overlays and checks
573
653
  both Tab boundaries, root/empty fallback, inaccessible children, positive
574
654
  tabindex order, top-entry precedence, page scope, suspension and parking.
@@ -666,12 +746,12 @@ P3 page scope notes:
666
746
 
667
747
  P2 sheet notes:
668
748
 
669
- - iOS presents the sheet (`.pageSheet` + one custom detent, ported from
670
- native-sheet) from the top of its level window's presentation chain.
671
- Non-sheet entries are subviews of the same window, so within a level,
672
- sheets and center / toast entries stack by request order. Dismissing a
673
- lower sheet makes UIKit dismiss the sheets presented above it; those report
674
- `onDismissed('system')` and the store closes them.
749
+ - iOS presents each global sheet (`.pageSheet` + one custom detent, ported
750
+ from native-sheet) from its own entry window root. Non-sheet entries also
751
+ have independent windows. All global presentations share level/request-order
752
+ ranking, and dismissing a lower entry leaves upper entries presented with
753
+ their original native controller, content, input and lifecycle. Genuine
754
+ unexpected UIKit dismissal still reports `onDismissed('system')`.
675
755
  - Android hosts the sheet in a CoordinatorLayout + BottomSheetBehavior inside
676
756
  the level container (no BottomSheetDialog window). Enter / exit use the
677
757
  overlay motion; dragging fades the backdrop; a drag to hidden reports
@@ -857,7 +937,7 @@ P5c tooltip and nested-level notes:
857
937
  stay open while the pointer is over the content.
858
938
  - A controlled `open` wins; requests go to `onOpenChange`.
859
939
  - Native Tooltip still renders only the trigger.
860
- - iOS: an overlay whose host view lives inside a level window resolves that
940
+ - iOS: an overlay whose host view lives inside an entry window resolves that
861
941
  window back to the app window. Before this, closing a sheet opened from a
862
942
  `secure` overlay recursed forever in `preferredStatusBarStyle`
863
943
  (`_appearingOrAppearedChildModalViewController` stack overflow). The level
@@ -909,10 +989,10 @@ P5f full-window container notes:
909
989
  hosts at `debug`.
910
990
  - The Market desktop fullscreen chart stays in place (a remount would reload
911
991
  TradingView), fixed at `OVERLAY_WEB_Z_INDEX_BASE.modal - 1`.
912
- - iOS: a touched level window becomes key, and React Native reads its window
992
+ - iOS: a touched entry window becomes key, and React Native reads its window
913
993
  dimensions from the key window. After a rotation while one was key (the
914
994
  fullscreen chart), JS kept the landscape size, so the page stayed in its
915
- wide layout and the native header stayed hidden. A level window now
995
+ wide layout and the native header stayed hidden. An entry window now
916
996
  re-reports the dimensions when it resigns key or resizes while key, by
917
997
  re-assigning the app window's frame (React Native observes it).
918
998
 
@@ -921,7 +1001,7 @@ Measurement:
921
1001
  - `RNCNativeOverlay` has a hand-written shadow node (`common/cpp`, codegen
922
1002
  `interfaceOnly`), like `<Modal>`: it is a `RootNodeKind` (measurements stop
923
1003
  at it) and `Unstable_uncullableView`. Its state holds the window origin of
924
- the view the content currently lives in (level window, sheet, page host,
1004
+ the view the content currently lives in (entry window, sheet, page host,
925
1005
  or the host itself while staged), returned from
926
1006
  `getContentOriginOffset`, so Fabric `measure` / `measureInWindow` report
927
1007
  on-screen frames.
@@ -961,7 +1041,7 @@ Status bar:
961
1041
  - The owner mounts a React Native `<StatusBar>`, the same stack the pages
962
1042
  use: the app runs without view-controller-based status bar appearance on
963
1043
  iOS, and Android sets the window appearance. Web has no status bar.
964
- - iOS asks the root view controller of level windows above the status bar
1044
+ - iOS asks the root view controller of entry windows above the status bar
965
1045
  (`lock`, `debug`) anyway; without view-controller-based appearance it
966
1046
  answers with the app-wide style, so the StatusBar stack still decides.
967
1047
 
@@ -245,7 +245,15 @@ final class NativeOverlayEntryView: UIView {
245
245
  case exiting
246
246
  }
247
247
 
248
- private var phase: Phase = .hidden
248
+ private var phase: Phase = .hidden {
249
+ didSet { NativeOverlayWindowManager.shared.setClosing(phase == .exiting || finishing, window: hostWindow) }
250
+ }
251
+ private var presentationGeneration = 0
252
+ private var dismissalGeneration = 0
253
+ private var invalidated = false
254
+ private var finishing = false
255
+ private weak var pendingReopenResponder: UIView?
256
+ private var activeGlobalLevel: NativeOverlayLevel?
249
257
  private weak var contentChild: UIView?
250
258
  private var entryView: NativeOverlayEntryView?
251
259
  private var sheetController: NativeOverlaySheetController?
@@ -263,7 +271,11 @@ final class NativeOverlayEntryView: UIView {
263
271
 
264
272
  override public func didMoveToWindow() {
265
273
  super.didMoveToWindow()
266
- if window != nil {
274
+ if let window {
275
+ if let hostWindow, hostWindow.windowScene !== window.windowScene {
276
+ finishDismiss(reason: "system")
277
+ return
278
+ }
267
279
  commitConfiguration()
268
280
  } else if phase != .hidden && !isPageScope {
269
281
  // A page overlay's owner screen leaves the window when another screen
@@ -315,6 +327,11 @@ final class NativeOverlayEntryView: UIView {
315
327
  }
316
328
 
317
329
  @objc public func commitConfiguration() {
330
+ guard !invalidated else { return }
331
+ NativeOverlayWindowManager.shared.update(
332
+ hostWindow, stackOrder: stackOrder,
333
+ blocking: usesSystemSheet || blocking, visible: visible
334
+ )
318
335
  if parsedConfigSource != animationConfig {
319
336
  parsedConfigSource = animationConfig
320
337
  config = NativeOverlayAnimationConfig(jsonString: animationConfig)
@@ -326,34 +343,28 @@ final class NativeOverlayEntryView: UIView {
326
343
  sheetController.update(style: sheetStyle(), animated: phase == .shown)
327
344
  }
328
345
  if visible {
346
+ if !cycleOpen && !isPageScope {
347
+ activeGlobalLevel = NativeOverlayLevel(rawValue: level)
348
+ }
329
349
  cycleOpen = true
330
- if phase == .exiting, usesSystemSheet, let controller = sheetController,
331
- controller.cancelHostDismissal(completion: { [weak self, weak controller] in
332
- DispatchQueue.main.async {
333
- guard let self, self.sheetController === controller, self.phase == .entering else { return }
334
- self.phase = .shown
335
- self.didPresent()
336
- if !self.visible { self.dismissSheet() }
337
- }
338
- }) {
339
- phase = .entering
340
- } else if phase == .hidden || (phase == .exiting && !usesSystemSheet) {
350
+ // A non-interactive UIKit sheet dismissal cannot safely be reversed.
351
+ // Its completion reconciles the latest desired visibility instead.
352
+ if phase == .hidden || (phase == .exiting && !usesSystemSheet) {
341
353
  present()
342
354
  }
343
355
  } else if cycleOpen {
344
356
  if phase == .entering || phase == .shown {
345
357
  dismiss()
346
358
  } else if phase == .hidden {
347
- cycleOpen = false
348
- onDismissed?(["reason": "programmatic"])
359
+ finishDismiss(reason: "programmatic")
349
360
  }
350
361
  }
351
362
  }
352
363
 
353
364
  @objc public func invalidate() {
354
- if phase != .hidden {
355
- finishDismiss(reason: nil)
356
- }
365
+ invalidated = true
366
+ activeGlobalLevel = nil
367
+ finishDismiss(reason: nil)
357
368
  onPresented = nil
358
369
  onDismissed = nil
359
370
  onRequestDismiss = nil
@@ -362,7 +373,11 @@ final class NativeOverlayEntryView: UIView {
362
373
  // MARK: - Presentation
363
374
 
364
375
  private func present() {
365
- guard let overlayLevel = NativeOverlayLevel(rawValue: level) else { return }
376
+ guard !invalidated else { return }
377
+ presentationGeneration += 1
378
+ let generation = presentationGeneration
379
+ guard let overlayLevel = isPageScope ? NativeOverlayLevel(rawValue: level)
380
+ : (activeGlobalLevel ?? NativeOverlayLevel(rawValue: level)) else { return }
366
381
  let entry: NativeOverlayEntryView
367
382
  if isPageScope {
368
383
  guard let pageHost = NativeOverlayPageHostView.host(for: hostKey) else { return }
@@ -373,7 +388,10 @@ final class NativeOverlayEntryView: UIView {
373
388
  pageHost.insert(entry)
374
389
  } else {
375
390
  guard let appWindow = window,
376
- let host = NativeOverlayWindowManager.shared.window(for: overlayLevel, appWindow: appWindow)
391
+ let host = NativeOverlayWindowManager.shared.window(
392
+ for: self, level: overlayLevel, stackOrder: stackOrder,
393
+ blocking: usesSystemSheet || blocking, appWindow: appWindow
394
+ )
377
395
  else { return }
378
396
  hostWindow = host
379
397
  if isSheet {
@@ -418,7 +436,8 @@ final class NativeOverlayEntryView: UIView {
418
436
  entry.contentView.transform = .identity
419
437
  }
420
438
  contentAnimator.addCompletion { [weak self] position in
421
- guard let self, position == .end, self.phase == .entering else { return }
439
+ guard let self, self.presentationGeneration == generation,
440
+ self.entryView === entry, position == .end, self.phase == .entering else { return }
422
441
  self.phase = .shown
423
442
  self.didPresent()
424
443
  }
@@ -440,6 +459,7 @@ final class NativeOverlayEntryView: UIView {
440
459
  return
441
460
  }
442
461
  stopAnimators()
462
+ let generation = presentationGeneration
443
463
  phase = .exiting
444
464
  let transition = config.exit.accessibilityAdjusted
445
465
  guard transition.kind != .none else {
@@ -458,7 +478,8 @@ final class NativeOverlayEntryView: UIView {
458
478
  entry.contentView.transform = hiddenTransform
459
479
  }
460
480
  contentAnimator.addCompletion { [weak self] position in
461
- guard let self, position == .end, self.phase == .exiting else { return }
481
+ guard let self, self.presentationGeneration == generation,
482
+ self.entryView === entry, position == .end, self.phase == .exiting else { return }
462
483
  self.finishDismiss(reason: "programmatic")
463
484
  }
464
485
  let backdrop = config.backdropMotion.makeAnimator()
@@ -471,6 +492,14 @@ final class NativeOverlayEntryView: UIView {
471
492
 
472
493
  /// `reason == nil` tears down without notifying JS (view invalidated).
473
494
  private func finishDismiss(reason: String?) {
495
+ guard !finishing else { return }
496
+ if reason != "programmatic" || !visible || invalidated {
497
+ pendingReopenResponder = nil
498
+ }
499
+ finishing = true
500
+ NativeOverlayWindowManager.shared.setClosing(true, window: hostWindow)
501
+ presentationGeneration += 1
502
+ dismissalGeneration += 1
474
503
  stopAnimators()
475
504
  phase = .hidden
476
505
  teardownSheet()
@@ -484,13 +513,20 @@ final class NativeOverlayEntryView: UIView {
484
513
  entryView = nil
485
514
  stageContent()
486
515
  reportContentOffset()
487
- NativeOverlayWindowManager.shared.entryRemoved(from: hostWindow)
488
- guard let reason, cycleOpen else { return }
516
+ let removedWindow = hostWindow
517
+ hostWindow = nil
518
+ NativeOverlayWindowManager.shared.entryRemoved(from: removedWindow)
519
+ finishing = false
520
+ guard let reason, cycleOpen else {
521
+ activeGlobalLevel = nil
522
+ return
523
+ }
489
524
  // A reopen at UIKit's completion boundary keeps the same JS entry.
490
- if reason == "programmatic", visible, window != nil {
525
+ if reason == "programmatic", visible, window != nil, !invalidated {
491
526
  present()
492
527
  return
493
528
  }
529
+ activeGlobalLevel = nil
494
530
  cycleOpen = visible
495
531
  onDismissed?(["reason": reason])
496
532
  }
@@ -564,10 +600,13 @@ final class NativeOverlayEntryView: UIView {
564
600
  private func presentSheet(in host: UIWindow) {
565
601
  guard sheetController == nil,
566
602
  let presenter = NativeOverlayWindowManager.shared.presenter(in: host) else { return }
567
- // UIKit refuses to present while another transition runs in this window.
603
+ let generation = presentationGeneration
604
+ // Only this entry's root can be transitioning in its private window.
568
605
  if presenter.isBeingPresented || presenter.transitionCoordinator != nil {
569
606
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
570
- guard let self, self.visible, self.phase == .hidden else { return }
607
+ guard let self, self.presentationGeneration == generation,
608
+ self.hostWindow === host, !self.invalidated,
609
+ self.visible, self.phase == .hidden else { return }
571
610
  self.present()
572
611
  }
573
612
  return
@@ -577,14 +616,23 @@ final class NativeOverlayEntryView: UIView {
577
616
  NativeOverlayDiagnostic.log("stage=present_begin controllerID=\(NativeOverlayDiagnostic.id(controller)) presenterID=\(NativeOverlayDiagnostic.id(presenter))")
578
617
  phase = .entering
579
618
  presenter.present(controller, animated: true) { [weak self, weak controller] in
580
- guard let self, let controller, self.sheetController === controller else { return }
619
+ guard let self, let controller, self.presentationGeneration == generation,
620
+ self.sheetController === controller else { return }
581
621
  NativeOverlayDiagnostic.log("stage=present_complete controllerID=\(NativeOverlayDiagnostic.id(controller)) visible=\(self.visible) entering=\(self.phase == .entering)")
582
622
  if self.phase == .entering {
583
623
  self.phase = .shown
584
624
  self.didPresent()
585
625
  }
586
626
  if !self.visible {
627
+ self.pendingReopenResponder = nil
587
628
  self.dismissSheet()
629
+ } else if let responder = self.pendingReopenResponder {
630
+ self.pendingReopenResponder = nil
631
+ if let child = self.contentChild,
632
+ responder === child || responder.isDescendant(of: child),
633
+ let window = self.hostWindow {
634
+ _ = NativeOverlayWindowManager.shared.restoreFocus(responder, in: window)
635
+ }
588
636
  }
589
637
  }
590
638
  }
@@ -595,16 +643,19 @@ final class NativeOverlayEntryView: UIView {
595
643
  return
596
644
  }
597
645
  NativeOverlayDiagnostic.log("stage=dismiss_request controllerID=\(NativeOverlayDiagnostic.id(controller)) reason=programmatic presenting=\(controller.isBeingPresented) exiting=\(phase == .exiting)")
598
- if controller.resumeHostDismissal() {
599
- phase = .exiting
600
- return
601
- }
602
646
  // Closing mid-presentation is handled by the present completion.
603
647
  guard !controller.isBeingPresented, phase != .exiting else { return }
648
+ pendingReopenResponder = hostWindow?.isKeyWindow == true
649
+ ? NativeOverlayWindowManager.firstResponder(in: controller.view) : nil
604
650
  phase = .exiting
651
+ let generation = presentationGeneration
652
+ dismissalGeneration += 1
653
+ let dismissal = dismissalGeneration
605
654
  controller.dismissRequestedByHost = true
606
655
  controller.dismiss(animated: true) { [weak self, weak controller] in
607
- guard let self, self.sheetController === controller, self.phase == .exiting else { return }
656
+ guard let self, self.presentationGeneration == generation,
657
+ self.dismissalGeneration == dismissal,
658
+ self.sheetController === controller, self.phase == .exiting else { return }
608
659
  NativeOverlayDiagnostic.log("stage=dismiss_complete controllerID=\(NativeOverlayDiagnostic.id(controller)) reason=programmatic")
609
660
  self.finishDismiss(reason: "programmatic")
610
661
  }
@@ -612,6 +663,7 @@ final class NativeOverlayEntryView: UIView {
612
663
 
613
664
  private func teardownSheet() {
614
665
  guard let controller = sheetController else { return }
666
+ sheetController = nil
615
667
  if let touchHandler, controller.isViewLoaded, touchHandler.view === controller.view {
616
668
  touchHandler.perform(NSSelectorFromString("detachFromView:"), with: controller.view)
617
669
  }
@@ -621,7 +673,6 @@ final class NativeOverlayEntryView: UIView {
621
673
  controller.dismissRequestedByHost = true
622
674
  controller.dismiss(animated: false)
623
675
  }
624
- sheetController = nil
625
676
  }
626
677
 
627
678
  // MARK: - Entry view
@@ -691,6 +742,7 @@ extension NativeOverlayContainerView: NativeOverlaySheetHost {
691
742
  }
692
743
 
693
744
  func sheetDidLoad(_ controller: NativeOverlaySheetController) {
745
+ guard !invalidated, sheetController === controller else { return }
694
746
  if let touchHandler, touchHandler.view == nil {
695
747
  touchHandler.perform(NSSelectorFromString("attachToView:"), with: controller.view)
696
748
  }
@@ -720,3 +772,10 @@ extension NativeOverlayContainerView: NativeOverlaySheetHost {
720
772
  onRequestDismiss?(["reason": reason])
721
773
  }
722
774
  }
775
+
776
+ extension NativeOverlayContainerView: NativeOverlayWindowOwner {
777
+ func overlaySceneDidDisconnect(window: UIWindow) {
778
+ guard hostWindow === window else { return }
779
+ finishDismiss(reason: "system")
780
+ }
781
+ }
@@ -7,8 +7,7 @@ protocol NativeOverlaySheetHost: AnyObject {
7
7
  /// The sheet's frame settled (presentation, detent or keyboard change).
8
8
  func sheetDidLayout(_ controller: NativeOverlaySheetController)
9
9
  func sheetDidDismissInteractively(_ controller: NativeOverlaySheetController)
10
- /// UIKit dismissed the sheet without being asked, e.g. because a sheet
11
- /// below it in the same level window was dismissed.
10
+ /// UIKit dismissed the sheet without the owning host requesting it.
12
11
  func sheetDidDisappearUnexpectedly(_ controller: NativeOverlaySheetController)
13
12
  func sheetRequestedDismiss(_ controller: NativeOverlaySheetController, reason: String)
14
13
  }
@@ -31,7 +30,6 @@ private final class NativeOverlaySheetTransitionAnimator: NSObject,
31
30
  private let presenting: Bool
32
31
  private let motion: NativeOverlayMotion
33
32
  private var animator: UIViewPropertyAnimator?
34
- private var cancellationCompletion: (() -> Void)?
35
33
 
36
34
  init(presenting: Bool, motion: NativeOverlayMotion) {
37
35
  self.presenting = presenting
@@ -96,35 +94,18 @@ private final class NativeOverlaySheetTransitionAnimator: NSObject,
96
94
  sheetController.setDimmingAlpha(self.presenting ? 0 : 1)
97
95
  }
98
96
  transitionContext.completeTransition(completed)
99
- if position == .start { self.cancellationCompletion?() }
100
- self.cancellationCompletion = nil
101
97
  }
102
98
  self.animator = animator
103
99
  return animator
104
100
  }
105
101
 
106
- func reverseDismissal(completion: @escaping () -> Void) -> Bool {
107
- guard !presenting, let animator, animator.isRunning, !animator.isReversed else { return false }
108
- cancellationCompletion = completion
109
- animator.isReversed = true
110
- return true
111
- }
112
-
113
- func resumeDismissal() -> Bool {
114
- guard !presenting, let animator, animator.isRunning, animator.isReversed else { return false }
115
- cancellationCompletion = nil
116
- animator.isReversed = false
117
- return true
118
- }
119
-
120
102
  func animationEnded(_ transitionCompleted: Bool) {
121
103
  animator = nil
122
104
  }
123
105
  }
124
106
 
125
107
  /// A `.pageSheet` with one custom detent, ported from native-sheet. It is
126
- /// presented from its level window, so sheets of different levels never
127
- /// share a presentation chain.
108
+ /// presented from its own entry window, independently of all other overlays.
128
109
  final class NativeOverlaySheetController: UIViewController,
129
110
  UIAdaptivePresentationControllerDelegate,
130
111
  UIViewControllerTransitioningDelegate {
@@ -137,7 +118,6 @@ final class NativeOverlaySheetController: UIViewController,
137
118
  private var dimmingView: UIView?
138
119
  private var backdropTap: UITapGestureRecognizer?
139
120
  private var heightAnimator: UIViewPropertyAnimator?
140
- private var dismissalAnimator: NativeOverlaySheetTransitionAnimator?
141
121
  private var shadowSuppressionDisplayLink: CADisplayLink?
142
122
  /// Set while the host itself asked UIKit to dismiss.
143
123
  var dismissRequestedByHost = false
@@ -251,22 +231,7 @@ final class NativeOverlaySheetController: UIViewController,
251
231
  func animationController(
252
232
  forDismissed dismissed: UIViewController
253
233
  ) -> UIViewControllerAnimatedTransitioning? {
254
- let animator = NativeOverlaySheetTransitionAnimator(presenting: false, motion: style.exitMotion)
255
- dismissalAnimator = animator
256
- return animator
257
- }
258
-
259
- func cancelHostDismissal(completion: @escaping () -> Void) -> Bool {
260
- guard dismissRequestedByHost,
261
- dismissalAnimator?.reverseDismissal(completion: completion) == true else { return false }
262
- dismissRequestedByHost = false
263
- return true
264
- }
265
-
266
- func resumeHostDismissal() -> Bool {
267
- guard dismissalAnimator?.resumeDismissal() == true else { return false }
268
- dismissRequestedByHost = true
269
- return true
234
+ NativeOverlaySheetTransitionAnimator(presenting: false, motion: style.exitMotion)
270
235
  }
271
236
 
272
237
  override func viewWillAppear(_ animated: Bool) {
@@ -25,8 +25,7 @@ enum NativeOverlayDiagnostic {
25
25
  }
26
26
  }
27
27
 
28
- /// Levels mirror `OVERLAY_LEVEL_ORDER`. Each active level gets its own
29
- /// window so that order between levels never depends on show order.
28
+ /// Levels mirror `OVERLAY_LEVEL_ORDER`; each level reserves a window-level band.
30
29
  enum NativeOverlayLevel: String, CaseIterable {
31
30
  case modal
32
31
  case hardware
@@ -144,76 +143,205 @@ final class NativeOverlayRootViewController: UIViewController {
144
143
  }
145
144
  }
146
145
 
147
- final class NativeOverlayWindowManager {
146
+ protocol NativeOverlayWindowOwner: AnyObject {
147
+ func overlaySceneDidDisconnect(window: UIWindow)
148
+ }
149
+
150
+ final class NativeOverlayWindowManager: NSObject {
148
151
  static let shared = NativeOverlayWindowManager()
149
152
 
150
- private struct SceneKey: Hashable {
151
- let id: ObjectIdentifier
153
+ private final class Entry {
154
+ weak var owner: NativeOverlayWindowOwner?
155
+ weak var appWindow: UIWindow?
156
+ let window: NativeOverlayPassthroughWindow
157
+ let sequence: Int
158
+ let level: NativeOverlayLevel
159
+ var stackOrder: Int
160
+ var blocking: Bool
161
+ var desiredVisible = true
162
+ var closing = false
163
+
164
+ init(owner: NativeOverlayWindowOwner, appWindow: UIWindow,
165
+ window: NativeOverlayPassthroughWindow, sequence: Int,
166
+ level: NativeOverlayLevel, stackOrder: Int, blocking: Bool) {
167
+ self.owner = owner
168
+ self.appWindow = appWindow
169
+ self.window = window
170
+ self.sequence = sequence
171
+ self.level = level
172
+ self.stackOrder = stackOrder
173
+ self.blocking = blocking
174
+ }
152
175
  }
153
176
 
154
- private var windows: [SceneKey: [NativeOverlayLevel: NativeOverlayPassthroughWindow]] = [:]
177
+ private var scenes: [ObjectIdentifier: [ObjectIdentifier: Entry]] = [:]
178
+ private var disconnectingScenes = Set<ObjectIdentifier>()
179
+ private var sequence = 0
155
180
 
156
- /// The level window for `level` in the scene of `appWindow`, shown on demand.
157
- /// Non-sheet entries are added directly to it so they interleave by insertion
158
- /// order with UIKit presentation containers of sheets in the same level.
159
- func window(for level: NativeOverlayLevel, appWindow hostWindow: UIWindow) -> UIWindow? {
160
- // An overlay opened from inside another overlay (a popover in a password
161
- // prompt) is hosted in a level window; follow it back to the app window.
181
+ override init() {
182
+ super.init()
183
+ NotificationCenter.default.addObserver(
184
+ self, selector: #selector(sceneDidDisconnect(_:)),
185
+ name: UIScene.didDisconnectNotification, object: nil
186
+ )
187
+ }
188
+
189
+ deinit { NotificationCenter.default.removeObserver(self) }
190
+
191
+ /// Every owner has an independent root presenter, shared by no other entry.
192
+ func window(for owner: NativeOverlayWindowOwner, level: NativeOverlayLevel,
193
+ stackOrder: Int, blocking: Bool, appWindow hostWindow: UIWindow) -> UIWindow? {
194
+ precondition(Thread.isMainThread)
162
195
  let appWindow =
163
196
  ((hostWindow as? NativeOverlayPassthroughWindow)?.rootViewController
164
197
  as? NativeOverlayRootViewController)?.appWindow ?? hostWindow
165
- guard let scene = appWindow.windowScene else { return nil }
166
- let key = SceneKey(id: ObjectIdentifier(scene))
167
- pruneDisconnectedScenes()
168
- var sceneWindows = windows[key] ?? [:]
169
- let window: NativeOverlayPassthroughWindow
170
- if let existing = sceneWindows[level] {
171
- window = existing
198
+ guard let scene = appWindow.windowScene, scene.activationState != .unattached else { return nil }
199
+ let sceneKey = ObjectIdentifier(scene)
200
+ guard !disconnectingScenes.contains(sceneKey) else { return nil }
201
+ let orphanWindows = (scenes[sceneKey] ?? [:]).values.filter { $0.owner == nil }.map(\.window)
202
+ orphanWindows.forEach { entryRemoved(from: $0) }
203
+ let ownerKey = ObjectIdentifier(owner)
204
+ var entries = scenes[sceneKey] ?? [:]
205
+ let entry: Entry
206
+ if let existing = entries[ownerKey], existing.owner === owner {
207
+ entry = existing
208
+ entry.stackOrder = stackOrder
209
+ entry.blocking = blocking
172
210
  } else {
173
- window = NativeOverlayPassthroughWindow(windowScene: scene)
174
- window.windowLevel = level.windowLevel
211
+ sequence += 1
212
+ let window = NativeOverlayPassthroughWindow(windowScene: scene)
175
213
  window.backgroundColor = .clear
176
- window.rootViewController = NativeOverlayRootViewController()
177
- sceneWindows[level] = window
178
- windows[key] = sceneWindows
179
- }
180
- (window.rootViewController as? NativeOverlayRootViewController)?.appWindow = appWindow
181
- if window.isHidden {
214
+ let root = NativeOverlayRootViewController()
215
+ root.appWindow = appWindow
216
+ window.rootViewController = root
182
217
  window.frame = scene.coordinateSpace.bounds
183
- window.isHidden = false
184
- window.rootViewController?.setNeedsStatusBarAppearanceUpdate()
218
+ entry = Entry(owner: owner, appWindow: appWindow, window: window,
219
+ sequence: sequence, level: level, stackOrder: stackOrder, blocking: blocking)
220
+ entries[ownerKey] = entry
221
+ scenes[sceneKey] = entries
185
222
  }
186
- return window
223
+ entry.appWindow = appWindow
224
+ (entry.window.rootViewController as? NativeOverlayRootViewController)?.appWindow = appWindow
225
+ reorder(entries)
226
+ entry.window.isHidden = false
227
+ entry.window.rootViewController?.setNeedsStatusBarAppearanceUpdate()
228
+ return entry.window
229
+ }
230
+
231
+ func update(_ window: UIWindow?, stackOrder: Int,
232
+ blocking: Bool, visible: Bool) {
233
+ precondition(Thread.isMainThread)
234
+ guard let (sceneKey, _, entry) = find(window) else { return }
235
+ let orderChanged = entry.stackOrder != stackOrder
236
+ entry.stackOrder = stackOrder
237
+ entry.blocking = blocking
238
+ entry.desiredVisible = visible
239
+ if orderChanged { reorder(scenes[sceneKey] ?? [:]) }
240
+ }
241
+
242
+ func setClosing(_ closing: Bool, window: UIWindow?) {
243
+ precondition(Thread.isMainThread)
244
+ find(window)?.2.closing = closing
187
245
  }
188
246
 
189
- /// Top of the level window's presentation chain; sheets of one level stack here.
190
247
  func presenter(in window: UIWindow) -> UIViewController? {
191
- var controller = window.rootViewController
192
- while let presented = controller?.presentedViewController, !presented.isBeingDismissed {
193
- controller = presented
194
- }
195
- return controller
248
+ window.rootViewController
196
249
  }
197
250
 
198
- /// Hides a level window once nothing is shown in it, and hands key status
199
- /// back to the app window if an input in the overlay had taken it.
200
251
  func entryRemoved(from window: UIWindow?) {
201
- guard let window = window as? NativeOverlayPassthroughWindow,
202
- let root = window.rootViewController else { return }
203
- let hasEntries = window.subviews.contains { $0 is NativeOverlayEntryView }
204
- let presented = root.presentedViewController
205
- guard !hasEntries, presented == nil || presented?.isBeingDismissed == true else { return }
206
- let wasKey = window.isKeyWindow
207
- window.isHidden = true
208
- if wasKey {
209
- (root as? NativeOverlayRootViewController)?.appWindow?.makeKey()
252
+ precondition(Thread.isMainThread)
253
+ guard let (sceneKey, ownerKey, entry) = find(window) else { return }
254
+ let wasKey = entry.window.isKeyWindow
255
+ let scene = entry.window.windowScene
256
+ scenes[sceneKey]?[ownerKey] = nil
257
+ let remaining = scenes[sceneKey] ?? [:]
258
+ if remaining.isEmpty { scenes[sceneKey] = nil }
259
+ release(entry.window)
260
+ reorder(remaining)
261
+ guard wasKey, let scene,
262
+ scene.activationState == .foregroundActive || scene.activationState == .foregroundInactive else { return }
263
+ let next = remaining.values.filter { Self.eligible($0, in: scene) }
264
+ .max { Self.ordered($0, before: $1) }
265
+ (next?.window ?? entry.appWindow)?.makeKey()
266
+ }
267
+
268
+ func restoreFocus(_ responder: UIView, in window: UIWindow) -> Bool {
269
+ precondition(Thread.isMainThread)
270
+ guard let (sceneKey, _, entry) = find(window),
271
+ let scene = window.windowScene, scene.activationState == .foregroundActive,
272
+ responder.window === window, responder.canBecomeFirstResponder else { return false }
273
+ let entries = scenes[sceneKey] ?? [:]
274
+ guard entries.values.filter({ Self.eligible($0, in: scene) })
275
+ .max(by: { Self.ordered($0, before: $1) }) === entry,
276
+ let key = scene.windows.first(where: { $0.isKeyWindow }) else { return false }
277
+ if key !== entry.appWindow {
278
+ guard let keyEntry = entries.values.first(where: { $0.window === key && $0.owner != nil }),
279
+ !Self.ordered(entry, before: keyEntry) else { return false }
210
280
  }
281
+ if let current = Self.firstResponder(in: window), current !== responder { return false }
282
+ window.makeKey()
283
+ return responder.becomeFirstResponder()
211
284
  }
212
285
 
213
- private func pruneDisconnectedScenes() {
214
- let connected = Set(
215
- UIApplication.shared.connectedScenes.map { SceneKey(id: ObjectIdentifier($0)) }
216
- )
217
- windows = windows.filter { connected.contains($0.key) }
286
+ private static func eligible(_ entry: Entry, in scene: UIWindowScene) -> Bool {
287
+ entry.owner != nil && entry.desiredVisible && !entry.closing &&
288
+ !entry.window.isHidden && entry.window.windowScene === scene &&
289
+ (entry.blocking || firstResponder(in: entry.window) != nil)
290
+ }
291
+
292
+ private func find(_ window: UIWindow?) -> (ObjectIdentifier, ObjectIdentifier, Entry)? {
293
+ guard let window else { return nil }
294
+ for (sceneKey, entries) in scenes {
295
+ if let (ownerKey, entry) = entries.first(where: { $0.value.window === window }) {
296
+ return (sceneKey, ownerKey, entry)
297
+ }
298
+ }
299
+ return nil
300
+ }
301
+
302
+ private static func ordered(_ a: Entry, before b: Entry) -> Bool {
303
+ if a.level.order != b.level.order { return a.level.order < b.level.order }
304
+ if a.stackOrder != b.stackOrder { return a.stackOrder < b.stackOrder }
305
+ return a.sequence < b.sequence
306
+ }
307
+
308
+ private func reorder(_ entries: [ObjectIdentifier: Entry]) {
309
+ let levels = Dictionary(grouping: entries.values, by: { $0.level })
310
+ for (level, group) in levels {
311
+ let sorted = group.sorted { Self.ordered($0, before: $1) }
312
+ for (index, entry) in sorted.enumerated() {
313
+ // A bounded rank cannot cross another band's base, even for large seq values.
314
+ let rank = CGFloat(index) / CGFloat(sorted.count + 1)
315
+ entry.window.windowLevel = UIWindow.Level(rawValue: level.windowLevel.rawValue + rank)
316
+ }
317
+ }
318
+ }
319
+
320
+ static func firstResponder(in view: UIView) -> UIView? {
321
+ if view.isFirstResponder { return view }
322
+ for child in view.subviews {
323
+ if let responder = firstResponder(in: child) { return responder }
324
+ }
325
+ return nil
326
+ }
327
+
328
+ private func release(_ window: UIWindow) {
329
+ window.isHidden = true
330
+ window.rootViewController = nil
331
+ window.windowScene = nil
332
+ }
333
+
334
+ @objc private func sceneDidDisconnect(_ notification: Notification) {
335
+ precondition(Thread.isMainThread)
336
+ guard let scene = notification.object as? UIWindowScene else { return }
337
+ let sceneKey = ObjectIdentifier(scene)
338
+ guard let entries = scenes.removeValue(forKey: sceneKey) else { return }
339
+ disconnectingScenes.insert(sceneKey)
340
+ defer { disconnectingScenes.remove(sceneKey) }
341
+ // Unregister first: owner callbacks must not restore a disconnected scene's key.
342
+ for entry in entries.values {
343
+ entry.owner?.overlaySceneDidDisconnect(window: entry.window)
344
+ release(entry.window)
345
+ }
218
346
  }
219
347
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onekeyfe/react-native-native-overlay",
3
- "version": "6.7.0-23",
3
+ "version": "6.7.0-24",
4
4
  "description": "Native and Web overlay hosts with ordered levels, page scope and Fabric measurement",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",