Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions packages/react-native/React/CoreModules/RCTAppearance.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,11 @@

#import <UIKit/UIKit.h>

#import <React/RCTAppearancePreference.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTConvert.h>
#import <React/RCTEventEmitter.h>

RCT_EXTERN void RCTEnableAppearancePreference(BOOL enabled);
RCT_EXTERN void RCTOverrideAppearancePreference(NSString * /*colorSchemeOverride*/);
RCT_EXTERN void RCTUseKeyWindowForSystemStyle(BOOL useMainScreen);
RCT_EXTERN NSString *RCTCurrentOverrideAppearancePreference(void);
RCT_EXTERN NSString *RCTColorSchemePreference(UITraitCollection *traitCollection);

@interface RCTAppearance : RCTEventEmitter <RCTBridgeModule>
- (instancetype)init;
@end
57 changes: 0 additions & 57 deletions packages/react-native/React/CoreModules/RCTAppearance.mm
Original file line number Diff line number Diff line change
Expand Up @@ -15,63 +15,6 @@

using namespace facebook::react;

NSString *const RCTAppearanceColorSchemeLight = @"light";
NSString *const RCTAppearanceColorSchemeDark = @"dark";

static BOOL sAppearancePreferenceEnabled = YES;
void RCTEnableAppearancePreference(BOOL enabled)
{
sAppearancePreferenceEnabled = enabled;
}

static NSString *sColorSchemeOverride = nil;
void RCTOverrideAppearancePreference(NSString *const colorSchemeOverride)
{
sColorSchemeOverride = colorSchemeOverride;
}

static BOOL sUseKeyWindowForSystemStyle = NO;
void RCTUseKeyWindowForSystemStyle(BOOL useMainScreen)
{
sUseKeyWindowForSystemStyle = useMainScreen;
}

NSString *RCTCurrentOverrideAppearancePreference()
{
return sColorSchemeOverride;
}

NSString *RCTColorSchemePreference(UITraitCollection *traitCollection)
{
static NSDictionary *appearances;
static dispatch_once_t onceToken;

if (sColorSchemeOverride) {
return sColorSchemeOverride;
}

dispatch_once(&onceToken, ^{
appearances = @{
@(UIUserInterfaceStyleLight) : RCTAppearanceColorSchemeLight,
@(UIUserInterfaceStyleDark) : RCTAppearanceColorSchemeDark
};
});

if (!sAppearancePreferenceEnabled) {
// Return the default if the app doesn't allow different color schemes.
return RCTAppearanceColorSchemeLight;
}

if (!traitCollection) {
traitCollection = [UITraitCollection currentTraitCollection];
}

UIUserInterfaceStyle systemStyle = sUseKeyWindowForSystemStyle ? RCTKeyWindow().traitCollection.userInterfaceStyle
: traitCollection.userInterfaceStyle;

return appearances[@(systemStyle)] ?: RCTAppearanceColorSchemeLight;
}

@interface RCTAppearance () <NativeAppearanceSpec>
@end

Expand Down
2 changes: 2 additions & 0 deletions packages/react-native/React/Fabric/RCTScheduler.h
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ NS_ASSUME_NONNULL_BEGIN

- (void)reportMount:(facebook::react::SurfaceId)surfaceId;

- (void)setMediaFeatures:(facebook::react::MediaFeatures)mediaFeatures;

- (void)addEventListener:(const std::shared_ptr<facebook::react::EventListener> &)listener;

- (void)removeEventListener:(const std::shared_ptr<facebook::react::EventListener> &)listener;
Expand Down
5 changes: 5 additions & 0 deletions packages/react-native/React/Fabric/RCTScheduler.mm
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,11 @@ - (void)reportMount:(facebook::react::SurfaceId)surfaceId
_scheduler->reportMount(surfaceId);
}

- (void)setMediaFeatures:(facebook::react::MediaFeatures)mediaFeatures
{
_scheduler->setMediaFeatures(mediaFeatures);
}

