|
| 1 | +import { useContext } from 'react'; |
| 2 | +import { useRecoilState, useRecoilValue } from 'recoil'; |
| 3 | + |
| 4 | +import { usePersistField } from '@/object-record/record-field/hooks/usePersistField'; |
| 5 | +import { useRecordFieldInput } from '@/object-record/record-field/hooks/useRecordFieldInput'; |
| 6 | +import { FieldEmailsValue } from '@/object-record/record-field/types/FieldMetadata'; |
| 7 | +import { isFieldEmails } from '@/object-record/record-field/types/guards/isFieldEmails'; |
| 8 | +import { emailsSchema } from '@/object-record/record-field/types/guards/isFieldEmailsValue'; |
| 9 | +import { recordStoreFamilySelector } from '@/object-record/record-store/states/selectors/recordStoreFamilySelector'; |
| 10 | +import { FieldMetadataType } from '~/generated-metadata/graphql'; |
| 11 | + |
| 12 | +import { FieldContext } from '../../contexts/FieldContext'; |
| 13 | +import { assertFieldMetadata } from '../../types/guards/assertFieldMetadata'; |
| 14 | + |
| 15 | +export const useEmailsField = () => { |
| 16 | + const { recordId, fieldDefinition, hotkeyScope } = useContext(FieldContext); |
| 17 | + |
| 18 | + assertFieldMetadata(FieldMetadataType.Emails, isFieldEmails, fieldDefinition); |
| 19 | + |
| 20 | + const fieldName = fieldDefinition.metadata.fieldName; |
| 21 | + |
| 22 | + const [fieldValue, setFieldValue] = useRecoilState<FieldEmailsValue>( |
| 23 | + recordStoreFamilySelector({ |
| 24 | + recordId, |
| 25 | + fieldName: fieldName, |
| 26 | + }), |
| 27 | + ); |
| 28 | + |
| 29 | + const { setDraftValue, getDraftValueSelector } = |
| 30 | + useRecordFieldInput<FieldEmailsValue>(`${recordId}-${fieldName}`); |
| 31 | + |
| 32 | + const draftValue = useRecoilValue(getDraftValueSelector()); |
| 33 | + |
| 34 | + const persistField = usePersistField(); |
| 35 | + |
| 36 | + const persistEmailsField = (nextValue: FieldEmailsValue) => { |
| 37 | + try { |
| 38 | + persistField(emailsSchema.parse(nextValue)); |
| 39 | + } catch { |
| 40 | + return; |
| 41 | + } |
| 42 | + }; |
| 43 | + |
| 44 | + return { |
| 45 | + fieldDefinition, |
| 46 | + fieldValue, |
| 47 | + draftValue, |
| 48 | + setDraftValue, |
| 49 | + setFieldValue, |
| 50 | + hotkeyScope, |
| 51 | + persistEmailsField, |
| 52 | + }; |
| 53 | +}; |
0 commit comments