fix: return the correct default trait collection (#38214)

Summary:
Currently, when the `_currentColorScheme` is nil the default comes from `[UITraitCollection currentTraitCollection]` which provides the trait collection of the context it was called in. Generally, this will work but in some cases the context can be different and this will return the wrong value also if the `Appearance` property is set in the plist, then initially that value is returned, regardless of if you have overridden it.  Seen as the `userInterfaceStyle` of the window is overridden when the value is changed, then the default should be whatever the current style of the window is and not dependent on the calling context.

<table>
    <tr><th>Before</th><th>After</th></tr>
    <tr>
    <td>
        <video src="https://github.com/facebook/react-native/assets/30924086/3bd2d217-00f2-41d5-9229-05c31da2ecf5"/>
   </td>
   <td>
       <video src="https://github.com/facebook/react-native/assets/30924086/6ed67e4c-dd01-40ff-84fd-0d7ffdf6534c"   />
    </td>
</tr>
</table>

## Changelog:

[IOS] [FIXED] - Fix the default trait collection to always return the value of the window

Pull Request resolved: https://github.com/facebook/react-native/pull/38214

Test Plan: Tested on rn-tester and verified the current behaviour is unaffected and also in our own repo to make sure it addresses the problem. Video provided above

Reviewed By: dmytrorykun

Differential Revision: D49186069

Pulled By: cipolleschi

fbshipit-source-id: f069fea8918fe17c53429564ed2a52e316ce893b
This commit is contained in:
Alan Hughes
2023-09-13 04:39:22 -07:00
committed by Facebook GitHub Bot
parent a8d268593a
commit 94fea182d6
@@ -36,6 +36,15 @@ NSString *RCTCurrentOverrideAppearancePreference()
return sColorSchemeOverride;
}
static UITraitCollection *getKeyWindowTraitCollection()
{
__block UITraitCollection *traitCollection = nil;
RCTExecuteOnMainQueue(^{
traitCollection = RCTSharedApplication().delegate.window.traitCollection;
});
return traitCollection;
}
NSString *RCTColorSchemePreference(UITraitCollection *traitCollection)
{
static NSDictionary *appearances;
@@ -57,7 +66,7 @@ NSString *RCTColorSchemePreference(UITraitCollection *traitCollection)
return RCTAppearanceColorSchemeLight;
}
traitCollection = traitCollection ?: [UITraitCollection currentTraitCollection];
traitCollection = traitCollection ?: getKeyWindowTraitCollection();
return appearances[@(traitCollection.userInterfaceStyle)] ?: RCTAppearanceColorSchemeLight;
// Default to light on older OS version - same behavior as Android.