2016-08-05 14:05:57 -07:00
|
|
|
import { Observable } from 'rx';
|
2017-02-07 21:26:02 +00:00
|
|
|
import store from 'store';
|
|
|
|
|
2016-08-05 14:05:57 -07:00
|
|
|
import { postJSON$ } from '../../common/utils/ajax-stream';
|
|
|
|
import {
|
2017-07-31 20:04:01 -07:00
|
|
|
types,
|
|
|
|
|
2016-08-05 14:05:57 -07:00
|
|
|
addThemeToBody,
|
|
|
|
updateTheme,
|
2017-07-31 20:04:01 -07:00
|
|
|
|
|
|
|
createErrorObservable,
|
|
|
|
|
|
|
|
themeSelector,
|
|
|
|
csrfSelector
|
|
|
|
} from '../../common/app/redux';
|
2016-08-05 14:05:57 -07:00
|
|
|
|
2017-02-07 21:26:02 +00:00
|
|
|
function persistTheme(theme) {
|
|
|
|
store.set('fcc-theme', theme);
|
|
|
|
}
|
|
|
|
|
2016-08-05 14:05:57 -07:00
|
|
|
export default function nightModeSaga(
|
|
|
|
actions,
|
2017-07-31 20:04:01 -07:00
|
|
|
{ getState },
|
2016-08-05 14:05:57 -07:00
|
|
|
{ document: { body } }
|
|
|
|
) {
|
|
|
|
const toggleBodyClass = actions
|
|
|
|
.filter(({ type }) => types.addThemeToBody === type)
|
|
|
|
.doOnNext(({ payload: theme }) => {
|
|
|
|
if (theme === 'night') {
|
|
|
|
body.classList.add('night');
|
2017-02-07 21:26:02 +00:00
|
|
|
// catch existing night mode users
|
|
|
|
persistTheme(theme);
|
2016-08-05 14:05:57 -07:00
|
|
|
} else {
|
|
|
|
body.classList.remove('night');
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.filter(() => false);
|
2017-09-02 09:09:20 +07:00
|
|
|
|
2016-08-05 14:05:57 -07:00
|
|
|
const toggle = actions
|
|
|
|
.filter(({ type }) => types.toggleNightMode === type);
|
|
|
|
|
|
|
|
const optimistic = toggle
|
|
|
|
.flatMap(() => {
|
2017-09-02 09:09:20 +07:00
|
|
|
const theme = themeSelector(getState());
|
2016-08-05 14:05:57 -07:00
|
|
|
const newTheme = !theme || theme === 'default' ? 'night' : 'default';
|
2017-02-07 21:26:02 +00:00
|
|
|
persistTheme(newTheme);
|
2016-08-05 14:05:57 -07:00
|
|
|
return Observable.of(
|
|
|
|
updateTheme(newTheme),
|
|
|
|
addThemeToBody(newTheme)
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
const ajax = toggle
|
|
|
|
.debounce(250)
|
|
|
|
.flatMapLatest(() => {
|
2017-07-31 20:04:01 -07:00
|
|
|
const _csrf = csrfSelector(getState());
|
|
|
|
const theme = themeSelector(getState());
|
2016-08-05 14:05:57 -07:00
|
|
|
return postJSON$('/update-my-theme', { _csrf, theme })
|
|
|
|
.catch(createErrorObservable);
|
|
|
|
});
|
|
|
|
|
|
|
|
return Observable.merge(optimistic, toggleBodyClass, ajax);
|
|
|
|
}
|