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

perf: memoize field row containers #6189

Merged
merged 3 commits into from
Apr 25, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
@@ -1,8 +1,17 @@
import { AdminFormDto } from '~shared/types/form'

import { useCreatePageSidebar } from '~features/admin-form/create/common/CreatePageSidebarContext'
import { augmentWithQuestionNo } from '~features/form/utils'
import { FieldIdSet } from '~features/logic/types'

import { useBuilderAndDesignContext } from '../BuilderAndDesignContext'
import { PENDING_CREATE_FIELD_ID } from '../constants'
import {
FieldBuilderState,
stateDataSelector,
useFieldBuilderStore,
} from '../useFieldBuilderStore'

import FieldRow from './FieldRow'

interface BuilderFieldsProps {
Expand All @@ -17,6 +26,13 @@ export const BuilderFields = ({
isDraggingOver,
}: BuilderFieldsProps) => {
const fieldsWithQuestionNos = augmentWithQuestionNo(fields)
const stateData = useFieldBuilderStore(stateDataSelector)

const { handleBuilderClick } = useCreatePageSidebar()
const {
deleteFieldModalDisclosure: { onOpen: onDeleteModalOpen },
} = useBuilderAndDesignContext()

return (
<>
{fieldsWithQuestionNos.map((f, i) => (
Expand All @@ -26,6 +42,16 @@ export const BuilderFields = ({
field={f}
isHiddenByLogic={!visibleFieldIds.has(f._id)}
isDraggingOver={isDraggingOver}
isActive={
stateData.state === FieldBuilderState.EditingField
? f._id === stateData.field._id
: stateData.state === FieldBuilderState.CreatingField
? f._id === PENDING_CREATE_FIELD_ID
: false
}
fieldBuilderState={stateData.state}
handleBuilderClick={handleBuilderClick}
onDeleteModalOpen={onDeleteModalOpen}
/>
))}
</>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef } from 'react'
import { memo, useCallback, useEffect, useMemo, useRef } from 'react'
import { Draggable } from 'react-beautiful-dnd'
import { FormProvider, useForm } from 'react-hook-form'
import { BiCog, BiDuplicate, BiGridHorizontal, BiTrash } from 'react-icons/bi'
Expand All @@ -12,7 +12,7 @@ import {
Flex,
Icon,
} from '@chakra-ui/react'
import { times } from 'lodash'
import { isEqual, times } from 'lodash'

import { FormColorTheme } from '~shared/types'
import { BasicField, FormFieldDto } from '~shared/types/field'
Expand Down Expand Up @@ -47,16 +47,15 @@ import { MobileFieldInput } from '~templates/Field/Mobile'
import { createTableRow } from '~templates/Field/Table/utils/createRow'

import { adminFormKeys } from '~features/admin-form/common/queries'
import { useCreatePageSidebar } from '~features/admin-form/create/common/CreatePageSidebarContext'
import { CreatePageSidebarContextProps } from '~features/admin-form/create/common'
import {
augmentWithMyInfoDisplayValue,
extractPreviewValue,
hasExistingFieldValue,
isMyInfo,
} from '~features/myinfo/utils'

import { useBuilderAndDesignContext } from '../../BuilderAndDesignContext'
import { PENDING_CREATE_FIELD_ID } from '../../constants'
import { BuilderAndDesignContextProps } from '../../BuilderAndDesignContext'
import { useDeleteFormField } from '../../mutations/useDeleteFormField'
import { useDuplicateFormField } from '../../mutations/useDuplicateFormField'
import { useCreateTabForm } from '../../useCreateTabForm'
Expand All @@ -69,7 +68,6 @@ import { isDirtySelector, useDirtyFieldStore } from '../../useDirtyFieldStore'
import {
FieldBuilderState,
setToInactiveSelector,
stateDataSelector,
updateEditStateSelector,
useFieldBuilderStore,
} from '../../useFieldBuilderStore'
Expand All @@ -84,35 +82,33 @@ export interface FieldRowContainerProps {
index: number
isHiddenByLogic: boolean
isDraggingOver: boolean
isActive: boolean
fieldBuilderState: FieldBuilderState
handleBuilderClick: CreatePageSidebarContextProps['handleBuilderClick']
onDeleteModalOpen: BuilderAndDesignContextProps['deleteFieldModalDisclosure']['onOpen']
}

export const FieldRowContainer = ({
const FieldRowContainer = ({
field,
index,
isHiddenByLogic,
isDraggingOver,
isActive,
fieldBuilderState,
handleBuilderClick,
onDeleteModalOpen,
}: FieldRowContainerProps): JSX.Element => {
const isMobile = useIsMobile()
const { data: form } = useCreateTabForm()
const numFormFieldMutations = useIsMutating(adminFormKeys.base)
const { stateData, setToInactive, updateEditState } = useFieldBuilderStore(
useCallback(
(state) => ({
stateData: stateDataSelector(state),
setToInactive: setToInactiveSelector(state),
updateEditState: updateEditStateSelector(state),
}),
[],
),
)
const setToInactive = useFieldBuilderStore(setToInactiveSelector)
const updateEditState = useFieldBuilderStore(updateEditStateSelector)

const isDirty = useDirtyFieldStore(isDirtySelector)
const toast = useToast({ status: 'danger', isClosable: true })

const setDesignState = useDesignStore(setStateSelector)

const { handleBuilderClick } = useCreatePageSidebar()

const { duplicateFieldMutation } = useDuplicateFormField()
const { deleteFieldMutation } = useDeleteFormField()

Expand Down Expand Up @@ -141,19 +137,6 @@ export const FieldRowContainer = ({
defaultValues: defaultFieldValues,
})

const isActive = useMemo(() => {
if (stateData.state === FieldBuilderState.EditingField) {
return field._id === stateData.field._id
} else if (stateData.state === FieldBuilderState.CreatingField) {
return field._id === PENDING_CREATE_FIELD_ID
}
return false
}, [stateData, field])

const {
deleteFieldModalDisclosure: { onOpen: onDeleteModalOpen },
} = useBuilderAndDesignContext()

const ref = useRef<HTMLDivElement | null>(null)
useEffect(() => {
if (isActive) {
Expand Down Expand Up @@ -208,7 +191,7 @@ export const FieldRowContainer = ({
const handleDuplicateClick = useCallback(() => {
if (!form) return
// Duplicate button should be hidden if field is not yet created, but guard here just in case
if (stateData.state === FieldBuilderState.CreatingField) return
if (fieldBuilderState === FieldBuilderState.CreatingField) return
// Disallow duplicating attachment fields if after the dupe, the filesize exceeds the limit
if (field.fieldType === BasicField.Attachment) {
const existingAttachmentsSize = form.form_fields.reduce(
Expand All @@ -230,15 +213,15 @@ export const FieldRowContainer = ({
}
}
duplicateFieldMutation.mutate(field._id)
}, [stateData.state, field, duplicateFieldMutation, form, toast])
}, [fieldBuilderState, field, duplicateFieldMutation, form, toast])

const handleDeleteClick = useCallback(() => {
if (stateData.state === FieldBuilderState.CreatingField) {
if (fieldBuilderState === FieldBuilderState.CreatingField) {
setToInactive()
} else if (stateData.state === FieldBuilderState.EditingField) {
} else if (fieldBuilderState === FieldBuilderState.EditingField) {
onDeleteModalOpen()
}
}, [setToInactive, stateData.state, onDeleteModalOpen])
}, [setToInactive, fieldBuilderState, onDeleteModalOpen])

const isAnyMutationLoading = useMemo(
() => duplicateFieldMutation.isLoading || deleteFieldMutation.isLoading,
Expand All @@ -250,9 +233,9 @@ export const FieldRowContainer = ({
!isActive ||
isDirty ||
!!numFormFieldMutations ||
stateData.state === FieldBuilderState.CreatingField
fieldBuilderState === FieldBuilderState.CreatingField
)
}, [isActive, isDirty, numFormFieldMutations, stateData.state])
}, [isActive, isDirty, numFormFieldMutations, fieldBuilderState])

return (
<Draggable
Expand Down Expand Up @@ -331,7 +314,7 @@ export const FieldRowContainer = ({
snapshot.isDragging ? 'secondary.300' : 'secondary.200'
}
>
{stateData.state === FieldBuilderState.EditingField &&
{fieldBuilderState === FieldBuilderState.EditingField &&
!isDragDisabled ? (
<Icon as={BiGridHorizontal} fontSize="1.5rem" />
) : (
Expand Down Expand Up @@ -377,7 +360,7 @@ export const FieldRowContainer = ({
) : null}
{
// Fields which are not yet created cannot be duplicated
stateData.state !== FieldBuilderState.CreatingField && (
fieldBuilderState !== FieldBuilderState.CreatingField && (
<Tooltip label="Duplicate field">
<IconButton
aria-label="Duplicate field"
Expand Down Expand Up @@ -410,6 +393,10 @@ export const FieldRowContainer = ({
)
}

export const MemoizedFieldRow = memo(FieldRowContainer, (prevProps, newProps) =>
isEqual(prevProps, newProps),
)

type FieldRowProps = {
field: FormFieldDto
colorTheme?: FormColorTheme
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { FieldRowContainer as default } from './FieldRowContainer'
export { MemoizedFieldRow as default } from './FieldRowContainer'
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createContext, useContext } from 'react'
import { UseDisclosureReturn } from '@chakra-ui/react'

type BuilderAndDesignContextProps = {
export type BuilderAndDesignContextProps = {
deleteFieldModalDisclosure: UseDisclosureReturn
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export enum DrawerTabs {
EndPage,
}

type CreatePageSidebarContextProps = {
export type CreatePageSidebarContextProps = {
activeTab: DrawerTabs | null
pendingTab?: DrawerTabs | null
movePendingToActiveTab: () => void
Expand Down