diff --git a/README.md b/README.md index d0b66b4..f25f1d1 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,21 @@ func application(_ application: UIApplication, supportedInterfaceOrientationsFor ``` +Starting from iOS 27, `application(_:supportedInterfaceOrientationsFor:)` is deprecated in favor of +`UIWindowSceneDelegate.supportedInterfaceOrientations(for:)`. The AppDelegate method above still works, but if your +app adopts the UIScene lifecycle and you build with the iOS 27 SDK, you can implement the new method in your +SceneDelegate instead: + +```swift + +import OrientationDirector + +func supportedInterfaceOrientations(for windowScene: UIWindowScene) -> UIInterfaceOrientationMask { + return SharedOrientationDirectorImpl.shared.supportedInterfaceOrientations +} + +``` + If you need help, you can check the example project. ## Usage @@ -147,6 +162,7 @@ This library exports a class called: [RNOrientationDirector](https://github.com/ | listenForDeviceOrientationChanges | Triggers a provided callback each time the device orientation changes | | listenForInterfaceOrientationChanges | Triggers a provided callback each time the interface orientation changes | | listenForLockChanges | Triggers a provided callback each time the interface orientation status changes | +| listenForDisplayChanges | Triggers a provided callback each time the app moves to a different display | | convertOrientationToHumanReadableString | Returns a human readable string based on the given orientation | | convertAutoRotationToHumanReadableString | Returns a human readable string based on the given auto rotation | | setHumanReadableOrientations | Sets the mapping needed to convert orientation values to human readable strings | @@ -184,6 +200,30 @@ documentation: 2. [iOS - UIDeviceOrientation](https://developer.apple.com/documentation/uikit/uideviceorientation) 3. [Android - getRotation]() +### iOS + +Starting from iOS 16, the interface orientation is read from the window scene geometry, which reflects what the +system actually displays. As a consequence, after calling `lockTo` or `resetSupportedInterfaceOrientations` the new +interface orientation is delivered through the listeners (and hooks) as soon as the system applies it, instead of +being assumed right away. + +#### Foldable devices (iPhone Duo) + +On foldable devices the app moves between the outer and the inner display when the device is folded or unfolded: + +1. The interface orientation is updated on fold / unfold, even though the device itself is not rotated; +2. The device orientation is the one reported by iOS (`UIDevice.orientation`), which is relative to the device body + and does not change on fold / unfold. The iPhone Duo inner display is mounted rotated by 90° relative to the + body, so an unfolded device can report a `portrait` device orientation together with a landscape interface + orientation, exactly like a native app would read them; +3. The inner display is a resizable environment: iOS treats the supported interface orientations as a preference and + ignores them there. This means that `lockTo` has no effect on the inner display, while it keeps working on the + outer one. `isLocked` still reports whether a lock has been requested, and the interface orientation always + reports the orientation actually displayed. + +To be notified when the app moves to another display (e.g. fold / unfold), use `listenForDisplayChanges`: the +orientation values alone might not change in that case. + ### Android Since on Android we need to deal with sensors and their usage, it is worth noting that the device orientation computation works diff --git a/android/src/main/java/com/orientationdirector/OrientationDirectorModule.kt b/android/src/main/java/com/orientationdirector/OrientationDirectorModule.kt index 25f201b..9cbca02 100644 --- a/android/src/main/java/com/orientationdirector/OrientationDirectorModule.kt +++ b/android/src/main/java/com/orientationdirector/OrientationDirectorModule.kt @@ -73,6 +73,14 @@ class OrientationDirectorModule(reactContext: ReactApplicationContext) : } } + override fun sendOnDisplayChanged(params: WritableMap) { + try { + emitOnDisplayChanged(params) + } catch(_: Exception) { + // No listener instance yet + } + } + companion object { const val NAME = OrientationDirectorModuleImpl.NAME } diff --git a/android/src/main/java/com/orientationdirector/implementation/DisplayChangesListener.kt b/android/src/main/java/com/orientationdirector/implementation/DisplayChangesListener.kt new file mode 100644 index 0000000..89cb943 --- /dev/null +++ b/android/src/main/java/com/orientationdirector/implementation/DisplayChangesListener.kt @@ -0,0 +1,106 @@ +package com.orientationdirector.implementation + +import android.content.Context +import android.graphics.Point +import android.hardware.display.DisplayManager +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.view.WindowManager +import com.facebook.react.bridge.ReactApplicationContext + +/** + * Notifies when the app moves to a display with a different physical size, + * e.g. when a foldable device is folded or unfolded. + * + * DisplayManager notifies any display change, rotations included, so the + * physical size is compared regardless of its orientation. + */ +class DisplayChangesListener internal constructor(private val context: ReactApplicationContext) : + DisplayManager.DisplayListener { + + private val displayManager = context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager + private val handler = Handler(Looper.getMainLooper()) + private var isRegistered = false + private var lastPhysicalSize: Pair? = null + + private var onDisplayChangedCallback: ((widthDp: Double, heightDp: Double) -> Unit)? = null + + fun setOnDisplayChangedCallback(callback: (widthDp: Double, heightDp: Double) -> Unit) { + onDisplayChangedCallback = callback + } + + fun register() { + if (isRegistered) { + return + } + + displayManager.registerDisplayListener(this, handler) + isRegistered = true + + // The display might have changed while the listener was unregistered + checkDisplay() + } + + fun unregister() { + if (!isRegistered) { + return + } + + displayManager.unregisterDisplayListener(this) + isRegistered = false + } + + override fun onDisplayAdded(displayId: Int) = Unit + + override fun onDisplayRemoved(displayId: Int) = Unit + + override fun onDisplayChanged(displayId: Int) { + checkDisplay() + } + + private fun checkDisplay() { + val size = computeDisplaySize() ?: return + val physicalSize = Pair(minOf(size.x, size.y), maxOf(size.x, size.y)) + + val previousPhysicalSize = lastPhysicalSize + lastPhysicalSize = physicalSize + + // First sync, nothing changed yet + if (previousPhysicalSize == null || previousPhysicalSize == physicalSize) { + return + } + + val density = computeDensity() + onDisplayChangedCallback?.invoke(size.x / density, size.y / density) + } + + /** + * Returns the size of the display the activity is on, in pixels, + * in the orientation it is currently displayed. + */ + private fun computeDisplaySize(): Point? { + val activity = context.currentActivity ?: return null + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val bounds = activity.windowManager.maximumWindowMetrics.bounds + return Point(bounds.width(), bounds.height()) + } + + val windowManager = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager + val size = Point() + @Suppress("DEPRECATION") + windowManager.defaultDisplay.getRealSize(size) + return size + } + + private fun computeDensity(): Double { + val activity = context.currentActivity + + if (activity != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + return activity.windowManager.maximumWindowMetrics.density.toDouble() + } + + return (activity?.resources ?: context.resources).displayMetrics.density.toDouble() + } +} diff --git a/android/src/main/java/com/orientationdirector/implementation/EventManager.kt b/android/src/main/java/com/orientationdirector/implementation/EventManager.kt index d126d14..3918c76 100644 --- a/android/src/main/java/com/orientationdirector/implementation/EventManager.kt +++ b/android/src/main/java/com/orientationdirector/implementation/EventManager.kt @@ -27,6 +27,14 @@ class EventManager(private val delegate: EventManagerDelegate) { delegate.sendOnLockChanged(params) } + fun sendDisplayDidChange(width: Double, height: Double) { + val params = Arguments.createMap().apply { + putDouble("width", width) + putDouble("height", height) + } + delegate.sendOnDisplayChanged(params) + } + companion object { const val NAME = "OrientationEventManager" } diff --git a/android/src/main/java/com/orientationdirector/implementation/EventManagerDelegate.kt b/android/src/main/java/com/orientationdirector/implementation/EventManagerDelegate.kt index 1f11c17..484bbbd 100644 --- a/android/src/main/java/com/orientationdirector/implementation/EventManagerDelegate.kt +++ b/android/src/main/java/com/orientationdirector/implementation/EventManagerDelegate.kt @@ -6,4 +6,5 @@ fun sendOnDeviceOrientationChanged(params: WritableMap) fun sendOnInterfaceOrientationChanged(params: WritableMap) fun sendOnLockChanged(params: WritableMap) + fun sendOnDisplayChanged(params: WritableMap) } diff --git a/android/src/main/java/com/orientationdirector/implementation/OrientationDirectorModuleImpl.kt b/android/src/main/java/com/orientationdirector/implementation/OrientationDirectorModuleImpl.kt index 27cd29b..c39a88c 100644 --- a/android/src/main/java/com/orientationdirector/implementation/OrientationDirectorModuleImpl.kt +++ b/android/src/main/java/com/orientationdirector/implementation/OrientationDirectorModuleImpl.kt @@ -16,6 +16,7 @@ class OrientationDirectorModuleImpl internal constructor(private val context: Re ) private var mLifecycleListener = LifecycleListener() private var mBroadcastReceiver = ConfigurationChangedBroadcastReceiver(context) + private var mDisplayChangesListener = DisplayChangesListener(context) private var initialSupportedInterfaceOrientations = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED private var lastInterfaceOrientation = Orientation.UNKNOWN @@ -36,6 +37,10 @@ class OrientationDirectorModuleImpl internal constructor(private val context: Re checkInterfaceOrientation(false) } + mDisplayChangesListener.setOnDisplayChangedCallback { width, height -> + mEventManager.sendDisplayDidChange(width, height) + } + // NOTE(1.init): This is needed to compute the initial device orientation mOrientationSensorsEventListener.enable() @@ -46,6 +51,7 @@ class OrientationDirectorModuleImpl internal constructor(private val context: Re } mAutoRotationObserver.enable() mBroadcastReceiver.register() + mDisplayChangesListener.register() } mLifecycleListener.setOnHostPauseCallback { if (!didComputeInitialDeviceOrientation || areOrientationSensorsEnabled) { @@ -53,6 +59,7 @@ class OrientationDirectorModuleImpl internal constructor(private val context: Re } mAutoRotationObserver.disable() mBroadcastReceiver.unregister() + mDisplayChangesListener.unregister() } mLifecycleListener.setOnHostDestroyCallback { if (!didComputeInitialDeviceOrientation || areOrientationSensorsEnabled) { @@ -60,6 +67,7 @@ class OrientationDirectorModuleImpl internal constructor(private val context: Re } mAutoRotationObserver.disable() mBroadcastReceiver.unregister() + mDisplayChangesListener.unregister() } initialSupportedInterfaceOrientations = diff --git a/example/src/screens/Explore.tsx b/example/src/screens/Explore.tsx index ba90ab3..d1cfc4a 100644 --- a/example/src/screens/Explore.tsx +++ b/example/src/screens/Explore.tsx @@ -1,3 +1,4 @@ +import { useEffect, useState } from 'react'; import { Button, Text, View } from 'react-native'; import { exploreStyle } from './styles'; import RNOrientationDirector, { @@ -13,6 +14,16 @@ function Explore() { const interfaceOrientation = useInterfaceOrientation(); const deviceOrientation = useDeviceOrientation(); const isInterfaceOrientationLocked = useIsInterfaceOrientationLocked(); + const [lastDisplayChange, setLastDisplayChange] = useState('None'); + + useEffect(() => { + const subscription = RNOrientationDirector.listenForDisplayChanges( + ({ width, height }) => { + setLastDisplayChange(`${Math.round(width)}x${Math.round(height)}`); + } + ); + return () => subscription.remove(); + }, []); const handleGoToInnerExploreOnPress = () => { navigation.navigate('InnerExplore' as never); @@ -44,6 +55,9 @@ function Explore() { Is Interface Orientation Locked: {isInterfaceOrientationLocked ? 'Yes' : 'No'} + + Last Display Change:{lastDisplayChange} + ); diff --git a/ios/OrientationDirector.mm b/ios/OrientationDirector.mm index 5d02375..116752b 100644 --- a/ios/OrientationDirector.mm +++ b/ios/OrientationDirector.mm @@ -69,6 +69,14 @@ -(void)emitOnLockChangedWithParams:(NSDictionary*)params { } } +-(void)emitDisplayChangedWithParams:(NSDictionary*)params { + try { + [self emitOnDisplayChanged:params]; + } catch (std::exception &e) { + // Ignore if no listeners + } +} + /// /////////////////////////////////////////////////////////////////////////////////////// diff --git a/ios/implementation/EventManager.swift b/ios/implementation/EventManager.swift index 486712a..6e75b97 100644 --- a/ios/implementation/EventManager.swift +++ b/ios/implementation/EventManager.swift @@ -36,10 +36,20 @@ public class EventManager: NSObject { let params = Dictionary(dictionaryLiteral: ("locked", value)) delegate.emitOnLockChanged(params: params as NSDictionary) } + + func sendDisplayDidChange(size: CGSize) { + guard let delegate = delegate else { + return + } + + let params: [String: Any] = ["width": size.width, "height": size.height] + delegate.emitDisplayChanged(params: params as NSDictionary) + } } @objc public protocol OrientationEventEmitterDelegate { func emitOnLockChanged(params: NSDictionary) func emitDeviceOrientationChanged(params: NSDictionary) func emitInterfaceOrientationChanged(params: NSDictionary) + func emitDisplayChanged(params: NSDictionary) } diff --git a/ios/implementation/OrientationDirectorImpl.swift b/ios/implementation/OrientationDirectorImpl.swift index e47d55b..5c07064 100644 --- a/ios/implementation/OrientationDirectorImpl.swift +++ b/ios/implementation/OrientationDirectorImpl.swift @@ -14,12 +14,18 @@ import UIKit private let bundleManager: BundleManager = BundleManager() private let utils: Utils = Utils() private let sensorListener: SensorListener = SensorListener() + private lazy var sceneGeometryListener: SceneGeometryListener = SceneGeometryListener(utils: utils) private let eventManager: EventManager = EventManager() private var initialSupportedInterfaceOrientations: UIInterfaceOrientationMask = UIInterfaceOrientationMask.all private var lastInterfaceOrientation = Orientation.UNKNOWN private var lastDeviceOrientation = Orientation.UNKNOWN private var isLocked = false + /// # Only on iOS >= 16 + /// The screen the scene was on at the last geometry change, + /// used to detect when the app moves to another display (e.g. fold / unfold). + private weak var lastScreen: UIScreen? + /// # Only on iOS < 16 /// This variable is needed to prevent a loop where /// we lock the interface to a specific orientation @@ -40,6 +46,13 @@ import UIKit isLocked = initIsLocked() supportedInterfaceOrientations = initialSupportedInterfaceOrientations + + sceneGeometryListener.setOnGeometryDidChange(callback: self.onSceneGeometryChanged) + sceneGeometryListener.attach() + // The scene might not be connected yet when this module is initialized + DispatchQueue.main.async { [weak self] in + self?.sceneGeometryListener.attach() + } } /////////////////////////////////////////////////////////////////////////////////////// @@ -70,6 +83,14 @@ import UIKit updateIsLockedTo(value: true) + /// On iOS >= 16 the scene geometry listener reports the orientation + /// actually applied by the system, which might differ from the requested + /// one or ignore it entirely (e.g. iPhone Duo inner display). + if #available(iOS 16.0, *) { + self.isLocking = false + return + } + let orientationCanBeUpdatedDirectly = jsOrientation != Orientation.LANDSCAPE if orientationCanBeUpdatedDirectly { updateLastInterfaceOrientationTo(value: jsOrientation) @@ -93,6 +114,11 @@ import UIKit self.requestInterfaceUpdateTo(mask: UIInterfaceOrientationMask.all) updateIsLockedTo(value: false) + + if #available(iOS 16.0, *) { + return + } + self.adaptInterfaceTo(deviceOrientation: lastDeviceOrientation) } @@ -101,6 +127,12 @@ import UIKit self.requestInterfaceUpdateTo(mask: self.supportedInterfaceOrientations) self.updateIsLockedTo(value: self.initIsLocked()) + /// On iOS >= 16 the scene geometry listener reports the orientation + /// actually applied by the system. + if #available(iOS 16.0, *) { + return + } + let lastMask = utils.convertToMaskFrom(jsOrientation: lastInterfaceOrientation) let isLastMaskSupported = self.supportedInterfaceOrientations.contains(lastMask) if isLastMaskSupported { @@ -174,15 +206,53 @@ import UIKit private func onOrientationChanged(uiDeviceOrientation: UIDeviceOrientation) { let deviceOrientation = utils.convertToOrientationFrom(deviceOrientation: uiDeviceOrientation) + updateLastDeviceOrientationTo(value: deviceOrientation) - if (!self.isLocking) { - self.eventManager.sendDeviceOrientationDidChange(value: deviceOrientation.rawValue) + /// On iOS >= 16 the interface orientation is driven by the scene + /// geometry listener, see onSceneGeometryChanged. + if #available(iOS 16.0, *) { + return } - lastDeviceOrientation = deviceOrientation adaptInterfaceTo(deviceOrientation: deviceOrientation) } + /// # Only on iOS >= 16 + /// The scene geometry is the source of truth for the interface orientation: + /// it reflects what the system actually displays, even when the supported + /// interface orientations are ignored (e.g. iPhone Duo inner display) and + /// when the scene moves to another screen (fold / unfold). + private func onSceneGeometryChanged(scene: UIWindowScene) { + checkDisplay(of: scene) + + let interfaceOrientation = utils.getInterfaceOrientation(scene: scene) + if interfaceOrientation == .unknown { + return + } + + let newInterfaceOrientation = utils.convertToOrientationFrom(uiInterfaceOrientation: interfaceOrientation) + updateLastInterfaceOrientationTo(value: newInterfaceOrientation) + } + + private func checkDisplay(of scene: UIWindowScene) { + let screen = scene.screen + + let previousScreen = lastScreen + lastScreen = screen + + // First sync, nothing changed yet + guard let previousScreen = previousScreen else { + return + } + + if previousScreen === screen { + return + } + + eventManager.sendDisplayDidChange(size: screen.bounds.size) + } + + /// # Only on iOS < 16 private func adaptInterfaceTo(deviceOrientation: Orientation) { let supportsLandscape = self.supportedInterfaceOrientations.contains(.landscape) if isLocked && !supportsLandscape { @@ -202,8 +272,24 @@ import UIKit isLocked = value } + private func updateLastDeviceOrientationTo(value: Orientation) { + if value == lastDeviceOrientation { + return + } + + if !self.isLocking { + self.eventManager.sendDeviceOrientationDidChange(value: value.rawValue) + } + + lastDeviceOrientation = value + } + private func updateLastInterfaceOrientationTo(value: Orientation) { - self.eventManager.sendInterfaceOrientationDidChange(value: value.rawValue) + if value == lastInterfaceOrientation { + return + } + + self.eventManager.sendInterfaceOrientationDidChange(value: value.rawValue) lastInterfaceOrientation = value } diff --git a/ios/implementation/SceneGeometryListener.swift b/ios/implementation/SceneGeometryListener.swift new file mode 100644 index 0000000..df28bba --- /dev/null +++ b/ios/implementation/SceneGeometryListener.swift @@ -0,0 +1,88 @@ +// +// SceneGeometryListener.swift +// react-native-orientation-director +// +// Created by gladiuscode on 25/09/2026. +// + +import Foundation +import UIKit + +/// # Only on iOS >= 16 +/// Observes the effective geometry of the current window scene. +/// This is the only reliable source of interface orientation changes: +/// - on foldable devices (iPhone Duo) folding / unfolding moves the scene +/// to another screen without triggering any device orientation change; +/// - the geometry is updated after UIDevice.orientationDidChangeNotification, +/// so reading it from the sensor callback would return a stale value. +/// https://developer.apple.com/documentation/uikit/uiwindowscene/effectivegeometry +public class SceneGeometryListener { + private let utils: Utils + private var onGeometryDidChangeCallback: ((UIWindowScene) -> Void)? + private var observation: NSKeyValueObservation? + private weak var observedScene: UIWindowScene? + + init(utils: Utils) { + self.utils = utils + + NotificationCenter.default.addObserver( + self, + selector: #selector(sceneDidActivate), + name: UIScene.didActivateNotification, + object: nil + ) + } + + deinit { + NotificationCenter.default.removeObserver(self) + observation?.invalidate() + } + + func setOnGeometryDidChange(callback: @escaping (UIWindowScene) -> Void) { + self.onGeometryDidChangeCallback = callback + } + + /// Starts observing the current window scene, if not already observed. + /// The callback is invoked right after attaching so that the caller + /// can sync its state with the current geometry. + func attach() { + attach(to: utils.getCurrentWindow()?.windowScene) + } + + @objc private func sceneDidActivate(_ notification: Notification) { + attach(to: notification.object as? UIWindowScene) + } + + private func attach(to scene: UIWindowScene?) { + guard #available(iOS 16.0, *) else { + return + } + + guard let scene = scene, scene.session.role == .windowApplication else { + return + } + + if observedScene === scene { + return + } + + observedScene = scene + observation?.invalidate() + observation = scene.observe(\.effectiveGeometry, options: [.new]) { [weak self] scene, _ in + self?.notifyGeometryDidChange(scene: scene) + } + + notifyGeometryDidChange(scene: scene) + } + + private func notifyGeometryDidChange(scene: UIWindowScene) { + guard Thread.isMainThread else { + DispatchQueue.main.async { [weak self] in + self?.notifyGeometryDidChange(scene: scene) + } + return + } + + onGeometryDidChangeCallback?(scene) + } +} diff --git a/ios/implementation/Utils.swift b/ios/implementation/Utils.swift index 65b3419..db063d3 100644 --- a/ios/implementation/Utils.swift +++ b/ios/implementation/Utils.swift @@ -93,11 +93,15 @@ class Utils { } } - public func getInterfaceOrientation() -> UIInterfaceOrientation { - guard let windowScene = self.getCurrentWindow()?.windowScene else { + public func getInterfaceOrientation(scene: UIWindowScene? = nil) -> UIInterfaceOrientation { + guard let windowScene = scene ?? self.getCurrentWindow()?.windowScene else { return UIInterfaceOrientation.unknown } + if #available(iOS 16.0, *) { + return windowScene.effectiveGeometry.interfaceOrientation + } + return windowScene.interfaceOrientation } @@ -110,6 +114,7 @@ class Utils { .shared .connectedScenes .compactMap { $0 as? UIWindowScene } + .filter { $0.session.role == .windowApplication } .flatMap { $0.windows } .last { $0.isKeyWindow } } diff --git a/src/EventEmitter.ts b/src/EventEmitter.ts index a827218..a19824d 100644 --- a/src/EventEmitter.ts +++ b/src/EventEmitter.ts @@ -2,6 +2,7 @@ import { type EventSubscription, Platform } from 'react-native'; import NativeOrientationDirector from './NativeOrientationDirector'; import type { OrientationEvent } from './types/OrientationEvent.interface'; import type { LockedEvent } from './types/LockedEvent.interface'; +import type { DisplayChangedEvent } from './types/DisplayChangedEvent.interface'; class EventEmitter { private static androidListenerCount = 0; @@ -34,6 +35,12 @@ class EventEmitter { return NativeOrientationDirector.onLockChanged(callback); } + static addDisplayDidChangeListener( + callback: (event: DisplayChangedEvent) => void + ) { + return NativeOrientationDirector.onDisplayChanged(callback); + } + private static createDeviceOrientationListenerProxy( listener: EventSubscription ) { diff --git a/src/NativeOrientationDirector.ts b/src/NativeOrientationDirector.ts index eb87b8a..14e72b7 100644 --- a/src/NativeOrientationDirector.ts +++ b/src/NativeOrientationDirector.ts @@ -28,6 +28,10 @@ export interface Spec extends TurboModule { orientation: number; }>; readonly onLockChanged: CodegenTypes.EventEmitter<{ locked: boolean }>; + readonly onDisplayChanged: CodegenTypes.EventEmitter<{ + width: number; + height: number; + }>; } export default TurboModuleRegistry.getEnforcing('OrientationDirector'); diff --git a/src/RNOrientationDirector.ts b/src/RNOrientationDirector.ts index 26a8148..ae9eee0 100644 --- a/src/RNOrientationDirector.ts +++ b/src/RNOrientationDirector.ts @@ -7,6 +7,7 @@ import { OrientationType } from './types/OrientationType.enum'; import type { OrientationEvent } from './types/OrientationEvent.interface'; import type { LockableOrientation } from './types/LockableOrientation.type'; import type { LockedEvent } from './types/LockedEvent.interface'; +import type { DisplayChangedEvent } from './types/DisplayChangedEvent.interface'; import type { HumanReadableAutoRotationsResource } from './types/HumanReadableAutoRotationsResource.type'; import EventEmitter from './EventEmitter'; @@ -123,6 +124,19 @@ class RNOrientationDirector { return EventEmitter.addLockDidChangeListener(callback); } + /** + * Triggers the provided callback each time the app moves to a different + * physical display, e.g. when a foldable device is folded or unfolded. + * It is not triggered by rotations or by window resizes (split view, multi-window). + * + * @param callback invoked with the new display size + */ + static listenForDisplayChanges( + callback: (event: DisplayChangedEvent) => void + ) { + return EventEmitter.addDisplayDidChangeListener(callback); + } + static convertOrientationToHumanReadableString(orientation: Orientation) { return RNOrientationDirector._humanReadableOrientationsResource[ orientation diff --git a/src/types/DisplayChangedEvent.interface.ts b/src/types/DisplayChangedEvent.interface.ts new file mode 100644 index 0000000..c99b06d --- /dev/null +++ b/src/types/DisplayChangedEvent.interface.ts @@ -0,0 +1,12 @@ +export interface DisplayChangedEvent { + /** + * Width of the new display, in points (iOS) / dp (Android), + * in the orientation it is currently displayed. + */ + width: number; + /** + * Height of the new display, in points (iOS) / dp (Android), + * in the orientation it is currently displayed. + */ + height: number; +}