feature/order-form #46

Merged
primakov merged 7 commits from feature/order-form into main 2024-12-08 11:31:18 +03:00
27 changed files with 582 additions and 0 deletions
Showing only changes of commit 93adc1fb7d - Show all commits

View File

@ -0,0 +1,23 @@
import React, { forwardRef } from 'react';
import { Select, SelectProps } from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import { carBodySelectOptions } from './helper';
export const CarBodySelect = forwardRef<HTMLSelectElement, SelectProps>(
function CarBodySelect(props, ref) {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create.car-body-select',
});
return (
<Select ref={ref} placeholder={t('placeholder')} {...props}>
{carBodySelectOptions.map(({ value, labelTKey }, i) => (
<option key={i} value={value}>
{t(`options.${labelTKey}`)}
</option>
))}
</Select>
);
},
);

View File

@ -0,0 +1,50 @@
import { Car } from "../../../../models/landing";
import { CarBodySelectOption } from "./types";
export const carBodySelectOptions: CarBodySelectOption[] = [
{
value: Car.BodyStyle.SEDAN,
labelTKey: 'sedan'
},
{
value: Car.BodyStyle.HATCHBACK,
labelTKey: 'hatchback'
},
{
value: Car.BodyStyle.CROSSOVER,
labelTKey: 'crossover'
},
{
value: Car.BodyStyle.SUV,
labelTKey: 'suv'
},
{
value: Car.BodyStyle.STATION_WAGON,
labelTKey: 'station-wagon'
},
{
value: Car.BodyStyle.COUPE,
labelTKey: 'coupe'
},
{
value: Car.BodyStyle.MINIVAN,
labelTKey: 'minivan'
},
{
value: Car.BodyStyle.PICKUP,
labelTKey: 'pickup'
},
{
value: Car.BodyStyle.LIFTBACK,
labelTKey: 'liftback'
},
{
value: Car.BodyStyle.SPORTS_CAR,
labelTKey: 'sports-car'
},
{
value: Car.BodyStyle.OTHER,
labelTKey: 'other'
},
];

View File

@ -0,0 +1 @@
export { CarBodySelect } from './car-body-select';

View File

@ -0,0 +1,17 @@
import { Car } from "../../../../models/landing";
export type CarBodySelectOption = {
value: Car.BodyStyle;
labelTKey:
'sedan' |
'hatchback' |
'crossover' |
'suv' |
'station-wagon' |
'coupe' |
'minivan' |
'pickup' |
'liftback' |
'sports-car' |
'other';
};

View File

@ -0,0 +1,23 @@
import React, { forwardRef, useId } from 'react';
import { Input, InputProps } from '@chakra-ui/react';
import { CAR_COLORS } from './helper';
export const CarColorInput = forwardRef<HTMLInputElement, InputProps>(
function CarColorInput(props, ref) {
const listId = useId();
return (
<>
<Input ref={ref} list={listId} {...props} />
<datalist id={listId}>
{CAR_COLORS.map(({ code, name }) => (
<option key={code} label={name} value={code}>{name}</option>
))}
</datalist>
</>
);
},
);
// todo: add option color visual indication

View File

@ -0,0 +1,34 @@
export const CAR_COLORS: Record<'name' | 'code', string>[] = [
{
name: 'white',
code: '#ffffff'
},
{
name: 'black',
code: '#000000'
},
{
name: 'silver',
code: '#c0c0c0'
},
{
name: 'gray',
code: '#808080'
},
{
name: 'beige-brown',
code: '#796745'
},
{
name: 'red',
code: '#b90000'
},
{
name: 'blue',
code: '#003B62'
},
{
name: 'green',
code: '#078d51'
},
];

View File

@ -0,0 +1 @@
export { CarColorInput } from './car-color-input';

View File

@ -0,0 +1,22 @@
import React, { forwardRef } from 'react';
import { Input, InputProps } from '@chakra-ui/react';
import { handleInputChange } from './helper';
export const CarNumberInput = forwardRef<HTMLInputElement, InputProps>(
function CarNumberInput({ onChange, ...props }, ref) {
return (
<Input
{...props}
ref={ref}
onChange={(e) => {
const formattedValue = handleInputChange(e.target.value);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
onChange?.(formattedValue);
}}
maxLength={8}
/>
);
},
);

