@onekeyfe/react-native-device-utils 6.7.0-5 → 6.7.0-50

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 (43) hide show
  1. package/README.md +117 -87
  2. package/android/src/main/java/com/margelo/nitro/reactnativedeviceutils/ReactNativeDeviceUtils.kt +156 -35
  3. package/ios/DualScreenDetector.swift +170 -0
  4. package/ios/MainMenuController.swift +170 -0
  5. package/ios/ReactNativeDeviceUtils.swift +29 -4
  6. package/ios/WindowControlsInsetsObserver.swift +151 -0
  7. package/lib/typescript/src/ReactNativeDeviceUtils.nitro.d.ts +46 -0
  8. package/nitrogen/generated/android/c++/JFunc_void_MainMenuCommand.hpp +77 -0
  9. package/nitrogen/generated/android/c++/JFunc_void_WindowControlsInsets.hpp +77 -0
  10. package/nitrogen/generated/android/c++/JHybridReactNativeDeviceUtilsSpec.cpp +45 -0
  11. package/nitrogen/generated/android/c++/JHybridReactNativeDeviceUtilsSpec.hpp +6 -0
  12. package/nitrogen/generated/android/c++/JMainMenuCommand.hpp +61 -0
  13. package/nitrogen/generated/android/c++/JMainMenuConfig.hpp +90 -0
  14. package/nitrogen/generated/android/c++/JMainMenuLink.hpp +61 -0
  15. package/nitrogen/generated/android/c++/JWindowControlsInsets.hpp +69 -0
  16. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/Func_void_MainMenuCommand.kt +78 -0
  17. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/Func_void_WindowControlsInsets.kt +78 -0
  18. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/HybridReactNativeDeviceUtilsSpec.kt +34 -0
  19. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/MainMenuCommand.kt +24 -0
  20. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/MainMenuConfig.kt +66 -0
  21. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/MainMenuLink.kt +56 -0
  22. package/nitrogen/generated/android/kotlin/com/margelo/nitro/reactnativedeviceutils/WindowControlsInsets.kt +66 -0
  23. package/nitrogen/generated/android/reactnativedeviceutilsOnLoad.cpp +4 -0
  24. package/nitrogen/generated/ios/ReactNativeDeviceUtils-Swift-Cxx-Bridge.cpp +16 -0
  25. package/nitrogen/generated/ios/ReactNativeDeviceUtils-Swift-Cxx-Bridge.hpp +73 -0
  26. package/nitrogen/generated/ios/ReactNativeDeviceUtils-Swift-Cxx-Umbrella.hpp +12 -0
  27. package/nitrogen/generated/ios/c++/HybridReactNativeDeviceUtilsSpecSwift.hpp +55 -1
  28. package/nitrogen/generated/ios/swift/Func_void_MainMenuCommand.swift +46 -0
  29. package/nitrogen/generated/ios/swift/Func_void_WindowControlsInsets.swift +46 -0
  30. package/nitrogen/generated/ios/swift/HybridReactNativeDeviceUtilsSpec.swift +6 -0
  31. package/nitrogen/generated/ios/swift/HybridReactNativeDeviceUtilsSpec_cxx.swift +79 -0
  32. package/nitrogen/generated/ios/swift/MainMenuCommand.swift +44 -0
  33. package/nitrogen/generated/ios/swift/MainMenuConfig.swift +50 -0
  34. package/nitrogen/generated/ios/swift/MainMenuLink.swift +34 -0
  35. package/nitrogen/generated/ios/swift/WindowControlsInsets.swift +44 -0
  36. package/nitrogen/generated/shared/c++/HybridReactNativeDeviceUtilsSpec.cpp +6 -0
  37. package/nitrogen/generated/shared/c++/HybridReactNativeDeviceUtilsSpec.hpp +15 -0
  38. package/nitrogen/generated/shared/c++/MainMenuCommand.hpp +80 -0
  39. package/nitrogen/generated/shared/c++/MainMenuConfig.hpp +98 -0
  40. package/nitrogen/generated/shared/c++/MainMenuLink.hpp +87 -0
  41. package/nitrogen/generated/shared/c++/WindowControlsInsets.hpp +95 -0
  42. package/package.json +8 -7
  43. package/src/ReactNativeDeviceUtils.nitro.ts +54 -0
package/README.md CHANGED
@@ -1,9 +1,39 @@
1
+ <div align="center">
2
+
1
3
  # @onekeyfe/react-native-device-utils
2
4
 
