Skip to content

Commit

Permalink
feat(projects): Synchronize the useRouterPush of soybean
Browse files Browse the repository at this point in the history
  • Loading branch information
mufeng889 committed Sep 1, 2024
1 parent 95243a0 commit 308dfdd
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 61 deletions.
11 changes: 9 additions & 2 deletions packages/simple-router/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import CreateRouter from './router';
import { useRoute } from './hooks/useRoute';
import { useRouter } from './hooks/useRouter';
import type { AfterEach, BeforeEach, RouteLocationNormalizedLoaded } from './types';
import type { RouteRecordNormalized } from './matcher/types';

export default CreateRouter;

export { useRoute, useRouter };

export type { RouteLocationNormalizedLoaded, RouteRecordNormalized, BeforeEach, AfterEach };
export type { RouteRecordNormalized };

export type {
LocationQueryValueRaw,
RouteLocationNamedRaw,
AfterEach,
BeforeEach,
RouteLocationNormalizedLoaded
} from './types';
4 changes: 3 additions & 1 deletion packages/simple-router/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class CreateRouter {
initRoute = false;
reactRouter: RemixRouter;
initReactRoutes: RouteObject[] = [];
matcher: CreateRouterMatcher;
private matcher: CreateRouterMatcher;
currentRoute = START_LOCATION_NORMALIZED;
getReactRoutes: (route: ElegantConstRoute) => RouteObject;

Expand Down Expand Up @@ -67,6 +67,8 @@ class CreateRouter {
await init(this.reactRouter);
this.reactRouter.navigate(this.reactRouter.state.location, { replace: true });
});