View File

@ -0,0 +1,33 @@
const VALID_LETTER = 'а|в|е|к|м|н|о|р|с|т|у|х';
const invalidCharsRe = new RegExp(`[^(${VALID_LETTER})0-9]`, 'gi');
const cleanValue = (value: string) => value.replace(invalidCharsRe, '');
const validCarNumberInputRe = new RegExp(`^([${VALID_LETTER}]{1}|$)((?:[0-9]|$)(?:[0-9]|$)(?:[0-9]|$))([${VALID_LETTER}]{1,2}|$)$`, 'gi');
const isValidInput = (cleanedValue: string) => validCarNumberInputRe.test(cleanedValue);
const formatAsCarNumber = (cleanedValue: string) => {
return cleanedValue.replace(validCarNumberInputRe, (_, p1, p2, p3) => [p1, p2, p3].join(' ')).toUpperCase();
};
const getWithoutLastChar = (value: string) => value.substring(0, value.length - 1);
export const handleInputChange = (value: string | undefined | null) => {
const cleanedValue = cleanValue(value);
if (!cleanedValue) {
return '';
}
if (isValidInput(cleanedValue)) {
return formatAsCarNumber(cleanedValue).trim();
}
return getWithoutLastChar(value).trim();
};
const validCarNumberRe = new RegExp(`^[${VALID_LETTER}][0-9]{3}[${VALID_LETTER}]{2}$`, 'i');
export const isValidCarNumber = (value: string) => {
const cleanedValue = cleanValue(value);
return validCarNumberRe.test(cleanedValue);
};

View File

@ -0,0 +1,2 @@
export { CarNumberInput } from './car-number-input';
export { isValidCarNumber } from './helper';

View File

@ -0,0 +1,12 @@
import React, { forwardRef } from 'react';
import { Input, InputProps } from '@chakra-ui/react';
export type DateTimeInputProps = InputProps;
export const DateTimeInput = forwardRef<HTMLInputElement, DateTimeInputProps>(
function DateTimeInput(props, ref) {
return <Input ref={ref} {...props} type='datetime-local' />;
},
);
// todo: apply brand styles to popover

View File

@ -0,0 +1 @@
export { type DateTimeInputProps, DateTimeInput } from './date-time';

View File

@ -0,0 +1,35 @@
import React from 'react';
import { FormControl, FormLabel, FormErrorMessage } from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
import { FormControllerFieldProps } from './types';
export const FormControllerField = ({
control,
name,
label,
isRequired,
rules,
errors,
Controller
}: FormControllerFieldProps) => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create.form.field',
});
const fieldErrors = errors[name];
return (
<FormControl isRequired={isRequired} isInvalid={!!fieldErrors}>
<FormLabel htmlFor={name}>{label}</FormLabel>
<Controller
control={control}
name={name}
rules={{
required: isRequired && t('validation.required'),
...rules,
}}
/>
<FormErrorMessage>{fieldErrors?.message}</FormErrorMessage>
</FormControl>
);
};

View File

@ -0,0 +1,47 @@
import React from 'react';
import {
FormControl,
FormLabel,
FormErrorMessage,
FormHelperText,
} from '@chakra-ui/react';
import { Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { FormInputFieldProps } from './types';
export const FormInputField = ({
control,
name,
label,
isRequired,
rules,
errors,
Input,
inputProps,
help,
}: FormInputFieldProps) => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create.form.field',
});
const fieldErrors = errors[name];
return (
<FormControl isRequired={label && isRequired} isInvalid={!!fieldErrors}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
<Controller
control={control}
name={name}
rules={{
required: isRequired && t('validation.required'),
...rules,
}}
render={({ field }) => (
<Input variant='filled' {...field} {...inputProps} />
)}
/>
<FormErrorMessage>{fieldErrors?.message}</FormErrorMessage>
{help && <FormHelperText>{help}</FormHelperText>}
</FormControl>
);
};

View File

@ -0,0 +1,3 @@
export type { FormFieldProps } from './types';
export { FormInputField } from './form-input-field';
export { FormControllerField } from './form-controller-field';

View File

