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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ React Native date & time picker component for iOS, Android and Windows (please n
- [`firstDayOfWeek` (`optional`, `Android and Windows only`)](#firstdayofweek-optional-android-and-windows-only)
- [`textColor` (`optional`, `iOS only`)](#textColor-optional-ios-only)
- [`accentColor` (`optional`, `iOS only`)](#accentColor-optional-ios-only)
- [`themeVariant` (`optional`, `iOS only`)](#themevariant-optional-ios-only)
- [`themeVariant` (`optional`)](#themevariant-optional)
- [`locale` (`optional`, `iOS only`)](#locale-optional-ios-only)
- [`is24Hour` (`optional`, `Windows and Android only`)](#is24hour-optional-windows-and-android-only)
- [`positiveButton` (`optional`, `Android only`)](#positiveButton-optional-android-only)
Expand Down Expand Up @@ -477,12 +477,14 @@ Allows changing of the textColor of the date picker. Has effect only when `displ
Allows changing the accentColor (tintColor) of the date picker.
Has no effect when `display` is `"spinner"`.

#### `themeVariant` (`optional`, `iOS only`)
#### `themeVariant` (`optional`)

Allows overriding system theme variant (dark or light mode) used by the date picker.

On Android this applies to the default (non-material) date and time dialogs, per dialog, without changing the Activity's night mode. This helps apps with an in-app theme switch that differs from the system theme.
However, we recommend that you instead control the theme of the whole application using [react-native-theme-control](https://github.com/vonovak/react-native-theme-control).

:warning: Has effect only on iOS 14 and later. On iOS 13 & less, use `textColor` to make the picker dark-theme compatible
:warning: On iOS, has effect only on iOS 14 and later. On iOS 13 & less, use `textColor` to make the picker dark-theme compatible

List of possible values:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,12 @@
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.ContextWrapper;
import android.view.LayoutInflater;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
Expand All @@ -15,6 +20,7 @@
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
Expand Down Expand Up @@ -244,6 +250,90 @@ public static Bundle createFragmentArguments(ReadableMap options) {
return args;
}

/**
* Returns a context for the picker dialog whose light/dark look matches the
* `themeVariant` arg ('light' | 'dark'), independent of the Activity's
* current night mode. The theme is built fresh from the Activity's theme
* resource on resources whose uiMode night bit is forced; it is not copied
* from the Activity's live Theme, which may hold attributes resolved under
* the other night mode. Window/system services still come from the
* Activity. Without a themeVariant the Activity context is returned as is.
*/
@Nullable
public static Context applyThemeVariant(@Nullable Context activityContext, @Nullable Bundle args) {
if (activityContext == null || args == null) {
return activityContext;
}
final String variant = args.getString(RNConstants.ARG_THEME_VARIANT);
final int nightFlag;
if ("dark".equals(variant)) {
nightFlag = Configuration.UI_MODE_NIGHT_YES;
} else if ("light".equals(variant)) {
nightFlag = Configuration.UI_MODE_NIGHT_NO;
} else {
return activityContext;
}

int themeResId = 0;
if (activityContext instanceof Activity) {
Activity activity = (Activity) activityContext;
try {
themeResId = activity.getPackageManager()
.getActivityInfo(activity.getComponentName(), 0)
.getThemeResource();
} catch (PackageManager.NameNotFoundException ignored) {
// fall through to the application theme
}
}
if (themeResId == 0) {
themeResId = activityContext.getApplicationInfo().theme;
}

final Configuration current = activityContext.getResources().getConfiguration();
final Configuration override = new Configuration(current);
override.uiMode = (current.uiMode & ~Configuration.UI_MODE_NIGHT_MASK) | nightFlag;
final Resources resources = activityContext.createConfigurationContext(override).getResources();
final Resources.Theme theme = resources.newTheme();
theme.applyStyle(themeResId, true);

return new ThemeVariantContext(activityContext, resources, theme);
}

/** Activity context with the picker's own resources and theme. */
private static final class ThemeVariantContext extends ContextWrapper {
private final Resources mResources;
private final Resources.Theme mTheme;

ThemeVariantContext(Context base, Resources resources, Resources.Theme theme) {
super(base);
mResources = resources;
mTheme = theme;
}

@Override
public Resources getResources() {
return mResources;
}

@Override
public Resources.Theme getTheme() {
return mTheme;
}

@Override
public void setTheme(int resid) {
mTheme.applyStyle(resid, true);
}

@Override
public Object getSystemService(String name) {
if (Context.LAYOUT_INFLATER_SERVICE.equals(name)) {
return LayoutInflater.from(getBaseContext()).cloneInContext(this);
}
return super.getSystemService(name);
}
}

public static Bundle createDatePickerArguments(ReadableMap options) {
final Bundle args = Common.createFragmentArguments(options);

Expand Down Expand Up @@ -276,6 +366,9 @@ public static Bundle createDatePickerArguments(ReadableMap options) {
if (options.hasKey(RNConstants.ARG_START_ON_YEAR_SELECTION) && !options.isNull(RNConstants.ARG_START_ON_YEAR_SELECTION)) {
args.putBoolean(RNConstants.ARG_START_ON_YEAR_SELECTION, options.getBoolean(RNConstants.ARG_START_ON_YEAR_SELECTION));
}
if (options.hasKey(RNConstants.ARG_THEME_VARIANT) && !options.isNull(RNConstants.ARG_THEME_VARIANT)) {
args.putString(RNConstants.ARG_THEME_VARIANT, options.getString(RNConstants.ARG_THEME_VARIANT));
}
return args;
}

Expand All @@ -297,6 +390,9 @@ public static Bundle createTimePickerArguments(ReadableMap options) {
if (options.hasKey(RNConstants.ARG_TZOFFSET_MINS) && !options.isNull(RNConstants.ARG_TZOFFSET_MINS)) {
args.putLong(RNConstants.ARG_TZOFFSET_MINS, (long) options.getDouble(RNConstants.ARG_TZOFFSET_MINS));
}
if (options.hasKey(RNConstants.ARG_THEME_VARIANT) && !options.isNull(RNConstants.ARG_THEME_VARIANT)) {
args.putString(RNConstants.ARG_THEME_VARIANT, options.getString(RNConstants.ARG_THEME_VARIANT));
}

return args;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public final class RNConstants {
public static final String ACTION_NEUTRAL_BUTTON = "neutralButtonAction";
public static final String FIRST_DAY_OF_WEEK = "firstDayOfWeek";
public static final String ARG_START_ON_YEAR_SELECTION = "startOnYearSelection";
public static final String ARG_THEME_VARIANT = "themeVariant";

/**
* Minimum date supported by {@link TimePickerDialog}, 01 Jan 1900
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ DatePickerDialog getDialog(
}

private DatePickerDialog createDialog(Bundle args) {
Context activityContext = getActivity();
Context activityContext = Common.applyThemeVariant(getActivity(), args);
DatePickerDialog dialog = getDialog(args, activityContext, mOnDateSetListener);

if (args != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ static TimePickerDialog getDialog(
}

private TimePickerDialog createDialog(Bundle args) {
Context activityContext = getActivity();
Context activityContext = Common.applyThemeVariant(getActivity(), args);
TimePickerDialog dialog = getDialog(args, activityContext, mOnTimeSetListener);

if (args != null) {
Expand Down
2 changes: 2 additions & 0 deletions src/DateTimePickerAndroid.android.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ function open(props: AndroidNativeProps) {
design,
fullscreen,
startOnYearSelection,
themeVariant,
} = props;
validateAndroidProps(props);
warnIfOnChangeIsUsed(onChange);
Expand Down Expand Up @@ -98,6 +99,7 @@ function open(props: AndroidNativeProps) {
initialInputMode,
fullscreen,
startOnYearSelection,
themeVariant,
});

switch (action) {
Expand Down
5 changes: 5 additions & 0 deletions src/androidUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type OpenParams = {
design: AndroidNativeProps['design'],
fullscreen: AndroidNativeProps['fullscreen'],
startOnYearSelection: AndroidNativeProps['startOnYearSelection'],
themeVariant: AndroidNativeProps['themeVariant'],
};

export type PresentPickerCallback =
Expand All @@ -62,6 +63,7 @@ function getOpenPicker(
dialogButtons,
title,
initialInputMode,
themeVariant,
}: OpenParams) =>
// $FlowFixMe - `AbstractComponent` [1] is not an instance type.
pickers[mode].open({
Expand All @@ -74,6 +76,7 @@ function getOpenPicker(
dialogButtons,
title,
initialInputMode,
themeVariant,
});
default:
return ({
Expand All @@ -90,6 +93,7 @@ function getOpenPicker(
initialInputMode,
fullscreen,
startOnYearSelection,
themeVariant,
}: OpenParams) =>
// $FlowFixMe - `AbstractComponent` [1] is not an instance type.
pickers[ANDROID_MODE.date].open({
Expand All @@ -106,6 +110,7 @@ function getOpenPicker(
initialInputMode,
fullscreen,
startOnYearSelection,
themeVariant,
});
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/datetimepicker.android.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export default function RNDateTimePickerAndroid(
design,
fullscreen,
startOnYearSelection,
themeVariant,
} = props;
const valueTimestamp = value.getTime();

Expand Down Expand Up @@ -74,6 +75,7 @@ export default function RNDateTimePickerAndroid(
design,
fullscreen,
startOnYearSelection,
themeVariant,
};
DateTimePickerAndroid.open(params);
},
Expand Down
9 changes: 8 additions & 1 deletion src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ export type IOSNativeProps = Readonly<
accentColor?: string;

/**
* Override theme variant used by iOS native picker
* Override theme variant used by the native picker (iOS, and Android's
* default design dialogs)
*/
themeVariant?: 'dark' | 'light';

Expand All @@ -166,6 +167,12 @@ export type AndroidNativeProps = Readonly<
*/
mode?: AndroidMode;

/**
* Override the light/dark theme of the default (non-material) date and
* time dialogs, independent of the Activity's night mode.
*/
themeVariant?: 'dark' | 'light';

/**
* The display options.
*
Expand Down
1 change: 1 addition & 0 deletions src/specs/NativeModuleDatePicker.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type DatePickerOpenParams = $ReadOnly<{
timeZoneName?: number,
timeZoneOffsetInMinutes?: number,
startOnYearSelection?: boolean,
themeVariant?: string,
}>;

type DateSetAction = 'dateSetAction' | 'dismissedAction';
Expand Down
1 change: 1 addition & 0 deletions src/specs/NativeModuleTimePicker.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export type TimePickerOpenParams = $ReadOnly<{
is24Hour?: boolean,
minuteInterval?: number,
timeZoneOffsetInMinutes?: number,
themeVariant?: string,
}>;

type TimeSetAction = 'timeSetAction' | 'dismissedAction';
Expand Down
9 changes: 8 additions & 1 deletion src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ export type IOSNativeProps = $ReadOnly<{|
accentColor?: ?ColorValue,

/**
* Override theme variant used by iOS native picker
* Override theme variant used by the native picker (iOS, and Android's
* default design dialogs)
*/
themeVariant?: 'dark' | 'light',

Expand All @@ -195,6 +196,12 @@ export type AndroidNativeProps = $ReadOnly<{|
*/
mode: AndroidMode,

/**
* Override the light/dark theme of the default (non-material) date and
* time dialogs, independent of the Activity's night mode.
*/
themeVariant?: 'dark' | 'light',

/**
* The display options.
*
Expand Down
39 changes: 39 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,45 @@ describe('DateTimePicker', () => {

jest.restoreAllMocks();
});

it('forwards themeVariant to the default date and time pickers', async () => {
const result = {action: 'dismissedAction', timestamp: 0, utcOffset: 0};
const dateOpen = jest.fn(() => Promise.resolve(result));
const timeOpen = jest.fn(() => Promise.resolve(result));
let IsolatedDateTimePickerAndroid;
jest.isolateModules(() => {
jest.doMock('../src/picker', () => ({
__esModule: true,
default: {date: {open: dateOpen}, time: {open: timeOpen}},
}));
({
DateTimePickerAndroid: IsolatedDateTimePickerAndroid,
} = require('../src/DateTimePickerAndroid.android'));
});

const onValueChange = jest.fn();
IsolatedDateTimePickerAndroid.open({
value: new Date(DATE),
mode: 'date',
themeVariant: 'light',
onValueChange,
});
IsolatedDateTimePickerAndroid.open({
value: new Date(DATE),
mode: 'time',
themeVariant: 'dark',
onValueChange,
});
await waitFor(() => expect(timeOpen).toHaveBeenCalled());

expect(dateOpen).toHaveBeenCalledWith(
expect.objectContaining({themeVariant: 'light'}),
);
expect(timeOpen).toHaveBeenCalledWith(
expect.objectContaining({themeVariant: 'dark'}),
);
jest.dontMock('../src/picker');
});
});

describe('RNDateTimePickerIOS', () => {
Expand Down