Skip to content

Commit

Permalink
fix(form): set sorting strategy for list axis
Browse files Browse the repository at this point in the history
  • Loading branch information
bjoerge committed Dec 16, 2022
1 parent 9bb85a5 commit 3c8fd87
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
Expand Up @@ -66,6 +66,7 @@ export function ListArrayInput<Item extends ObjectItem>(props: ArrayOfObjectsInp
) : (
<Card border radius={1}>
<List
axis="y"
gap={1}
paddingY={1}
items={memberKeys}
Expand Down
28 changes: 18 additions & 10 deletions packages/sanity/src/core/form/inputs/arrays/common/list.tsx
Expand Up @@ -10,7 +10,13 @@ import {
useSensor,
useSensors,
} from '@dnd-kit/core'
import {SortableContext, sortableKeyboardCoordinates, useSortable} from '@dnd-kit/sortable'
import {
horizontalListSortingStrategy,
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import {CSS} from '@dnd-kit/utilities'
import {restrictToHorizontalAxis, restrictToVerticalAxis} from '@dnd-kit/modifiers'
import {SortableItemIdContext} from './DragHandle'
Expand Down Expand Up @@ -43,12 +49,17 @@ const TRANSITION = {
easing: 'linear',
}

function restrictToAxis(axis: 'x' | 'y') {
type Axis = 'x' | 'y'

function restrictToAxis(axis: Axis) {
return axis === 'x' ? restrictToHorizontalAxis : restrictToVerticalAxis
}
function sortingStrategy(axis: Axis) {
return axis === 'x' ? horizontalListSortingStrategy : verticalListSortingStrategy
}

function SortableList(props: ListProps) {
const {items, lockAxis, onItemMove, children, ...rest} = props
const {items, axis, onItemMove, children, ...rest} = props

const sensors = useSensors(useSensor(PointerSensor), useSensor(KeyboardSensor, SENSOR_OPTIONS))

Expand All @@ -66,11 +77,8 @@ function SortableList(props: ListProps) {
[items, onItemMove]
)
const modifiers = useMemo(
() => [
restrictToParentElementWithMargins({y: 4}),
...(lockAxis ? [restrictToAxis(lockAxis)] : []),
],
[lockAxis]
() => [restrictToParentElementWithMargins({y: 4}), ...(axis ? [restrictToAxis(axis)] : [])],
[axis]
)

return (
Expand All @@ -81,7 +89,7 @@ function SortableList(props: ListProps) {
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext items={items}>
<SortableContext items={items} strategy={axis ? sortingStrategy(axis) : undefined}>
<Grid {...rest}>{children}</Grid>
</SortableContext>
</DndContext>
Expand Down Expand Up @@ -120,7 +128,7 @@ function SortableListItem(props: ItemProps) {

interface ListProps extends ComponentProps<typeof Grid> {
sortable?: boolean
lockAxis?: 'x' | 'y'
axis?: Axis
items: string[]
onItemMove?: (event: {fromIndex: number; toIndex: number}) => void
children?: React.ReactNode
Expand Down

0 comments on commit 3c8fd87

Please sign in to comment.