setting.ts
2.66 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Reducer } from 'redux';
import { message } from 'antd';
import defaultSettings, { DefaultSettings } from '../../config/defaultSettings';
import themeColorClient from '../components/SettingDrawer/themeColorClient';
export interface SettingModelType {
namespace: 'settings';
state: DefaultSettings;
reducers: {
getSetting: Reducer<DefaultSettings>;
changeSetting: Reducer<DefaultSettings>;
};
}
const updateTheme = (newPrimaryColor?: string) => {
if (newPrimaryColor) {
const timeOut = 0;
const hideMessage = message.loading('正在切换主题!', timeOut);
themeColorClient.changeColor(newPrimaryColor).finally(() => hideMessage());
}
};
const updateColorWeak: (colorWeak: boolean) => void = colorWeak => {
const root = document.getElementById('root');
if (root) {
root.className = colorWeak ? 'colorWeak' : '';
}
};
const SettingModel: SettingModelType = {
namespace: 'settings',
state: defaultSettings,
reducers: {
getSetting(state = defaultSettings) {
const setting: Partial<DefaultSettings> = {};
const urlParams = new URL(window.location.href);
Object.keys(state).forEach(key => {
if (urlParams.searchParams.has(key)) {
const value = urlParams.searchParams.get(key);
setting[key] = value === '1' ? true : value;
}
});
const { primaryColor, colorWeak } = setting;
if (primaryColor && state.primaryColor !== primaryColor) {
updateTheme(primaryColor);
}
updateColorWeak(!!colorWeak);
return {
...state,
...setting,
};
},
changeSetting(state = defaultSettings, { payload }) {
const urlParams = new URL(window.location.href);
Object.keys(defaultSettings).forEach(key => {
if (urlParams.searchParams.has(key)) {
urlParams.searchParams.delete(key);
}
});
Object.keys(payload).forEach(key => {
if (key === 'collapse') {
return;
}
let value = payload[key];
if (value === true) {
value = 1;
}
if (defaultSettings[key] !== value) {
urlParams.searchParams.set(key, value);
}
});
const { primaryColor, colorWeak, contentWidth } = payload;
if (primaryColor && state.primaryColor !== primaryColor) {
updateTheme(primaryColor);
}
if (state.contentWidth !== contentWidth && window.dispatchEvent) {
window.dispatchEvent(new Event('resize'));
}
updateColorWeak(!!colorWeak);
window.history.replaceState(null, 'setting', urlParams.href);
return {
...state,
...payload,
};
},
},
};
export default SettingModel;