Skip to content
Draft
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
Expand Up @@ -8,17 +8,22 @@ import useInsertStrategy from '.';
const ITEM_HEIGHT = 50;

type Options = {
fixedIndex?: number;
columnGap?: number;
fixedIndex?: Array<number> | number;
heights?: Array<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.
// with functions that drag one of them.
const setup = (
widths: Array<number>,
containerWidth: number,
{ fixedIndex, rowGap }: Options = {}
{ columnGap, fixedIndex = [], heights, rowGap }: Options = {}
) => {
const fixedIndexes = [fixedIndex].flat();
const heightOf = (index: number) => heights?.[index] ?? ITEM_HEIGHT;

let context!: ReturnType<typeof useCommonValuesContext>;
let updater!: OrderUpdater;
const useStrategy = () => {
Expand All @@ -28,11 +33,15 @@ const setup = (

render(
<GestureHandlerRootView>
<Sortable.Flex rowGap={rowGap} strategy={useStrategy} customHandle>
<Sortable.Flex
columnGap={columnGap}
rowGap={rowGap}
strategy={useStrategy}
customHandle>
{widths.map((_, index) => (
<Sortable.Handle
key={index}
mode={index === fixedIndex ? 'fixed-order' : 'draggable'}
mode={fixedIndexes.includes(index) ? 'fixed-order' : 'draggable'}
/>
))}
</Sortable.Flex>
Expand All @@ -42,7 +51,9 @@ const setup = (
const keys = context.indexToKey.value;
act(() => {
context.containerWidth.value = containerWidth;
context.itemHeights.value = ITEM_HEIGHT;
context.itemHeights.value = Object.fromEntries(
keys.map((key, index) => [key, heightOf(index)])
);
context.itemWidths.value = Object.fromEntries(
keys.map((key, index) => [key, widths[index]!])
);
Expand All @@ -60,13 +71,48 @@ const setup = (
updater({
activeIndex,
activeKey,
dimensions: { height: ITEM_HEIGHT, width: widths[activeIndex]! },
dimensions: {
height: heightOf(activeIndex),
width: widths[activeIndex]!
},
position
}) ?? keys
);
};

return { context, drag, keys };
const applyOrder = (order: Array<string>) =>
act(() => {
context.indexToKey.value = order;
jest.runAllTimers();
});

// Keeps the item at the given position, applies every order the strategy
// returns (as when the finger moves by a pixel) and returns all of them
const hold = (activeIndex: number, position: Vector) => {
const activeKey = keys[activeIndex]!;
act(() => {
context.activeItemKey.value = activeKey;
jest.runAllTimers();
});
const orders: Array<Array<string>> = [];
for (let i = 0; i < 6; i++) {
const order = updater({
activeIndex: context.keyToIndex.value[activeKey]!,
activeKey,
dimensions: {
height: heightOf(activeIndex),
width: widths[activeIndex]!
},
position
});
if (!order) break;
orders.push(order);
applyOrder(order);
}
return orders;
};

return { context, drag, hold, keys };
};

it('moves an item to the next line when rounded sizes overflow the line', () => {
Expand All @@ -83,16 +129,54 @@ it('moves an item next to a fixed last item without replacing it', () => {
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);
// The fixed item cannot be passed, so the slot before it is taken
expect(drag(0, { x: 240, y: 75 })).toEqual([b, c, a, d]);
});

it('moves an item to the next line when the pointer is over its fixed last item', () => {
// a b | c D -> a | c b D
const { drag, keys } = setup([54, 298, 270, 48], 352, { fixedIndex: 3 });
const [a, b, c, d] = keys;

expect(drag(1, { x: 203, y: 75 })).toEqual([a, c, b, d]);
});

it('moves an item to the last line when only a fixed item can follow it', () => {
// a b | c d | e F -> a b | c e | d F
const { drag, keys } = setup([233, 129, 160, 154, 146, 58], 380, {
fixedIndex: 5
});
const [a, b, c, d, e, f] = keys;

expect(drag(3, { x: 263, y: 125 })).toEqual([a, b, c, e, d, f]);
});

describe('when taking the item out lets the next item join the previous line', () => {
it('moves the first item of a line to the next line', () => {
// a | b c d | e -> a c | d e | b
const { drag, keys } = setup([220, 100, 60, 110, 180], 300);
const [a, b, c, d, e] = keys;

expect(drag(1, { x: 50, y: 125 })).toEqual([a, c, d, e, b]);
});

it('moves an item before a fixed last item', () => {
// a | b c | d | E -> a c | d | b E
const { drag, keys } = setup([220, 210, 70, 240, 90], 300, {
fixedIndex: 4
});
const [a, b, c, d, e] = keys;

expect(drag(1, { x: 150, y: 125 })).toEqual([a, c, d, b, e]);
});
});

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 });
it('moves an item wider than the container to the previous line', () => {
// a | b | c d -> b | a c d
const { drag, keys } = setup([57, 368, 162, 35], 362);
const [a, b, c, d] = keys;

expect(drag(1, { x: 150, y: 125 })).toEqual(keys);
expect(drag(1, { x: 184, y: 40 })).toEqual([b, a, c, d]);
});

it('moves an item wider than half of the line to the end of the line', () => {
Expand All @@ -107,3 +191,57 @@ it('does not leave an empty line before a first item wider than the container',

expect(context.itemLayoutPositions.value[keys[0]!]).toEqual({ x: 0, y: 0 });
});

describe('with the item held at one position', () => {
it('settles above a tall fixed line', () => {
// a b | C | d E, where C and E are fixed and C is 150 high
const { hold, keys } = setup([150, 100, 300, 200, 50], 300, {
fixedIndex: [2, 4],
heights: [50, 50, 150, 50, 50]
});
const [a, b, c, d, e] = keys;

expect(hold(3, { x: 100, y: 110 })).toEqual([
[d, a, c, b, e],
[a, d, c, b, e]
]);
});

it('settles above three fixed lines', () => {
// a b | C | D | E | f G, where C, D, E and G are fixed
const { hold, keys } = setup([150, 100, 300, 300, 300, 200, 50], 300, {
fixedIndex: [2, 3, 4, 6]
});
const [a, b, c, d, e, f, g] = keys;

expect(hold(5, { x: 100, y: 112 })).toEqual([
[f, a, c, d, e, b, g],
[a, f, c, d, e, b, g]
]);
});

it('settles when the item is wider than the container', () => {
// a | b c | D | e, where D is fixed and 150 high
const { hold, keys } = setup([200, 150, 100, 300, 320], 300, {
fixedIndex: 3,
heights: [50, 50, 50, 150, 50]
});
const [a, b, c, d, e] = keys;

expect(hold(4, { x: 150, y: 160 })).toEqual([
[a, e, b, d, c],
[a, b, e, d, c]
]);
});

it('ends on the line under the pointer when lines have gaps', () => {
// a | b | c | d | e | f g, the pointer is in the line of c
const { hold, keys } = setup([100, 120, 140, 160, 100, 140, 40], 200, {
columnGap: 16,
rowGap: 8
});
const [a, b, c, d, e, f, g] = keys;

expect(hold(6, { x: 6, y: 150 }).at(-1)).toEqual([a, b, c, g, d, e, f]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,26 @@ import {
getTotalGroupSize
} from './utils';

// The line the active item really is in after the swap. The predicted one is
// one too far when the item taking the place of the active item joins the
// previous line.
const getSwappedGroupIndex = (
indexes: ItemGroupSwapResult,
layout: FlexLayout | null,
activeKey: string
) => {
'worklet';
const groups = layout?.itemGroups;
if (
groups &&
!groups[indexes.groupIndex]?.includes(activeKey) &&
groups[indexes.groupIndex - 1]?.includes(activeKey)
) {
return indexes.groupIndex - 1;
}
return indexes.groupIndex;
};

const useInsertStrategy: SortStrategyFactory = () => {
const { activeItemKey, indexToKey, itemHeights, itemWidths, keyToIndex } =
useCommonValuesContext();
Expand Down Expand Up @@ -216,7 +236,7 @@ const useInsertStrategy: SortStrategyFactory = () => {
if (swapGroupAfterBound !== -Infinity) {
swappedAfterGroupsCount =
swappedAfterLayout.value?.itemGroups.length ?? 0;
groupIndex = afterIndexes.groupIndex;
groupIndex = getSwappedGroupIndex(afterIndexes, afterLayout, activeKey);
firstAvailableInGroupIndex = afterIndexes.itemIndex;
itemIndexInGroup = afterIndexes.itemIndexInGroup;

Expand All @@ -238,10 +258,15 @@ const useInsertStrategy: SortStrategyFactory = () => {
swapGroupAfterOffset =
currentGroupBeforeOffset +
(currentLayout.crossAxisGroupSizes[groupIndex] ?? 0);
const afterGroupIndex = getSwappedGroupIndex(
afterIndexes,
afterLayout,
activeKey
);
const afterSwapGroupBeforeOffset =
afterLayout?.crossAxisGroupOffsets[afterIndexes.groupIndex] ?? 0;
afterLayout?.crossAxisGroupOffsets[afterGroupIndex] ?? 0;
const afterSwapGroupSize = Math.max(
afterLayout?.crossAxisGroupSizes?.[afterIndexes.groupIndex] ?? 0,
afterLayout?.crossAxisGroupSizes?.[afterGroupIndex] ?? 0,
activeItemDimensions[crossDimension]
);
const swapOffset = afterSwapGroupBeforeOffset
Expand All @@ -251,7 +276,7 @@ const useInsertStrategy: SortStrategyFactory = () => {
2
: swapGroupAfterOffset;
const additionalSwapOffset = getAdditionalSwapOffset(
afterLayout?.crossAxisGroupSizes?.[afterIndexes.groupIndex] ?? 0
afterLayout?.crossAxisGroupSizes?.[afterGroupIndex] ?? 0
);
swapGroupAfterBound = swapOffset + additionalSwapOffset;
} while (
Expand All @@ -263,7 +288,15 @@ const useInsertStrategy: SortStrategyFactory = () => {
// MAIN AXIS BOUNDS
// currentGroup is the updated group after new layout calculation
// that contains the active item
const currentGroup = currentLayout.itemGroups[groupIndex];
let currentGroup = currentLayout.itemGroups[groupIndex];
// Taking the active item out of its line can let the next item join the
// previous line, so the active item is one line before the expected one
if (
!currentGroup?.includes(activeKey) &&
currentLayout.itemGroups[groupIndex - 1]?.includes(activeKey)
) {
currentGroup = currentLayout.itemGroups[--groupIndex];
}
if (!currentGroup) {
const lastItemIndex = indexToKey.value.length - 1;
if (
Expand All @@ -281,13 +314,10 @@ const useInsertStrategy: SortStrategyFactory = () => {
}
const mainAxisPosition = position[mainCoordinate];

// Find the itemIndexInGroup of the active item if it is in the same group
if (groupIndex === activeGroupIndex.value) {
const firstItemKey = currentGroup[0];
if (firstItemKey === undefined) return;
const firstItemIndex = keyToIndex.value[firstItemKey];
if (firstItemIndex === undefined) return;
itemIndexInGroup = activeIndex - firstItemIndex;
// The layout knows where in its line the active item really is
const activeIndexInGroup = currentGroup.indexOf(activeKey);
if (activeIndexInGroup !== -1) {
itemIndexInGroup = activeIndexInGroup;
}

const initialItemIndexInGroup = itemIndexInGroup;
Expand Down Expand Up @@ -465,10 +495,19 @@ const useInsertStrategy: SortStrategyFactory = () => {
}
}

const newIndex = Math.min(
let newIndex = Math.min(
firstAvailableInGroupIndex + (itemIndexInGroup - initialItemIndexInGroup),
indexToKey.value.length - 1
);
// A fixed item cannot be replaced, so take the closest free slot on the
// way to it
const step = Math.sign(firstAvailableInGroupIndex - newIndex);
while (
newIndex !== firstAvailableInGroupIndex &&
fixedItemKeys?.value?.[indexToKey.value[newIndex]!]
) {
newIndex += step;
}

if (
newIndex === activeIndex ||
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,11 @@ const getIndexesWhenSwappedToGroupBefore = ({
if (itemKey === undefined) {
return null;
}
if (totalGroupSize + activeMainSize > groupSizeLimit) {
// The first item of a line never wraps (same rule as in the layout)
if (
itemIndex > firstInGroupBeforeIndex &&
totalGroupSize + activeMainSize > groupSizeLimit
) {
break;
}

Expand Down Expand Up @@ -196,7 +200,14 @@ const getIndexesWhenSwappedToGroupAfter = ({
totalGroupSize += itemMainSize + mainGap;
};

for (let i = activeItemIndex + 1; i < indexToKey.length; i++) {
// Fixed items at the end cannot be passed, so the slot before them is the
// last one the active item can take
let lastFreeIndex = indexToKey.length - 1;
while (fixedKeys?.[indexToKey[lastFreeIndex]!]) {
lastFreeIndex--;
}

for (let i = activeItemIndex + 1; i <= lastFreeIndex; i++) {
const key = indexToKey[i]!;

if (fixedKeys?.[key]) {
Expand All @@ -212,8 +223,7 @@ const getIndexesWhenSwappedToGroupAfter = ({
emptyIndex = i;

if (doesNotFitInGroup(activeItemKey)) {
const nextItemKey = indexToKey[i + 1];
if (nextItemKey === undefined || doesNotFitInGroup(nextItemKey)) {
if (i === lastFreeIndex || doesNotFitInGroup(indexToKey[i + 1]!)) {
return {
groupIndex: groupIndex + 1,
itemIndex: i,
Expand Down
Loading