Files
AFFiNE-Mirror/apps/web/src/hooks/use-router-helper.ts
2023-04-14 17:07:41 -05:00

100 lines
2.3 KiB
TypeScript

import type { NextRouter } from 'next/router';
import { useCallback } from 'react';
import type { WorkspaceSubPath } from '../shared';
export const enum RouteLogic {
REPLACE = 'replace',
PUSH = 'push',
}
export function useRouterHelper(router: NextRouter) {
const jumpToPage = useCallback(
(
workspaceId: string,
pageId: string,
logic: RouteLogic = RouteLogic.PUSH
) => {
return router[logic]({
pathname: `/workspace/[workspaceId]/[pageId]`,
query: {
workspaceId,
pageId,
},
});
},
[router]
);
const jumpToWorkspace = useCallback(
(workspaceId: string, logic: RouteLogic = RouteLogic.PUSH) => {
if (router.pathname === '/workspace/[workspaceId]/[pageId]') {
return router[logic]({
pathname: `/workspace/[workspaceId]`,
query: {
workspaceId: workspaceId,
},
});
} else {
return router[logic]({
pathname: router.pathname,
query: {
workspaceId: workspaceId,
},
});
}
},
[router]
);
const jumpToPublicWorkspacePage = useCallback(
(
workspaceId: string,
pageId: string,
logic: RouteLogic = RouteLogic.PUSH
) => {
return router[logic]({
pathname: `/public-workspace/[workspaceId]/[pageId]`,
query: {
workspaceId,
pageId,
},
});
},
[router]
);
const jumpToSubPath = useCallback(
(
workspaceId: string,
subPath: WorkspaceSubPath,
logic: RouteLogic = RouteLogic.PUSH
): Promise<boolean> => {
return router[logic]({
pathname: `/workspace/[workspaceId]/${subPath}`,
query: {
workspaceId,
},
});
},
[router]
);
const openPage = useCallback(
(workspaceId: string, pageId: string) => {
const isPublicWorkspace =
router.pathname.split('/')[1] === 'public-workspace';
if (isPublicWorkspace) {
return jumpToPublicWorkspacePage(workspaceId, pageId);
} else {
return jumpToPage(workspaceId, pageId);
}
},
[jumpToPage, jumpToPublicWorkspacePage, router.pathname]
);
return {
jumpToPage,
jumpToWorkspace,
jumpToPublicWorkspacePage,
jumpToSubPath,
openPage,
};
}