Skip to content

Commit

Permalink
refactor: Remove formsSubscription hooks in favor of EE components (
Browse files Browse the repository at this point in the history
  • Loading branch information
dougfabris authored Nov 3, 2023
1 parent a7647f9 commit 694a70b
Show file tree
Hide file tree
Showing 25 changed files with 193 additions and 272 deletions.
12 changes: 3 additions & 9 deletions apps/meteor/client/components/Omnichannel/Tags.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useToastMessageDispatch, useTranslation } from '@rocket.chat/ui-context
import type { ChangeEvent, ReactElement } from 'react';
import React, { useMemo, useState } from 'react';

import { useFormsSubscription } from '../../views/omnichannel/additionalForms';
import { CurrentChatTags } from '../../views/omnichannel/additionalForms';
import { FormSkeleton } from './Skeleton';
import { useLivechatTags } from './hooks/useLivechatTags';

Expand All @@ -18,12 +18,6 @@ type TagsProps = {

const Tags = ({ tags = [], handler, error, tagRequired, department }: TagsProps): ReactElement => {
const t = useTranslation();
const forms = useFormsSubscription() as any;

// TODO: Refactor the formsSubscription to use components instead of hooks (since the only thing the hook does is return a component)
const { useCurrentChatTags } = forms;
// Conditional hook was required since the whole formSubscription uses hooks in an incorrect manner
const EETagsComponent = useCurrentChatTags?.();

const { data: tagsResult, isInitialLoading } = useLivechatTags({
department,
Expand Down Expand Up @@ -75,9 +69,9 @@ const Tags = ({ tags = [], handler, error, tagRequired, department }: TagsProps)
{t('Tags')}
</FieldLabel>

{EETagsComponent && tagsResult?.tags && tagsResult?.tags.length ? (
{tagsResult?.tags && tagsResult?.tags.length ? (
<FieldRow>
<EETagsComponent
<CurrentChatTags
value={paginatedTagValue}
handler={(tags: { label: string; value: string }[]): void => {
handler(tags.map((tag) => tag.label));
Expand Down
71 changes: 28 additions & 43 deletions apps/meteor/client/views/omnichannel/additionalForms.tsx
Original file line number Diff line number Diff line change
@@ -1,44 +1,29 @@
import type { ReactElement } from 'react';
import { useSyncExternalStore } from 'use-sync-external-store/shim';

// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-empty-interface
export interface EEFormHooks {}

const createFormSubscription = (): {
registerForm: (form: EEFormHooks) => void;
unregisterForm: (form: keyof EEFormHooks) => void;
formsSubscription: readonly [subscribe: (onStoreChange: () => void) => () => void, getSnapshot: () => EEFormHooks];
getForm: (form: keyof EEFormHooks) => () => ReactElement;
} => {
let forms = {} as EEFormHooks;
let updateCb = (): void => undefined;

const formsSubscription = [
(cb: () => void): (() => void) => {
updateCb = cb;
return (): void => {
updateCb = (): void => undefined;
};
},
(): EEFormHooks => forms,
] as const;

const registerForm = (newForm: EEFormHooks): void => {
forms = { ...forms, ...newForm };
updateCb();
};
const unregisterForm = (form: keyof EEFormHooks): void => {
delete forms[form];
updateCb();
};

const getForm = (form: keyof EEFormHooks): (() => ReactElement) => (forms as any)[form] as any;

return { registerForm, unregisterForm, formsSubscription, getForm };
import BusinessHoursMultipleContainer from '../../../ee/client/omnichannel/additionalForms/BusinessHoursMultipleContainer';
import ContactManager from '../../../ee/client/omnichannel/additionalForms/ContactManager';
import CurrentChatTags from '../../../ee/client/omnichannel/additionalForms/CurrentChatTags';
import CustomFieldsAdditionalFormContainer from '../../../ee/client/omnichannel/additionalForms/CustomFieldsAdditionalFormContainer';
import DepartmentBusinessHours from '../../../ee/client/omnichannel/additionalForms/DepartmentBusinessHours';
import DepartmentForwarding from '../../../ee/client/omnichannel/additionalForms/DepartmentForwarding';
import EeNumberInput from '../../../ee/client/omnichannel/additionalForms/EeNumberInput';
import EeTextAreaInput from '../../../ee/client/omnichannel/additionalForms/EeTextAreaInput';
import EeTextInput from '../../../ee/client/omnichannel/additionalForms/EeTextInput';
import MaxChatsPerAgentContainer from '../../../ee/client/omnichannel/additionalForms/MaxChatsPerAgentContainer';
import MaxChatsPerAgentDisplay from '../../../ee/client/omnichannel/additionalForms/MaxChatsPerAgentDisplay';
import PrioritiesSelect from '../../../ee/client/omnichannel/additionalForms/PrioritiesSelect';
import SlaPoliciesSelect from '../../../ee/client/omnichannel/additionalForms/SlaPoliciesSelect';

export {
CustomFieldsAdditionalFormContainer,
MaxChatsPerAgentContainer,
MaxChatsPerAgentDisplay,
EeNumberInput,
EeTextAreaInput,
BusinessHoursMultipleContainer,
EeTextInput,
ContactManager,
CurrentChatTags,
DepartmentBusinessHours,
DepartmentForwarding,
SlaPoliciesSelect,
PrioritiesSelect,
};

const { registerForm, unregisterForm, formsSubscription, getForm } = createFormSubscription();

export { registerForm, unregisterForm, getForm };

export const useFormsSubscription = (): EEFormHooks => useSyncExternalStore(...formsSubscription);
11 changes: 3 additions & 8 deletions apps/meteor/client/views/omnichannel/agents/AgentEdit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ import {
} from '@rocket.chat/fuselage';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import { useToastMessageDispatch, useRoute, useSetting, useMethod, useTranslation, useEndpoint } from '@rocket.chat/ui-contexts';
import type { FC, ReactElement } from 'react';
import type { FC } from 'react';
import React, { useMemo, useRef, useState } from 'react';

import { getUserEmailAddress } from '../../../../lib/getUserEmailAddress';
import { ContextualbarScrollableContent } from '../../../components/Contextualbar';
import UserInfo from '../../../components/UserInfo';
import { useForm } from '../../../hooks/useForm';
import { useFormsSubscription } from '../additionalForms';
import { MaxChatsPerAgentContainer } from '../additionalForms';

// TODO: TYPE:
// Department
Expand Down Expand Up @@ -63,7 +63,6 @@ const AgentEdit: FC<AgentEditProps> = ({ data, userDepartments, availableDepartm
() => (userDepartments.departments ? userDepartments.departments.map(({ departmentId }) => departmentId) : []),
[userDepartments],
);
const eeForms = useFormsSubscription();

const saveRef = useRef({
values: {},
Expand All @@ -82,8 +81,6 @@ const AgentEdit: FC<AgentEditProps> = ({ data, userDepartments, availableDepartm
}
});

const { useMaxChatsPerAgent = (): ReactElement | null => null } = eeForms as any; // TODO: Find out how to use ts with eeForms

const { values, handlers, hasUnsavedChanges, commit } = useForm({
departments: initialDepartmentValue,
status: statusLivechat,
Expand All @@ -98,8 +95,6 @@ const AgentEdit: FC<AgentEditProps> = ({ data, userDepartments, availableDepartm
voipExtension: string;
};

const MaxChats = useMaxChatsPerAgent();

const saveAgentInfo = useMethod('livechat:saveAgentInfo');
const saveAgentStatus = useEndpoint('POST', '/v1/livechat/agent.status');

Expand Down Expand Up @@ -177,7 +172,7 @@ const AgentEdit: FC<AgentEditProps> = ({ data, userDepartments, availableDepartm
/>
</FieldRow>
</Field>
{MaxChats && <MaxChats data={user} onChange={onChangeMaxChats} />}
<MaxChatsPerAgentContainer data={user as any} onChange={onChangeMaxChats} />
{voipEnabled && (
<Field>
<FieldLabel>{t('VoIP_Extension')}</FieldLabel>
Expand Down
8 changes: 2 additions & 6 deletions apps/meteor/client/views/omnichannel/agents/AgentInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import UserInfo from '../../../components/UserInfo';
import { UserStatus } from '../../../components/UserStatus';
import { AsyncStatePhase } from '../../../hooks/useAsyncState';
import { useEndpointData } from '../../../hooks/useEndpointData';
import { useFormsSubscription } from '../additionalForms';
import { MaxChatsPerAgentDisplay } from '../additionalForms';

type AgentInfoProps = {
uid: string;
Expand All @@ -19,10 +19,6 @@ const AgentInfo = memo<AgentInfoProps>(function AgentInfo({ uid, children, ...pr
const t = useTranslation();
const result = useEndpointData('/v1/livechat/users/agent/:_id', { keys: { _id: uid } });

const { useMaxChatsPerAgentDisplay } = useFormsSubscription();

const MaxChats = useMaxChatsPerAgentDisplay?.();

if (result.phase === AsyncStatePhase.LOADING) {
return <FormSkeleton />;
}
Expand Down Expand Up @@ -58,7 +54,7 @@ const AgentInfo = memo<AgentInfoProps>(function AgentInfo({ uid, children, ...pr
</>
)}

{MaxChats && <MaxChats data={user} />}
<MaxChatsPerAgentDisplay data={user} />
</Margins>
</ContextualbarScrollableContent>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import React, { useEffect, useState } from 'react';
import { businessHourManager } from '../../../../app/livechat/client/views/app/business-hours/BusinessHours';
import { useForm } from '../../../hooks/useForm';
import { useReactiveValue } from '../../../hooks/useReactiveValue';
import { useFormsSubscription } from '../additionalForms';
import { BusinessHoursMultipleContainer } from '../additionalForms';
import BusinessHourForm from './BusinessHoursForm';
import BusinessHoursTimeZone from './BusinessHoursTimeZone';

Expand All @@ -22,18 +22,10 @@ const getInitalData = ({ workHours }) => ({
}, {}),
});

const cleanFunc = () => {};

const BusinessHoursFormContainer = ({ data, saveRef, onChange = () => {} }) => {
const forms = useFormsSubscription();

const [hasChangesMultiple, setHasChangesMultiple] = useState(false);
const [hasChangesTimeZone, setHasChangesTimeZone] = useState(false);

const { useBusinessHoursMultiple = cleanFunc } = forms;

const MultipleBHForm = useBusinessHoursMultiple();

const showMultipleBHForm = useReactiveValue(useMutableCallback(() => businessHourManager.showCustomTemplate(data)));

const onChangeTimezone = useChangeHandler('timezone', saveRef);
Expand All @@ -50,8 +42,8 @@ const BusinessHoursFormContainer = ({ data, saveRef, onChange = () => {} }) => {
return (
<Box maxWidth='600px' w='full' alignSelf='center'>
<FieldGroup>
{showMultipleBHForm && MultipleBHForm && (
<MultipleBHForm onChange={onChangeMultipleBHForm} data={data} hasChangesAndIsValid={setHasChangesMultiple} />
{showMultipleBHForm && (
<BusinessHoursMultipleContainer onChange={onChangeMultipleBHForm} data={data} hasChangesAndIsValid={setHasChangesMultiple} />
)}
<BusinessHoursTimeZone
onChange={onChangeTimezone}
Expand Down
14 changes: 3 additions & 11 deletions apps/meteor/client/views/omnichannel/currentChats/FilterByText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import React, { useEffect } from 'react';
import AutoCompleteAgent from '../../../components/AutoCompleteAgent';
import AutoCompleteDepartment from '../../../components/AutoCompleteDepartment';
import GenericModal from '../../../components/GenericModal';
import { useFormsSubscription } from '../additionalForms';
import { CurrentChatTags } from '../additionalForms';
import Label from './Label';
import RemoveAllClosed from './RemoveAllClosed';

Expand Down Expand Up @@ -59,14 +59,6 @@ const FilterByText: FilterByTextType = ({ setFilter, reload, customFields, setCu
setCustomFields(undefined);
});

const forms = useFormsSubscription() as any;

// TODO: Refactor the formsSubscription to use components instead of hooks (since the only thing the hook does is return a component)
// Conditional hook was required since the whole formSubscription uses hooks in an incorrect manner
const { useCurrentChatTags = (): void => undefined } = forms;

const EETagsComponent = useCurrentChatTags();

const onSubmit = useMutableCallback((e) => e.preventDefault());

useEffect(() => {
Expand Down Expand Up @@ -146,11 +138,11 @@ const FilterByText: FilterByTextType = ({ setFilter, reload, customFields, setCu
<AutoCompleteDepartment haveAll showArchived value={department} onChange={handleDepartment} onlyMyDepartments />
</Box>
</Box>
{EETagsComponent && (
{CurrentChatTags && (
<Box display='flex' flexDirection='row' marginBlockStart={8} {...props}>
<Box display='flex' mie={8} flexGrow={1} flexDirection='column'>
<Label mb={4}>{t('Tags')}</Label>
<EETagsComponent value={tags} handler={handleTags} viewAll />
<CurrentChatTags value={tags} handler={handleTags} viewAll />
</Box>
</Box>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import React, { useCallback, useState } from 'react';

import Page from '../../../components/Page';
import { useForm } from '../../../hooks/useForm';
import { useFormsSubscription } from '../additionalForms';
import { CustomFieldsAdditionalFormContainer } from '../additionalForms';
import NewCustomFieldsForm from './NewCustomFieldsForm';

const getInitialValues = (cf) => ({
Expand All @@ -24,9 +24,6 @@ const EditCustomFieldsPage = ({ customField, id, reload }) => {

const [additionalValues, setAdditionalValues] = useState({});

const { useCustomFieldsAdditionalForm = () => {} } = useFormsSubscription();
const AdditionalForm = useCustomFieldsAdditionalForm();

const router = useRoute('omnichannel-customfields');

const handleReturn = useCallback(() => {
Expand Down Expand Up @@ -79,7 +76,7 @@ const EditCustomFieldsPage = ({ customField, id, reload }) => {
<Box maxWidth='x600' w='full' alignSelf='center'>
<FieldGroup>
<NewCustomFieldsForm values={values} handlers={handlers} />
{AdditionalForm && <AdditionalForm onChange={handleAdditionalForm} state={values} data={customField} />}
<CustomFieldsAdditionalFormContainer onChange={handleAdditionalForm} state={values} data={customField} />
</FieldGroup>
</Box>
</Page.ScrollableContentWithShadow>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import React, { useCallback, useState } from 'react';

import Page from '../../../components/Page';
import { useForm } from '../../../hooks/useForm';
import { useFormsSubscription } from '../additionalForms';
import { CustomFieldsAdditionalFormContainer } from '../additionalForms';
import NewCustomFieldsForm from './NewCustomFieldsForm';

const initialValues = {
Expand All @@ -23,9 +23,6 @@ const NewCustomFieldsPage = ({ reload }) => {

const [additionalValues, setAdditionalValues] = useState({});

const { useCustomFieldsAdditionalForm = () => {} } = useFormsSubscription();
const AdditionalForm = useCustomFieldsAdditionalForm();

const router = useRoute('omnichannel-customfields');

const handleReturn = useCallback(() => {
Expand Down Expand Up @@ -78,7 +75,7 @@ const NewCustomFieldsPage = ({ reload }) => {
<Box maxWidth='x600' w='full' alignSelf='center'>
<FieldGroup>
<NewCustomFieldsForm values={values} handlers={handlers} />
{AdditionalForm && <AdditionalForm onChange={handleAdditionalForm} state={values} />}
<CustomFieldsAdditionalFormContainer onChange={handleAdditionalForm} state={values} />
</FieldGroup>
</Box>
</Page.ScrollableContentWithShadow>
Expand Down
Loading

0 comments on commit 694a70b

Please sign in to comment.