Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v2): allow creation of date fields in admin form builder #3844

Merged
merged 7 commits into from
May 25, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { useIsMobile } from '~hooks/useIsMobile'
import IconButton from '~components/IconButton'
import {
CheckboxField,
DateField,
DecimalField,
DropdownField,
EmailField,
Expand Down Expand Up @@ -313,6 +314,8 @@ const MemoFieldRow = memo(({ field, ...rest }: MemoFieldRowProps) => {
return <NumberField schema={field} {...rest} />
case BasicField.Decimal:
return <DecimalField schema={field} {...rest} />
case BasicField.Date:
return <DateField schema={field} {...rest} />
case BasicField.Dropdown:
return <DropdownField schema={field} {...rest} />
case BasicField.Statement:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from '../../useBuilderAndDesignStore'
import { CreatePageDrawerCloseButton } from '../CreatePageDrawerCloseButton'

import { EditDate } from './edit-fieldtype/EditDate'
import {
EditCheckbox,
EditDecimal,
Expand Down Expand Up @@ -146,6 +147,8 @@ export const MemoFieldDrawerContent = memo<MemoFieldDrawerContentProps>(
return <EditNric {...props} field={field} />
case BasicField.Number:
return <EditNumber {...props} field={field} />
case BasicField.Date:
return <EditDate {...props} field={field} />
case BasicField.Decimal:
return <EditDecimal {...props} field={field} />
case BasicField.Section:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { Meta, Story } from '@storybook/react'

import {
BasicField,
DateFieldBase,
DateSelectedValidation,
} from '~shared/types'

import { EditFieldDrawerDecorator, StoryRouter } from '~utils/storybook'

import { EditDate } from './EditDate'

const DEFAULT_DATE_FIELD: DateFieldBase = {
title: 'Storybook Date',
description: 'Some description',
dateValidation: {
selectedDateValidation: null,
customMaxDate: null,
customMinDate: null,
},
required: true,
disabled: false,
fieldType: BasicField.Date,
globalId: 'unused',
}

export default {
title: 'Features/AdminForm/EditFieldDrawer/EditDate',
component: EditDate,
decorators: [
StoryRouter({
initialEntries: ['/61540ece3d4a6e50ac0cc6ff'],
path: '/:formId',
}),
EditFieldDrawerDecorator,
],
parameters: {
// Required so skeleton "animation" does not hide content.
chromatic: { pauseAnimationAtEnd: true },
},
args: {
field: DEFAULT_DATE_FIELD,
},
} as Meta<StoryArgs>

interface StoryArgs {
field: DateFieldBase
}

const Template: Story<StoryArgs> = ({ field }) => {
return <EditDate field={field} />
}

export const Default = Template.bind({})

export const WithNoFutureDates = Template.bind({})
WithNoFutureDates.args = {
field: {
...DEFAULT_DATE_FIELD,
dateValidation: {
selectedDateValidation: DateSelectedValidation.NoFuture,
customMaxDate: null,
customMinDate: null,
},
},
}

export const WithCustomDateRange = Template.bind({})
WithCustomDateRange.args = {
field: {
...DEFAULT_DATE_FIELD,
dateValidation: {
selectedDateValidation: DateSelectedValidation.Custom,
customMinDate: new Date('2020-01-01T00:00:00Z'),
customMaxDate: new Date('2020-01-12T00:00:00Z'),
},
},
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import { useMemo } from 'react'
import { Controller, RegisterOptions } from 'react-hook-form'
import { Box, FormControl, SimpleGrid } from '@chakra-ui/react'
import { isBefore, isDate, isEqual } from 'date-fns'
import { extend, get, isEmpty, pick } from 'lodash'

import {
DateFieldBase,
DateSelectedValidation,
DateValidationOptions,
} from '~shared/types/field'

import {
transformDateToShortIsoString,
transformShortIsoStringToDate,
} from '~utils/date'
import { createBaseValidationRules } from '~utils/fieldValidation'
import DateInput from '~components/DatePicker'
import { SingleSelect } from '~components/Dropdown'
import FormErrorMessage from '~components/FormControl/FormErrorMessage'
import FormLabel from '~components/FormControl/FormLabel'
import Input from '~components/Input'
import Textarea from '~components/Textarea'
import Toggle from '~components/Toggle'

import { DrawerContentContainer } from '../common/DrawerContentContainer'
import { FormFieldDrawerActions } from '../common/FormFieldDrawerActions'
import { EditFieldProps } from '../common/types'
import { useEditFieldForm } from '../common/useEditFieldForm'

type EditDateProps = EditFieldProps<DateFieldBase>

const EDIT_DATE_FIELD_KEYS = ['title', 'description', 'required'] as const

type EditDateInputs = Pick<
DateFieldBase,
typeof EDIT_DATE_FIELD_KEYS[number]
> & {
dateValidation: {
selectedDateValidation: DateSelectedValidation | ''
customMaxDate: string
customMinDate: string
}
}

const transformDateFieldToEditForm = (field: DateFieldBase): EditDateInputs => {
const nextValidationOptions = {
selectedDateValidation:
field.dateValidation.selectedDateValidation ?? ('' as const),
customMaxDate: field.dateValidation.selectedDateValidation
? transformDateToShortIsoString(field.dateValidation.customMaxDate) ?? ''
: ('' as const),
customMinDate: field.dateValidation.selectedDateValidation
? transformDateToShortIsoString(field.dateValidation.customMinDate) ?? ''
: ('' as const),
}
return {
...pick(field, EDIT_DATE_FIELD_KEYS),
dateValidation: nextValidationOptions,
}
}

const transformDateEditFormToField = (
inputs: EditDateInputs,
originalField: DateFieldBase,
): DateFieldBase => {
let nextValidationOptions: DateValidationOptions
switch (inputs.dateValidation.selectedDateValidation) {
case '':
nextValidationOptions = {
selectedDateValidation: null,
customMinDate: null,
customMaxDate: null,
}
break
case DateSelectedValidation.NoFuture:
case DateSelectedValidation.NoPast:
nextValidationOptions = {
selectedDateValidation: inputs.dateValidation.selectedDateValidation,
customMinDate: null,
customMaxDate: null,
}
break
case DateSelectedValidation.Custom: {
nextValidationOptions = {
selectedDateValidation: inputs.dateValidation.selectedDateValidation,
customMinDate: transformShortIsoStringToDate(
inputs.dateValidation.customMinDate,
),
customMaxDate: transformShortIsoStringToDate(
inputs.dateValidation.customMaxDate,
),
}
}
}

return extend({}, originalField, inputs, {
dateValidation: nextValidationOptions,
})
}

export const EditDate = ({ field }: EditDateProps): JSX.Element => {
const {
register,
formState: { errors },
getValues,
isSaveEnabled,
control,
buttonText,
handleUpdateField,
isLoading,
handleCancel,
} = useEditFieldForm<EditDateInputs, DateFieldBase>({
field,
transform: {
input: transformDateFieldToEditForm,
output: transformDateEditFormToField,
},
})

const requiredValidationRule = useMemo(
() => createBaseValidationRules({ required: true }),
[],
)

const customMinValidationOptions: RegisterOptions<
EditDateInputs,
'dateValidation.customMinDate'
> = useMemo(
() => ({
// customMin is required if there is selected validation.
validate: {
hasValidation: (val) => {
const hasMaxValue =
getValues('dateValidation.selectedDateValidation') ===
DateSelectedValidation.Custom &&
!!getValues('dateValidation.customMaxDate')
return !!val || hasMaxValue || 'You must specify at least one date.'
},
validDate: (val) =>
!val || isDate(new Date(val)) || 'Please enter a valid date',
inRange: (val) => {
const date = new Date(val)
const maxDate = new Date(getValues('dateValidation.customMaxDate'))
return (
isEqual(date, maxDate) ||
isBefore(date, maxDate) ||
'Max date cannot be less than min date.'
)
},
},
}),
[getValues],
)

return (
<DrawerContentContainer>
<FormControl isRequired isReadOnly={isLoading} isInvalid={!!errors.title}>
<FormLabel>Question</FormLabel>
<Input autoFocus {...register('title', requiredValidationRule)} />
<FormErrorMessage>{errors?.title?.message}</FormErrorMessage>
</FormControl>
<FormControl isReadOnly={isLoading} isInvalid={!!errors.description}>
<FormLabel>Description</FormLabel>
<Textarea {...register('description')} />
<FormErrorMessage>{errors?.description?.message}</FormErrorMessage>
</FormControl>
<FormControl isReadOnly={isLoading}>
<Toggle {...register('required')} label="Required" />
</FormControl>
<FormControl
isReadOnly={isLoading}
isInvalid={!isEmpty(errors.dateValidation)}
>
<FormLabel isRequired>Date validation</FormLabel>
<SimpleGrid mt="0.5rem" columns={2} spacing="0.5rem">
<Box gridColumn="1/3">
<Controller
name="dateValidation.selectedDateValidation"
rules={{
deps: [
'dateValidation.customMinDate',
'dateValidation.customMaxDate',
],
}}
control={control}
render={({ field }) => (
<SingleSelect
items={Object.values(DateSelectedValidation)}
{...field}
/>
)}
/>
</Box>
{getValues('dateValidation.selectedDateValidation') ===
DateSelectedValidation.Custom ? (
<>
<Controller
control={control}
name="dateValidation.customMinDate"
rules={customMinValidationOptions}
render={({ field }) => <DateInput {...field} />}
/>
<Controller
control={control}
rules={{
deps: ['dateValidation.customMinDate'],
}}
name="dateValidation.customMaxDate"
render={({ field }) => <DateInput {...field} />}
/>
</>
) : null}
</SimpleGrid>
<FormErrorMessage>
{get(errors, 'dateValidation.customMinDate.message')}
</FormErrorMessage>
</FormControl>
<FormFieldDrawerActions
isLoading={isLoading}
isSaveEnabled={isSaveEnabled}
buttonText={buttonText}
handleClick={handleUpdateField}
handleCancel={handleCancel}
/>
</DrawerContentContainer>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { EditDate } from './EditDate'
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { FieldCreateDto, FormFieldDto } from '~shared/types/field'

import { transformAllIsoStringsToDate } from '~utils/date'
import { ApiService } from '~services/ApiService'

import { ADMIN_FORM_ENDPOINT } from '~features/admin-form/common/AdminViewFormService'
Expand All @@ -24,7 +25,9 @@ export const createSingleFormField = async ({
`${ADMIN_FORM_ENDPOINT}/${formId}/fields`,
createFieldBody,
{ params: { to: insertionIndex } },
).then(({ data }) => data)
)
.then(({ data }) => data)
.then(transformAllIsoStringsToDate)
}

export const updateSingleFormField = async ({
Expand All @@ -37,7 +40,9 @@ export const updateSingleFormField = async ({
return ApiService.put<FormFieldDto>(
`${ADMIN_FORM_ENDPOINT}/${formId}/fields/${updateFieldBody._id}`,
updateFieldBody,
).then(({ data }) => data)
)
.then(({ data }) => data)
.then(transformAllIsoStringsToDate)
}

/**
Expand All @@ -60,7 +65,9 @@ export const reorderSingleFormField = async ({
`${ADMIN_FORM_ENDPOINT}/${formId}/fields/${fieldId}/reorder`,
{},
{ params: { to: newPosition } },
).then(({ data }) => data)
)
.then(({ data }) => data)
.then(transformAllIsoStringsToDate)
}

/**
Expand All @@ -79,7 +86,9 @@ export const duplicateSingleFormField = async ({
}): Promise<FormFieldDto> => {
return ApiService.post<FormFieldDto>(
`${ADMIN_FORM_ENDPOINT}/${formId}/fields/${fieldId}/duplicate`,
).then(({ data }) => data)
)
.then(({ data }) => data)
.then(transformAllIsoStringsToDate)
}

/**
Expand Down
Loading