2019-12-04 16:39:53 +00:00
|
|
|
import { Appearance } from 'react-native-appearance';
|
|
|
|
import changeNavigationBarColor from 'react-native-navigation-bar-color';
|
|
|
|
import setRootViewColor from 'rn-root-view';
|
|
|
|
|
|
|
|
import { themes } from '../constants/colors';
|
2021-09-13 20:41:05 +00:00
|
|
|
import { isAndroid } from './deviceInfo';
|
2019-12-04 16:39:53 +00:00
|
|
|
|
|
|
|
let themeListener;
|
|
|
|
|
|
|
|
export const defaultTheme = () => {
|
|
|
|
const systemTheme = Appearance.getColorScheme();
|
|
|
|
if (systemTheme && systemTheme !== 'no-preference') {
|
|
|
|
return systemTheme;
|
|
|
|
}
|
|
|
|
return 'light';
|
|
|
|
};
|
|
|
|
|
2021-09-13 20:41:05 +00:00
|
|
|
export const getTheme = themePreferences => {
|
2019-12-04 16:39:53 +00:00
|
|
|
const { darkLevel, currentTheme } = themePreferences;
|
|
|
|
let theme = currentTheme;
|
|
|
|
if (currentTheme === 'automatic') {
|
|
|
|
theme = defaultTheme();
|
|
|
|
}
|
|
|
|
return theme === 'dark' ? darkLevel : 'light';
|
|
|
|
};
|
|
|
|
|
|
|
|
export const newThemeState = (prevState, newTheme) => {
|
|
|
|
// new theme preferences
|
|
|
|
const themePreferences = {
|
|
|
|
...prevState.themePreferences,
|
|
|
|
...newTheme
|
|
|
|
};
|
|
|
|
// set new state of themePreferences
|
|
|
|
// and theme (based on themePreferences)
|
|
|
|
return { themePreferences, theme: getTheme(themePreferences) };
|
|
|
|
};
|
|
|
|
|
2021-09-13 20:41:05 +00:00
|
|
|
export const setNativeTheme = async themePreferences => {
|
2019-12-04 16:39:53 +00:00
|
|
|
const theme = getTheme(themePreferences);
|
|
|
|
if (isAndroid) {
|
|
|
|
const iconsLight = theme === 'light';
|
2020-05-13 20:26:26 +00:00
|
|
|
try {
|
|
|
|
await changeNavigationBarColor(themes[theme].navbarBackground, iconsLight);
|
|
|
|
} catch (error) {
|
|
|
|
// Do nothing
|
|
|
|
}
|
2019-12-04 16:39:53 +00:00
|
|
|
}
|
|
|
|
setRootViewColor(themes[theme].backgroundColor);
|
|
|
|
};
|
|
|
|
|
|
|
|
export const unsubscribeTheme = () => {
|
|
|
|
if (themeListener && themeListener.remove) {
|
|
|
|
themeListener.remove();
|
|
|
|
themeListener = null;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
export const subscribeTheme = (themePreferences, setTheme) => {
|
|
|
|
const { currentTheme } = themePreferences;
|
|
|
|
if (!themeListener && currentTheme === 'automatic') {
|
|
|
|
// not use listener params because we use getTheme
|
|
|
|
themeListener = Appearance.addChangeListener(() => setTheme());
|
|
|
|
} else if (currentTheme !== 'automatic') {
|
|
|
|
// unsubscribe appearance changes when automatic was disabled
|
|
|
|
unsubscribeTheme();
|
|
|
|
}
|
|
|
|
// set native components theme
|
|
|
|
setNativeTheme(themePreferences);
|
|
|
|
};
|