Skip to content

Commit df689df

Browse files
committed
refactor(projects): add logout route
1 parent 6ff150b commit df689df

File tree

14 files changed

+126
-114
lines changed

14 files changed

+126
-114
lines changed

build/plugins/router.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ export function setupElegantRouter() {
2222
'document_vite',
2323
'document_unocss',
2424
'document_proComponents',
25-
'document_antd'
25+
'document_antd',
26+
'logout'
2627
]
2728
},
2829
onRouteMetaGen(routeName) {

packages/simple-router/src/router.tsx

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import CreateRouterMatcher from './matcher';
1010
import type { RouteRecordNormalized, RouteRecordRaw } from './matcher/types';
1111
import { START_LOCATION_NORMALIZED } from './types';
1212
import { RouterContext } from './hooks/useRouter';
13-
1413
import { warn } from './warning';
1514

1615
const historyCreatorMap: Record<
@@ -102,7 +101,6 @@ class CreateRouter {
102101
return reactRoute;
103102
})
104103
.filter(Boolean);
105-
console.log(this.reactRouter);
106104

107105
// Add to react-router's routes
108106
this.reactRouter.patchRoutes(parent, reactRoutes);

packages/simple-router/src/types/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
2-
1+
/* eslint-disable */
2+
/* prettier-ignore */
3+
// @ts-nocheck
34
import type { ElegantConstRoute, RouteMeta } from '@ohh-889/react-auto-route';
45
import type { RouteObject } from 'react-router-dom';
56
import type { Router as RemixRouter } from '@remix-run/router';