@ -0,0 +1,26 @@
import { ReactElement, ReactNode } from 'react';
import { ControllerProps, ControllerRenderProps, FieldErrors } from 'react-hook-form';
import { FormLabelProps, FormControlProps, HelpTextProps, InputProps as ChakraInputProps, SelectProps as ChakraSelectProps } from '@chakra-ui/react';
import { OrderFormValues } from '../types';
export type FormFieldProps<FormValues = OrderFormValues> = {
name: ControllerProps<FormValues>['name'] & FormLabelProps['htmlFor'];
label?: FormLabelProps['children'];
errors: FieldErrors<FormValues>;
control: ControllerProps<FormValues>['control'];
isRequired?: FormControlProps['isRequired'];
rules?: ControllerProps<FormValues>['rules'];
};
type InputProps<FormValues = OrderFormValues> = Partial<ControllerRenderProps<FormValues> & ChakraInputProps & ChakraSelectProps>;
export type FormInputFieldProps<FormValues = OrderFormValues, Input = (props: InputProps<FormValues>) => ReactNode> = FormFieldProps<FormValues> & {
Input: Input;
inputProps?: InputProps<FormValues>;
help?: HelpTextProps['children'];
};
export type FormControllerFieldProps<FormValues = OrderFormValues> = FormFieldProps<FormValues> & {
Controller: (props: Pick<ControllerProps<FormValues>, 'control' | 'name' | 'rules'>) => ReactElement;
};

View File

@ -0,0 +1,67 @@
import { useTranslation } from "react-i18next";
import { InputProps, SelectProps } from "@chakra-ui/react";
import { Order } from "../../../models/landing";
import { FormFieldProps } from "./field";
import { OrderFormValues } from "./types";
import { isValidCarNumber } from "./car-number";
import { isValidPhoneNumber } from "./phone";
export const defaultValues: Partial<OrderFormValues> = {
phone: '',
carNumber: '',
carColor: '',
availableDatetimeBegin: '',
availableDatetimeEnd: '',
};
export const useGetValidationRules = () => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create.form',
});
return {
isValidPhoneNumber: {
validate: (value: string) => isValidPhoneNumber(value) || t('phone-field.invalid')
},
isValidCarNumber: {
validate: (value: string) => isValidCarNumber(value) || t('car-number-field.invalid')
},
} satisfies Record<string, FormFieldProps['rules']>;
};
const removeAllSpaces = (str: string) => str.replace(/\s+/g, '');
const getValidCarBodyStyle = (fieldValue: string) => {
const carBodyAsNumber = Number(fieldValue);
return Number.isNaN(carBodyAsNumber) ? undefined : carBodyAsNumber;
};
export const formatFormValues = ({ phone, carNumber, carBody, carColor, carLocation, availableDatetimeBegin, availableDatetimeEnd }: OrderFormValues): Order.Create => {
return {
customer: {
phone
},
car: {
number: removeAllSpaces(carNumber),
body: getValidCarBodyStyle(carBody),
color: carColor
},
washing: {
location: carLocation,
begin: availableDatetimeBegin,
end: availableDatetimeEnd,
}
};
};
export const onSubmit = (values: OrderFormValues) => {
return new Promise((resolve) => {
console.log(formatFormValues(values));
resolve(formatFormValues(values));
});
};
export const inputCommonStyles: Partial<InputProps & SelectProps> = {
};

View File

@ -0,0 +1 @@
export { OrderForm } from './order-form';

View File

