Skip to content

Commit

Permalink
Merge pull request #3681 from LiteFarmOrg/LF-4718b-repair-deployment-…
Browse files Browse the repository at this point in the history
…of-webapp

TypeScript cleanup -- hookFormValidationUtils.ts and ts-expect-error
  • Loading branch information
antsgar authored Feb 6, 2025
2 parents 1a46748 + d57522c commit 03d3aef
Show file tree
Hide file tree
Showing 23 changed files with 72 additions and 67 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ const AnimalDetails = ({
originProps,
namePrefix,
}: AnimalDetailsProps) => {
const { expandedIds, toggleExpanded } = useExpandable(
// @ts-ignore
{ isSingleExpandable: true },
);
const { expandedIds, toggleExpanded } = useExpandable({ isSingleExpandable: true });
const { t } = useTranslation(['translation', 'common', 'animal']);
const commonProps = { t, namePrefix };

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export default function AddAnimalsFormCard({
}}
/>
{!shouldCreateIndividualProfiles && (
// @ts-ignore
// @ts-expect-error
<Input
label={t('ADD_ANIMAL.BATCH_NAME')}
optional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { useTranslation } from 'react-i18next';
import { RefObject } from 'react';
import { GroupBase, SelectInstance, OptionsOrGroups } from 'react-select';
import { Error } from '../../Typography';
import { hookFormSelectOptionMaxLength } from '../../Form/hookformValidationUtils';
import { validateOptionLength } from '../../Form/hookformValidationUtils';

export type Option = {
label: string;
Expand Down Expand Up @@ -50,8 +50,7 @@ export function AnimalTypeSelect<T extends FieldValues>({
control={control}
rules={{
required: { value: true, message: t('common:REQUIRED') },
// @ts-ignore
validate: hookFormSelectOptionMaxLength,
validate: validateOptionLength,
}}
render={({ field: { onChange, value } }) => (
<CreatableSelect
Expand Down Expand Up @@ -98,8 +97,7 @@ export function AnimalBreedSelect<T extends FieldValues>({
name={name}
control={control}
rules={{
// @ts-ignore
validate: hookFormSelectOptionMaxLength,
validate: validateOptionLength,
}}
render={({ field: { onChange, value } }) => (
<CreatableSelect
Expand All @@ -112,7 +110,6 @@ export function AnimalBreedSelect<T extends FieldValues>({
isDisabled={!isTypeSelected || isDisabled}
onChange={(option: any) => {
onChange(option);
// @ts-ignore
onBreedChange?.(option);
}}
value={value || null}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ const GeneralDetails = ({
animalOrBatch === AnimalOrBatchKeys.ANIMAL ? (
<div>
<InputBaseLabel optional label={t('ANIMAL.ANIMAL_SEXES')} />
{/* @ts-ignore */}
{/* @ts-expect-error */}
<RadioGroup
name={`${namePrefix}${DetailsFields.SEX}`}
radios={sexOptions}
Expand Down Expand Up @@ -160,7 +160,6 @@ const GeneralDetails = ({
<div className={clsx(styles.sectionWrapper, mode === 'edit' && styles.edit)}>
{(mode === 'readonly' || mode === 'edit') && (
<>
{/* @ts-ignore */}
<LockedInput
label={t('ANIMAL.ATTRIBUTE.LITEFARM_ID')}
placeholder={`${t('ANIMAL.ANIMAL_ID')}${getValues(`${namePrefix}${DetailsFields.ID}`)}`}
Expand All @@ -169,7 +168,7 @@ const GeneralDetails = ({
)}
{animalOrBatch === AnimalOrBatchKeys.BATCH && (
<>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
type="text"
label={t('ANIMAL.ATTRIBUTE.BATCH_NAME')}
Expand Down Expand Up @@ -226,7 +225,7 @@ const GeneralDetails = ({
/>
{isOtherUseSelected && (
<>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
type="text"
label={t('ANIMAL.ATTRIBUTE.OTHER_USE')}
Expand Down
14 changes: 7 additions & 7 deletions packages/webapp/src/components/Animals/DetailCards/Origin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const Origin = ({ t, currency, originOptions, namePrefix = '', mode = 'add' }: O
const fields = useMemo(() => {
return origin === AnimalOrigins.BROUGHT_IN ? (
<>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
key={DetailsFields.BROUGHT_IN_DATE}
type="date"
Expand All @@ -79,7 +79,7 @@ const Origin = ({ t, currency, originOptions, namePrefix = '', mode = 'add' }: O
optional
disabled={mode === 'readonly'}
/>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
key={DetailsFields.SUPPLIER}
type="text"
Expand All @@ -94,7 +94,7 @@ const Origin = ({ t, currency, originOptions, namePrefix = '', mode = 'add' }: O
errors={getInputErrors(errors, `${namePrefix}${DetailsFields.SUPPLIER}`)}
disabled={mode === 'readonly'}
/>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
key={DetailsFields.PRICE}
type="number"
Expand All @@ -112,7 +112,7 @@ const Origin = ({ t, currency, originOptions, namePrefix = '', mode = 'add' }: O
</>
) : (
<>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
key={DetailsFields.DAM}
type="text"
Expand All @@ -127,7 +127,7 @@ const Origin = ({ t, currency, originOptions, namePrefix = '', mode = 'add' }: O
errors={getInputErrors(errors, `${namePrefix}${DetailsFields.DAM}`)}
disabled={mode === 'readonly'}
/>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
key={DetailsFields.SIRE}
type="text"
Expand All @@ -147,7 +147,7 @@ const Origin = ({ t, currency, originOptions, namePrefix = '', mode = 'add' }: O
}, [origin, Object.entries(errors)]);
return (
<div className={styles.sectionWrapper}>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
type="date"
label={t('ANIMAL.ATTRIBUTE.DATE_OF_BIRTH')}
Expand All @@ -171,7 +171,7 @@ const Origin = ({ t, currency, originOptions, namePrefix = '', mode = 'add' }: O
disabled={mode === 'readonly'}
/>
<div>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<RadioGroup
name={`${namePrefix}${DetailsFields.ORIGIN}`}
radios={originOptions}
Expand Down
4 changes: 2 additions & 2 deletions packages/webapp/src/components/Animals/DetailCards/Other.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ const OtherDetails = ({
<div className={styles.sectionWrapper}>
{animalOrBatch === AnimalOrBatchKeys.ANIMAL && (
<>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
type="date"
label={t('ANIMAL.ATTRIBUTE.WEANING_DATE')}
Expand All @@ -102,7 +102,7 @@ const OtherDetails = ({
/>
)}
/>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<InputAutoSize
label={t(`ANIMAL.ATTRIBUTE.OTHER_DETAILS_${animalOrBatch.toUpperCase()}`)}
hookFormRegister={register(`${namePrefix}${DetailsFields.OTHER_DETAILS}`, {
Expand Down
6 changes: 3 additions & 3 deletions packages/webapp/src/components/Animals/DetailCards/Unique.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const UniqueDetails = ({

return (
<div className={styles.sectionWrapper}>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
type="text"
label={t('common:NAME')}
Expand All @@ -61,7 +61,7 @@ const UniqueDetails = ({
errors={getInputErrors(errors, `${namePrefix}${DetailsFields.NAME}`)}
disabled={mode === 'readonly'}
/>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
type="text"
label={t('ANIMAL.ATTRIBUTE.TAG_NUMBER')}
Expand Down Expand Up @@ -106,7 +106,7 @@ const UniqueDetails = ({
/>
{shouldShowTagTypeInput && (
<>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
type="text"
hookFormRegister={register(`${namePrefix}${DetailsFields.TAG_TYPE_INFO}`, {
Expand Down
2 changes: 1 addition & 1 deletion packages/webapp/src/components/Animals/Inventory/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ const PureAnimalInventory = ({
{showActionFloaterButton && (
<div className={styles.ctaButtonWrapper}>
<FloatingActionButton
// @ts-ignore
// @ts-expect-error
type={'add'}
onClick={() => history.push(ADD_ANIMALS_URL)}
aria-label={t('ADD_ANIMAL.ADD_ANIMALS')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ export default function RemoveAnimalsModal(props: RemoveAnimalsModalProps) {

return (
<>
{/* @ts-ignore */}
<Drawer
title={t('REMOVE_ANIMALS.REMOVE_ANIMALS')}
isOpen={props.isOpen}
Expand Down Expand Up @@ -189,7 +188,7 @@ export default function RemoveAnimalsModal(props: RemoveAnimalsModalProps) {
)}

{!isCreatedInError(selectedOption) && (
/* @ts-ignore */
/* @ts-expect-error */
<Input
type={'date'}
label={t('common:DATE')}
Expand All @@ -209,7 +208,7 @@ export default function RemoveAnimalsModal(props: RemoveAnimalsModalProps) {
</div>
) : (
<>
{/*@ts-ignore*/}
{/*@ts-expect-error*/}
<Input
hookFormRegister={register(EXPLANATION)}
label={t('REMOVE_ANIMALS.EXPLANATION')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const WithPageTitle = ({
<ClickAwayListener onClickAway={onClickAway} mouseEvent="onMouseDown" touchEvent="onTouchStart">
<div>
<Layout>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<MultiStepPageTitle
title={title}
onGoBack={onGoBack}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ const CreatableSelect = React.forwardRef((props, ref) => {
return (
inputValue.trim().length > 0 &&
!options?.some((opt) => {
// @ts-ignore
// @ts-expect-error
return compareUpperCaseTrim(opt?.label, inputValue);
})
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023 LiteFarm.org
* Copyright 2023, 2025 LiteFarm.org
* This file is part of LiteFarm.
*
* LiteFarm is free software: you can redistribute it and/or modify
Expand All @@ -16,20 +16,24 @@
// This file contains validation functions for use with react-hook-forms input validator

import i18n from '../../locales/i18n';
import { TFunction } from 'react-i18next';

export const hookFormMaxValidation = (max = 9999, message = '') => ({
export const hookFormMaxValidation = (max: number = 9999, message: string = '') => ({
value: max,
message: message || i18n.t('common:MAX_ERROR', { value: max + 1 }),
});
export const hookFormMinValidation = (min) => ({

export const hookFormMinValidation = (min: number) => ({
value: min,
message: i18n.t('common:MIN_ERROR', { value: min - 1 }),
});
export const hookFormMaxLengthValidation = (length = 60) => ({

export const hookFormMaxLengthValidation = (length: number = 60) => ({
value: length,
message: i18n.t('common:WORD_LIMIT_ERROR', { value: length }),
});
export const hookFormMaxCharsValidation = (max = 9999) => ({

export const hookFormMaxCharsValidation = (max: number = 9999) => ({
value: max,
message: i18n.t('common:CHAR_LIMIT_ERROR', { value: max }),
});
Expand All @@ -43,8 +47,12 @@ export const hookFormMaxCharsValidation = (max = 9999) => ({
* @returns {(value: any) => string|boolean} A validation function that takes a value to validate and returns
* either the error message (if not unique) or `true` (if unique).
*/
export const hookFormUniquePropertyValidation = (objArr, property, message) => {
return (value) => {
export const hookFormUniquePropertyValidation = (
objArr: Array<{ [key: string]: any }>,
property: string,
message: string,
) => {
return (value: any) => {
const alreadyExists = objArr.some((item) => {
return item[property] === value;
});
Expand All @@ -57,7 +65,7 @@ export const hookFormUniquePropertyValidation = (objArr, property, message) => {

/**
* Validates if a value is unique within an array of objects based on a specified property.
* Returns different messages depending on the bolean status of a specified property in the found object.
* Returns different messages depending on the boolean status of a specified property in the found object.
*
* @param {Array<Object>} objArr - The array of objects to search for duplicates in.
* @param {string} property - The property within each object to check for uniqueness.
Expand All @@ -73,8 +81,14 @@ export const hookFormUniquePropertyWithStatusValidation = ({
status = 'deleted',
messageStatusTrue,
messageStatusFalse,
}: {
objArr: Array<{ [key: string]: any }>;
property: string;
status?: string;
messageStatusTrue: string;
messageStatusFalse: string;
}) => {
return (value) => {
return (value: any) => {
const foundItem = objArr.find((item) => item[property] === value);

if (foundItem) {
Expand All @@ -92,13 +106,16 @@ export const hookFormUniquePropertyWithStatusValidation = ({
* Validates whether the length of the selected option's label exceeds the specified maximum.
* Returns an error message if the length is greater than the allowed limit; otherwise, returns true.
*
* @param {string} Option - The option whose label length is being validated.
* @param {string} selectedOption - The option whose label length is being validated.
* @param {number} length - The maximum allowed length for the label.
* @returns {string | boolean} A validation function that checks the label's length
* and returns either an error message or `true` if the validation passes.
*/
export const hookFormSelectOptionMaxLength = (selectedOption, length = 255) => {
return (
selectedOption?.label.length <= length || i18n.t('common:CHAR_LIMIT_ERROR', { value: length })
);
const hookFormSelectOptionMaxLength = (selectedOption: { label: string }, length: number = 255) => {
const t: TFunction = i18n.t;
return selectedOption?.label.length <= length || t('common:CHAR_LIMIT_ERROR', { value: length });
};

export const validateOptionLength = (value: { label: string }) => {
return hookFormSelectOptionMaxLength(value);
};
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export default function useImagePickerUpload(): { getOnFileUpload: GetOnFileUplo
}

dispatch(
// @ts-ignore
// @ts-expect-error
uploadImage({
file: blob,
onUploadSuccess,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ const ProductDetails = ({

<Collapse id={`product_details-${productId}`} in={isExpanded} timeout="auto" unmountOnExit>
<div className={styles.productDetailsContent}>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
name={SUPPLIER}
label={t('ADD_PRODUCT.SUPPLIER_LABEL')}
Expand All @@ -381,7 +381,7 @@ const ProductDetails = ({
{interested && inCanada && (
<div className={styles.permitedSubstance}>
<InputBaseLabel hasLeaf label={t('ADD_TASK.SOIL_AMENDMENT_VIEW.IS_PERMITTED')} />
{/* @ts-ignore */}
{/* @ts-expect-error */}
<RadioGroup
hookFormControl={control}
name={PERMITTED}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ const SoilAmendmentProductCard = ({

{purposes?.includes(otherPurposeId) && (
<>
{/* @ts-ignore */}
{/* @ts-expect-error */}
<Input
label={t('ADD_TASK.SOIL_AMENDMENT_VIEW.OTHER_PURPOSE')}
name={OTHER_PURPOSE}
Expand Down
Loading

0 comments on commit 03d3aef

Please sign in to comment.