Add support for native pseudo-OS to Platform.select (#26966)

Summary:
When you write platform-specific code using [file extensions](https://facebook.github.io/react-native/docs/platform-specific-code#platform-specific-extensions), you can specify `.ios.js`, `.android.js`, or the catch-all `.native.js` when you are sharing code with a web project.

This `native` shortcut is missing for the `Platform.select` method, and this PR is adding support for that.

## Changelog

[General] [Added] - Platform.select now supports native as an option.
Pull Request resolved: https://github.com/facebook/react-native/pull/26966

Test Plan: Added relevant passing unit tests for Platform module.

Differential Revision: D18323670

Pulled By: cpojer

fbshipit-source-id: 7524c1914beab4f86041dcf8e60875380ebf7e02
This commit is contained in:
Jorge Bernal
2019-11-05 05:39:20 -08:00
committed by Facebook Github Bot
parent e1d03b4cc0
commit a6fc0898de
3 changed files with 24 additions and 6 deletions
+8 -3
View File
@@ -12,8 +12,9 @@
import NativePlatformConstantsAndroid from './NativePlatformConstantsAndroid';
export type PlatformSelectSpec<A, D> = {
export type PlatformSelectSpec<A, N, D> = {
android?: A,
native?: N,
default?: D,
};
@@ -53,8 +54,12 @@ const Platform = {
get isTV(): boolean {
return this.constants.uiMode === 'tv';
},
select: <A, D>(spec: PlatformSelectSpec<A, D>): A | D =>
'android' in spec ? spec.android : spec.default,
select: <A, N, D>(spec: PlatformSelectSpec<A, N, D>): A | N | D =>
'android' in spec
? spec.android
: 'native' in spec
? spec.native
: spec.default,
};
module.exports = Platform;
+4 -3
View File
@@ -12,8 +12,9 @@
import NativePlatformConstantsIOS from './NativePlatformConstantsIOS';
export type PlatformSelectSpec<D, I> = {
export type PlatformSelectSpec<D, N, I> = {
default?: D,
native?: N,
ios?: I,
};
@@ -59,8 +60,8 @@ const Platform = {
}
return false;
},
select: <D, I>(spec: PlatformSelectSpec<D, I>): D | I =>
'ios' in spec ? spec.ios : spec.default,
select: <D, N, I>(spec: PlatformSelectSpec<D, N, I>): D | N | I =>
'ios' in spec ? spec.ios : 'native' in spec ? spec.native : spec.default,
};
module.exports = Platform;
@@ -27,5 +27,17 @@ describe('Platform', () => {
expect(PlatformIOS.select(obj)).toEqual(obj.ios);
expect(PlatformAndroid.select(obj)).toEqual(obj.android);
});
it('should return native value if no specific value was found', () => {
const obj = {native: 'native', default: 'default'};
expect(PlatformIOS.select(obj)).toEqual(obj.native);
expect(PlatformAndroid.select(obj)).toEqual(obj.native);
});
it('should return default value if no specific value was found', () => {
const obj = {default: 'default'};
expect(PlatformIOS.select(obj)).toEqual(obj.default);
expect(PlatformAndroid.select(obj)).toEqual(obj.default);
});
});
});