Skip to content

Commit

Permalink
refactor(projects): add logout route
Browse files Browse the repository at this point in the history
  • Loading branch information
Ohh-889 committed Sep 10, 2024
1 parent 6ff150b commit df689df
Show file tree
Hide file tree
Showing 14 changed files with 126 additions and 114 deletions.
3 changes: 2 additions & 1 deletion build/plugins/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export function setupElegantRouter() {
'document_vite',
'document_unocss',
'document_proComponents',
'document_antd'
'document_antd',
'logout'
]
},
onRouteMetaGen(routeName) {
Expand Down
2 changes: 0 additions & 2 deletions packages/simple-router/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import CreateRouterMatcher from './matcher';
import type { RouteRecordNormalized, RouteRecordRaw } from './matcher/types';
import { START_LOCATION_NORMALIZED } from './types';
import { RouterContext } from './hooks/useRouter';

import { warn } from './warning';

const historyCreatorMap: Record<
Expand Down Expand Up @@ -102,7 +101,6 @@ class CreateRouter {
return reactRoute;
})
.filter(Boolean);
console.log(this.reactRouter);

// Add to react-router's routes
this.reactRouter.patchRoutes(parent, reactRoutes);
Expand Down
5 changes: 3 additions & 2 deletions packages/simple-router/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment

