Skip to content

Commit 708d735

Browse files
committed
refactor(livechat): fix some lint warnings
1 parent fd4d58f commit 708d735

12 files changed

Lines changed: 63 additions & 81 deletions

File tree

packages/livechat/src/components/Form/HookFormExample/stories.tsx

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,36 @@
11
import { action } from '@storybook/addon-actions';
22
import type { Meta, StoryFn } from '@storybook/preact';
33
import type { ComponentProps } from 'preact';
4-
import type { JSXInternal } from 'preact/src/jsx';
54
import { Controller, useForm } from 'react-hook-form';
65

76
import { Form, PasswordInput, SelectInput, TextInput, FormField } from '..';
87
import { Button } from '../../Button';
98
import { ButtonGroup } from '../../ButtonGroup';
109

10+
type FormData = {
11+
text: string;
12+
password: string;
13+
options: string;
14+
};
15+
1116
export default {
1217
title: 'Forms/HookFormExample',
1318
component: Form,
14-
args: {
15-
onSubmit: (event) => {
16-
action('submit')(event);
17-
},
18-
},
1919
parameters: {
2020
layout: 'centered',
2121
},
2222
} satisfies Meta<ComponentProps<typeof Form>>;
2323

24-
export const Default: StoryFn<ComponentProps<typeof Form>> = (args) => {
24+
export const Default: StoryFn<ComponentProps<typeof Form>> = () => {
2525
const {
2626
handleSubmit,
2727
formState: { errors },
2828
control,
2929
reset,
30-
} = useForm();
30+
} = useForm<FormData>();
3131

3232
return (
33-
<Form onSubmit={handleSubmit(args.onSubmit as any) as unknown as JSXInternal.GenericEventHandler<HTMLFormElement>}>
33+
<Form onSubmit={handleSubmit(action('submit'))}>
3434
<FormField label='Text' description='Input field for plain text' error={errors?.text?.message?.toString()}>
3535
<Controller name='text' control={control} rules={{ required: true }} render={({ field }) => <TextInput {...field} />} />
3636
</FormField>

packages/livechat/src/definitions/triggerMessage.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export type TriggerMessage = {
44
msg?: string;
55
token: string;
66
u: Serialized<IOmnichannelAgent>;
7-
ts: string;
7+
ts: number;
88
_id: string;
99
trigger: boolean;
1010
};

packages/livechat/src/helpers/canRenderMessage.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ export const getHiddenSystemMessages = () => {
3131
return [...configHiddenSystemMessages, ...localHiddenSystemMessages] as string[];
3232
};
3333

34-
export const canRenderMessage = ({ t }: { t: string }) => {
34+
export const canRenderMessage = ({ t }: { t?: string }) => {
35+
if (!t) return true;
36+
3537
const hiddenSystemMessages = getHiddenSystemMessages();
3638

3739
return !msgTypesNotRendered.includes(t) && !hiddenSystemMessages.includes(t);

packages/livechat/src/lib/triggerActions.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export const sendMessageAction = async (_: string, action: ILivechatSendMessageA
1717
msg: action.params?.msg,
1818
token,
1919
u: agent,
20-
ts: new Date().toISOString(),
20+
ts: new Date().getTime(),
2121
_id: createToken(),
2222
trigger: true,
2323
};
@@ -32,7 +32,7 @@ export const sendMessageAction = async (_: string, action: ILivechatSendMessageA
3232
}
3333

3434
if (agent && '_id' in agent) {
35-
await store.setState({ agent });
35+
store.setState({ agent });
3636
parentCall('callback', 'assign-agent', normalizeAgent(agent));
3737
}
3838

@@ -80,7 +80,7 @@ export const sendMessageExternalServiceAction = async (
8080
msg,
8181
token,
8282
u: agent,
83-
ts: new Date().toISOString(),
83+
ts: new Date().getTime(),
8484
_id: createToken(),
8585
trigger: true,
8686
}));
@@ -98,7 +98,7 @@ export const sendMessageExternalServiceAction = async (
9898
);
9999

100100
if (agent && '_id' in agent) {
101-
await store.setState({ agent });
101+
store.setState({ agent });
102102
parentCall('callback', 'assign-agent', normalizeAgent(agent));
103103
}
104104

packages/livechat/src/lib/triggerUtils.ts

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import type { ILivechatAgent, ILivechatTrigger, ILivechatTriggerAction, ILivechatTriggerType, Serialized } from '@rocket.chat/core-typings';
22

33
import { Livechat } from '../api';
4+
import { processUnread } from './main';
45
import type { Agent } from '../definitions/agents';
56
import { upsert } from '../helpers/upsert';
67
import store from '../store';
7-
import { processUnread } from './main';
88

99
type AgentPromise = { username: string } | Serialized<ILivechatAgent> | null;
1010

@@ -27,14 +27,11 @@ const getNextAgentFromQueue = async () => {
2727
const dep = department || defaultDepartment;
2828

2929
let agent = null;
30-
try {
31-
const tempAgent = await Livechat.nextAgent({ department: dep });
3230

33-
if (isAgentWithInfo(tempAgent?.agent)) {
34-
agent = tempAgent.agent;
35-
}
36-
} catch (error) {
37-
return Promise.reject(error);
31+
const tempAgent = await Livechat.nextAgent({ department: dep });
32+
33+
if (isAgentWithInfo(tempAgent?.agent)) {
34+
agent = tempAgent.agent;
3835
}
3936

4037
store.setState({ defaultAgent: { ...agent, department: dep, ts: Date.now() } as Agent });
@@ -47,23 +44,20 @@ export const getAgent = async (triggerAction: ILivechatTriggerAction): Promise<A
4744
return agentPromise;
4845
}
4946

50-
agentPromise = new Promise(async (resolve, reject) => {
47+
agentPromise = new Promise((resolve, reject) => {
5148
const { sender, name = '' } = triggerAction.params || {};
5249

5350
if (sender === 'custom') {
5451
resolve({ username: name });
5552
}
5653

5754
if (sender === 'queue') {
58-
try {
59-
const agent = await getNextAgentFromQueue();
60-
resolve(agent);
61-
} catch (_) {
62-
resolve({ username: 'rocket.cat' });
63-
}
55+
getNextAgentFromQueue()
56+
.then((agent) => resolve(agent))
57+
.catch(() => resolve({ username: 'rocket.cat' }));
6458
}
6559

66-
return reject('Unknown sender type.');
60+
return reject(new Error('Unknown sender type'));
6761
});
6862

6963
// expire the promise cache as well
@@ -74,8 +68,8 @@ export const getAgent = async (triggerAction: ILivechatTriggerAction): Promise<A
7468
return agentPromise;
7569
};
7670

77-
export const upsertMessage = async (message: Record<string, unknown>) => {
78-
await store.setState({
71+
export const upsertMessage = async (message: { _id: string; msg?: string; t?: string; ts: number }) => {
72+
store.setState({
7973
messages: upsert(
8074
store.state.messages,
8175
message,
@@ -89,12 +83,12 @@ export const upsertMessage = async (message: Record<string, unknown>) => {
8983

9084
export const removeMessage = async (messageId: string) => {
9185
const { messages } = store.state;
92-
await store.setState({ messages: messages.filter(({ _id }) => _id !== messageId) });
86+
store.setState({ messages: messages.filter(({ _id }) => _id !== messageId) });
9387
};
9488

9589
export const removeTriggerMessage = async (messageId: string) => {
9690
const { renderedTriggers } = store.state;
97-
await store.setState({ renderedTriggers: renderedTriggers.filter(({ _id }) => _id !== messageId) });
91+
store.setState({ renderedTriggers: renderedTriggers.filter(({ _id }) => _id !== messageId) });
9892
};
9993

10094
export const hasTriggerCondition = (conditionName: ILivechatTriggerType) => (trigger: ILivechatTrigger) => {
@@ -122,9 +116,9 @@ export const requestTriggerMessages = async ({
122116

123117
const { response } = await Livechat.rest.post(`/v1/livechat/triggers/${triggerId}/external-service/call`, { extraData, token });
124118
return response.contents;
125-
} catch (_) {
119+
} catch (error) {
126120
if (!fallbackMessage) {
127-
throw Error('Unable to fetch message from external service.');
121+
throw Error('Unable to fetch message from external service.', { cause: error });
128122
}
129123

130124
return [{ msg: fallbackMessage, order: 0 }];

packages/livechat/src/routes/Chat/connector.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { TFunction } from 'i18next';
2-
import type { FunctionalComponent } from 'preact';
2+
import type { Ref } from 'preact';
33
import { useContext } from 'preact/hooks';
44
import { withTranslation } from 'react-i18next';
55

@@ -9,7 +9,7 @@ import { canRenderMessage } from '../../helpers/canRenderMessage';
99
import { formatAgent } from '../../helpers/formatAgent';
1010
import { StoreContext } from '../../store';
1111

12-
export const ChatConnector: FunctionalComponent<{ path: string; default: boolean; t: TFunction }> = ({ ref, t }) => {
12+
export const ChatConnector = ({ ref, t }: { path: string; default: boolean; t: TFunction; ref?: Ref<any> }) => {
1313
const { theme } = useContext(ScreenContext);
1414
const {
1515
config: {

packages/livechat/src/routes/LeaveMessage/index.tsx

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import type { FunctionalComponent } from 'preact';
22
import { useContext, useRef } from 'preact/hooks';
3-
import type { JSXInternal } from 'preact/src/jsx';
4-
import type { FieldValues, SubmitHandler } from 'react-hook-form';
53
import { Controller, useForm } from 'react-hook-form';
64
import { useTranslation } from 'react-i18next';
75

@@ -44,7 +42,7 @@ const LeaveMessage: FunctionalComponent<{ path: string }> = () => {
4442
handleSubmit,
4543
formState: { errors, isDirty, isValid, isSubmitting },
4644
control,
47-
} = useForm({ mode: 'onChange' });
45+
} = useForm<FormValues>({ mode: 'onChange' });
4846

4947
const customOfflineTitle = iframe?.theme?.offlineTitle;
5048

@@ -58,7 +56,7 @@ const LeaveMessage: FunctionalComponent<{ path: string }> = () => {
5856
message,
5957
};
6058

61-
await dispatch({ loading: true });
59+
dispatch({ loading: true });
6260

6361
try {
6462
// TODO: Remove intersection after ts refactor of parseOfflineMessage
@@ -73,10 +71,10 @@ const LeaveMessage: FunctionalComponent<{ path: string }> = () => {
7371
const errorMessage = (error as { error: string })?.error;
7472
console.error(errorMessage);
7573
const alert = { id: createToken(), children: errorMessage, error: true, timeout: 5000 };
76-
await dispatch({ alerts: (alerts.push(alert), alerts) });
74+
dispatch({ alerts: (alerts.push(alert), alerts) });
7775
return false;
7876
} finally {
79-
await dispatch({ loading: false });
77+
dispatch({ loading: false });
8078
}
8179
};
8280

@@ -97,7 +95,7 @@ const LeaveMessage: FunctionalComponent<{ path: string }> = () => {
9795

9896
<Form
9997
// The price of using react-hook-form on a preact project ¯\_(ツ)_/¯
100-
onSubmit={handleSubmit(onSubmit as SubmitHandler<FieldValues>) as unknown as JSXInternal.GenericEventHandler<HTMLFormElement>}
98+
onSubmit={handleSubmit(onSubmit)}
10199
id='leaveMessage'
102100
>
103101
<FormField required label={t('name')} error={errors.name?.message?.toString()}>

packages/livechat/src/routes/Register/index.tsx

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import type { FunctionalComponent } from 'preact';
22
import { useContext, useEffect, useMemo, useRef } from 'preact/hooks';
3-
import type { JSXInternal } from 'preact/src/jsx';
43
import { route } from 'preact-router';
5-
import type { FieldValues, SubmitHandler } from 'react-hook-form';
64
import { Controller, useForm } from 'react-hook-form';
75
import { useTranslation } from 'react-i18next';
86

@@ -21,9 +19,6 @@ import Triggers from '../../lib/triggers';
2119
import { StoreContext } from '../../store';
2220
import type { StoreState } from '../../store';
2321

24-
// Custom field as in the form payload
25-
type FormPayloadCustomField = { [key: string]: string };
26-
2722
export type RegisterFormValues = { name: string; email: string; department?: string; [key: string]: any };
2823

2924
export const Register: FunctionalComponent<{ path: string }> = () => {
@@ -71,17 +66,7 @@ export const Register: FunctionalComponent<{ path: string }> = () => {
7166
});
7267
};
7368

74-
const onSubmit = async ({
75-
name,
76-
email,
77-
department,
78-
...customFields
79-
}: {
80-
name: string;
81-
email: string;
82-
department?: string;
83-
customFields: FormPayloadCustomField;
84-
}) => {
69+
const onSubmit = async ({ name, email, department, ...customFields }: RegisterFormValues) => {
8570
const guestDepartment = department || defaultDepartment;
8671
const fields = {
8772
name,
@@ -93,7 +78,7 @@ export const Register: FunctionalComponent<{ path: string }> = () => {
9378

9479
try {
9580
const { visitor: user } = await Livechat.grantVisitor({ visitor: { ...fields, token } });
96-
await dispatch({
81+
dispatch({
9782
user,
9883
...(user.contactManager && { agent: user.contactManager }),
9984
} as Omit<StoreState['user'], 'ts'>);
@@ -130,7 +115,7 @@ export const Register: FunctionalComponent<{ path: string }> = () => {
130115
<Form
131116
id='register'
132117
// The price of using react-hook-form on a preact project ¯\_(ツ)_/¯
133-
onSubmit={handleSubmit(onSubmit as SubmitHandler<FieldValues>) as unknown as JSXInternal.GenericEventHandler<HTMLFormElement>}
118+
onSubmit={handleSubmit(onSubmit)}
134119
>
135120
<div id='top' ref={topRef} style={{ height: '1px', width: '100%' }} />
136121
<p className={createClassName(styles, 'register__message')}>{message || defaultMessage}</p>

packages/livechat/src/routes/SwitchDepartment/index.tsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,25 +63,25 @@ const SwitchDepartment = (_: SwitchDepartmentProps) => {
6363

6464
if (!room) {
6565
const { visitor: user } = await Livechat.grantVisitor({ visitor: { department, token } });
66-
await dispatch({
66+
dispatch({
6767
user: user as StoreState['user'],
6868
alerts: (alerts.push({ id: createToken(), children: t('department_switched'), success: true }), alerts),
6969
});
7070
route('/');
7171
return;
7272
}
7373

74-
await dispatch({ loading: true });
74+
dispatch({ loading: true });
7575
try {
7676
const { _id: rid } = room;
7777
const result = await Livechat.transferChat({ rid, department });
7878
const { success } = result;
7979

8080
if (!success) {
81-
throw t('no_available_agents_to_transfer');
81+
throw new Error(t('no_available_agents_to_transfer'));
8282
}
8383

84-
await dispatch({ iframe: { ...iframe, guest: { ...guest, department } }, loading: false } as Pick<StoreState, 'iframe' | 'loading'>);
84+
dispatch({ iframe: { ...iframe, guest: { ...guest, department } }, loading: false } as Pick<StoreState, 'iframe' | 'loading'>);
8585
await loadConfig();
8686

8787
await ModalManager.alert({
@@ -91,11 +91,11 @@ const SwitchDepartment = (_: SwitchDepartmentProps) => {
9191
route('/');
9292
} catch (error) {
9393
console.error(error);
94-
await dispatch({
94+
dispatch({
9595
alerts: (alerts.push({ id: createToken(), children: t('no_available_agents_to_transfer'), warning: true }), alerts),
9696
});
9797
} finally {
98-
await dispatch({ loading: false });
98+
dispatch({ loading: false });
9999
}
100100
};
101101

packages/livechat/src/routes/TriggerMessage/container.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { FunctionalComponent } from 'preact';
1+
import type { Ref } from 'preact';
22
import { useContext, useEffect } from 'preact/hooks';
33
import { route } from 'preact-router';
44

@@ -9,7 +9,7 @@ import { formatAgent } from '../../helpers/formatAgent';
99
import { parentCall } from '../../lib/parentCall';
1010
import { StoreContext } from '../../store';
1111

12-
export const TriggerMessageContainer: FunctionalComponent<{ path: string }> = ({ ref }) => {
12+
export const TriggerMessageContainer = ({ ref }: { path: string; ref?: Ref<any> }) => {
1313
const { messages, agent, unread } = useContext(StoreContext);
1414
const { theme, onRestore } = useContext(ScreenContext);
1515

0 commit comments

Comments
 (0)