- (void)dealloc
{
if (_animationDriver) {
Expand Down
44 changes: 44 additions & 0 deletions packages/react-native/React/Fabric/RCTSurfacePresenter.mm
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#import <shared_mutex>
#import <unordered_set>

#import <React/RCTAppearancePreference.h>
#import <React/RCTAssert.h>
#import <React/RCTBridge+Private.h>
#import <React/RCTComponentViewFactory.h>
Expand Down Expand Up @@ -63,6 +64,19 @@ void activityDidChange(const RunLoopObserver::Delegate * /*delegate*/, RunLoopOb
private:
__weak RCTSurfacePresenter *surfacePresenter_;
};

// The key window can be missing at startup. Only on the main thread.
UITraitCollection *currentTraitCollection()
{
return RCTKeyWindow().traitCollection ?: UITraitCollection.currentTraitCollection;
}

// The same color scheme as `useColorScheme()`, with the app's overrides.
MediaFeatures mediaFeaturesFromTraitCollection(UITraitCollection *traitCollection)
{
BOOL isDark = [RCTColorSchemePreference(traitCollection) isEqualToString:@"dark"];
return {.colorScheme = isDark ? ColorScheme::Dark : ColorScheme::Light};
}
} // namespace

@implementation RCTSurfacePresenter {
Expand Down Expand Up @@ -110,11 +124,20 @@ - (instancetype)initWithContextContainer:(std::shared_ptr<const ContextContainer
}

_scheduler = [self _createScheduler];
__weak __typeof(self) weakSelf = self;
// Reads UIKit, so it must run on main. The reload after a fatal JS error (`maxReloadAttempts`) runs this off main.
RCTExecuteOnMainQueue(^{
[weakSelf _updateMediaFeatures:currentTraitCollection()];
});

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_applicationWillTerminate)
name:UIApplicationWillTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_userInterfaceStyleDidChange:)
name:RCTUserInterfaceStyleDidChangeNotification
object:nil];
}

return self;
Expand Down Expand Up @@ -337,6 +360,27 @@ - (void)_applicationWillTerminate
[self suspend];
}

#pragma mark - Media features

- (void)_userInterfaceStyleDidChange:(NSNotification *)notification
{
UITraitCollection *traitCollection =
notification.userInfo[RCTUserInterfaceStyleDidChangeNotificationTraitCollectionKey];
[self _updateMediaFeatures:traitCollection ?: currentTraitCollection()];
}

- (void)_updateMediaFeatures:(UITraitCollection *)traitCollection
{
auto mediaFeatures = mediaFeaturesFromTraitCollection(traitCollection);
if (RCTScheduler *scheduler = [self scheduler]) {
[scheduler setMediaFeatures:mediaFeatures];
} else {
// Suspended: the next scheduler reads the store.
auto store = [self contextContainer]->at<std::shared_ptr<MediaFeaturesStore>>(kMediaFeaturesStoreKey);
store->set(mediaFeatures);
}
}

#pragma mark - RCTSchedulerDelegate

- (void)schedulerDidFinishTransaction:(std::shared_ptr<const MountingCoordinator>)mountingCoordinator
Expand Down
17 changes: 17 additions & 0 deletions packages/react-native/React/Modules/RCTAppearancePreference.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#import <UIKit/UIKit.h>

#import <React/RCTDefines.h>

// Used by the `Appearance` module and by Fabric, so both use the same color scheme.
RCT_EXTERN void RCTEnableAppearancePreference(BOOL enabled);
RCT_EXTERN void RCTOverrideAppearancePreference(NSString * /*colorSchemeOverride*/);
RCT_EXTERN void RCTUseKeyWindowForSystemStyle(BOOL useMainScreen);
RCT_EXTERN NSString *RCTCurrentOverrideAppearancePreference(void);
RCT_EXTERN NSString *RCTColorSchemePreference(UITraitCollection *traitCollection);
67 changes: 67 additions & 0 deletions packages/react-native/React/Modules/RCTAppearancePreference.mm
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#import "RCTAppearancePreference.h"

#import <React/RCTUtils.h>

NSString *const RCTAppearanceColorSchemeLight = @"light";
NSString *const RCTAppearanceColorSchemeDark = @"dark";

static BOOL sAppearancePreferenceEnabled = YES;
void RCTEnableAppearancePreference(BOOL enabled)
{
sAppearancePreferenceEnabled = enabled;
}

static NSString *sColorSchemeOverride = nil;
void RCTOverrideAppearancePreference(NSString *const colorSchemeOverride)
{
sColorSchemeOverride = colorSchemeOverride;
}

static BOOL sUseKeyWindowForSystemStyle = NO;
void RCTUseKeyWindowForSystemStyle(BOOL useMainScreen)
{
sUseKeyWindowForSystemStyle = useMainScreen;
}

NSString *RCTCurrentOverrideAppearancePreference()
{
return sColorSchemeOverride;
}

NSString *RCTColorSchemePreference(UITraitCollection *traitCollection)
{
static NSDictionary *appearances;
static dispatch_once_t onceToken;

if (sColorSchemeOverride) {
return sColorSchemeOverride;
}

dispatch_once(&onceToken, ^{
appearances = @{
@(UIUserInterfaceStyleLight) : RCTAppearanceColorSchemeLight,
@(UIUserInterfaceStyleDark) : RCTAppearanceColorSchemeDark
};
});

if (!sAppearancePreferenceEnabled) {
// Return the default if the app doesn't allow different color schemes.
return RCTAppearanceColorSchemeLight;
}

if (!traitCollection) {
traitCollection = [UITraitCollection currentTraitCollection];
}

UIUserInterfaceStyle systemStyle = sUseKeyWindowForSystemStyle ? RCTKeyWindow().traitCollection.userInterfaceStyle
: traitCollection.userInterfaceStyle;

return appearances[@(systemStyle)] ?: RCTAppearanceColorSchemeLight;
}
Original file line number Diff line number Diff line change
Expand Up @@ -1118,6 +1118,15 @@ void setBinding(FabricUIManagerBinding binding) {
mBinding = binding;
}

