Primakov Alexandr Alexandrovich 3dfd854a4c inline edit mode
2024-10-30 14:28:42 +03:00

141 lines
3.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React from 'react'
import { useForm, Controller } from 'react-hook-form'
import {
Box,
Card,
CardBody,
CardHeader,
Heading,
Button,
CloseButton,
VStack,
FormControl,
FormLabel,
FormHelperText,
FormErrorMessage,
Input,
} from '@chakra-ui/react'
import { AddIcon } from '@chakra-ui/icons'
import { dateToCalendarFormat } from '../../../utils/time'
import { Lesson } from '../../../__data__/model'
import { ErrorSpan } from '../style'
interface NewLessonForm {
name: string
date: string
}
interface LessonFormProps {
lesson?: Partial<Lesson>
isLoading: boolean
onCancel: () => void
onSubmit: (lesson: Lesson) => void
error?: string
title: string
nameButton: string
}
export const LessonForm = ({
lesson,
isLoading,
onCancel,
onSubmit,
error,
title,
nameButton,
}: LessonFormProps) => {
const {
control,
handleSubmit,
reset,
formState: { errors },
} = useForm<NewLessonForm>({
defaultValues: (lesson && {
...lesson,
date: dateToCalendarFormat(lesson.date),
}) || {
name: '',
date: dateToCalendarFormat(),
},
})
return (
<Card align="left">
<CardHeader display="flex">
<Heading as="h2" mt="0">
{title}
</Heading>
<CloseButton
ml="auto"
onClick={() => {
reset()
onCancel()
}}
/>
</CardHeader>
<CardBody>
<form onSubmit={handleSubmit(onSubmit)}>
<VStack spacing="10" align="left">
<Controller
control={control}
name="date"
rules={{ required: 'Обязательное поле' }}
render={({ field }) => (
<FormControl>
<FormLabel>Дата</FormLabel>
<Input
{...field}
required={false}
placeholder="Укажите дату лекции"
size="md"
type="datetime-local"
/>
{errors.date ? (
<FormErrorMessage>{errors.date?.message}</FormErrorMessage>
) : (
<FormHelperText>Укажите дату и время лекции</FormHelperText>
)}
</FormControl>
)}
/>
<Controller
control={control}
name="name"
rules={{ required: 'Обязательное поле' }}
render={({ field }) => (
<FormControl isRequired isInvalid={Boolean(errors.name)}>
<FormLabel>Название новой лекции:</FormLabel>
<Input
{...field}
required={false}
placeholder="Название лекции"
size="md"
/>
{errors.name && (
<FormErrorMessage>{errors.name.message}</FormErrorMessage>
)}
</FormControl>
)}
/>
<Box mt="10">
<Button
size="lg"
type="submit"
leftIcon={<AddIcon />}
colorScheme="blue"
isLoading={isLoading}
>
{nameButton}
</Button>
</Box>
</VStack>
{error && <ErrorSpan>{error}</ErrorSpan>}
</form>
</CardBody>
</Card>
)
}