1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
import axios from 'axios';
import { createContext, ReactNode, useEffect, useState } from 'react';
import { userPreferences } from '../api/api';
function applyPreferences(preferences: userPreferences) {
if (typeof preferences === 'undefined') return;
document.getElementsByTagName('html')[0].classList[preferences.darkMode ? 'add' : 'remove']('dark');
document.getElementById('theme').setAttribute('href', '/themes/' + preferences.theme);
}
var PreferencesContext = createContext<
{ preferences?: userPreferences; updatePreference?: (newPreference: userPreferences) => void; }
>({});
export function PreferencesContextWrapper(props: { children?: ReactNode; }) {
var server = typeof window === 'undefined';
var loggedIn = !server && document.cookie.includes('token');
var [preferences, setPreferences] = useState<userPreferences>();
var [dummy, setDummy] = useState(false); // FIXME: janky fix to cause rerender
useEffect(() => {
(async () => {
if (!loggedIn) return;
var local_prefs = window.localStorage.getItem('preferences');
if (local_prefs) {
var local_prefs_json = JSON.parse(local_prefs) as userPreferences;
setPreferences(local_prefs_json);
applyPreferences(local_prefs_json);
}
var preferencesReq = await axios.request<{ preferences: userPreferences; }>({
method: 'get',
url: `/api/user/preferences`,
headers: { 'content-type': 'application/json' },
});
window.localStorage.setItem('preferences', JSON.stringify(preferencesReq.data.preferences));
setPreferences(preferencesReq.data.preferences);
})();
}, []);
applyPreferences(preferences);
function updatePreference(newPreference: userPreferences) {
var prefs: userPreferences = Object.assign(preferences, newPreference);
setPreferences(prefs);
axios.request({
method: 'post',
url: `/api/user/preferences`,
headers: { 'content-type': 'application/json' },
data: { 'newPreferences': prefs },
});
setDummy(!dummy);
}
return <PreferencesContext.Provider value={{ preferences, updatePreference }}>
{props.children}
</PreferencesContext.Provider>;
}
export default PreferencesContext;
|