Skip to content

Commit

Permalink
Brute-force more type assertions
Browse files Browse the repository at this point in the history
  • Loading branch information
tassoevan committed May 1, 2024
1 parent 0608ef2 commit ff55e00
Show file tree
Hide file tree
Showing 87 changed files with 288 additions and 206 deletions.
8 changes: 5 additions & 3 deletions apps/meteor/client/components/BurgerMenu/BurgerBadge.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { css } from '@rocket.chat/css-in-js';
import { Box, Badge } from '@rocket.chat/fuselage';
import type { ReactElement } from 'react';
import type { ReactElement, ReactNode } from 'react';
import React from 'react';

const BurgerBadge = ({ children }: { children?: unknown }): ReactElement => (
type BurgerBadgeProps = { children?: ReactNode };

const BurgerBadge = ({ children }: BurgerBadgeProps): ReactElement => (
<Box
className={css`
position: absolute;
zindex: 3;
z-index: 3;
top: -5px;
right: -5px;
`}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ const UserAutoCompleteMultipleFederated = ({
);

return (
<OptionsContext.Provider value={{ options }}>
// FIXME
<OptionsContext.Provider value={{ options: options as any }}>
{' '}
<MultiSelectFiltered
{...props}
data-qa-type='user-auto-complete-input'
Expand Down
23 changes: 12 additions & 11 deletions apps/meteor/client/hooks/useEndpointAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,28 @@ import type { EndpointFunction } from '@rocket.chat/ui-contexts';
import { useToastMessageDispatch, useEndpoint } from '@rocket.chat/ui-contexts';
import { useMutation } from '@tanstack/react-query';

type UseEndpointActionOptions<TPathPattern extends PathPattern> = (undefined extends UrlParams<TPathPattern>
type UseEndpointActionOptions<TPathPattern extends PathPattern> = undefined extends UrlParams<TPathPattern>
? {
keys?: UrlParams<TPathPattern>;
successMessage?: string;
}
: {
keys: UrlParams<TPathPattern>;
}) & {
successMessage?: string;
};
export function useEndpointAction<TMethod extends Method, TPathPattern extends PathPattern>(
method: TMethod,
pathPattern: TPathPattern,
options: UseEndpointActionOptions<TPathPattern> = { keys: {} as UrlParams<TPathPattern> },
) {
const sendData = useEndpoint(method, pathPattern, options.keys as UrlParams<TPathPattern>);
successMessage?: string;
};

export function useEndpointAction<
TMethod extends Method,
TPathPattern extends PathPattern,
TOptions extends UseEndpointActionOptions<TPathPattern>,
>(method: TMethod, pathPattern: TPathPattern, options?: TOptions) {
const sendData = useEndpoint(method, pathPattern, options?.keys as any);

const dispatchToastMessage = useToastMessageDispatch();

const mutation = useMutation(sendData, {
onSuccess: () => {
if (options.successMessage) {
if (options?.successMessage) {
dispatchToastMessage({ type: 'success', message: options.successMessage });
}
},
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/client/hooks/useEndpointData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ const deprecationWarning = log('useEndpointData is deprecated, use @tanstack/rea
* use @tanstack/react-query with useEndpoint instead
* @deprecated
*/
export const useEndpointData = <TPathPattern extends PathPattern>(
export const useEndpointData = <TPathPattern extends PathPattern, TKeys extends UrlParams<TPathPattern>>(
endpoint: TPathPattern,
options: {
keys?: UrlParams<TPathPattern>;
keys?: TKeys;
params?: OperationParams<'GET', TPathPattern>;
initialValue?: Serialized<OperationResult<'GET', TPathPattern>> | (() => Serialized<OperationResult<'GET', TPathPattern>>);
} = {},
Expand Down
13 changes: 10 additions & 3 deletions apps/meteor/client/lib/createRouteGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,16 @@ type RouteNamesOf<TGroupName extends GroupName> = Extract<
: never]: never;
}
| `${GroupName}-index`,
RouteName
keyof IRouterPaths
>;

type RouterPathsItem = {
pattern: string;
pathname: string;
};

type AssertRouterPathItem<T> = Extract<T, RouterPathsItem>;

type TrimPrefix<T extends string, P extends string> = T extends `${P}${infer U}` ? U : T;

export const createRouteGroup = <TGroupName extends GroupName>(
Expand All @@ -41,14 +48,14 @@ export const createRouteGroup = <TGroupName extends GroupName>(
]);

return <TRouteName extends RouteNamesOf<TGroupName>>(
path: TrimPrefix<IRouterPaths[TRouteName]['pattern'], GroupPrefix<TGroupName>>,
path: TrimPrefix<AssertRouterPathItem<IRouterPaths[TRouteName]>['pattern'], GroupPrefix<TGroupName>>,
{
name,
component: RouteComponent,
props,
ready = true,
}: {
name: TRouteName;
name: TRouteName & RouteNamesOf<any>;
component: ElementType;
props?: Record<string, unknown>;
ready?: boolean;
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/client/lib/utils/createAnchor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function createAnchor(id: string, tag: keyof HTMLElementTagNameMap = 'div
document.body.appendChild(element);

registerAnchor(element, () => {
element.remove();
document.body.removeChild(element);
});
return element;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import type { Device, IExperimentalHTMLAudioElement, DeviceContextValue } from '@rocket.chat/ui-contexts';
import type { Device, DeviceContextValue } from '@rocket.chat/ui-contexts';
import { DeviceContext } from '@rocket.chat/ui-contexts';
import type { ReactElement, ReactNode } from 'react';
import React, { useEffect, useState, useMemo } from 'react';
Expand Down Expand Up @@ -33,7 +33,7 @@ export const DeviceProvider = ({ children }: DeviceProviderProps): ReactElement
};

const setAudioOutputDevice = useMutableCallback(
({ outputDevice, HTMLAudioElement }: { outputDevice: Device; HTMLAudioElement: IExperimentalHTMLAudioElement }): void => {
({ outputDevice, HTMLAudioElement }: { outputDevice: Device; HTMLAudioElement: HTMLAudioElement }): void => {
if (!isSetSinkIdAvailable()) {
throw new Error('setSinkId is not available in this browser');
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import type { IExperimentalHTMLAudioElement } from '@rocket.chat/ui-contexts';

export const isSetSinkIdAvailable = (): boolean => {
const audio = new Audio() as IExperimentalHTMLAudioElement;
const audio = new Audio();
return !!audio.setSinkId;
};
2 changes: 1 addition & 1 deletion apps/meteor/client/sidebar/RoomMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ const RoomMenu = ({
title={t('Options')}
mini
aria-keyshortcuts='alt'
options={menuOptions}
options={menuOptions as any} // FIXME
maxHeight={300}
renderItem={({ label: { label, icon }, ...props }): JSX.Element => <Option label={label} icon={icon} {...props} />}
/>
Expand Down
5 changes: 3 additions & 2 deletions apps/meteor/client/views/admin/customSounds/EditSound.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ function EditSound({ close, onChange, data, ...props }: EditSoundProps): ReactEl
const hasUnsavedChanges = previousName !== name || previousSound !== sound;

const saveAction = useCallback(
async (sound) => {
// FIXME
async (sound: any) => {
const soundData = createSoundData(sound, name, { previousName, previousSound, _id, extension: sound.extension });
const validation = validate(soundData, sound);
if (validation.length === 0) {
Expand Down Expand Up @@ -127,7 +128,7 @@ function EditSound({ close, onChange, data, ...props }: EditSoundProps): ReactEl
);
}, [_id, close, deleteCustomSound, dispatchToastMessage, onChange, setModal, t]);

const [clickUpload] = useSingleFileInput(handleChangeFile, 'audio/mp3');
const [clickUpload] = useSingleFileInput(handleChangeFile as any, 'audio/mp3'); // FIXME

return (
<>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import type { Button } from '@rocket.chat/fuselage';
import { IconButton } from '@rocket.chat/fuselage';
import { useTranslation } from '@rocket.chat/ui-contexts';
import type { ComponentProps, ReactElement } from 'react';
import type { ComponentProps } from 'react';
import React from 'react';

function ResetSettingButton(props: ComponentProps<typeof Button>): ReactElement {
type ResetSettingButtonProps = Omit<ComponentProps<typeof IconButton>, 'icon'>;

function ResetSettingButton(props: ResetSettingButtonProps) {
const t = useTranslation();

return <IconButton icon='undo' danger small title={t('Reset')} {...props} />;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ const AdminUserInfoActions = ({
flexShrink={0}
key='menu'
renderItem={({ label: { label, icon }, ...props }): ReactElement => <Option label={label} title={label} icon={icon} {...props} />}
options={menuOptions}
options={menuOptions as any} // FIXME
/>
);
}, [menuOptions]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,18 +83,7 @@ const ChannelsTable = () => {

const getDirectoryData = useEndpoint('GET', '/v1/directory');
const query = useDirectoryQuery({ text: debouncedText, current, itemsPerPage }, [sortBy, sortDirection], 'channels');
const { data, isFetched, isLoading, isError, refetch } = useQuery(
['getDirectoryData', query],
() =>
getDirectoryData(query) as Promise<
Serialized<{
count: number;
offset: number;
total: number;
result: (IRoom & { belongsTo: string })[];
}>
>,
);
const { data, isFetched, isLoading, isError, refetch } = useQuery(['getDirectoryData', query], () => getDirectoryData(query));

const onClick = useMemo(
() => (name: IRoom['name'], type: IRoom['t']) => (e: React.KeyboardEvent | React.MouseEvent) => {
Expand Down Expand Up @@ -122,7 +111,12 @@ const ChannelsTable = () => {
<GenericTableHeader>{headers}</GenericTableHeader>
<GenericTableBody>
{data.result.map((room) => (
<ChannelsTableRow key={room._id} room={room} onClick={onClick} mediaQuery={mediaQuery} />
<ChannelsTableRow
key={room._id}
room={room as Serialized<IRoom & { belongsTo: string }>}
onClick={onClick}
mediaQuery={mediaQuery}
/>
))}
</GenericTableBody>
</GenericTable>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,12 @@ const TeamsTable = () => {
<GenericTableHeader>{headers}</GenericTableHeader>
<GenericTableBody>
{data.result.map((team) => (
<TeamsTableRow key={team._id} team={team} onClick={onClick} mediaQuery={mediaQuery} />
<TeamsTableRow
key={team._id}
team={team as Serialized<IRoom & { roomsCount?: number }>}
onClick={onClick}
mediaQuery={mediaQuery}
/>
))}
</GenericTableBody>
</GenericTable>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,22 @@ const UsersTable = ({ workspace = 'local' }): ReactElement => {
key={user._id}
onClick={handleClick}
mediaQuery={mediaQuery}
user={user}
user={
user as Serialized<
| (IUser & { domain?: unknown })
| {
_id?: string;
username?: string;
name?: string;
bio?: string;
nickname?: string;
emails?: IUserEmail[];
federation?: unknown;
isRemote: true;
domain?: unknown;
}
>
}
federation={federation}
canViewFullOtherUserInfo={canViewFullOtherUserInfo}
/>
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/client/views/marketplace/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { appErroredStatuses } from './helpers/appErroredStatuses';

export const appEnabledStatuses = [AppStatus.AUTO_ENABLED, AppStatus.MANUALLY_ENABLED];

export type Actions = 'update' | 'install' | 'purchase' | 'request';
export type Actions = 'update' | 'install' | 'purchase' | 'request' | 'subscribe';

type appButtonResponseProps = {
action: Actions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ import { useOpenIncompatibleModal } from './useOpenIncompatibleModal';

export type AppInstallationHandlerParams = {
app: App;
action: Actions | '';
action: Actions | undefined;
isAppPurchased?: boolean;
onDismiss: () => void;
onSuccess: (action: Actions | '', appPermissions?: App['permissions']) => void;
onSuccess: (action: Actions | undefined, appPermissions?: App['permissions']) => void;
};

export function useAppInstallationHandler({ app, action, isAppPurchased, onDismiss, onSuccess }: AppInstallationHandlerParams) {
Expand Down
14 changes: 7 additions & 7 deletions apps/meteor/client/views/marketplace/hooks/useAppMenu.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AppStatus } from '@rocket.chat/apps-engine/definition/AppStatus';
import type { App } from '@rocket.chat/core-typings';
import type { App, AppPermission } from '@rocket.chat/core-typings';
import { Box, Icon } from '@rocket.chat/fuselage';
import {
useSetModal,
Expand Down Expand Up @@ -70,12 +70,12 @@ export const useAppMenu = (app: App, isAppDetailsPage: boolean) => {
| 'Buy'
| 'Request'
| 'Requested';
const action = button?.action || '';
const action = button?.action;

const setAppStatus = useEndpoint<'POST', '/apps/:id/status'>('POST', '/apps/:id/status', { id: app.id });
const setAppStatus = useEndpoint('POST', '/apps/:id/status', { id: app.id });
const buildExternalUrl = useEndpoint('GET', '/apps');
const syncApp = useEndpoint<'POST', '/apps/:id/sync'>('POST', '/apps/:id/sync', { id: app.id });
const uninstallApp = useEndpoint<'DELETE', '/apps/:id'>('DELETE', '/apps/:id', { id: app.id });
const syncApp = useEndpoint('POST', '/apps/:id/sync', { id: app.id });
const uninstallApp = useEndpoint('DELETE', '/apps/:id', { id: app.id });

const canAppBeSubscribed = app.purchaseType === 'subscription';
const isSubscribed = app.subscriptionInfo && ['active', 'trialing'].includes(app.subscriptionInfo.status);
Expand All @@ -89,7 +89,7 @@ export const useAppMenu = (app: App, isAppDetailsPage: boolean) => {
const marketplaceActions = useMarketplaceActions();

const installationSuccess = useCallback(
async (action: Actions | '', permissionsGranted) => {
async (action: Actions | undefined, permissionsGranted?: AppPermission[]) => {
if (action) {
if (action === 'purchase') {
setPurchased(true);
Expand Down Expand Up @@ -269,7 +269,7 @@ export const useAppMenu = (app: App, isAppDetailsPage: boolean) => {
]);

const incompatibleIconName = useCallback(
(app, action) => {
(app: App, action: Actions) => {
if (!app.versionIncompatible) {
if (action === 'update') {
return 'refresh';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { App, AppPermission } from '@rocket.chat/core-typings';
import { useMutation } from '@tanstack/react-query';

import type { Actions } from '../helpers';
import { handleAPIError } from '../helpers/handleAPIError';
import { warnAppInstall } from '../helpers/warnAppInstall';
import { warnStatusChange } from '../helpers/warnStatusChange';
Expand Down Expand Up @@ -53,5 +54,7 @@ export const useMarketplaceActions = () => {
purchase: installAppMutation.mutateAsync,
install: installAppMutation.mutateAsync,
update: updateAppMutation.mutateAsync,
} as const;
request: () => undefined, // TODO: is it right?
subscribe: () => undefined, // TODO: is it right?
} as const satisfies Record<Actions, (...args: any) => void>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const useOpenIncompatibleModal = () => {
}

return useCallback(
async (app: App, actionName: Actions, cancelAction: () => void) => {
async (app: App, actionName: Actions | undefined, cancelAction: () => void) => {
const handleCancel = () => {
setModal(null);
cancelAction();
Expand All @@ -29,7 +29,7 @@ export const useOpenIncompatibleModal = () => {
};

try {
const incompatibleData = await appsOrchestrator.buildIncompatibleExternalUrl(app.id, app.marketplaceVersion, actionName);
const incompatibleData = await appsOrchestrator.buildIncompatibleExternalUrl(app.id, app.marketplaceVersion, actionName ?? '');
setModal(<IframeModal url={incompatibleData.url} cancel={handleCancel} confirm={handleConfirm} />);
} catch (e) {
handleAPIError(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const RoomInfo = ({ room, icon, onClickBack, onClickClose, onClickEnterRoom, onC
maxHeight='initial'
secondary
renderItem={({ label: { label, icon }, ...props }) => <Option {...props} label={label} icon={icon} />}
options={menuOptions}
options={menuOptions as any} // FIXME
/>
);
}, [menuOptions]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ const TeamsInfo = ({
maxHeight='initial'
secondary
renderItem={({ label: { label, icon }, ...props }): ReactElement => <Option {...props} label={label} icon={icon} />}
options={menuOptions}
options={menuOptions as any} // FIXME
/>
);
}, [menuOptions]);
Expand Down
Loading

0 comments on commit ff55e00

Please sign in to comment.