@ -0,0 +1,130 @@
import React, { FC } from 'react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import {
Box,
Flex,
FormControl,
FormLabel,
Input,
VStack,
} from '@chakra-ui/react';
import { CarBodySelect } from './car-body';
import { CarColorInput } from './car-color';
import { CarNumberInput } from './car-number';
import { FormInputField, FormControllerField } from './field';
import { OrderFormValues } from './types';
import { PhoneInput } from './phone';
import { SubmitButton } from './submit';
import { defaultValues, onSubmit, useGetValidationRules } from './helper';
import { DateTimeInput } from './date-time';
export const OrderForm: FC = () => {
const {
handleSubmit,
control,
formState: { errors, isSubmitting },
watch,
} = useForm<OrderFormValues>({ defaultValues, shouldFocusError: true });
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create.form',
});
const RULES = useGetValidationRules();
const [availableDatetimeBegin, availableDatetimeEnd] = watch([
'availableDatetimeBegin',
'availableDatetimeEnd',
]);
return (
<Box p={4} marginInline='auto'>
<VStack
as='form'
noValidate
onSubmit={handleSubmit(onSubmit)}
align='flex-start'
gap={6}
>
<FormControllerField
control={control}
name='phone'
label={t('phone-field.label')}
isRequired
rules={RULES.isValidPhoneNumber}
errors={errors}
Controller={PhoneInput}
/>
<FormInputField
control={control}
name='carNumber'
label={t('car-number-field.label')}
isRequired
rules={RULES.isValidCarNumber}
errors={errors}
Input={CarNumberInput}
/>
<FormInputField
control={control}
name='carColor'
label={t('car-color-field.label')}
errors={errors}
Input={CarColorInput}
/>
<FormInputField
control={control}
name='carBody'
label={t('car-body-field.label')}
isRequired
errors={errors}
Input={CarBodySelect}
/>
<FormInputField
control={control}
name='carLocation'
label={t('washing-location-field.label')}
isRequired
errors={errors}
Input={Input}
help={t('washing-location-field.help')}
/>
<FormControl isRequired>
<FormLabel>{t('washing-datetime-field.label')}</FormLabel>
<Flex flexWrap='wrap' gap={4}>
<Box flex='1 0 100px'>
<FormInputField
control={control}
name='availableDatetimeBegin'
isRequired
errors={errors}
Input={DateTimeInput}
inputProps={{
max: availableDatetimeEnd,
}}
/>
</Box>
<Box flex='1 0 100px'>
<FormInputField
control={control}
name='availableDatetimeEnd'
isRequired
errors={errors}
Input={DateTimeInput}
inputProps={{
min: availableDatetimeBegin,
}}
/>
</Box>
</Flex>
</FormControl>
<SubmitButton isLoading={isSubmitting} mt={4} />
</VStack>
</Box>
);
};
// todo: remove layout shift, when a validation message is displayed
// todo: select location using an interactive map
// todo: fix time range available values

View File

@ -0,0 +1 @@
export { isValidPhoneNumber } from "react-phone-number-input";

View File

@ -0,0 +1,2 @@
export { PhoneInput } from './phone-input';
export { isValidPhoneNumber } from './helper';

View File

@ -0,0 +1,18 @@
import React from 'react';
import ReactPhoneNumberInput from 'react-phone-number-input/react-hook-form-input';
import { Input } from '@chakra-ui/react';
import 'react-phone-number-input/style.css';
import { PhoneInputType } from './types';
export const PhoneInput: PhoneInputType = (props) => {
return (
<ReactPhoneNumberInput
defaultCountry='RU'
inputComponent={Input}
variant='filled'
{...props}
/>
);
};

View File

@ -0,0 +1,7 @@
import { FieldValues } from 'react-hook-form';
import { DefaultInputComponentProps } from 'react-phone-number-input';
import { DefaultFormValues, Props } from 'react-phone-number-input/react-hook-form';
type PhoneInputProps<FormValues, InputComponentProps = DefaultInputComponentProps> = Props<InputComponentProps, FormValues>;
export type PhoneInputType = <FormValues extends FieldValues = DefaultFormValues, InputComponentProps = DefaultInputComponentProps>(props: PhoneInputProps<FormValues, InputComponentProps>) => JSX.Element;

View File

@ -0,0 +1 @@
export { SubmitButton } from './submit-button';

View File

@ -0,0 +1,15 @@
import React, { FC } from 'react';
import { Button, ButtonProps } from '@chakra-ui/react';
import { useTranslation } from 'react-i18next';
export const SubmitButton: FC<ButtonProps> = (props) => {
const { t } = useTranslation('~', {
keyPrefix: 'dry-wash.order-create.form.submit-button',
});
return (
<Button type='submit' colorScheme='primary' borderRadius={50} paddingInline={8} {...props}>
{t('label')}
</Button>
);
};

View File

@ -0,0 +1,9 @@
export type OrderFormValues = {
phone: string;
carNumber: string;
carColor: string;
carBody: string;
carLocation: string;
availableDatetimeBegin: string;
availableDatetimeEnd: string;
};

View File

@ -0,0 +1 @@
export * from './form';