src/hooks/common/routerPush.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,19 +75,15 @@ export function useRouterPush() {
7575
async function toLogin(loginModule?: UnionKey.LoginModule, redirectUrl?: string) {
7676
const module = loginModule || 'pwd-login';
7777

78-
const options: RouterPushOptions = {
79-
params: {
80-
module
81-
}
82-
};
78+
const options: RouterPushOptions = {};
8379

8480
const redirect = redirectUrl || router.currentRoute.fullPath;
8581

8682
options.query = {
8783
redirect
8884
};
8985

90-
return routerPushByKey('login', options);
86+
return routerPushByKey(`login_${module}`, options);
9187
}
9288

9389
/**
@@ -119,6 +115,7 @@ export function useRouterPush() {
119115
return {
120116
routerPush,
121117
routerBack,
118+
routerPushByKey,
122119
toLogin,
123120
routerPushByKeyWithMetaQuery,
124121
redirectFromLogin,

src/layouts/modules/global-header/components/UserAvatar.tsx

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,26 @@
11
import { Button, Dropdown } from 'antd';
22
import type { MenuProps } from 'antd';
3-
import { useNavigate } from 'react-router-dom';
4-
import { resetStore, selectToken, selectUserInfo } from '@/store/slice/auth';
3+
import { useSubmit } from 'react-router-dom';
4+
import { selectToken, selectUserInfo } from '@/store/slice/auth';
55

66
const UserAvatar = memo(() => {
77
const token = useAppSelector(selectToken);
8-
const dispatch = useAppDispatch();
98
const { t } = useTranslation();
109
const userInfo = useAppSelector(selectUserInfo);
11-
const navigate = useNavigate();
10+
const submit = useSubmit();
11+
const route = useRoute();
12+
const router = useRouterPush();
13+
1214
function logout() {
1315
window?.$modal?.confirm({
1416
title: t('common.tip'),
1517
content: t('common.logoutConfirm'),
1618
okText: t('common.confirm'),
1719
cancelText: t('common.cancel'),
1820
onOk: () => {
19-
loginOrRegister();
21+
let needRedirect = false;
22+
if (!route.meta?.constant) needRedirect = true;
23+
submit({ redirectFullPath: route.fullPath, needRedirect }, { method: 'post', action: '/logout' });
2024
}
2125
});
2226
}
@@ -25,11 +29,11 @@ const UserAvatar = memo(() => {
2529
if (key === '1') {
2630
logout();
2731
} else {
28-
navigate('/user-center');
32+
router.routerPushByKey('user-center');
2933
}
3034
}
3135
function loginOrRegister() {
32-
dispatch(resetStore());
36+
router.routerPushByKey('login');
3337
}
3438

3539
const items: MenuProps['items'] = [

src/locales/langs/en-us/route.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const route: App.I18n.Schema['translation']['route'] = {
66
'iframe-page': 'Iframe',
77
home: 'Home',
88
document: 'Document',
9+
logout: 'Logout',
910
document_project: 'Project Document',
1011
'document_project-link': 'Project Document(External Link)',
1112
document_react: 'React Document',

src/locales/langs/zh-cn/route.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ const route: App.I18n.Schema['translation']['route'] = {
66
'iframe-page': '外链页面',
77
home: '首页',
88
document: '文档',
9+
logout: '退出登录',
910
document_project: '项目文档',
1011
'document_project-link': '项目文档(外链)',
1112
document_react: 'React文档',

src/router/elegant/transform.ts

Lines changed: 52 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,20 @@
55
// Vue auto route: https://github.com/soybeanjs/elegant-router
66

77

8-
import type { LazyRouteFunction, RouteObject,IndexRouteObject } from "react-router-dom";
9-
import type { FunctionComponent } from "react";
8+
import type { IndexRouteObject, LazyRouteFunction,RouteObject } from "react-router-dom";
9+
import type { FunctionComponent } from 'react';
1010
import type { ElegantConstRoute } from '@ohh-889/react-auto-route';
11-
import type { RouteMap, RouteKey, RoutePath } from '@elegant-router/types';
12-
import { redirect as redirectTo } from 'react-router-dom'
11+
import type { RouteKey, RouteMap, RoutePath } from '@elegant-router/types';
12+
import { redirect as redirectTo } from 'react-router-dom';
1313
import ErrorBoundary from "../../../ErrorBoundary.tsx"
1414

15-
16-
type CustomRouteObject = Omit<RouteObject, 'Component'|'index'> & {
17-
Component?: React.ComponentType<any>|null;
15+
type CustomRouteObject = Omit<RouteObject, 'Component' | 'index'> & {
16+
Component?: React.ComponentType<any> | null;
1817
};
1918

20-
2119
/**
2220
* transform elegant const routes to react routes
21+
*
2322
* @param routes elegant const routes
2423
* @param layouts layout components
2524
* @param views view components
@@ -34,15 +33,16 @@ export function transformElegantRoutesToReactRoutes(
3433

3534
/**
3635
* transform elegant route to react route
36+
*
3737
* @param route elegant const route
3838
* @param layouts layout components
3939
* @param views view components
4040
*/
4141
export function transformElegantRouteToReactRoute(
4242
route: ElegantConstRoute,
4343
layouts: Record<string, LazyRouteFunction<CustomRouteObject>>,
44-
views: Record<string,LazyRouteFunction<CustomRouteObject>>
45-
):RouteObject {
44+
views: Record<string, LazyRouteFunction<CustomRouteObject>>
45+
): RouteObject {
4646
const LAYOUT_PREFIX = 'layout.';
4747
const VIEW_PREFIX = 'view.';
4848
const ROUTE_DEGREE_SPLITTER = '_';
@@ -55,7 +55,7 @@ export function transformElegantRouteToReactRoute(
5555
function getLayoutName(component: string) {
5656
const layout = component.replace(LAYOUT_PREFIX, '');
5757

58-
if(!layouts[layout]) {
58+
if (!layouts[layout]) {
5959
throw new Error(`Layout component "${layout}" not found`);
6060
}
6161

@@ -69,7 +69,7 @@ export function transformElegantRouteToReactRoute(
6969
function getViewName(component: string) {
7070
const view = component.replace(VIEW_PREFIX, '');
7171

72-
if(!views[view]) {
72+
if (!views[view]) {
7373
throw new Error(`View component "${view}" not found`);
7474
}
7575

@@ -88,31 +88,36 @@ export function transformElegantRouteToReactRoute(
8888
const [layout, view] = component.split(FIRST_LEVEL_ROUTE_COMPONENT_SPLIT);
8989

9090
return {
91-
layout: layout?getLayoutName(layout):undefined,
91+
layout: layout ? getLayoutName(layout) : undefined,
9292
view: getViewName(view)
9393
};
9494
}
9595

96+
const { name, props, path, meta, component, children, redirect, layout, ...rest } = route;
9697

97-
const { name,props, path,meta, component, children,redirect,layout,loader, ...rest } = route;
98-
99-
const reactRoute = {id:name, path,handle: {
100-
...meta
101-
}, children:[],ErrorBoundary }as RouteObject
98+
const reactRoute = {
99+
id: name,
100+
path,
101+
handle: {
102+
...meta
103+
},
104+
children: [],
105+
ErrorBoundary
106+
} as RouteObject;
102107

103108
try {
104109
if (component) {
105110
if (isSingleLevelRoute(route)) {
106111
const { layout, view } = getSingleLevelRouteComponent(component);
107112

108-
if (layout) {
109-
const singleLevelRoute:RouteObject= {
113+
if (layout) {
114+
const singleLevelRoute: RouteObject = {
110115
path,
111116
lazy: layouts[layout],
112117
ErrorBoundary,
113118
children: [
114119
{
115-
id:name,
120+
id: name,
116121
index: true,
117122
lazy: views[view],
118123
handle: {
@@ -123,77 +128,67 @@ export function transformElegantRouteToReactRoute(
123128
]
124129
};
125130

126-
return singleLevelRoute;
131+
return singleLevelRoute;
127132
}
128133

129-
return {
134+
return {
130135
path,
131136
lazy: views[view],
132137
id: name,
133138
...rest
134-
} as RouteObject;
139+
} as RouteObject;
135140
}
136141

137142
if (isLayout(component)) {
138143
if (layout) {
139-
reactRoute.lazy=views[name]
144+
reactRoute.lazy = views[name];
140145
} else {
141146
const layoutName = getLayoutName(component);
142147
reactRoute.lazy = layouts[layoutName];
143148
}
144-
145149
}
146150

147-
148151
if (isView(component)) {
149152
const viewName = getViewName(component);
150153
if (props) {
151154
reactRoute.lazy = async () => {
152-
const data= (await views[viewName]()).Component as FunctionComponent
155+
const data = (await views[viewName]()).Component as FunctionComponent;
153156
return {
154-
Component: ()=>data(props) ,
155-
ErrorBoundary: null
156-
}
157-
}
157+
Component: () => data(props),
158+
ErrorBoundary: null
159+
};
160+
};
158161
} else {
159-
reactRoute.lazy = views[viewName]
162+
reactRoute.lazy = views[viewName];
160163
}
161164
}
162-
163-
}
165+
} else if (!layout && !redirect) {
166+
return Object.assign(reactRoute, rest);
167+
}
164168
} catch (error: any) {
165-
console.error(`Error transforming route "${route.name}": ${error.toString()}`);
169+
console.error(`Error transforming route "${route.name}": ${error.toString()}`);
166170
return {};
167171
}
168172

169-
170-
171-
172-
173-
if (children?.length) {
173+
if (children?.length) {
174174
reactRoute.children = children.flatMap(child => transformElegantRouteToReactRoute(child, layouts, views));
175-
const defaultRedirectPath = redirect || getRedirectPath(path as string, children[0].path as string);
176-
177-
reactRoute.children.unshift({
178-
index: true,
179-
loader: () => redirectTo(defaultRedirectPath),
180-
...rest
181-
});
182-
}else if (redirect) {
183-
reactRoute.loader=()=>redirectTo(redirect)
184-
}
185-
186-
if (loader) {
187-
reactRoute.loader = () => loader
175+
const defaultRedirectPath = redirect || getRedirectPath(path as string, children[0].path as string);
176+
177+
reactRoute.children.unshift({
178+
index: true,
179+
loader: () => redirectTo(defaultRedirectPath),
180+
...rest
181+
});
182+
} else if (redirect) {
183+
reactRoute.loader = () => redirectTo(redirect);
188184
}
189185

190186
if (layout) {
191-
192187
return {
193188
lazy: layouts[layout],
194189
children: [reactRoute],
195190
ErrorBoundary
196-
}as RouteObject;
191+
} as RouteObject;
197192
}
198193

199194
return reactRoute;
@@ -217,6 +212,7 @@ const routeMap: RouteMap = {
217212
"document_unocss": "unocss",
218213
"document_procomponents": "procomponents",
219214
"document_antd": "antd",
215+
"logout": "/logout",
220216
"403": "/403",
221217
"404": "/404",
222218
"500": "/500",

src/router/routes/builtin.ts

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import type { CustomRoute } from '@elegant-router/types';
22
import type { ElegantConstRoute } from '@ohh-889/react-auto-route';
3+
import type { ActionFunctionArgs } from 'react-router-dom';
4+
import { redirect } from 'react-router-dom';
5+
import { store } from '@/store';
6+
import { resetStore } from '@/store/slice/auth';
37
import { getRoutePath } from '../elegant/transform';
48

59
export const ROOT_ROUTE: CustomRoute = {
@@ -22,5 +26,34 @@ const NOT_FOUND_ROUTE: CustomRoute = {
2226
}
2327
};
2428

29+
/** - logout route 通过 action 触发做相关的登出操作 */
30+
/** - logout route triggers related logout operations through the action */
31+
const LOG_OUT_ROUTE: CustomRoute = {
32+
name: 'logout',
33+
path: '/logout',
34+
action: async ({ request }: ActionFunctionArgs) => {
35+
const formData = await request.formData();
36+
37+
store.dispatch(resetStore());
38+
39+
// 如果需要还需要调用登出接口 也是在这里 去做相关的操作
40+
// If needed, you can also call the logout API and perform related operations here
41+
42+
const needRedirect = formData.get('needRedirect');
43+
44+
if (needRedirect) {
45+
const redirectFullPath = formData.get('redirectFullPath');
46+
return redirect(`/login/pwd-login?redirect=${redirectFullPath}`);
47+
}
48+
49+
return redirect('/login/pwd-login');
50+
},
51+
meta: {
52+
title: 'logout',
53+
i18nKey: 'route.logout',
54+
hideInMenu: true
55+
}
56+
};
57+
2558
/** builtin routes, it must be constant and setup in vue-router */
26-
export const builtinRoutes: ElegantConstRoute[] = [ROOT_ROUTE, NOT_FOUND_ROUTE];
59+
export const builtinRoutes: ElegantConstRoute[] = [ROOT_ROUTE, NOT_FOUND_ROUTE, LOG_OUT_ROUTE];

0 commit comments

Comments
 (0)