Skip to content

Commit

Permalink
chore(form-builder): keep array item focus in sync with focusPath
Browse files Browse the repository at this point in the history
This fixes a bug that caused focus loss on array items after closing the edit dialog
  • Loading branch information
bjoerge committed Dec 17, 2021
1 parent 351251f commit 4f1cf8c
Showing 1 changed file with 9 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ import {Box} from '@sanity/ui'
import PatchEvent from '../../../../PatchEvent'
import {ArrayMember, ReferenceItemComponentType} from '../types'
import {EMPTY_ARRAY} from '../../../../utils/empty'
import {hasFocusWithinPath} from '../../../../utils/focusUtils'
import {hasFocusAtPath, hasFocusWithinPath} from '../../../../utils/focusUtils'
import {useScrollIntoViewOnFocusWithin} from '../../../../hooks/useScrollIntoViewOnFocusWithin'
import {EditPortal} from '../../../../EditPortal'
import {useDidUpdate} from '../../../../hooks/useDidUpdate'
import {getItemType, isEmpty} from './helpers'
import {ItemForm} from './ItemForm'
import {RowItem} from './RowItem'
Expand Down Expand Up @@ -66,6 +67,13 @@ export const ArrayItem = memo(function ArrayItem(props: ArrayInputListItemProps)
const hasFocusWithin = hasFocusWithinPath(props.focusPath, props.value)
useScrollIntoViewOnFocusWithin(innerElementRef, hasFocusWithin)

useDidUpdate(hasFocusAtPath(props.focusPath, props.value), (hadFocus, hasFocus) => {
if (!hadFocus && hasFocus && innerElementRef.current) {
// Note: if editing an inline item, focus is handled by the item input itself and no ref is being set
innerElementRef.current.focus()
}
})

const itemPath = useMemo(() => pathFor([itemKey ? {_key: itemKey} : index]), [index, itemKey])

const emitFocus = useCallback(
Expand Down

3 comments on commit 4f1cf8c

@vercel
Copy link

@vercel vercel bot commented on 4f1cf8c Dec 17, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

studio-workshop – ./dev/workshop

studio-workshop-git-next.sanity.build
studio-workshop.sanity.build

@vercel
Copy link

@vercel vercel bot commented on 4f1cf8c Dec 17, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

test-studio – ./

test-studio-git-next.sanity.build
test-studio.sanity.build

@vercel
Copy link

@vercel vercel bot commented on 4f1cf8c Dec 17, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

perf-studio – ./

perf-studio.sanity.build
perf-studio-git-next.sanity.build

Please sign in to comment.