/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
import type { ElegantConstRoute, RouteMeta } from '@ohh-889/react-auto-route';
import type { RouteObject } from 'react-router-dom';
import type { Router as RemixRouter } from '@remix-run/router';
Expand Down
9 changes: 3 additions & 6 deletions src/hooks/common/routerPush.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,19 +75,15 @@ export function useRouterPush() {
async function toLogin(loginModule?: UnionKey.LoginModule, redirectUrl?: string) {
const module = loginModule || 'pwd-login';

const options: RouterPushOptions = {
params: {
module
}
};
const options: RouterPushOptions = {};

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

options.query = {
redirect
};

return routerPushByKey('login', options);
return routerPushByKey(`login_${module}`, options);
}

/**
Expand Down Expand Up @@ -119,6 +115,7 @@ export function useRouterPush() {
return {
routerPush,
routerBack,
routerPushByKey,
toLogin,
routerPushByKeyWithMetaQuery,
redirectFromLogin,
Expand Down
18 changes: 11 additions & 7 deletions src/layouts/modules/global-header/components/UserAvatar.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
import { Button, Dropdown } from 'antd';
import type { MenuProps } from 'antd';
import { useNavigate } from 'react-router-dom';
import { resetStore, selectToken, selectUserInfo } from '@/store/slice/auth';
import { useSubmit } from 'react-router-dom';
import { selectToken, selectUserInfo } from '@/store/slice/auth';

const UserAvatar = memo(() => {
const token = useAppSelector(selectToken);
const dispatch = useAppDispatch();
const { t } = useTranslation();
const userInfo = useAppSelector(selectUserInfo);
const navigate = useNavigate();
const submit = useSubmit();
const route = useRoute();
const router = useRouterPush();

function logout() {
window?.$modal?.confirm({
title: t('common.tip'),
content: t('common.logoutConfirm'),
okText: t('common.confirm'),
cancelText: t('common.cancel'),
onOk: () => {
loginOrRegister();
let needRedirect = false;
if (!route.meta?.constant) needRedirect = true;
submit({ redirectFullPath: route.fullPath, needRedirect }, { method: 'post', action: '/logout' });
}
});
}
Expand All @@ -25,11 +29,11 @@ const UserAvatar = memo(() => {
if (key === '1') {
logout();
} else {
navigate('/user-center');
router.routerPushByKey('user-center');
}
}
function loginOrRegister() {
dispatch(resetStore());
router.routerPushByKey('login');
}

const items: MenuProps['items'] = [
Expand Down
1 change: 1 addition & 0 deletions src/locales/langs/en-us/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const route: App.I18n.Schema['translation']['route'] = {
'iframe-page': 'Iframe',
home: 'Home',
document: 'Document',
logout: 'Logout',
document_project: 'Project Document',
'document_project-link': 'Project Document(External Link)',
document_react: 'React Document',
Expand Down
1 change: 1 addition & 0 deletions src/locales/langs/zh-cn/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const route: App.I18n.Schema['translation']['route'] = {
'iframe-page': '外链页面',
home: '首页',
document: '文档',
logout: '退出登录',
document_project: '项目文档',
'document_project-link': '项目文档(外链)',
document_react: 'React文档',
Expand Down
108 changes: 52 additions & 56 deletions src/router/elegant/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,20 @@
// Vue auto route: https://github.com/soybeanjs/elegant-router


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


type CustomRouteObject = Omit<RouteObject, 'Component'|'index'> & {
Component?: React.ComponentType<any>|null;
type CustomRouteObject = Omit<RouteObject, 'Component' | 'index'> & {
Component?: React.ComponentType<any> | null;
};


/**
* transform elegant const routes to react routes
*
* @param routes elegant const routes
* @param layouts layout components
* @param views view components
Expand All @@ -34,15 +33,16 @@ export function transformElegantRoutesToReactRoutes(

/**
* transform elegant route to react route
*
* @param route elegant const route
* @param layouts layout components
* @param views view components
*/
export function transformElegantRouteToReactRoute(
route: ElegantConstRoute,
layouts: Record<string, LazyRouteFunction<CustomRouteObject>>,
views: Record<string,LazyRouteFunction<CustomRouteObject>>
):RouteObject {
views: Record<string, LazyRouteFunction<CustomRouteObject>>
): RouteObject {
const LAYOUT_PREFIX = 'layout.';
const VIEW_PREFIX = 'view.';
const ROUTE_DEGREE_SPLITTER = '_';
Expand All @@ -55,7 +55,7 @@ export function transformElegantRouteToReactRoute(
function getLayoutName(component: string) {
const layout = component.replace(LAYOUT_PREFIX, '');

if(!layouts[layout]) {
if (!layouts[layout]) {
throw new Error(`Layout component "${layout}" not found`);
}

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

if(!views[view]) {
if (!views[view]) {
throw new Error(`View component "${view}" not found`);
}

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

return {
layout: layout?getLayoutName(layout):undefined,
layout: layout ? getLayoutName(layout) : undefined,
view: getViewName(view)
};
}

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

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

const reactRoute = {id:name, path,handle: {
...meta
}, children:[],ErrorBoundary }as RouteObject
const reactRoute = {
id: name,
path,
handle: {
...meta
},
children: [],
ErrorBoundary
} as RouteObject;

try {
if (component) {
if (isSingleLevelRoute(route)) {
const { layout, view } = getSingleLevelRouteComponent(component);

if (layout) {
const singleLevelRoute:RouteObject= {
if (layout) {
const singleLevelRoute: RouteObject = {
path,
lazy: layouts[layout],
ErrorBoundary,
children: [
{
id:name,
id: name,
index: true,
lazy: views[view],
handle: {
Expand All @@ -123,77 +128,67 @@ export function transformElegantRouteToReactRoute(
]
};

return singleLevelRoute;
return singleLevelRoute;
}

return {
return {
path,
lazy: views[view],
id: name,
...rest
} as RouteObject;
} as RouteObject;
}

if (isLayout(component)) {
if (layout) {
reactRoute.lazy=views[name]
reactRoute.lazy = views[name];
} else {
const layoutName = getLayoutName(component);
reactRoute.lazy = layouts[layoutName];
}

}


if (isView(component)) {
const viewName = getViewName(component);
if (props) {
reactRoute.lazy = async () => {
const data= (await views[viewName]()).Component as FunctionComponent
const data = (await views[viewName]()).Component as FunctionComponent;
return {
Component: ()=>data(props) ,
ErrorBoundary: null
}
}
Component: () => data(props),
ErrorBoundary: null
};
};
} else {
reactRoute.lazy = views[viewName]
reactRoute.lazy = views[viewName];
}
}

}
} else if (!layout && !redirect) {
return Object.assign(reactRoute, rest);
}
} catch (error: any) {
console.error(`Error transforming route "${route.name}": ${error.toString()}`);
console.error(`Error transforming route "${route.name}": ${error.toString()}`);
return {};
}





if (children?.length) {
if (children?.length) {
reactRoute.children = children.flatMap(child => transformElegantRouteToReactRoute(child, layouts, views));
const defaultRedirectPath = redirect || getRedirectPath(path as string, children[0].path as string);

reactRoute.children.unshift({
index: true,
loader: () => redirectTo(defaultRedirectPath),
...rest
});
}else if (redirect) {
reactRoute.loader=()=>redirectTo(redirect)
}

if (loader) {
reactRoute.loader = () => loader
const defaultRedirectPath = redirect || getRedirectPath(path as string, children[0].path as string);

reactRoute.children.unshift({
index: true,
loader: () => redirectTo(defaultRedirectPath),
...rest
});
} else if (redirect) {
reactRoute.loader = () => redirectTo(redirect);
}

if (layout) {

return {
lazy: layouts[layout],
children: [reactRoute],
ErrorBoundary
}as RouteObject;
} as RouteObject;
}

return reactRoute;
Expand All @@ -217,6 +212,7 @@ const routeMap: RouteMap = {
"document_unocss": "unocss",
"document_procomponents": "procomponents",
"document_antd": "antd",
"logout": "/logout",
"403": "/403",
"404": "/404",
"500": "/500",
Expand Down
35 changes: 34 additions & 1 deletion src/router/routes/builtin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { CustomRoute } from '@elegant-router/types';
import type { ElegantConstRoute } from '@ohh-889/react-auto-route';
import type { ActionFunctionArgs } from 'react-router-dom';
import { redirect } from 'react-router-dom';
import { store } from '@/store';
import { resetStore } from '@/store/slice/auth';
import { getRoutePath } from '../elegant/transform';

export const ROOT_ROUTE: CustomRoute = {
Expand All @@ -22,5 +26,34 @@ const NOT_FOUND_ROUTE: CustomRoute = {
}
};

/** - logout route 通过 action 触发做相关的登出操作 */
/** - logout route triggers related logout operations through the action */
const LOG_OUT_ROUTE: CustomRoute = {
name: 'logout',
path: '/logout',
action: async ({ request }: ActionFunctionArgs) => {
const formData = await request.formData();

store.dispatch(resetStore());

// 如果需要还需要调用登出接口 也是在这里 去做相关的操作
// If needed, you can also call the logout API and perform related operations here

const needRedirect = formData.get('needRedirect');

if (needRedirect) {
const redirectFullPath = formData.get('redirectFullPath');
return redirect(`/login/pwd-login?redirect=${redirectFullPath}`);
}

return redirect('/login/pwd-login');
},
meta: {
title: 'logout',
i18nKey: 'route.logout',
hideInMenu: true
}
};

/** builtin routes, it must be constant and setup in vue-router */
export const builtinRoutes: ElegantConstRoute[] = [ROOT_ROUTE, NOT_FOUND_ROUTE];
export const builtinRoutes: ElegantConstRoute[] = [ROOT_ROUTE, NOT_FOUND_ROUTE, LOG_OUT_ROUTE];
Loading

0 comments on commit df689df

Please sign in to comment.