Add settings management functions to choo app; Add language to state

This commit is contained in:
Robbie Antenesse 2019-09-09 14:22:09 -06:00
parent bd749fa796
commit 30cd02f680
1 changed files with 31 additions and 1 deletions

View File

@ -10,10 +10,34 @@ if (process.env.NODE_ENV !== 'production') {
app.use(require('choo-devtools')()); // Exposes `choo` to the console for debugging!
}
app.use((state, emitter) => {
app.getSettingsItem = settingsKey => {
let savedSettings = window.localStorage.getItem('settings');
if (savedSettings) {
savedSettings = JSON.parse(savedSettings);
if (typeof savedSettings[settingsKey] !== 'undefined') {
return savedSettings[settingsKey];
}
}
return null;
}
app.setSettingsItem = (settingsKey, value) => {
let savedSettings = window.localStorage.getItem('settings');
if (savedSettings) {
savedSettings = JSON.parse(savedSettings);
} else {
savedSettings = {};
}
savedSettings[settingsKey] = value;
return window.localStorage.setItem(JSON.stringify(savedSettings));
}
});
// App state and emitters
app.use((state, emitter) => {
// Default state variables
state.currentView = 'home';
state.language = app.getSettingsItem('lang') ? app.getSettingsItem('lang') : (navigator.language || navigator.userLanguage);
state.viewStates = {};
// Listeners
@ -34,6 +58,12 @@ app.use((state, emitter) => {
state.currentView = newView;
emitter.emit('render', () => {});
});
emitter.on('set-language', newLanguage => {
app.setSettingsItem('lang', newLanguage);
state.language = newLanguage;
emitter.emit('render', () => {});
});
});
});
@ -44,4 +74,4 @@ app.route('/', viewManager);
app.route('/:page', viewManager);
app.route('/404', viewManager);
app.mount('body'); // Overwrite the `<body>` tag with the content of the Choo app
app.mount('body'); // Overwrite the `<body>` tag with the content of the Choo app