3
- Native application and device integration utilities for OneKey on iOS and
4
- Android. The Nitro interface groups launch information, display and system-bar
5
- appearance, device tokens, boot recovery and platform-service inspection.
6
- These are host integration helpers rather than a portable browser device API.
5
+ **Host integration for OneKey apps: launch data, device tokens, foldables, iPadOS windows and a process-wide primitive store.**
6
+
7
+ [![npm](https://img.shields.io/npm/v/%40onekeyfe%2Freact-native-device-utils?label=npm&color=4D6BFE)](https://www.npmjs.com/package/@onekeyfe/react-native-device-utils)
8
+ [![license](https://img.shields.io/npm/l/%40onekeyfe%2Freact-native-device-utils?label=license&color=4D6BFE)](LICENSE)
9
+ ![iOS](https://img.shields.io/badge/iOS-000000?logo=apple&logoColor=white)
10
+ ![Android](https://img.shields.io/badge/Android-3DDC84?logo=android&logoColor=white)
11
+ ![Nitro Modules](https://img.shields.io/badge/Nitro_Modules-4D6BFE)
12
+
13
+ </div>
14
+
15
+ One Nitro HybridObject that groups the small native capabilities a host app
16
+ needs but React Native does not expose: launch options and startup time, push
17
+ device tokens, foldable/dual-screen state on both platforms, iPadOS window
18
+ controls and the app menu, Android navigation-bar styling and Play Services
19
+ inspection, boot-failure recovery, and a bounded in-memory primitive store. It
20
+ is a set of host integration helpers, not a portable device API: several calls
21
+ are deliberately no-ops on the platform that cannot honor them, and the store is
22
+ process-scoped and never persisted.
23
+
24
+ ## Features
25
+
26
+ - **One object, many host capabilities** — launch options, tokens, appearance,
27
+ foldables, services and recovery behind a single imported HybridObject.
28
+ - **Shared in-memory store** — 128 entries of string/boolean/number values shared
29
+ by the main and background runtimes, with atomic set-if-absent claims and type
30
+ preservation.
31
+ - **Explicit listener lifecycle** — every subscription returns a numeric ID that
32
+ its owner removes; no hidden global listeners.
33
+ - **Platform-honest** — iOS-only and Android-only calls are documented as such
34
+ and are safe no-ops on the other platform instead of throwing.
35
+ - **Typed boundary** — enums and result objects land in TypeScript through
36
+ Nitro-generated bindings, so adapters get compile-time checks.
7
37
 
8
38
  ## Installation
9
39
 
@@ -11,99 +41,99 @@ These are host integration helpers rather than a portable browser device API.
11
41
  yarn add @onekeyfe/react-native-device-utils react-native-nitro-modules
12
42
  ```
13
43
 
14
- Install the application's iOS pods and rebuild the native application. Features
15
- such as push tokens and launch options also require the application's native
16
- host configuration; installing this package does not register those services.
17
-
18
- ## Usage
19
-
20
- ```ts
21
- import { ReactNativeDeviceUtils } from '@onekeyfe/react-native-device-utils';
44
+ Install the native peer packages this package links as well:
22
45
 
23
- const launch = await ReactNativeDeviceUtils.getLaunchOptions();
24
- const startupTime = await ReactNativeDeviceUtils.getStartupTime();
25
- const installer = ReactNativeDeviceUtils.getInstallerPackageName();
46
+ ```sh
47
+ yarn add @onekeyfe/react-native-native-logger
26
48
  ```
27
49
 
28
- ## API groups
50
+ This package ships native code. Install the app's iOS pods and rebuild the
51
+ native binary; a JavaScript-only update does not register the module. Push
52
+ tokens and launch options additionally depend on the host application's native
53
+ configuration — installing this package does not register those services.
29
54
 
30
- - Display: dual-screen status, window/hinge rectangles, background color and
31
- interface style.
32
- - Android navigation bar: `setNavigationBarAppearance(r, g, b, a, useDarkIcons)`.
33
- Color channels use 0–255; this method is a no-op on iOS.
34
- - Launch and notifications: read/clear launch options, register/store device
35
- tokens and consume cold-start local notification data.
36
- - Android services: WebView package information, Google Play Services status,
37
- distribution channel and installer identification.
38
- - Boot recovery: mark boot success, inspect/update failure counts and consume
39
- a pending recovery action.
40
-
41
- Spanning listeners return IDs that must be removed when their owner finishes.
42
- Cold-start local notification consumption is meaningful on iOS; Android returns
43
- an empty string. Platform-specific results should not be interpreted as a
44
- cross-platform guarantee that a service or hardware feature is available.
45
-
46
- See [src/ReactNativeDeviceUtils.nitro.ts](src/ReactNativeDeviceUtils.nitro.ts)
47
- for the complete signatures, enum values and platform notes.
48
- See [docs/SPEC.md](docs/SPEC.md) for the InMemoryStore contract and acceptance status.
55
+ ## Usage
49
56
 
50
- ## In-memory store
57
+ ```ts
58
+ import { ReactNativeDeviceUtils } from '@onekeyfe/react-native-device-utils';
51
59
 
52
- `ReactNativeDeviceUtils` exposes synchronous Android/iOS methods:
60
+ // Call once during startup so native event listeners exist.
61
+ ReactNativeDeviceUtils.initEventListeners();
53
62
 
54
- ```ts
55
- type InMemoryValue = string | boolean | number;
63
+ const { launchType, deepLink } =
64
+ await ReactNativeDeviceUtils.getLaunchOptions();
65
+ const startupTime = await ReactNativeDeviceUtils.getStartupTime();
56
66
 
57
- getInMemoryValue(key: string): InMemoryValue | undefined;
58
- setInMemoryValue(key: string, value: InMemoryValue): void;
59
- removeInMemoryValue(key: string): boolean;
60
- setInMemoryValueIfAbsent(key: string, value: InMemoryValue): boolean;
67
+ // Claim a startup stage exactly once across runtimes.
68
+ const claimed = ReactNativeDeviceUtils.setInMemoryValueIfAbsent(
69
+ 'analytics:startup:jsReadyTime',
70
+ Date.now(),
71
+ );
61
72
  ```
62
73
 
63
- Values are strings (including empty strings), booleans, or numbers. Reads preserve
64
- the original type; false and 0 are stored values rather than missing keys. Numbers
65
- use IEEE-754 doubles, including negative zero, NaN, and infinities. Objects, arrays,
66
- null, and undefined are not supported. `setInMemoryValueIfAbsent` inserts
67
- only when the key is missing and returns whether it inserted. All operations use
68
- the same native lock. A module recreation, JS reload, or main/background runtime
69
- recreation retains the same native Map. Process exit discards it. No data is
70
- persisted, and there is no implicit reset on React lifecycle events.
71
-
72
- Keys use exact UTF-8 identity, without Unicode normalization. The store holds at
73
- most 128 entries; keys are limited to 256 UTF-8 bytes and string values to 4096
74
- bytes. Boolean and number payloads are fixed size.
75
- Overlong arguments or a new key at capacity throw synchronously without changing
76
- the Map. Existing keys can still be replaced or removed; no entry is evicted.
77
- Both write methods validate their arguments even when the key already exists.
78
-
79
- Use namespaced keys. For startup reporting, only main UI may claim
80
- `analytics:startup:jsReadyTime` or `analytics:startup:uiVisibleTime`. Claim and
81
- enqueue synchronously; remove the key if local enqueue throws. Keep the key after
82
- enqueue succeeds; network delivery remains the existing analytics path's job.
83
- A pending JS logger queue can still lose entries on runtime loss or later queue
84
- errors; acceptance into that queue does not guarantee delivery.
85
-
86
- This API requires a rebuilt native host containing the updated module. It is not
87
- an OTA-only change. Desktop/web/extension are not implemented by this package.
88
-
89
- After `yarn nitrogen`, run `node tests/in-memory-store.cjs` from this package to
90
- compile the production Swift/Kotlin stores with the generated primitive union,
91
- exercise type preservation, concurrent claims and independent keys, and run each
92
- executable in two fresh processes. Requires Swift, Kotlin, and Java.
93
-
94
- ## Consumed launch data and listener cleanup
95
-
96
- `getAndClearColdStartLocalNotification()` returns serialized local-notification
97
- user info on iOS and consumes that value. An empty string means there is no
98
- pending payload. Parse it only after checking for an empty result and avoid
99
- logging notification contents or stored device tokens.
100
-
101
- `addSpanningChangedListener` returns a numeric ID; retain it for
102
- `removeSpanningChangedListener`. `getLaunchOptions()` returns a `LaunchOptions`
103
- object with `launchType` and optional `deepLink`, rather than a raw URL string.
104
- Use the exported result types for WebView, Google Play Services and hinge/window
105
- geometry when building a platform adapter.
74
+ Consumers own key namespaces and decide what to do with each result. Store
75
+ values are native copies, not retained JS objects.
76
+
77
+ ## API
78
+
79
+ | Method | Result | Platforms | Description |
80
+ | --- | --- | :-: | --- |
81
+ | `initEventListeners()` | `void` | iOS, Android | Registers native listeners; call once at startup. |
82
+ | `getLaunchOptions()` / `clearLaunchOptions()` | `Promise<LaunchOptions>` / `Promise<boolean>` | iOS, Android | Read or consume the app's launch type and optional deep link. |
83
+ | `getStartupTime()` | `Promise<number>` | iOS, Android | Native startup timestamp. |
84
+ | `getDeviceToken()` / `saveDeviceToken(token)` / `registerDeviceToken()` | `Promise<string>` / `Promise<void>` / `Promise<boolean>` | iOS, Android | Push-token plumbing; host setup still owns registration. |
85
+ | `getInMemoryValue(key)` / `setInMemoryValue(key, value)` / `removeInMemoryValue(key)` / `setInMemoryValueIfAbsent(key, value)` | `InMemoryValue \| undefined` / `void` / `boolean` / `boolean` | iOS, Android | Synchronous bounded primitive store. |
86
+ | `getAndClearColdStartLocalNotification()` | `Promise<string>` | iOS, Android | Returns local-notification JSON once; Android returns `""`. |
87
+ | `isDualScreenDevice()` / `isSpanning()` | `boolean` | iOS, Android | Foldable detection and spanning state. |
88
+ | `getWindowRects()` / `getHingeBounds()` | `Promise<DualScreenInfoRect[]>` / `Promise<DualScreenInfoRect>` | iOS, Android | Window and hinge geometry; iOS keeps empty/zero results. |
89
+ | `getWindowControlsInsets()` + change listeners | `WindowControlsInsets` / listener ID | iOS 26+ | Room taken by system window controls; zero elsewhere. |
90
+ | `setMainMenuConfig(config)` + command listeners | `void` / listener ID | iOS (iPadOS) | Rebuilds the iPadOS app menu; Android ignores it. |
91
+ | `setNavigationBarAppearance(r, g, b, a, useDarkIcons)` | `void` | Android | Applies the navigation-bar color and icon style; no-op on iOS. |
92
+ | `getCurrentWebViewPackageInfo()` / `isGooglePlayServicesAvailable()` | `Promise<WebViewPackageInfo>` / `Promise<GooglePlayServicesStatus>` | Android | WebView package and Play Services status. |
93
+ | `getAndroidChannel()` / `getInstallerPackageName()` | `AndroidChannel` / `InstallerPackageName` | Android | Distribution channel and installer source. |
94
+ | `markBootSuccess()` / `getConsecutiveBootFailCount()` / `incrementConsecutiveBootFailCount()` / `setConsecutiveBootFailCount(count)` / `getAndClearRecoveryAction()` | varies | iOS, Android | Boot-failure counter and one-shot recovery action. |
95
+ | `exitApp()` | `void` | iOS, Android | Terminates the app process. |
96
+
97
+ See [`src/ReactNativeDeviceUtils.nitro.ts`](src/ReactNativeDeviceUtils.nitro.ts)
98
+ for full signatures, result types and enum values.
99
+
100
+ ## Platform support
101
+
102
+ | Capability | iOS | Android | Web |
103
+ | --- | :-: | :-: | :-: |
104
+ | Launch options, startup time, device tokens | ✅ | ✅ | — |
105
+ | In-memory primitive store | ✅ | ✅ | — |
106
+ | Dual-screen detection and spanning listeners | ✅ foldable iPhone | ✅ | — |
107
+ | Window controls insets | ✅ iOS 26+ | — | — |
108
+ | iPadOS main menu | ✅ iPadOS | — | — |
109
+ | Navigation-bar appearance | — | ✅ | — |
110
+ | WebView / Play Services / installer inspection | — | ✅ | — |
111
+ | Boot recovery | ✅ | ✅ | — |
112
+
113
+ ## Caveats
114
+
115
+ > [!IMPORTANT]
116
+ > The in-memory store API needs a rebuilt native host containing these bindings;
117
+ > it is not an OTA-only change. The store survives JS reloads and runtime
118
+ > recreation but not process exit, and it is never written to disk.
119
+
120
+ > [!NOTE]
121
+ > The store holds at most 128 entries. Keys are limited to 256 UTF-8 bytes and
122
+ > string values to 4096 UTF-8 bytes; overlong arguments or a write to a new key
123
+ > at capacity throw synchronously and leave the map unchanged.
124
+
125
+ > [!WARNING]
126
+ > Do not treat a successful call as proof that the underlying platform feature
127
+ > exists. Android returns `""` for cold-start local notifications, iOS ignores the
128
+ > navigation-bar call, and window-controls insets are zero outside iOS 26+.
129
+
130
+ ## References
131
+
132
+ - [Package spec](docs/SPEC.md)
133
+ - [Native interface](src/ReactNativeDeviceUtils.nitro.ts)
134
+ - [Example page](../../example/react-native/pages/DeviceUtilsTestPage.tsx)
135
+ - [Changelog](../../CHANGELOG.md)
106
136
 
107
137
  ## License
108
138
 
109
- MIT.
139
+ MIT. See [LICENSE](LICENSE).
@@ -4,9 +4,11 @@ import android.app.Activity
4
4
  import android.content.Context
5
5
  import android.content.pm.PackageManager
6
6
  import android.graphics.Color
7
+ import android.graphics.drawable.GradientDrawable
7
8
  import android.graphics.Rect
8
9
  import android.os.Build
9
10
  import android.view.Gravity
11
+ import android.view.WindowInsetsController
10
12
  import android.view.View
11
13
  import android.view.ViewGroup
12
14
  import android.widget.FrameLayout
@@ -23,6 +25,7 @@ import androidx.window.layout.WindowLayoutInfo
23
25
  import androidx.window.java.layout.WindowInfoTrackerCallbackAdapter
24
26
  import androidx.appcompat.app.AppCompatDelegate
25
27
  import com.facebook.proguard.annotations.DoNotStrip
28
+ import com.facebook.react.ReactRootView
26
29
  import com.facebook.react.bridge.LifecycleEventListener
27
30
  import com.facebook.react.bridge.ReactApplicationContext
28
31
  import com.margelo.nitro.NitroModules
@@ -763,6 +766,35 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven
763
766
  spanningChangedListeners.removeIf { it.id == id }
764
767
  }
765
768
 
769
+ // Android has no window controls inside the app window: the value is always
770
+ // zero and never changes, so listeners are accepted but never called.
771
+ override fun getWindowControlsInsets(): WindowControlsInsets =
772
+ WindowControlsInsets(0.0, 0.0, 0.0, 0.0)
773
+
774
+ override fun addWindowControlsInsetsChangedListener(
775
+ callback: (insets: WindowControlsInsets) -> Unit
776
+ ): Double = synchronized(this) {
777
+ val id = nextListenerId
778
+ nextListenerId++
779
+ return@synchronized id
780
+ }
781
+
782
+ override fun removeWindowControlsInsetsChangedListener(id: Double) {}
783
+
784
+ // Android has no app-owned main menu bar: the config is ignored, and
785
+ // listeners are accepted but never called.
786
+ override fun setMainMenuConfig(config: MainMenuConfig) {}
787
+
788
+ override fun addMainMenuCommandListener(
789
+ callback: (command: MainMenuCommand) -> Unit
790
+ ): Double = synchronized(this) {
791
+ val id = nextListenerId
792
+ nextListenerId++
793
+ return@synchronized id
794
+ }
795
+
796
+ override fun removeMainMenuCommandListener(id: Double) {}
797
+
766
798
  private fun startObservingLayoutChanges() {
767
799
  if (isObservingLayoutChanges) {
768
800
  return
@@ -909,20 +941,34 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven
909
941
  val window = activity.window
910
942
  val decorView = window.decorView
911
943
 
912
- WindowCompat.getInsetsController(window, decorView)
913
- .isAppearanceLightNavigationBars = appearance.useDarkIcons
944
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
945
+ // WindowInsetsControllerCompat leaves the previous value in place on
946
+ // Android 11-14 once the window is appearance-controlled, so runtime
947
+ // theme switches kept stale button colors. Use the platform API.
948
+ window.insetsController?.setSystemBarsAppearance(
949
+ if (appearance.useDarkIcons) WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS else 0,
950
+ WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,
951
+ )
952
+ } else {
953
+ WindowCompat.getInsetsController(window, decorView)
954
+ .isAppearanceLightNavigationBars = appearance.useDarkIcons
955
+ }
914
956
 
915
957
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
916
958
  window.isNavigationBarContrastEnforced = false
917
959
  }
918
960
 
919
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM) {
920
- // Android 15 enforces edge-to-edge. Keep the platform bar transparent
921
- // and draw the requested color only behind three-button navigation.
961
+ if (
962
+ Build.VERSION.SDK_INT >= Build.VERSION_CODES.VANILLA_ICE_CREAM ||
963
+ com.facebook.react.views.view.isEdgeToEdgeFeatureFlagOn
964
+ ) {
965
+ // Edge-to-edge windows (enforced on Android 15, opted in below it) keep
966
+ // the platform bar transparent and draw the requested color only
967
+ // behind three-button navigation.
922
968
  window.navigationBarColor = Color.TRANSPARENT
923
- installNavigationBarProtection(decorView, appearance.color)
969
+ installNavigationBarProtection(activity, appearance.color)
924
970
  } else {
925
- removeNavigationBarProtection(decorView)
971
+ removeNavigationBarProtection(activity)
926
972
  window.navigationBarColor = appearance.color
927
973
  }
928
974
  } catch (e: Exception) {
@@ -934,28 +980,40 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven
934
980
  }
935
981
  }
936
982
 
937
- private fun installNavigationBarProtection(decorView: View, color: Int) {
938
- val decorContainer = decorView as? ViewGroup ?: return
939
- val protectionView = findNavigationBarProtection(decorContainer) ?: View(
940
- decorContainer.context
941
- ).also { view ->
942
- view.tag = NAVIGATION_BAR_PROTECTION_VIEW_TAG
943
- view.isClickable = false
944
- view.isFocusable = false
945
- view.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
946
- decorContainer.addView(
947
- view,
948
- FrameLayout.LayoutParams(
949
- ViewGroup.LayoutParams.MATCH_PARENT,
950
- 0,
951
- Gravity.BOTTOM,
952
- ),
953
- )
954
- }
983
+ private fun installNavigationBarProtection(activity: Activity, color: Int) {
984
+ val decorView = activity.window?.decorView as? ViewGroup ?: return
985
+ val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
986
+ val reactRootIndex = contentView?.let(::findReactRootIndex)
987
+ // Overlay hosts are content-view children added after the React root, and a
988
+ // dimmed overlay must cover this bar together with the rest of the screen,
989
+ // so the protection belongs directly above the React root and below them.
990
+ // While the React root does not exist yet, fall back to the decor view; the
991
+ // next call moves it into place.
992
+ val container =
993
+ if (contentView != null && reactRootIndex != null) contentView else decorView
994
+ val targetIndex =
995
+ if (container === contentView && reactRootIndex != null) {
996
+ reactRootIndex + 1
997
+ } else {
998
+ container.childCount
999
+ }
1000
+ // A detached React root falls back to the decor view while an earlier
1001
+ // protection may still live in the content view. Reuse it (moving it to the
1002
+ // fallback container) and drop any duplicate, so one activity never ends up
1003
+ // with a second protection stacked above later overlays.
1004
+ val protectionView =
1005
+ findNavigationBarProtection(contentView ?: decorView)
1006
+ ?: findNavigationBarProtection(decorView)
1007
+ ?: View(container.context).also { view ->
1008
+ view.tag = NAVIGATION_BAR_PROTECTION_VIEW_TAG
1009
+ view.isClickable = false
1010
+ view.isFocusable = false
1011
+ view.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
1012
+ }
1013
+ removeDuplicateNavigationBarProtections(contentView, decorView, protectionView)
1014
+ placeNavigationBarProtection(container, protectionView, targetIndex)
955
1015
 
956
- protectionView.setBackgroundColor(color)
957
1016
  protectionView.visibility = View.VISIBLE
958
- protectionView.bringToFront()
959
1017
  ViewCompat.setOnApplyWindowInsetsListener(protectionView) { view, windowInsets ->
960
1018
  val navigationBarInsets = windowInsets.getInsets(
961
1019
  WindowInsetsCompat.Type.navigationBars()
@@ -985,6 +1043,17 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven
985
1043
  )
986
1044
  else -> Triple(0, 0, Gravity.BOTTOM)
987
1045
  }
1046
+ // Fade in over the first third from the content edge so the protection never
1047
+ // draws a hard line against the page; the buttons sit on the solid rest.
1048
+ val fadeOrientation = when (gravity) {
1049
+ Gravity.LEFT -> GradientDrawable.Orientation.RIGHT_LEFT
1050
+ Gravity.RIGHT -> GradientDrawable.Orientation.LEFT_RIGHT
1051
+ else -> GradientDrawable.Orientation.TOP_BOTTOM
1052
+ }
1053
+ view.background = GradientDrawable(
1054
+ fadeOrientation,
1055
+ intArrayOf(color and 0x00FFFFFF, color, color, color),
1056
+ )
988
1057
  if (
989
1058
  layoutParams.width != width ||
990
1059
  layoutParams.height != height ||
@@ -1005,9 +1074,57 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven
1005
1074
  ViewCompat.requestApplyInsets(protectionView)
1006
1075
  }
1007
1076
 
1008
- private fun findNavigationBarProtection(decorContainer: ViewGroup): View? {
1009
- for (index in 0 until decorContainer.childCount) {
1010
- val child = decorContainer.getChildAt(index)
1077
+ /** Removes extra protection views left by an earlier fallback. */
1078
+ private fun removeDuplicateNavigationBarProtections(
1079
+ contentView: ViewGroup?,
1080
+ decorView: ViewGroup,
1081
+ keep: View,
1082
+ ) {
1083
+ for (container in listOfNotNull(contentView, decorView)) {
1084
+ for (index in container.childCount - 1 downTo 0) {
1085
+ val child = container.getChildAt(index)
1086
+ if (child !== keep && child.tag == NAVIGATION_BAR_PROTECTION_VIEW_TAG) {
1087
+ ViewCompat.setOnApplyWindowInsetsListener(child, null)
1088
+ container.removeView(child)
1089
+ }
1090
+ }
1091
+ }
1092
+ }
1093
+
1094
+ /** Index of the React root child, or null before the root view exists. */
1095
+ private fun findReactRootIndex(container: ViewGroup): Int? {
1096
+ for (index in 0 until container.childCount) {
1097
+ if (container.getChildAt(index) is ReactRootView) {
1098
+ return index
1099
+ }
1100
+ }
1101
+ return null
1102
+ }
1103
+
1104
+ private fun placeNavigationBarProtection(
1105
+ container: ViewGroup,
1106
+ protectionView: View,
1107
+ index: Int,
1108
+ ) {
1109
+ val parent = protectionView.parent as? ViewGroup
1110
+ if (parent === container && container.indexOfChild(protectionView) == index) {
1111
+ return
1112
+ }
1113
+ parent?.removeView(protectionView)
1114
+ container.addView(
1115
+ protectionView,
1116
+ index.coerceIn(0, container.childCount),
1117
+ FrameLayout.LayoutParams(
1118
+ ViewGroup.LayoutParams.MATCH_PARENT,
1119
+ 0,
1120
+ Gravity.BOTTOM,
1121
+ ),
1122
+ )
1123
+ }
1124
+
1125
+ private fun findNavigationBarProtection(container: ViewGroup): View? {
1126
+ for (index in 0 until container.childCount) {
1127
+ val child = container.getChildAt(index)
1011
1128
  if (child.tag == NAVIGATION_BAR_PROTECTION_VIEW_TAG) {
1012
1129
  return child
1013
1130
  }
@@ -1015,11 +1132,15 @@ class ReactNativeDeviceUtils : HybridReactNativeDeviceUtilsSpec(), LifecycleEven
1015
1132
  return null
1016
1133
  }
1017
1134
 
1018
- private fun removeNavigationBarProtection(decorView: View) {
1019
- val decorContainer = decorView as? ViewGroup ?: return
1020
- val protectionView = findNavigationBarProtection(decorContainer) ?: return
1021
- ViewCompat.setOnApplyWindowInsetsListener(protectionView, null)
1022
- decorContainer.removeView(protectionView)
1135
+ private fun removeNavigationBarProtection(activity: Activity?) {
1136
+ if (activity == null) return
1137
+ val decorView = activity.window?.decorView as? ViewGroup
1138
+ val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
1139
+ for (container in listOfNotNull(contentView, decorView)) {
1140
+ val protectionView = findNavigationBarProtection(container) ?: continue
1141
+ ViewCompat.setOnApplyWindowInsetsListener(protectionView, null)
1142
+ container.removeView(protectionView)
1143
+ }
1023
1144
  }
1024
1145
 
1025
1146
  override fun onHostResume() {
@@ -0,0 +1,170 @@
1
+ import Foundation
2
+ import UIKit
3
+ import ReactNativeNativeLogger
4
+
5
+ /// Detects foldable iPhones such as iPhone Duo.
6
+ ///
7
+ /// Detection runs in two steps so the answer is available synchronously at
8
+ /// launch and still covers models that are not listed yet:
9
+ /// 1. The model identifier is matched against known foldable iPhones.
10
+ /// 2. A `UIHingeInteraction` (iOS 27.1+) confirms the hinge at runtime.
11
+ /// A positive result is persisted, so later launches answer synchronously
12
+ /// even for models that only the hinge check recognized.
13
+ final class DualScreenDetector {
14
+ static let shared = DualScreenDetector()
15
+
16
+ private static let cacheKey = "1k_is_dual_screen_device"
17
+ private static let foldableModelIdentifiers: Set<String> = [
18
+ "iPhone19,4", // iPhone Duo
19
+ ]
20
+
21
+ private let lock = NSLock()
22
+ private var isDualScreen: Bool
23
+ private var spanning = false
24
+ private var listeners: [Double: (Bool) -> Void] = [:]
25
+ private var nextListenerId: Double = 1
26
+ private var hingeInteraction: UIInteraction?
27
+ private var keyWindowObserver: NSObjectProtocol?
28
+ private var resignKeyWindowObserver: NSObjectProtocol?
29
+
30
+ private init() {
31
+ let modelIdentifier = DualScreenDetector.modelIdentifier()
32
+ let isKnownModel = DualScreenDetector.foldableModelIdentifiers.contains(modelIdentifier)
33
+ let isCached = UserDefaults.standard.string(forKey: DualScreenDetector.cacheKey) == modelIdentifier
34
+ isDualScreen = isKnownModel || isCached
35
+ if isKnownModel && !isCached {
36
+ UserDefaults.standard.set(modelIdentifier, forKey: DualScreenDetector.cacheKey)
37
+ }
38
+ OneKeyLog.info(
39
+ "DeviceUtils",
40
+ "Dual screen detection: model=\(modelIdentifier), knownModel=\(isKnownModel), cached=\(isCached)"
41
+ )
42
+ installHingeObserver()
43
+ }
44
+
45
+ static func modelIdentifier() -> String {
46
+ #if targetEnvironment(simulator)
47
+ if let identifier = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"],
48
+ !identifier.isEmpty {
49
+ return identifier
50
+ }
51
+ #endif
52
+ var systemInfo = utsname()
53
+ uname(&systemInfo)
54
+ return withUnsafePointer(to: &systemInfo.machine) { pointer in
55
+ pointer.withMemoryRebound(to: CChar.self, capacity: MemoryLayout.size(ofValue: pointer.pointee)) {
56
+ String(cString: $0)
57
+ }
58
+ }
59
+ }
60
+
61
+ var isDualScreenDevice: Bool {
62
+ lock.lock()
63
+ defer { lock.unlock() }
64
+ return isDualScreen
65
+ }
66
+
67
+ var isSpanning: Bool {
68
+ lock.lock()
69
+ defer { lock.unlock() }
70
+ return spanning
71
+ }
72
+
73
+ func addSpanningChangedListener(_ callback: @escaping (Bool) -> Void) -> Double {
74
+ lock.lock()
75
+ defer { lock.unlock() }
76
+ let id = nextListenerId
77
+ nextListenerId += 1
78
+ listeners[id] = callback
79
+ return id
80
+ }
81
+
82
+ func removeSpanningChangedListener(_ id: Double) {
83
+ lock.lock()
84
+ defer { lock.unlock() }
85
+ listeners.removeValue(forKey: id)
86
+ }
87
+
88
+ private func installHingeObserver() {
89
+ // UIHinge ships in the iOS 27.1 SDK (Swift 6.4). Older toolchains keep
90
+ // the model identifier and cache only.
91
+ #if compiler(>=6.4)
92
+ guard #available(iOS 27.1, *) else { return }
93
+ DispatchQueue.main.async { [weak self] in
94
+ guard let self else { return }
95
+ self.keyWindowObserver = NotificationCenter.default.addObserver(
96
+ forName: UIWindow.didBecomeKeyNotification,
97
+ object: nil,
98
+ queue: .main
99
+ ) { [weak self] notification in
100
+ guard let window = notification.object as? UIWindow else { return }
101
+ self?.attachHingeInteraction(in: window)
102
+ }
103
+ self.resignKeyWindowObserver = NotificationCenter.default.addObserver(
104
+ forName: UIWindow.didResignKeyNotification,
105
+ object: nil,
106
+ queue: .main
107
+ ) { [weak self] notification in
108
+ guard let self, let window = notification.object as? UIWindow,
109
+ self.hingeInteraction?.view === window else { return }
110
+ self.attachHingeInteraction(in: nil)
111
+ }
112
+ self.attachHingeInteraction(in: DualScreenDetector.keyWindow())
113
+ }
114
+ #endif
115
+ }
116
+
117
+ #if compiler(>=6.4)
118
+ @available(iOS 27.1, *)
119
+ private func attachHingeInteraction(in window: UIWindow?) {
120
+ if let interaction = hingeInteraction, interaction.view === window { return }
121
+ let previousInteraction = hingeInteraction
122
+ hingeInteraction = nil
123
+ if let interaction = previousInteraction {
124
+ interaction.view?.removeInteraction(interaction)
125
+ }
126
+ handleHingeUpdate(nil)
127
+ // A listener can change the key window while spanning is reset.
128
+ guard let window, window.isKeyWindow, hingeInteraction == nil else { return }
129
+ let interaction = UIHingeInteraction { [weak self] interaction, update in
130
+ guard let self, self.hingeInteraction === interaction else { return }
131
+ self.handleHingeUpdate(update.hinge)
132
+ }
133
+ hingeInteraction = interaction
134
+ window.addInteraction(interaction)
135
+ }
136
+
137
+ @available(iOS 27.1, *)
138
+ private func handleHingeUpdate(_ hinge: UIHinge?) {
139
+ let nextSpanning = hinge?.status == .fullyOpen || hinge?.status == .partiallyOpen
140
+
141
+ lock.lock()
142
+ let isNewlyDetected = hinge != nil && !isDualScreen
143
+ if hinge != nil { isDualScreen = true }
144
+ let didChangeSpanning = spanning != nextSpanning
145
+ spanning = nextSpanning
146
+ let callbacks = Array(listeners.values)
147
+ lock.unlock()
148
+
149
+ if isNewlyDetected {
150
+ UserDefaults.standard.set(DualScreenDetector.modelIdentifier(), forKey: DualScreenDetector.cacheKey)
151
+ OneKeyLog.info(
152
+ "DeviceUtils",
153
+ "Dual screen detected by hinge: model=\(DualScreenDetector.modelIdentifier())"
154
+ )
155
+ }
156
+ // A newly detected device also notifies, so JS can react without
157
+ // waiting for the next fold.
158
+ if didChangeSpanning || isNewlyDetected {
159
+ callbacks.forEach { $0(nextSpanning) }
160
+ }
161
+ }
162
+ #endif
163
+
164
+ private static func keyWindow() -> UIWindow? {
165
+ UIApplication.shared.connectedScenes
166
+ .compactMap { $0 as? UIWindowScene }
167
+ .flatMap { $0.windows }
168
+ .first { $0.isKeyWindow }
169
+ }
170
+ }