this.push = this.push.bind(this);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/components/advanced/DragContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const DragContent: FC<Props> = ({ columns, setColumnChecks }) => {
{...provider.dragHandleProps}
className="h-36px flex-y-center rd-4px hover:(bg-primary bg-opacity-20)"
>
{IconMdiDrag({ className: 'mr-8px h-full cursor-move text-icon' })}
<IconMdiDrag className="mr-8px h-full cursor-move text-icon" />
<Checkbox
checked={item.checked}
onClick={() => handleChange(item.checked, index)}
Expand Down
2 changes: 1 addition & 1 deletion src/components/advanced/TableColumnSetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const TableColumnSetting: FC<Props> = memo(({ content }) => {
content={content}
>
<Button
icon={IconAntDesignSettingOutlined({})}
icon={<IconAntDesignSettingOutlined />}
size="small"
>
{t('common.columnSetting')}
Expand Down
3 changes: 1 addition & 2 deletions src/constants/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ export const loginModuleRecord: Record<UnionKey.LoginModule, App.I18n.I18nKey> =
'pwd-login': 'page.login.pwdLogin.title',
'code-login': 'page.login.codeLogin.title',
register: 'page.login.register.title',
'reset-pwd': 'page.login.resetPwd.title',
'bind-wechat': 'page.login.bindWeChat.title'
'reset-pwd': 'page.login.resetPwd.title'
};

export const themeLayoutModeRecord: Record<UnionKey.ThemeLayoutMode, App.I18n.I18nKey> = {
Expand Down
4 changes: 1 addition & 3 deletions src/hooks/common/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ export function useLogin() {

if (userName) {
dispatch(initAuthRoute());
if (redirect) {
redirectFromLogin();
}
await redirectFromLogin(redirect);
window.$notification?.success({
message: t('page.login.common.loginSuccess'),
description: t('page.login.common.welcomeBack', { userName })
Expand Down
126 changes: 76 additions & 50 deletions src/hooks/common/routerPush.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,43 @@
import { useSearchParams } from 'react-router-dom';
import { startTransition } from 'react';
import { router } from '@/router';
import { useRouter } from '@sa/simple-router';
import type { RouteKey } from '@elegant-router/types';
import type { RouteLocationNamedRaw } from '@sa/simple-router';

interface RouterPushOptions {
query?: Record<string, string>;
params?: Record<string, string>;
}

/**
* Router push
*
* Jump to the specified route, it can replace function router.push
*/
export function useRouterPush() {
const router = useRouter();

const [searchParams] = useSearchParams();
const { pathname } = useLocation();

const routerBack = () => {
router.reactRouter.navigate(-1);
};
const routerPush = router.push;

async function toHome() {
return router.push('/');
}
const routerBack = router.back;

function getQuery() {
const query: Record<string, string> = {};
for (const pairs of searchParams.entries()) {
query[pairs[0]] = pairs[1];
}
return query;
}
async function routerPushByKey(key: RouteKey, options?: RouterPushOptions) {
const { query, params } = options || {};

/**
* Navigate to login page
*
* @param loginModule The login module
* @param redirectUrl The redirect url, if not specified, it will be the current route fullPath
*/
async function toLogin(loginModule?: UnionKey.LoginModule, redirectUrl?: string) {
const module = loginModule || 'pwd-login';
const routeLocation: RouteLocationNamedRaw = {
name: key
};

const redirect = redirectUrl || pathname;
if (Object.keys(query || {}).length) {
routeLocation.query = query;
}

return router.reactRouter.navigate({ pathname: `/login/${module}`, search: `redirect=${redirect}` });
}
function objectToQueryParams(obj: Record<string, string | number>) {
const params = new URLSearchParams();
for (const key in obj) {
if (Object.hasOwn(obj, key)) {
params.append(key, obj[key] as string);
}
if (Object.keys(params || {}).length) {
routeLocation.params = params;
}
return params.toString();

return routerPush(routeLocation);
}

/**
Expand All @@ -67,41 +57,77 @@ export function useRouterPush() {
return query;
};

const menuPush = (key: string) => {
startTransition(() => {
const query = getRouteQueryOfMetaByKey(key);
router.push({ name: key, query });
});
};
function routerPushByKeyWithMetaQuery(key: RouteKey) {
const query = getRouteQueryOfMetaByKey(key);

return routerPushByKey(key, { query });
}

async function toHome() {
return routerPush('/');
}

/**
* Navigate to login page
*
* @param loginModule The login module
* @param redirectUrl The redirect url, if not specified, it will be the current route fullPath
*/
async function toLogin(loginModule?: UnionKey.LoginModule, redirectUrl?: string) {
const module = loginModule || 'pwd-login';

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

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

options.query = {
redirect
};

return routerPushByKey('login', options);
}

/**
* Toggle login module
*
* @param module
*/
function toggleLoginModule(module: UnionKey.LoginModule) {
const query = getQuery();
async function toggleLoginModule(module: UnionKey.LoginModule) {
const query = router.currentRoute.query as Record<string, string>;

return routerPushByKey(`login_${module}`, { query });
}

router.reactRouter.navigate({
pathname: `/login/${module}`,
search: objectToQueryParams(query)
function menuPush(key: string) {
startTransition(() => {
routerPushByKeyWithMetaQuery(key as RouteKey);
});
}

/** Redirect from login */
function redirectFromLogin() {
/**
* Redirect from login
*
* @param [needRedirect=true] Whether to redirect after login. Default is `true`
*/
async function redirectFromLogin(needRedirect = true) {
const redirect = searchParams.get('redirect');

if (redirect) {
router.reactRouter.navigate(redirect);
if (needRedirect && redirect) {
routerPush(redirect);
} else {
toHome();
}
}

return {
routerPush: router,
routerPush,
routerBack,
toLogin,
routerPushByKeyWithMetaQuery,
menuPush,
redirectFromLogin,
toggleLoginModule
Expand Down
2 changes: 1 addition & 1 deletion src/types/union-key.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ declare namespace UnionKey {
* - reset-pwd: reset password
* - bind-wechat: bind wechat
*/
type LoginModule = 'pwd-login' | 'code-login' | 'register' | 'reset-pwd' | 'bind-wechat';
type LoginModule = 'pwd-login' | 'code-login' | 'register' | 'reset-pwd';

/** Theme scheme */
type ThemeScheme = 'light' | 'dark' | 'auto';
Expand Down

0 comments on commit 308dfdd

Please sign in to comment.