diff --git a/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/index.test.tsx b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/index.test.tsx new file mode 100644 index 00000000..da32e588 --- /dev/null +++ b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/index.test.tsx @@ -0,0 +1,109 @@ +import { act, render } from '@testing-library/react-native'; +import { GestureHandlerRootView } from 'react-native-gesture-handler'; + +import Sortable, { useCommonValuesContext } from '../../../../../index'; +import type { OrderUpdater, Vector } from '../../../../../types'; +import useInsertStrategy from '.'; + +const ITEM_HEIGHT = 50; + +type Options = { + fixedIndex?: number; + rowGap?: number; +}; + +// Renders a wrapping row of items with the given widths and returns their keys +// with a function that drags one of them. +const setup = ( + widths: Array, + containerWidth: number, + { fixedIndex, rowGap }: Options = {} +) => { + let context!: ReturnType; + let updater!: OrderUpdater; + const useStrategy = () => { + context = useCommonValuesContext(); + return (updater = useInsertStrategy()); + }; + + render( + + + {widths.map((_, index) => ( + + ))} + + + ); + + const keys = context.indexToKey.value; + act(() => { + context.containerWidth.value = containerWidth; + context.itemHeights.value = ITEM_HEIGHT; + context.itemWidths.value = Object.fromEntries( + keys.map((key, index) => [key, widths[index]!]) + ); + jest.runAllTimers(); + }); + + // Returns the order after dragging the item to the given position + const drag = (activeIndex: number, position: Vector) => { + const activeKey = keys[activeIndex]!; + act(() => { + context.activeItemKey.value = activeKey; + jest.runAllTimers(); + }); + return ( + updater({ + activeIndex, + activeKey, + dimensions: { height: ITEM_HEIGHT, width: widths[activeIndex]! }, + position + }) ?? keys + ); + }; + + return { context, drag, keys }; +}; + +it('moves an item to the next line when rounded sizes overflow the line', () => { + // a b c | d e f -> b c d | a e f + const { drag, keys } = setup(Array(6).fill(125.00001), 375); + const [a, b, c, d, e, f] = keys; + + expect(drag(0, { x: 60, y: 75 })).toEqual([b, c, d, a, e, f]); +}); + +it('moves an item next to a fixed last item without replacing it', () => { + // a b | c D -> b | c a D + const { drag, keys } = setup([50, 200, 100, 50], 250, { fixedIndex: 3 }); + const [a, b, c, d] = keys; + + expect(drag(0, { x: 130, y: 75 })).toEqual([b, c, a, d]); + // The fixed item cannot be passed + expect(drag(0, { x: 240, y: 75 })).toEqual(keys); +}); + +it('keeps a fixed last item when the target line does not exist', () => { + // a | b c | d | E: with b taken out, c joins a, so the layout has one line + // less than the strategy expects + const { drag, keys } = setup([220, 210, 70, 240, 90], 300, { fixedIndex: 4 }); + + expect(drag(1, { x: 150, y: 125 })).toEqual(keys); +}); + +it('moves an item wider than half of the line to the end of the line', () => { + const { drag, keys } = setup([200, 50, 50], 300); + const [a, b, c] = keys; + + expect(drag(0, { x: 290, y: 25 })).toEqual([b, c, a]); +}); + +it('does not leave an empty line before a first item wider than the container', () => { + const { context, keys } = setup([300, 80], 250, { rowGap: 12 }); + + expect(context.itemLayoutPositions.value[keys[0]!]).toEqual({ x: 0, y: 0 }); +}); diff --git a/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/index.ts b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/index.ts index e97664a4..615b20ca 100644 --- a/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/index.ts +++ b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/index.ts @@ -266,7 +266,10 @@ const useInsertStrategy: SortStrategyFactory = () => { const currentGroup = currentLayout.itemGroups[groupIndex]; if (!currentGroup) { const lastItemIndex = indexToKey.value.length - 1; - if (activeIndex === lastItemIndex) { + if ( + activeIndex === lastItemIndex || + fixedItemKeys?.value?.[indexToKey.value[lastItemIndex]!] + ) { return null; } return reorderInsert( @@ -293,7 +296,6 @@ const useInsertStrategy: SortStrategyFactory = () => { // Item after let swapItemAfterOffset = -Infinity; let swapItemAfterBound = -Infinity; - let totalGroupSize = 0; do { if (swapItemAfterBound !== -Infinity) { @@ -337,11 +339,6 @@ const useInsertStrategy: SortStrategyFactory = () => { const additionalSwapOffset = getAdditionalSwapOffset(sizeToAdd); swapItemAfterBound = averageOffset + (isCurrentBeforeNext ? 1 : -1) * additionalSwapOffset; - - totalGroupSize += itemMainSize + mainGap; - if (totalGroupSize + activeItemMainSize > currentLayout.groupSizeLimit) { - break; - } } while ( itemIndexInGroup < currentGroup.length - 1 && gt(mainAxisPosition, swapItemAfterBound) @@ -468,8 +465,10 @@ const useInsertStrategy: SortStrategyFactory = () => { } } - const newIndex = - firstAvailableInGroupIndex + (itemIndexInGroup - initialItemIndexInGroup); + const newIndex = Math.min( + firstAvailableInGroupIndex + (itemIndexInGroup - initialItemIndexInGroup), + indexToKey.value.length - 1 + ); if ( newIndex === activeIndex || diff --git a/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/utils.test.ts b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/utils.test.ts new file mode 100644 index 00000000..f4831378 --- /dev/null +++ b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/utils.test.ts @@ -0,0 +1,77 @@ +import { getKeyToIndex } from '../../../../../utils'; +import { getSwappedToGroupAfterIndices } from './utils'; + +it.each([ + // a b | c d -> b | c a | d + [undefined, ['b', 'c', 'a', 'd']], + // a B | c d -> c | B a | d (the fixed B keeps its index) + [{ b: true }, ['c', 'b', 'a', 'd']] +])( + 'returns the in-group index of an item moved to the next group (fixed keys: %j)', + (fixedKeys, expectedOrder) => { + const indexToKey = ['a', 'b', 'c', 'd']; + + expect( + getSwappedToGroupAfterIndices({ + activeItemIndex: 0, + activeItemKey: 'a', + currentGroupIndex: 0, + fixedKeys, + groupSizeLimit: 250, + indexToKey, + itemGroups: [ + ['a', 'b'], + ['c', 'd'] + ], + keyToIndex: getKeyToIndex(indexToKey), + mainGap: 0, + mainItemSizes: { a: 50, b: 200, c: 180, d: 60 } + }) + ).toMatchObject({ + groupIndex: 1, + indexToKey: expectedOrder, + itemIndex: 2, + itemIndexInGroup: 1 + }); + } +); + +it('keeps an item wider than the limit in the line it starts', () => { + // a | B | c -> B | a c (B is wider than the limit and never wraps alone) + const indexToKey = ['a', 'b', 'c']; + + expect( + getSwappedToGroupAfterIndices({ + activeItemIndex: 0, + activeItemKey: 'a', + currentGroupIndex: 0, + fixedKeys: undefined, + groupSizeLimit: 100, + indexToKey, + itemGroups: [['a'], ['b'], ['c']], + keyToIndex: getKeyToIndex(indexToKey), + mainGap: 0, + mainItemSizes: { a: 40, b: 120, c: 40 } + }) + ).toMatchObject({ groupIndex: 1, itemIndex: 1 }); +}); + +it('wraps an item wider than the limit after an item without a size', () => { + // a z | B -> z | B | a (z has no size, but B still cannot join its line) + const indexToKey = ['a', 'z', 'b']; + + expect( + getSwappedToGroupAfterIndices({ + activeItemIndex: 0, + activeItemKey: 'a', + currentGroupIndex: 0, + fixedKeys: undefined, + groupSizeLimit: 100, + indexToKey, + itemGroups: [['a', 'z'], ['b']], + keyToIndex: getKeyToIndex(indexToKey), + mainGap: 0, + mainItemSizes: { a: 40, b: 120, z: 0 } + }) + ).toMatchObject({ groupIndex: 2, itemIndex: 2 }); +}); diff --git a/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/utils.ts b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/utils.ts index cc5efd1a..fde32012 100644 --- a/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/utils.ts +++ b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/updates/insert/utils.ts @@ -185,12 +185,13 @@ const getIndexesWhenSwappedToGroupAfter = ({ const doesNotFitInGroup = (key: string) => totalGroupSize + getItemMainSize(key) > groupSizeLimit; - const includeItem = (key: string) => { + const includeItem = (key: string, newIndex: number) => { const itemMainSize = getItemMainSize(key); - if (doesNotFitInGroup(key)) { + // The first item of a line never wraps (same rule as in the layout) + if (newIndex > firstInGroupIndex && doesNotFitInGroup(key)) { groupIndex++; totalGroupSize = 0; - firstInGroupIndex = keyToIndex[key]!; + firstInGroupIndex = newIndex; } totalGroupSize += itemMainSize + mainGap; }; @@ -204,9 +205,9 @@ const getIndexesWhenSwappedToGroupAfter = ({ // Fill the empty slot with the current item and add all fixed // position items that were before this item - includeItem(key); + includeItem(key, emptyIndex); for (let j = emptyIndex + 1; j < i; j++) { - includeItem(indexToKey[j]!); + includeItem(indexToKey[j]!, j); } emptyIndex = i; diff --git a/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/utils/layout.ts b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/utils/layout.ts index 34ffa864..a4c860c7 100644 --- a/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/utils/layout.ts +++ b/packages/react-native-sortables/src/providers/flex/FlexLayoutProvider/utils/layout.ts @@ -42,7 +42,8 @@ const createGroups = ( const currentTotalSize = totalGroupItemsMainSize + currentGroup.length * gap + mainItemDimension; - if (currentTotalSize > groupMainSizeLimit + 0.1) { + // An item wider than the limit doesn't wrap if it starts the line + if (currentGroup.length && currentTotalSize > groupMainSizeLimit) { groups.push(currentGroup); crossAxisGroupSizes.push(groupCrossSize); currentGroup = []; @@ -368,6 +369,9 @@ export const calculateLayout = ({ if (groupSizeLimit <= 0) { return null; } + // Tolerance for rounding errors, kept in the limit so that the sort + // strategy wraps items exactly as the layout does + groupSizeLimit += 0.1; const groupingResult = createGroups( indexToKey,