application-amicale/utils/ThemeManager.js

93 lines
2.4 KiB
JavaScript
Raw Normal View History

// @flow
2019-06-25 22:20:24 +02:00
import {AsyncStorage} from 'react-native'
import platform from '../native-base-theme/variables/platform';
import platformDark from '../native-base-theme/variables/platformDark';
import getTheme from '../native-base-theme/components';
const nightModeKey = 'nightMode';
/**
* Singleton class used to manage themes
*/
2019-06-25 22:20:24 +02:00
export default class ThemeManager {
static instance: ThemeManager | null = null;
nightMode: boolean;
updateThemeCallback: Function;
2019-06-25 22:20:24 +02:00
constructor() {
this.nightMode = false;
this.updateThemeCallback = null;
2019-06-25 22:20:24 +02:00
}
/**
* Get this class instance or create one if none is found
* @returns {ThemeManager}
*/
static getInstance(): ThemeManager {
return ThemeManager.instance === null ?
ThemeManager.instance = new ThemeManager() :
ThemeManager.instance;
2019-06-25 22:20:24 +02:00
}
/**
* Set the function to be called when the theme is changed (allows for general reload of the app)
* @param callback Function to call after theme change
*/
setUpdateThemeCallback(callback: ?Function) {
2019-06-25 22:20:24 +02:00
this.updateThemeCallback = callback;
}
/**
* Read async storage to get preferences
* @returns {Promise<void>}
*/
async getDataFromPreferences(): Promise<void> {
let result: string = await AsyncStorage.getItem(nightModeKey);
2019-06-25 22:20:24 +02:00
if (result === '1')
this.nightMode = true;
// console.log('nightmode: ' + this.nightMode);
2019-06-25 22:20:24 +02:00
}
/**
* Set night mode and save it to preferences
*
* @param isNightMode Whether to enable night mode
*/
setNightMode(isNightMode: boolean) {
2019-06-25 22:20:24 +02:00
this.nightMode = isNightMode;
AsyncStorage.setItem(nightModeKey, isNightMode ? '1' : '0');
if (this.updateThemeCallback !== null)
2019-06-25 22:20:24 +02:00
this.updateThemeCallback();
}
/**
* @returns {boolean} Night mode state
*/
getNightMode(): boolean {
2019-06-25 22:20:24 +02:00
return this.nightMode;
}
/**
* Get the current theme based on night mode
* @returns {Object}
*/
getCurrentTheme(): Object {
2019-06-25 22:20:24 +02:00
if (this.nightMode)
return getTheme(platformDark);
else
return getTheme(platform);
}
/**
* Get the variables contained in the current theme
* @returns {Object}
*/
getCurrentThemeVariables(): Object {
2019-06-28 11:35:15 +02:00
return this.getCurrentTheme().variables;
}
2019-06-25 22:20:24 +02:00
};