/** Sets the media features. `AppearanceModule` calls it, so styles match `useColorScheme()`. */
@UnstableReactNativeAPI
public void setMediaFeatures(boolean isDarkMode) {
final @Nullable FabricUIManagerBinding binding = mBinding;
if (binding != null) {
binding.setMediaFeatures(isDarkMode);
}
}

/**
* Updates the layout metrics of the root view based on the Measure specs received by parameters.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ internal class FabricUIManagerBinding : HybridClassBase() {
uiManager: FabricUIManager,
eventBeatManager: EventBeatManager,
componentsRegistry: ComponentFactory,
isDarkMode: Boolean,
)

external fun startSurface(surfaceId: Int, moduleName: String, initialProps: NativeMap?)
Expand Down Expand Up @@ -65,6 +66,8 @@ internal class FabricUIManagerBinding : HybridClassBase() {

external fun setPixelDensity(pointScaleFactor: Float)

external fun setMediaFeatures(isDarkMode: Boolean)

external fun setConstraints(
surfaceId: Int,
minWidth: Float,
Expand Down Expand Up @@ -95,6 +98,7 @@ internal class FabricUIManagerBinding : HybridClassBase() {
fabricUIManager: FabricUIManager,
eventBeatManager: EventBeatManager,
componentFactory: ComponentFactory,
isDarkMode: Boolean,
) {
fabricUIManager.setBinding(this)

Expand All @@ -104,6 +108,7 @@ internal class FabricUIManagerBinding : HybridClassBase() {
fabricUIManager,
eventBeatManager,
componentFactory,
isDarkMode,
)
setPixelDensity(getDisplayMetricDensity())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import com.facebook.react.bridge.UIManager
import com.facebook.react.bridge.UIManagerProvider
import com.facebook.react.fabric.events.EventBeatManager
import com.facebook.react.uimanager.ViewManagerRegistry
import com.facebook.react.views.common.UiModeUtils
import com.facebook.systrace.Systrace

/**
Expand Down Expand Up @@ -65,6 +66,7 @@ public class FabricUIManagerProviderImpl(
fabricUIManager,
eventBeatManager,
componentFactory,
UiModeUtils.isDarkMode(context.currentActivity ?: context),
)
} else {
throw IllegalStateException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ import com.facebook.jni.annotations.DoNotStrip
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.bridge.buildReadableMap
import com.facebook.react.common.annotations.UnstableReactNativeAPI
import com.facebook.react.fabric.FabricUIManager
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.uimanager.UIManagerHelper
import com.facebook.react.uimanager.common.UIManagerType
import com.facebook.react.views.common.UiModeUtils

/** Module that exposes the user's preferred color scheme. */
Expand All @@ -36,6 +40,8 @@ constructor(
init {
// Register as a listener for color scheme changes if override is provided
overrideColorScheme?.addSchemeChangeListener(schemeChangeListener)
// The renderer starts from `uiMode`, so send the override.
overrideColorScheme?.let { updateMediaFeatures(it.getScheme()) }
}

/** Optional override to the current color scheme */
Expand Down Expand Up @@ -109,9 +115,19 @@ constructor(
if (lastEmittedColorScheme != newColorScheme) {
lastEmittedColorScheme = newColorScheme
emitAppearanceChanged(newColorScheme)
updateMediaFeatures(newColorScheme)
}
}

/** Conditional styles use the same color scheme as `useColorScheme()`. */
@OptIn(UnstableReactNativeAPI::class)
private fun updateMediaFeatures(colorScheme: String) {
val fabricUIManager =
UIManagerHelper.getUIManager(reactApplicationContext, UIManagerType.FABRIC)
as? FabricUIManager
fabricUIManager?.setMediaFeatures(colorScheme == "dark")
}

/** Sends an event to the JS instance that the preferred color scheme has changed. */
public fun emitAppearanceChanged(colorScheme: String) {
val appearancePreferences = buildReadableMap { put("colorScheme", colorScheme) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ import com.facebook.react.uimanager.ViewManagerRegistry
import com.facebook.react.uimanager.ViewManagerResolver
import com.facebook.react.uimanager.events.EventDispatcher
import com.facebook.react.util.RNLog
import com.facebook.react.views.common.UiModeUtils
import com.facebook.soloader.SoLoader
import com.facebook.systrace.Systrace
import com.facebook.systrace.SystraceMessage
Expand Down Expand Up @@ -265,6 +266,7 @@ internal class ReactInstance(
fabricUIManager,
eventBeatManager,
componentFactory,
UiModeUtils.isDarkMode(context.currentActivity ?: context),
)

// Initialize the FabricUIManager
Expand Down
Loading
Loading