Skip to content

Commit

Permalink
Redesign a useRouter hook
Browse files Browse the repository at this point in the history
  • Loading branch information
tassoevan committed Jun 16, 2023
1 parent 2dd54f3 commit a8305ec
Show file tree
Hide file tree
Showing 62 changed files with 245 additions and 307 deletions.
2 changes: 1 addition & 1 deletion apps/meteor/app/mail-messages/server/functions/sendMail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Users } from '@rocket.chat/models';
import { placeholders } from '../../../utils/server';
import { SystemLogger } from '../../../../server/lib/logger/system';
import * as Mailer from '../../../mailer/server/api';
import { generatePath } from '../../../../lib/router';
import { generatePath } from '../../../../lib/utils/generatePath';

export const sendMail = async function ({
from,
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/ui-utils/client/lib/AccountBox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { IUIActionButton, IUActionButtonWhen } from '@rocket.chat/apps-engi
import type { UserStatus } from '@rocket.chat/core-typings';
import { ReactiveVar } from 'meteor/reactive-var';
import { Tracker } from 'meteor/tracker';
import type { RouterPaths, TranslationKey } from '@rocket.chat/ui-contexts';
import type { IRouterPaths, TranslationKey } from '@rocket.chat/ui-contexts';
import type { Icon } from '@rocket.chat/fuselage';
import type { ComponentProps } from 'react';

Expand All @@ -22,7 +22,7 @@ export interface IAppAccountBoxItem extends IUIActionButton {
export type AccountBoxItem = {
name: TranslationKey;
icon: ComponentProps<typeof Icon>['name'];
href: RouterPaths[keyof RouterPaths]['pathname'];
href: IRouterPaths[keyof IRouterPaths]['pathname'];
sideNav?: string;
condition: () => boolean;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { OptionTitle } from '@rocket.chat/fuselage';
import { useTranslation, useRoute, useMethod, useSetModal, useRole, useNavigate } from '@rocket.chat/ui-contexts';
import { useTranslation, useRoute, useMethod, useSetModal, useRole, useRouter } from '@rocket.chat/ui-contexts';
import { useQuery } from '@tanstack/react-query';
import type { FC } from 'react';
import React from 'react';
Expand Down Expand Up @@ -34,7 +34,7 @@ const AdministrationModelList: FC<AdministrationModelListProps> = ({ accountBoxI
setModal(<RegisterWorkspaceModal onClose={handleModalClose} />);
};

const navigate = useNavigate();
const router = useRouter();
const upgradeRoute = useRoute('upgrade');
const cloudRoute = useRoute('cloud');
const showUpgradeItem = !isLoading && tabType;
Expand Down Expand Up @@ -79,7 +79,7 @@ const AdministrationModelList: FC<AdministrationModelListProps> = ({ accountBoxI
role='listitem'
text={t('Workspace')}
onClick={() => {
navigate('/admin');
router.navigate('/admin');
onDismiss();
}}
/>
Expand All @@ -89,7 +89,7 @@ const AdministrationModelList: FC<AdministrationModelListProps> = ({ accountBoxI
{accountBoxItems.map((item, key) => {
const action = () => {
if (item.href) {
navigate(item.href);
router.navigate(item.href);
}
onDismiss();
};
Expand Down
9 changes: 5 additions & 4 deletions apps/meteor/client/components/GazzodownText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import type { IRoom } from '@rocket.chat/core-typings';
import type { ChannelMention, UserMention } from '@rocket.chat/gazzodown';
import { MarkupInteractionContext } from '@rocket.chat/gazzodown';
import { escapeRegExp } from '@rocket.chat/string-helpers';
import { useLayout, useUserPreference } from '@rocket.chat/ui-contexts';
import { useLayout, useRouter, useUserPreference } from '@rocket.chat/ui-contexts';
import type { UIEvent } from 'react';
import React, { useCallback, memo, useMemo } from 'react';

import { generatePath } from '../../lib/router';
import { detectEmoji } from '../lib/utils/detectEmoji';
import { fireGlobalEvent } from '../lib/utils/fireGlobalEvent';
import { useChat } from '../views/room/contexts/ChatContext';
Expand Down Expand Up @@ -85,20 +84,22 @@ const GazzodownText = ({ mentions, channels, searchText, children }: GazzodownTe

const resolveChannelMention = useCallback((mention: string) => channels?.find(({ name }) => name === mention), [channels]);

const router = useRouter();

const onChannelMentionClick = useCallback(
({ _id: rid }: ChannelMention) =>
(event: UIEvent): void => {
if (isEmbedded) {
fireGlobalEvent('click-mention-link', {
path: generatePath('/channel/:name', { name: rid }),
path: router.getRoutePath('/channel/:name/:tab?/:context?', { name: rid }),
channel: rid,
});
}

event.stopPropagation();
goToRoom(rid);
},
[isEmbedded, goToRoom],
[router, isEmbedded, goToRoom],
);

return (
Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/client/components/NotFoundState.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Box, States, StatesAction, StatesActions, StatesIcon, StatesSubtitle, StatesTitle } from '@rocket.chat/fuselage';
import { useNavigate, useTranslation } from '@rocket.chat/ui-contexts';
import { useRouter, useTranslation } from '@rocket.chat/ui-contexts';
import type { ReactElement } from 'react';
import React from 'react';

Expand All @@ -10,10 +10,10 @@ type NotFoundProps = {

const NotFoundState = ({ title, subtitle }: NotFoundProps): ReactElement => {
const t = useTranslation();
const navigate = useNavigate();
const router = useRouter();

const handleGoHomeClick = () => {
navigate('/home');
router.navigate('/home');
};

return (
Expand Down
14 changes: 7 additions & 7 deletions apps/meteor/client/lib/createRouteGroup.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { RouterPaths } from '@rocket.chat/ui-contexts';
import type { IRouterPaths } from '@rocket.chat/ui-contexts';
import type {
Context,
Current,
Expand Down Expand Up @@ -27,7 +27,7 @@ const registerLazyComponentRoute = <TGroupName extends GroupName, TRouteName ext
RouterComponent: ElementType<{
children?: ReactNode;
}>,
path: TrimPrefix<RouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
path: TrimPrefix<IRouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
{
component: RouteComponent,
props,
Expand Down Expand Up @@ -112,15 +112,15 @@ export const createRouteGroup = <TGroupName extends GroupName>(
},
): [register: () => void, unregister: () => void];
<TRouteName extends RouteNamesOf<TGroupName>>(
path: TrimPrefix<RouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
path: TrimPrefix<IRouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
options: RouteOptions<TRouteName> & {
component: ElementType;
props?: Record<string, unknown>;
ready?: boolean;
},
): [register: () => void, unregister: () => void];
<TRouteName extends RouteNamesOf<TGroupName>>(
path: TrimPrefix<RouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
path: TrimPrefix<IRouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
options: RouteOptions<TRouteName>,
): void;
} => {
Expand All @@ -131,19 +131,19 @@ export const createRouteGroup = <TGroupName extends GroupName>(

function registerRoute(path: '/' | '', options: RouteOptions<`${TGroupName}-index`>): [register: () => void, unregister: () => void];
function registerRoute<TRouteName extends RouteNamesOf<TGroupName>>(
path: TrimPrefix<RouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
path: TrimPrefix<IRouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
options: RouteOptions<TRouteName> & {
component: ElementType;
props?: Record<string, unknown>;
ready?: boolean;
},
): [register: () => void, unregister: () => void];
function registerRoute<TRouteName extends RouteNamesOf<TGroupName>>(
path: TrimPrefix<RouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
path: TrimPrefix<IRouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
options: RouteOptions<TRouteName>,
): void;
function registerRoute<TRouteName extends RouteNamesOf<TGroupName>>(
path: TrimPrefix<RouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
path: TrimPrefix<IRouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
options:
| RouteOptions<TRouteName>
| (RouteOptions<TRouteName> & {
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/client/lib/createSidebarItems.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { IconProps } from '@rocket.chat/fuselage';
import type { RouterPaths } from '@rocket.chat/ui-contexts';
import type { IRouterPaths } from '@rocket.chat/ui-contexts';
import type { ReactElement } from 'react';

export type Item = {
i18nLabel: string;
href?: RouterPaths[keyof RouterPaths]['pathname'] | `https://go.rocket.chat/i/${string}`;
href?: IRouterPaths[keyof IRouterPaths]['pathname'] | `https://go.rocket.chat/i/${string}`;
icon?: IconProps['name'];
tag?: 'Alpha' | 'Beta';
permissionGranted?: () => boolean;
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/client/lib/rooms/roomCoordinator.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { IRoom, RoomType, IUser, AtLeast, ValueOf, ISubscription } from '@rocket.chat/core-typings';
import { isRoomFederated } from '@rocket.chat/core-typings';
import type { RouterPaths } from '@rocket.chat/ui-contexts';
import type { IRouterPaths } from '@rocket.chat/ui-contexts';
import { FlowRouter } from 'meteor/kadira:flow-router';
import React from 'react';

Expand Down Expand Up @@ -167,7 +167,7 @@ class RoomCoordinatorClient extends RoomCoordinator {
return true;
}

private validateRoute<TRouteName extends keyof RouterPaths>(route: IRoomTypeRouteConfig<TRouteName>): void {
private validateRoute<TRouteName extends keyof IRouterPaths>(route: IRoomTypeRouteConfig<TRouteName>): void {
const { name, path, link } = route;

if (typeof name !== 'string' || name.length === 0) {
Expand Down
8 changes: 4 additions & 4 deletions apps/meteor/client/providers/CallProvider/CallProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import { Random } from '@rocket.chat/random';
import type { Device, IExperimentalHTMLAudioElement } from '@rocket.chat/ui-contexts';
import {
useNavigate,
useRouter,
useUser,
useSetting,
useEndpoint,
Expand Down Expand Up @@ -88,7 +88,7 @@ export const CallProvider: FC = ({ children }) => {

const result = useVoipClient();
const user = useUser();
const navigate = useNavigate();
const router = useRouter();
const setOutputMediaDevice = useSetOutputMediaDevice();
const setInputMediaDevice = useSetInputMediaDevice();

Expand All @@ -110,14 +110,14 @@ export const CallProvider: FC = ({ children }) => {
token: roomInfo.v.token || '',
options: { comment: data?.comment, tags: data?.tags },
}));
navigate('/home');
router.navigate('/home');

const queueAggregator = result.voipClient?.getAggregator();
if (queueAggregator) {
queueAggregator.callEnded();
}
},
[navigate, result?.voipClient, roomInfo, voipCloseRoomEndpoint],
[router, result?.voipClient, roomInfo, voipCloseRoomEndpoint],
);

const openWrapUpModal = useCallback((): void => {
Expand Down
8 changes: 4 additions & 4 deletions apps/meteor/client/providers/LayoutProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useBreakpoints } from '@rocket.chat/fuselage-hooks';
import { LayoutContext, useNavigate, useQueryStringParameter, useSetting } from '@rocket.chat/ui-contexts';
import { LayoutContext, useRouter, useQueryStringParameter, useSetting } from '@rocket.chat/ui-contexts';
import type { FC } from 'react';
import React, { useMemo, useState, useEffect } from 'react';

Expand All @@ -16,7 +16,7 @@ const LayoutProvider: FC = ({ children }) => {
setIsCollapsed(isMobile);
}, [isMobile]);

const navigate = useNavigate();
const router = useRouter();

return (
<LayoutContext.Provider
Expand All @@ -31,7 +31,7 @@ const LayoutProvider: FC = ({ children }) => {
toggle: () => setIsCollapsed((isCollapsed) => !isCollapsed),
collapse: () => setIsCollapsed(true),
expand: () => setIsCollapsed(false),
close: () => (isEmbedded ? setIsCollapsed(true) : navigate('/home')),
close: () => (isEmbedded ? setIsCollapsed(true) : router.navigate('/home')),
},
size: {
sidebar: '240px',
Expand All @@ -41,7 +41,7 @@ const LayoutProvider: FC = ({ children }) => {
// eslint-disable-next-line no-nested-ternary
contextualBarPosition: breakpoints.includes('sm') ? (breakpoints.includes('lg') ? 'relative' : 'absolute') : 'fixed',
}),
[isMobile, isEmbedded, showTopNavbarEmbeddedLayout, isCollapsed, breakpoints, navigate],
[isMobile, isEmbedded, showTopNavbarEmbeddedLayout, isCollapsed, breakpoints, router],
)}
/>
);
Expand Down
23 changes: 13 additions & 10 deletions apps/meteor/client/providers/RouterProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { RouterContextValue, RouterPaths } from '@rocket.chat/ui-contexts';
import type { RouterContextValue, RouterPathPattern, RouterPathName } from '@rocket.chat/ui-contexts';
import { RouterContext } from '@rocket.chat/ui-contexts';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { Tracker } from 'meteor/tracker';
Expand All @@ -7,6 +7,12 @@ import React from 'react';

import { createSubscription } from '../lib/createSubscription';

const getRoutePath = (
patternOrName: RouterPathPattern | RouterPathName,
parameters?: Record<string, string>,
search?: Record<string, string>,
): string => Tracker.nonreactive(() => FlowRouter.path(patternOrName, parameters, search));

export const navigate = (
toOrDelta:
| string
Expand Down Expand Up @@ -103,8 +109,8 @@ const pushRoute = (
const queryParams =
typeof queryStringParameters === 'function' ? queryStringParameters(FlowRouter.current().queryParams) : queryStringParameters;
navigate({
pathname: name,
params: parameters,
pattern: name,
params: parameters ?? {},
search: queryParams,
});
};
Expand All @@ -118,8 +124,8 @@ const replaceRoute = (
typeof queryStringParameters === 'function' ? queryStringParameters(FlowRouter.current().queryParams) : queryStringParameters;
navigate(
{
pathname: name,
params: parameters,
pattern: name,
params: parameters ?? {},
search: queryParams,
},
{ replace: true },
Expand Down Expand Up @@ -149,20 +155,17 @@ const setQueryString = (paramsOrFn: Record<string, string | null> | ((prev: Reco
FlowRouter.setQueryParams(paramsOrFn);
};

const getRoutePath = (name: keyof RouterPaths, parameters?: Record<string, string>, queryStringParameters?: Record<string, string>) =>
Tracker.nonreactive(() => FlowRouter.path(name, parameters, queryStringParameters));

const contextValue = {
getRoutePath,
navigate,
queryRoutePath,
queryRouteUrl,
navigate,
pushRoute,
replaceRoute,
queryRouteParameter,
queryQueryStringParameter,
queryCurrentRoute,
setQueryString,
getRoutePath,
};

const RouterProvider: FC = ({ children }) => <RouterContext.Provider children={children} value={contextValue} />;
Expand Down
8 changes: 4 additions & 4 deletions apps/meteor/client/sidebar/RoomMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Option, Menu } from '@rocket.chat/fuselage';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import type { TranslationKey, Fields } from '@rocket.chat/ui-contexts';
import {
useNavigate,
useRouter,
useSetModal,
useToastMessageDispatch,
useUserSubscription,
Expand Down Expand Up @@ -77,7 +77,7 @@ const RoomMenu = ({

const closeModal = useMutableCallback(() => setModal());

const navigate = useNavigate();
const router = useRouter();

const subscription = useUserSubscription(rid, fields);
const canFavorite = useSetting('Favorite_Rooms');
Expand Down Expand Up @@ -115,7 +115,7 @@ const RoomMenu = ({
try {
await leaveRoom({ roomId: rid });
if (roomOpen) {
navigate('/home');
router.navigate('/home');
}
LegacyRoomManager.close(rid);
} catch (error) {
Expand Down Expand Up @@ -184,7 +184,7 @@ const RoomMenu = ({
}
LegacyRoomManager.close(subscription.t + subscription.name);

navigate('/home');
router.navigate('/home');
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
Expand Down
Loading

0 comments on commit a8305ec

Please sign in to comment.