Unverified Commit be80e7ac authored by Licho's avatar Licho Committed by GitHub

refactor: theme and languange (#2097)

* refactor: package uri wrong, and trivial optimization * refactor: theme Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * Spotless Apply * refactor: theme * fix: not initialized * refactor: add useEffect Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * refactor: format async * chore: async Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * refactor: --------- Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> Co-authored-by: 's avatarleechor <leechor@users.noreply.github.com>
parent beae9eb6
...@@ -67,6 +67,7 @@ ...@@ -67,6 +67,7 @@
"react-helmet-async": "^1.3.0", "react-helmet-async": "^1.3.0",
"react-monaco-editor": "^0.52.0", "react-monaco-editor": "^0.52.0",
"react-spring": "^9.7.1", "react-spring": "^9.7.1",
"react-use-cookie": "^1.4.0",
"screenfull": "^6.0.2", "screenfull": "^6.0.2",
"styled-components": "^6.0.0-rc.3", "styled-components": "^6.0.0-rc.3",
"use-sse": "^2.0.1" "use-sse": "^2.0.1"
......
...@@ -21,13 +21,13 @@ import {PageLoading, Settings as LayoutSettings} from "@ant-design/pro-component ...@@ -21,13 +21,13 @@ import {PageLoading, Settings as LayoutSettings} from "@ant-design/pro-component
import type {RunTimeLayoutConfig} from "@umijs/max"; import type {RunTimeLayoutConfig} from "@umijs/max";
import {history} from "@umijs/max"; import {history} from "@umijs/max";
import defaultSettings from "../config/defaultSettings"; import defaultSettings from "../config/defaultSettings";
import Settings from "../config/defaultSettings";
import {errorConfig} from "./requestErrorConfig"; import {errorConfig} from "./requestErrorConfig";
import {currentUser as queryCurrentUser} from "./services/BusinessCrud"; import {currentUser as queryCurrentUser} from "./services/BusinessCrud";
import {API_CONSTANTS} from "@/services/constants"; import {API_CONSTANTS} from "@/services/constants";
import {THEME} from "@/types/Public/data"; import {THEME} from "@/types/Public/data";
import {UnAccessible} from "@/pages/Other/403"; import {UnAccessible} from "@/pages/Other/403";
import {l} from "@/utils/intl"; import {l} from "@/utils/intl";
import Settings from "../config/defaultSettings";
// const isDev = process.env.NODE_ENV === "development"; // const isDev = process.env.NODE_ENV === "development";
const loginPath = API_CONSTANTS.LOGIN_PATH; const loginPath = API_CONSTANTS.LOGIN_PATH;
...@@ -41,9 +41,8 @@ export async function getInitialState(): Promise<{ ...@@ -41,9 +41,8 @@ export async function getInitialState(): Promise<{
loading?: boolean; loading?: boolean;
fetchUserInfo?: () => Promise<API.CurrentUser | undefined>; fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> { }> {
const fetchUserInfo = async () => { const fetchUserInfo = async () =>
try { queryCurrentUser().then((result) => {
const result = await queryCurrentUser();
const user = result.datas.user; const user = result.datas.user;
const currentUser: API.CurrentUser = { const currentUser: API.CurrentUser = {
user: { user: {
...@@ -65,11 +64,11 @@ export async function getInitialState(): Promise<{ ...@@ -65,11 +64,11 @@ export async function getInitialState(): Promise<{
currentTenant: result.datas.currentTenant, currentTenant: result.datas.currentTenant,
}; };
return currentUser; return currentUser;
} catch (error) { }, (error) => {
history.push(loginPath); history.push(loginPath);
}
return undefined; return undefined;
}; });
// 如果不是登录页面,执行 // 如果不是登录页面,执行
const {location} = history; const {location} = history;
if (location.pathname !== loginPath) { if (location.pathname !== loginPath) {
...@@ -94,19 +93,19 @@ export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => ...@@ -94,19 +93,19 @@ export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) =>
return { return {
headerTitleRender: () => { headerTitleRender: () => {
// 重新对 title 的设置进行设置 // 重新对 title 的设置进行设置
Settings.title =l('layouts.userLayout.title'); Settings.title = l('layouts.userLayout.title');
// 重新对 logo 的设置进行设置 由于 logo 是一个组件,所以需要重新渲染, 重新渲染的时候,会重新执行一次 layout // 重新对 logo 的设置进行设置 由于 logo 是一个组件,所以需要重新渲染, 重新渲染的时候,会重新执行一次 layout
return <> return <>
<img height={50} width={50} src={Settings.logo}/> <img height={50} width={50} src={Settings.logo}/>
<span style={{marginLeft: 10 ,color:'white'}}>{Settings.title}</span> <span style={{marginLeft: 10, color: 'white'}}>{Settings.title}</span>
</>; </>;
}, },
rightContentRender: () => <RightContent />, rightContentRender: () => <RightContent/>,
footerRender: () => <Footer />, footerRender: () => <Footer/>,
siderWidth: 180, siderWidth: 180,
waterMarkProps: { waterMarkProps: {
content: initialState?.currentUser?.user.username + " " + new Date().toLocaleString(), content: initialState?.currentUser?.user.username + " " + new Date().toLocaleString(),
fontColor: theme === THEME.light|| undefined ? "rgba(0, 0, 0, 0.15)" : "rgba(255, 255, 255, 0.15)", fontColor: theme === THEME.light || undefined ? "rgba(0, 0, 0, 0.15)" : "rgba(255, 255, 255, 0.15)",
}, },
isChildrenLayout: true, isChildrenLayout: true,
onPageChange: () => { onPageChange: () => {
...@@ -117,10 +116,10 @@ export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => ...@@ -117,10 +116,10 @@ export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) =>
} }
}, },
// 自定义 403 页面 // 自定义 403 页面
unAccessible:<UnAccessible/>, unAccessible: <UnAccessible/>,
// 增加一个 loading 的状态 // 增加一个 loading 的状态
childrenRender: (children) => { childrenRender: (children) => {
if (initialState?.loading) return <PageLoading />; if (initialState?.loading) return <PageLoading/>;
return ( return (
<> <>
{children} {children}
......
...@@ -15,18 +15,10 @@ ...@@ -15,18 +15,10 @@
* limitations under the License. * limitations under the License.
*/ */
import {STORY_LANGUAGE, VERSION} from '@/services/constants'; import {LANGUAGE_KEY, LANGUAGE_ZH, STORY_LANGUAGE, VERSION} from '@/services/constants';
import {
getLocalStorageLanguage, getValueFromLocalStorage,
setCookieByKey,
setKeyToLocalStorage,
} from '@/utils/function';
import {l} from "@/utils/intl"; import {l} from "@/utils/intl";
import { import useCookie from 'react-use-cookie';
FullscreenExitOutlined, import {FullscreenExitOutlined, FullscreenOutlined, GlobalOutlined} from "@ant-design/icons";
FullscreenOutlined,
GlobalOutlined
} from "@ant-design/icons";
import {useEmotionCss} from "@ant-design/use-emotion-css"; import {useEmotionCss} from "@ant-design/use-emotion-css";
import {SelectLang, useModel} from "@umijs/max"; import {SelectLang, useModel} from "@umijs/max";
import {Space, Switch, Tooltip} from "antd"; import {Space, Switch, Tooltip} from "antd";
...@@ -35,6 +27,7 @@ import screenfull from "screenfull"; ...@@ -35,6 +27,7 @@ import screenfull from "screenfull";
import Avatar from "./AvatarDropdown"; import Avatar from "./AvatarDropdown";
import {ThemeCloud, ThemeStar} from "@/components/ThemeSvg/ThemeSvg"; import {ThemeCloud, ThemeStar} from "@/components/ThemeSvg/ThemeSvg";
import {THEME} from "@/types/Public/data"; import {THEME} from "@/types/Public/data";
import {useLocalStorage} from "@/utils/hook/useLocalStorage";
const GlobalHeaderRight: React.FC = () => { const GlobalHeaderRight: React.FC = () => {
...@@ -42,38 +35,27 @@ const GlobalHeaderRight: React.FC = () => { ...@@ -42,38 +35,27 @@ const GlobalHeaderRight: React.FC = () => {
* status * status
*/ */
const [fullScreen, setFullScreen] = useState(true); const [fullScreen, setFullScreen] = useState(true);
const [themeChecked, setThemeChecked] = useState(false);
const {initialState, setInitialState} = useModel("@@initialState"); const {initialState, setInitialState} = useModel("@@initialState");
const {currentUser,settings} = initialState || {}; const [theme, setTheme] = useLocalStorage(THEME.NAV_THEME, initialState?.settings?.navTheme);
const [language, setLanguage] = useLocalStorage(LANGUAGE_KEY, LANGUAGE_ZH);
const [langCache, setLangCache] = useCookie(STORY_LANGUAGE, language);
/**
* init render theme status
*/
useEffect(() => { useEffect(() => {
const theme :any = getValueFromLocalStorage(THEME.NAV_THEME) !== undefined ? getValueFromLocalStorage(THEME.NAV_THEME) : settings?.navTheme (async () => await setInitialState((initialStateType) => ({
setThemeChecked(theme === THEME.dark ? true : false); ...initialStateType,
setInitialState((preInitialState) => { locale: language,
return {
...preInitialState,
settings: { settings: {
...initialState?.settings, navTheme: theme ...initialStateType?.settings,
navTheme: theme,
colorMenuBackground: (theme === THEME.dark ? "transparent" : "#fff")
} }
}; })))();
}); }, [theme, language]);
}, []);
useEffect(() => { function changeHandler(value: boolean) {
const lang = getLocalStorageLanguage(); setTheme(value ? THEME.dark : THEME.light)
if (lang) { setLangCache(STORY_LANGUAGE, language);
setCookieByKey(STORY_LANGUAGE, lang);
setInitialState((s) => ({
...s,
locale: lang,
}));
} }
}, [initialState?.settings]);
if (!initialState || !initialState.settings) { if (!initialState || !initialState.settings) {
return null; return null;
...@@ -128,17 +110,17 @@ const GlobalHeaderRight: React.FC = () => { ...@@ -128,17 +110,17 @@ const GlobalHeaderRight: React.FC = () => {
const screenFull = () => { const screenFull = () => {
setFullScreen(screenfull.isFullscreen); setFullScreen(screenfull.isFullscreen);
if (screenfull.isEnabled) { if (screenfull.isEnabled) {
screenfull.toggle(); (async () => await screenfull.toggle())();
} }
}; };
const fullScreenProps = { const fullScreenProps = {
style: {color: "white"}, style: {color: "white"},
className: fullScreenClassName className: fullScreenClassName
}; };
const menuVersion = l("menu.version", "", {version: VERSION});
return ( return (
<> <>
<Tooltip placement="bottom" <Tooltip placement="bottom"
...@@ -147,30 +129,16 @@ const GlobalHeaderRight: React.FC = () => { ...@@ -147,30 +129,16 @@ const GlobalHeaderRight: React.FC = () => {
<FullscreenExitOutlined {...fullScreenProps} onClick={screenFull}/>} <FullscreenExitOutlined {...fullScreenProps} onClick={screenFull}/>}
</Tooltip> </Tooltip>
<Avatar/> <Avatar/>
<Tooltip <Tooltip placement="bottom" title={<span>{menuVersion}</span>}>
placement="bottom" <Space className={actionClassName}>{menuVersion}</Space>
title={<span>{l("menu.version", "", {version: VERSION})}</span>}
>
<Space className={actionClassName}>{l("menu.version", "", {version: VERSION})}</Space>
</Tooltip> </Tooltip>
<SelectLang icon={<GlobalOutlined/>} className={actionClassName}/> <SelectLang icon={<GlobalOutlined/>} className={actionClassName}/>
<Switch <Switch
key={"themeSwitch"} key={"themeSwitch"}
checked={themeChecked} checked={theme === THEME.dark}
checkedChildren={<ThemeCloud/>} checkedChildren={<ThemeCloud/>}
unCheckedChildren={<ThemeStar/>} unCheckedChildren={<ThemeStar/>}
onChange={(value) => { onChange={changeHandler}/>
setKeyToLocalStorage(THEME.NAV_THEME, !value ? THEME.light : THEME.dark);
setInitialState((preInitialState :any) => {
return {
...preInitialState,
settings: {
...settings, navTheme: !value ? THEME.light : THEME.dark,colorMenuBackground: (getValueFromLocalStorage(THEME.NAV_THEME) === THEME.dark ? "transparent" : "#fff")
}
};
});
setThemeChecked(value);
}}/>
</> </>
); );
}; };
......
...@@ -46,7 +46,7 @@ const LoginForm: React.FC<LoginFormProps> = (props) => { ...@@ -46,7 +46,7 @@ const LoginForm: React.FC<LoginFormProps> = (props) => {
getData(API_CONSTANTS.GET_LDAP_ENABLE).then(res => { getData(API_CONSTANTS.GET_LDAP_ENABLE).then(res => {
setLdapEnabled(res.datas) setLdapEnabled(res.datas)
form.setFieldValue("ldapLogin",res.datas) form.setFieldValue("ldapLogin",res.datas)
}) }, err => console.error(err))
}, []); }, []);
......
...@@ -38,7 +38,7 @@ const APPLICATION_JSON = 'application/json'; ...@@ -38,7 +38,7 @@ const APPLICATION_JSON = 'application/json';
export async function currentUser(options?: { [key: string]: any }) { export async function currentUser(options?: { [key: string]: any }) {
return request<API.Result>(API_CONSTANTS.CURRENT_USER, { return request<API.Result>(API_CONSTANTS.CURRENT_USER, {
method: METHOD_CONSTANTS.GET, method: METHOD_CONSTANTS.GET,
...(options || {}), ...(options ?? {}),
}); });
} }
...@@ -49,7 +49,7 @@ export async function currentUser(options?: { [key: string]: any }) { ...@@ -49,7 +49,7 @@ export async function currentUser(options?: { [key: string]: any }) {
export async function outLogin(options?: { [key: string]: any }) { export async function outLogin(options?: { [key: string]: any }) {
return request<Record<string, any>>(API_CONSTANTS.LOGOUT, { return request<Record<string, any>>(API_CONSTANTS.LOGOUT, {
method: METHOD_CONSTANTS.DELETE, method: METHOD_CONSTANTS.DELETE,
...(options || {}), ...(options ?? {}),
}); });
} }
...@@ -65,7 +65,7 @@ export async function login(body: API.LoginParams, options?: { [key: string]: an ...@@ -65,7 +65,7 @@ export async function login(body: API.LoginParams, options?: { [key: string]: an
CONTENT_TYPE: APPLICATION_JSON, CONTENT_TYPE: APPLICATION_JSON,
}, },
data: body, data: body,
...(options || {}), ...(options ?? {}),
}); });
} }
...@@ -95,9 +95,9 @@ export const handleAddOrUpdate = async (url: string, params: any) => { ...@@ -95,9 +95,9 @@ export const handleAddOrUpdate = async (url: string, params: any) => {
try { try {
const {code, msg} = await addOrUpdateData(url, {...params}); const {code, msg} = await addOrUpdateData(url, {...params});
if (code === RESPONSE_CODE.SUCCESS) { if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg); await SuccessMessage(msg);
} else { } else {
WarningMessage(msg); await WarningMessage(msg);
} }
return true; return true;
} catch (error) { } catch (error) {
...@@ -115,9 +115,9 @@ export const handleRemoveById = async (url: string, id: number) => { ...@@ -115,9 +115,9 @@ export const handleRemoveById = async (url: string, id: number) => {
try { try {
const {code, msg} = await removeById(url, {id}); const {code, msg} = await removeById(url, {id});
if (code === RESPONSE_CODE.SUCCESS) { if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg); await SuccessMessage(msg);
} else { } else {
WarningMessage(msg); await WarningMessage(msg);
} }
return true; return true;
} catch (error) { } catch (error) {
...@@ -134,9 +134,9 @@ export const updateEnabled = async (url: string, params: any) => { ...@@ -134,9 +134,9 @@ export const updateEnabled = async (url: string, params: any) => {
try { try {
const {code, msg} = await updateDataByParams(url, {...params}); const {code, msg} = await updateDataByParams(url, {...params});
if (code === RESPONSE_CODE.SUCCESS) { if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg); await SuccessMessage(msg);
} else { } else {
WarningMessage(msg); await WarningMessage(msg);
} }
return true; return true;
} catch (error) { } catch (error) {
...@@ -149,10 +149,10 @@ export const handleOption = async (url: string, title: string, param: any) => { ...@@ -149,10 +149,10 @@ export const handleOption = async (url: string, title: string, param: any) => {
try { try {
const result = await postAll(url, param); const result = await postAll(url, param);
if (result.code === RESPONSE_CODE.SUCCESS) { if (result.code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(result.msg); await SuccessMessage(result.msg);
return result; return result;
} else { } else {
WarningMessage(result.msg); await WarningMessage(result.msg);
return false; return false;
} }
} catch (error) { } catch (error) {
...@@ -180,9 +180,9 @@ export const handlePutData = async (url: string, fields: any) => { ...@@ -180,9 +180,9 @@ export const handlePutData = async (url: string, fields: any) => {
try { try {
const {code, msg} = await postAll(url, {...fields}); const {code, msg} = await postAll(url, {...fields});
if (code === RESPONSE_CODE.SUCCESS) { if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg); await SuccessMessage(msg);
} else { } else {
WarningMessage(msg); await WarningMessage(msg);
} }
return true; return true;
} catch (error) { } catch (error) {
...@@ -215,10 +215,10 @@ export const handlePutDataByParams = async (url: string, title: string, params: ...@@ -215,10 +215,10 @@ export const handlePutDataByParams = async (url: string, title: string, params:
try { try {
const {code, msg} = await putData(url, {...params}); const {code, msg} = await putData(url, {...params});
if (code === RESPONSE_CODE.SUCCESS) { if (code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(msg); await SuccessMessage(msg);
return true; return true;
} else { } else {
WarningMessage(msg); await WarningMessage(msg);
return false; return false;
} }
} catch (error) { } catch (error) {
...@@ -231,10 +231,10 @@ export const getDataByIdReturnResult = async (url: string, id: any) => { ...@@ -231,10 +231,10 @@ export const getDataByIdReturnResult = async (url: string, id: any) => {
try { try {
const result = await getInfoById(url, id); const result = await getInfoById(url, id);
if (result.code === RESPONSE_CODE.SUCCESS) { if (result.code === RESPONSE_CODE.SUCCESS) {
SuccessMessage(result.msg); await SuccessMessage(result.msg);
return result; return result;
} else { } else {
WarningMessage(result.msg); await WarningMessage(result.msg);
return false; return false;
} }
} catch (error) { } catch (error) {
......
...@@ -231,11 +231,11 @@ export const LANGUAGE_EN = 'en-US'; ...@@ -231,11 +231,11 @@ export const LANGUAGE_EN = 'en-US';
/** /**
* REQUEST METHOD CONSTANTS * REQUEST METHOD CONSTANTS
*/ */
export const METHOD_CONSTANTS = { export enum METHOD_CONSTANTS {
GET: "GET", GET = "GET",
POST: "POST", POST = "POST",
PUT: "PUT", PUT = "PUT",
DELETE: "DELETE", DELETE = "DELETE",
}; };
......
...@@ -39,15 +39,15 @@ import {l} from '@/utils/intl'; ...@@ -39,15 +39,15 @@ import {l} from '@/utils/intl';
/** /**
* get language by localStorage's umi_locale , if not exist , return zh-CN * get language by localStorage's umi_locale , if not exist , return zh-CN
* @param tenantId
*/ */
export function getLocalStorageLanguage() { export function getLocalStorageLanguage() {
return localStorage.getItem(LANGUAGE_KEY) || LANGUAGE_ZH; return localStorage.getItem(LANGUAGE_KEY) ?? LANGUAGE_ZH;
} }
/** /**
* set key value to localStorage * set key value to localStorage
* @param tenantId * @param key
* @param value
*/ */
export function setKeyToLocalStorage(key: string, value: string) { export function setKeyToLocalStorage(key: string, value: string) {
localStorage.setItem(key, value); localStorage.setItem(key, value);
...@@ -56,16 +56,15 @@ export function setKeyToLocalStorage(key: string, value: string) { ...@@ -56,16 +56,15 @@ export function setKeyToLocalStorage(key: string, value: string) {
/** /**
* get value by localStorage's key * get value by localStorage's key
* @param tenantId * @param key
*/ */
export function getValueFromLocalStorage(key: string) { export function getValueFromLocalStorage(key: string) {
return localStorage.getItem(key) || ''; return localStorage.getItem(key) ?? '';
} }
/** /**
* get tenant id * get tenant id
* @param tenantId
*/ */
export function getTenantByLocalStorage() { export function getTenantByLocalStorage() {
return getValueFromLocalStorage(TENANT_ID); return getValueFromLocalStorage(TENANT_ID);
...@@ -74,15 +73,17 @@ export function getTenantByLocalStorage() { ...@@ -74,15 +73,17 @@ export function getTenantByLocalStorage() {
/** /**
* get cookie by key * get cookie by key
* @param tenantId * @param key
*/ */
export function getCookieByKey(key: string) { export function getCookieByKey(key: string) {
return cookies.get(key) || ''; return cookies.get(key) ?? '';
} }
/** /**
* set cookie by key * set cookie by key
* @param tenantId * @param key
* @param value
* @param options
*/ */
export function setCookieByKey(key: string, value: string, options?: {}) { export function setCookieByKey(key: string, value: string, options?: {}) {
cookies.set(key, value, options); cookies.set(key, value, options);
......
import React from "react";
export function useLocalStorage(key: string, initialValue: any) {
const readValue = React.useCallback(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.warn(error);
return initialValue;
}
}, [key, initialValue]);
const [localState, setLocalState] = React.useState(readValue);
const handleSetState = React.useCallback(
(value: any) => {
try {
const nextState =
typeof value === "function" ? value(localState) : value;
window.localStorage.setItem(key, JSON.stringify(nextState));
setLocalState(nextState);
window.dispatchEvent(new Event("local-storage"));
} catch (e) {
console.warn(e);
}
},
[key, localState]
);
return [localState, handleSetState];
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment