react-native-swappable-grid 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +284 -0
  2. package/lib/commonjs/ChildWrapper.js +320 -0
  3. package/lib/commonjs/ChildWrapper.js.map +1 -0
  4. package/lib/commonjs/SwappableGrid.js +378 -0
  5. package/lib/commonjs/SwappableGrid.js.map +1 -0
  6. package/lib/commonjs/index.js +14 -0
  7. package/lib/commonjs/index.js.map +1 -0
  8. package/lib/commonjs/utils/helpers/computerMinHeight.js +11 -0
  9. package/lib/commonjs/utils/helpers/computerMinHeight.js.map +1 -0
  10. package/lib/commonjs/utils/helpers/gestures/PanWithLongPress.js +249 -0
  11. package/lib/commonjs/utils/helpers/gestures/PanWithLongPress.js.map +1 -0
  12. package/lib/commonjs/utils/helpers/indexCalculations.js +73 -0
  13. package/lib/commonjs/utils/helpers/indexCalculations.js.map +1 -0
  14. package/lib/commonjs/utils/useGridLayout.js +205 -0
  15. package/lib/commonjs/utils/useGridLayout.js.map +1 -0
  16. package/lib/module/ChildWrapper.js +313 -0
  17. package/lib/module/ChildWrapper.js.map +1 -0
  18. package/lib/module/SwappableGrid.js +370 -0
  19. package/lib/module/SwappableGrid.js.map +1 -0
  20. package/lib/module/index.js +2 -0
  21. package/lib/module/index.js.map +1 -0
  22. package/lib/module/utils/helpers/computerMinHeight.js +5 -0
  23. package/lib/module/utils/helpers/computerMinHeight.js.map +1 -0
  24. package/lib/module/utils/helpers/gestures/PanWithLongPress.js +242 -0
  25. package/lib/module/utils/helpers/gestures/PanWithLongPress.js.map +1 -0
  26. package/lib/module/utils/helpers/indexCalculations.js +64 -0
  27. package/lib/module/utils/helpers/indexCalculations.js.map +1 -0
  28. package/lib/module/utils/useGridLayout.js +199 -0
  29. package/lib/module/utils/useGridLayout.js.map +1 -0
  30. package/lib/typescript/ChildWrapper.d.ts +23 -0
  31. package/lib/typescript/SwappableGrid.d.ts +85 -0
  32. package/lib/typescript/index.d.ts +2 -0
  33. package/lib/typescript/utils/helpers/computerMinHeight.d.ts +1 -0
  34. package/lib/typescript/utils/helpers/gestures/PanWithLongPress.d.ts +40 -0
  35. package/lib/typescript/utils/helpers/indexCalculations.d.ts +28 -0
  36. package/lib/typescript/utils/useGridLayout.d.ts +46 -0
  37. package/package.json +68 -0
  38. package/src/ChildWrapper.tsx +376 -0
  39. package/src/SwappableGrid.tsx +492 -0
  40. package/src/index.ts +2 -0
  41. package/src/utils/helpers/computerMinHeight.ts +9 -0
  42. package/src/utils/helpers/gestures/PanWithLongPress.ts +304 -0
  43. package/src/utils/helpers/indexCalculations.ts +91 -0
  44. package/src/utils/useGridLayout.ts +236 -0
@@ -0,0 +1,492 @@
1
+ import React, {
2
+ ReactNode,
3
+ useEffect,
4
+ useState,
5
+ useImperativeHandle,
6
+ forwardRef,
7
+ } from "react";
8
+ import {
9
+ View,
10
+ StyleSheet,
11
+ ScrollView,
12
+ StyleProp,
13
+ ViewStyle,
14
+ LayoutChangeEvent,
15
+ } from "react-native";
16
+ import Animated, {
17
+ useAnimatedRef,
18
+ useAnimatedStyle,
19
+ useDerivedValue,
20
+ useAnimatedReaction,
21
+ runOnJS,
22
+ } from "react-native-reanimated";
23
+ import { GestureDetector } from "react-native-gesture-handler";
24
+ import computeMinHeight from "./utils/helpers/computerMinHeight";
25
+ import { useGridLayout } from "./utils/useGridLayout";
26
+ import ChildWrapper from "./ChildWrapper";
27
+ import { indexToXY } from "./utils/helpers/indexCalculations";
28
+
29
+ const AnimatedScrollView = Animated.createAnimatedComponent(ScrollView);
30
+
31
+ const normalizeKey = (k: React.Key) => String(k).replace(/^\.\$/, "");
32
+
33
+ /**
34
+ * Props for the SwappableGrid component
35
+ */
36
+ type SwappableGridProps = {
37
+ /** The child components to render in the grid. Each child should have a unique key. */
38
+ children: ReactNode;
39
+ /** Width of each grid item in pixels */
40
+ itemWidth: number;
41
+ /** Height of each grid item in pixels */
42
+ itemHeight: number;
43
+ /** Gap between grid items in pixels. Defaults to 8. */
44
+ gap?: number;
45
+ /** Padding around the container in pixels. Defaults to 8. */
46
+ containerPadding?: number;
47
+ /** Duration in milliseconds to hold before drag starts. Defaults to 300. */
48
+ longPressMs?: number;
49
+ /** Number of columns in the grid. If not provided, will be calculated automatically based on container width. */
50
+ numColumns?: number;
51
+ /** Wiggle animation configuration when items are in drag mode or delete mode */
52
+ wiggle?: {
53
+ /** Duration of one wiggle cycle in milliseconds */
54
+ duration: number;
55
+ /** Rotation degrees for the wiggle animation */
56
+ degrees: number;
57
+ };
58
+ /** Callback fired when drag ends, providing the ordered array of child nodes */
59
+ onDragEnd?: (ordered: ChildNode[]) => void;
60
+ /** Callback fired when the order changes, providing an array of keys in the new order */
61
+ onOrderChange?: (keys: string[]) => void;
62
+ /** Callback fired when an item is deleted, providing the key of the deleted item */
63
+ onDelete?: (key: string) => void;
64
+ /** Factor by which the dragged item scales up. Defaults to 1.06. */
65
+ dragSizeIncreaseFactor?: number;
66
+ /** Speed of auto-scrolling when dragging near edges. Defaults to 10. */
67
+ scrollSpeed?: number;
68
+ /** Distance from edge in pixels that triggers auto-scroll. Defaults to 100. */
69
+ scrollThreshold?: number;
70
+ /** Custom style for the ScrollView container */
71
+ style?: StyleProp<ViewStyle>;
72
+ /** Component to render after all grid items (e.g., an "Add" button) */
73
+ trailingComponent?: ReactNode;
74
+ /** Component to render as a delete target (shown when dragging). If provided, disables hold-to-delete feature. */
75
+ deleteComponent?: ReactNode;
76
+ /** Custom style for the delete component. If provided, allows custom positioning. */
77
+ deleteComponentStyle?: StyleProp<ViewStyle>;
78
+ /** If true, reverses the order of items (right-to-left, bottom-to-top). Defaults to false. */
79
+ reverse?: boolean;
80
+ };
81
+
82
+ /**
83
+ * Ref methods for SwappableGrid component
84
+ */
85
+ export interface SwappableGridRef {
86
+ /** Cancels the delete mode if any item is currently in delete mode */
87
+ cancelDeleteMode: () => void;
88
+ }
89
+
90
+ /**
91
+ * SwappableGrid - A React Native component for creating a draggable, swappable grid layout.
92
+ *
93
+ * Features:
94
+ * - Drag and drop to reorder items
95
+ * - Long press to enter drag mode
96
+ * - Auto-scroll when dragging near edges
97
+ * - Optional wiggle animation during drag mode
98
+ * - Optional delete functionality with hold-to-delete or delete component
99
+ * - Support for trailing components (e.g., "Add" button)
100
+ * - Automatic column calculation based on container width
101
+ *
102
+ * @example
103
+ * ```tsx
104
+ * <SwappableGrid
105
+ * itemWidth={100}
106
+ * itemHeight={100}
107
+ * numColumns={3}
108
+ * onOrderChange={(keys) => console.log('New order:', keys)}
109
+ * >
110
+ * {items.map(item => (
111
+ * <View key={item.id}>{item.content}</View>
112
+ * ))}
113
+ * </SwappableGrid>
114
+ * ```
115
+ */
116
+ const SwappableGrid = forwardRef<SwappableGridRef, SwappableGridProps>(
117
+ (
118
+ {
119
+ children,
120
+ itemWidth,
121
+ itemHeight,
122
+ gap = 8,
123
+ containerPadding = 8,
124
+ longPressMs = 300,
125
+ numColumns,
126
+ onDragEnd,
127
+ onOrderChange,
128
+ onDelete,
129
+ wiggle,
130
+ style,
131
+ dragSizeIncreaseFactor = 1.06,
132
+ scrollThreshold = 100,
133
+ scrollSpeed = 10,
134
+ trailingComponent,
135
+ deleteComponent,
136
+ deleteComponentStyle,
137
+ reverse = false,
138
+ },
139
+ ref
140
+ ) => {
141
+ // MUST be Animated ref for scrollTo
142
+ const scrollViewRef = useAnimatedRef<Animated.ScrollView>();
143
+ const [showTrailingComponent, setShowTrailingComponent] =
144
+ useState<boolean>(false);
145
+ const [showDeleteComponent, setShowDeleteComponent] =
146
+ useState<boolean>(false);
147
+ const [isDragging, setIsDragging] = useState<boolean>(false);
148
+ const [currentNumColumns, setCurrentNumColumns] = useState<number>(
149
+ numColumns || 1
150
+ );
151
+ const touchEndTimeoutRef = React.useRef<ReturnType<
152
+ typeof setTimeout
153
+ > | null>(null);
154
+ const deleteComponentRef = React.useRef<View>(null);
155
+
156
+ useEffect(() => {
157
+ setTimeout(() => {
158
+ setShowTrailingComponent(true);
159
+ setShowDeleteComponent(true);
160
+ }, 50); // This is kinda a hack that makes the trailing component render in the correct position because it lets the other components render first to make the position calculation correct.
161
+ }, []);
162
+
163
+ const handleOnOrderChange = (order: string[]) => {
164
+ if (onOrderChange) onOrderChange(order.map((key) => normalizeKey(key)));
165
+ };
166
+
167
+ // Extract paddingBottom from style prop to allow dragging into padding area
168
+ const paddingBottom = React.useMemo(() => {
169
+ if (!style) return 0;
170
+ const styleObj = StyleSheet.flatten(style);
171
+ return (styleObj.paddingBottom as number) || 0;
172
+ }, [style]);
173
+
174
+ const {
175
+ orderState,
176
+ composed,
177
+ dynamicNumColumns,
178
+ onLayoutContent: originalOnLayoutContent, // layout of the inner content view (for width/cols)
179
+ onLayoutScrollView, // layout of the scroll viewport (for height)
180
+ onScroll,
181
+ deleteItem,
182
+ childArray,
183
+ positions,
184
+ dragMode,
185
+ anyItemInDeleteMode,
186
+ order,
187
+ deleteComponentPosition,
188
+ } = useGridLayout({
189
+ reverse,
190
+ children,
191
+ longPressMs,
192
+ itemWidth,
193
+ itemHeight,
194
+ gap,
195
+ containerPadding,
196
+ numColumns,
197
+ onDragEnd,
198
+ onOrderChange: handleOnOrderChange,
199
+ onDelete: onDelete ? (key) => onDelete(normalizeKey(key)) : undefined,
200
+ scrollViewRef,
201
+ scrollSpeed,
202
+ scrollThreshold,
203
+ contentPaddingBottom: paddingBottom,
204
+ });
205
+
206
+ // Track numColumns changes for height calculation
207
+ const onLayoutContent = (e: LayoutChangeEvent) => {
208
+ originalOnLayoutContent(e);
209
+ // Update currentNumColumns for height calculation
210
+ if (numColumns) {
211
+ setCurrentNumColumns(numColumns);
212
+ } else {
213
+ const possibleCols = Math.floor(
214
+ (e.nativeEvent.layout.width - containerPadding * 2 + gap) /
215
+ (itemWidth + gap)
216
+ );
217
+ setCurrentNumColumns(Math.max(1, possibleCols));
218
+ }
219
+ };
220
+
221
+ // Track drag state to show/hide delete component
222
+ useAnimatedReaction(
223
+ () => dragMode.value,
224
+ (isDraggingValue) => {
225
+ runOnJS(setIsDragging)(isDraggingValue);
226
+ }
227
+ );
228
+
229
+ // Expose cancel delete mode function to parent
230
+ useImperativeHandle(
231
+ ref,
232
+ () => ({
233
+ cancelDeleteMode: () => {
234
+ if (anyItemInDeleteMode.value) {
235
+ anyItemInDeleteMode.value = false;
236
+ }
237
+ },
238
+ }),
239
+ [anyItemInDeleteMode]
240
+ );
241
+
242
+ const trailingX = useDerivedValue(() => {
243
+ const { x } = indexToXY({
244
+ index: order.value.length, // AFTER last swappable
245
+ itemWidth,
246
+ itemHeight,
247
+ dynamicNumColumns,
248
+ containerPadding,
249
+ gap,
250
+ });
251
+ return x;
252
+ });
253
+
254
+ const trailingY = useDerivedValue(() => {
255
+ const { y } = indexToXY({
256
+ index: order.value.length,
257
+ itemWidth,
258
+ itemHeight,
259
+ dynamicNumColumns,
260
+ containerPadding,
261
+ gap,
262
+ });
263
+ return y;
264
+ });
265
+
266
+ const trailingStyle = useAnimatedStyle(() => ({
267
+ left: trailingX.value,
268
+ top: trailingY.value,
269
+ }));
270
+
271
+ // Calculate default delete component position (bottom center)
272
+ const deleteComponentX = useDerivedValue(() => {
273
+ if (deleteComponentStyle) {
274
+ // If custom style provided, position will be set by user
275
+ return 0;
276
+ }
277
+ // Default: center horizontally
278
+ const cols = dynamicNumColumns.value;
279
+ const totalWidth =
280
+ cols * itemWidth + (cols - 1) * gap + containerPadding * 2;
281
+ return (totalWidth - itemWidth) / 2;
282
+ });
283
+
284
+ const deleteComponentY = useDerivedValue(() => {
285
+ if (deleteComponentStyle) {
286
+ // If custom style provided, position will be set by user
287
+ return 0;
288
+ }
289
+ // Default: bottom of grid (after all items)
290
+ // Account for trailing component if it exists
291
+ const rows = Math.ceil(order.value.length / dynamicNumColumns.value);
292
+ const baseY = containerPadding + rows * (itemHeight + gap);
293
+
294
+ // If trailing component exists, add extra space so delete component appears below it
295
+ if (trailingComponent && showTrailingComponent) {
296
+ return baseY + (itemHeight + gap);
297
+ }
298
+
299
+ return baseY + gap;
300
+ });
301
+
302
+ const deleteComponentStyleAnimated = useAnimatedStyle(() => {
303
+ const baseStyle: any = {
304
+ position: "absolute",
305
+ width: itemWidth,
306
+ height: itemHeight,
307
+ };
308
+
309
+ // Use custom position if provided, otherwise use default
310
+ if (deleteComponentStyle) {
311
+ return baseStyle;
312
+ }
313
+
314
+ return {
315
+ ...baseStyle,
316
+ left: deleteComponentX.value,
317
+ top: deleteComponentY.value,
318
+ };
319
+ });
320
+
321
+ // Update delete component position for drop detection when default position changes
322
+ useDerivedValue(() => {
323
+ if (deleteComponent && deleteComponentPosition && !deleteComponentStyle) {
324
+ // Only update if using default position (custom style uses onLayout)
325
+ deleteComponentPosition.value = {
326
+ x: deleteComponentX.value,
327
+ y: deleteComponentY.value,
328
+ width: itemWidth,
329
+ height: itemHeight,
330
+ };
331
+ }
332
+ });
333
+
334
+ const showTrailing = !!(trailingComponent && showTrailingComponent);
335
+ const showDelete = !!(deleteComponent && showDeleteComponent);
336
+ // Make sure we calculate room for both trailing and delete components
337
+ // Trailing component is part of the grid, delete component is positioned below
338
+ const itemsCountForHeight = orderState.length + (showTrailing ? 1 : 0);
339
+
340
+ // Calculate minimum height needed (on JS thread since computeMinHeight is not a worklet)
341
+ const baseHeight = computeMinHeight(
342
+ itemsCountForHeight,
343
+ currentNumColumns,
344
+ itemHeight + gap,
345
+ containerPadding
346
+ );
347
+
348
+ // If delete component is shown and using default position, add extra space for it
349
+ let calculatedHeight = baseHeight;
350
+ if (showDelete && !deleteComponentStyle) {
351
+ // Account for trailing component when calculating rows (same logic as deleteComponentY)
352
+ const totalItems = orderState.length + (showTrailing ? 1 : 0);
353
+ const rows = Math.ceil(totalItems / currentNumColumns);
354
+ const baseY = containerPadding + rows * (itemHeight + gap);
355
+
356
+ // If trailing component exists, add extra space so delete component appears below it
357
+ let deleteComponentY = baseY;
358
+ if (showTrailing) {
359
+ deleteComponentY = baseY + (itemHeight + gap);
360
+ } else {
361
+ deleteComponentY = baseY + gap;
362
+ }
363
+
364
+ const deleteComponentBottom = deleteComponentY + itemHeight;
365
+ // Ensure container is tall enough to show the delete component
366
+ calculatedHeight = Math.max(
367
+ baseHeight,
368
+ deleteComponentBottom + containerPadding
369
+ );
370
+ }
371
+
372
+ return (
373
+ <AnimatedScrollView
374
+ ref={scrollViewRef}
375
+ onScroll={onScroll}
376
+ onLayout={onLayoutScrollView} // viewport height comes from the SCROLLVIEW
377
+ scrollEventThrottle={16}
378
+ contentContainerStyle={[style]}
379
+ onTouchEnd={() => {
380
+ // Cancel delete mode when user touches outside items
381
+ // Add a small delay to avoid canceling when user taps on items
382
+ // (items might briefly activate, which would prevent cancellation)
383
+ if (touchEndTimeoutRef.current) {
384
+ clearTimeout(touchEndTimeoutRef.current);
385
+ }
386
+ touchEndTimeoutRef.current = setTimeout(() => {
387
+ // Only cancel if still in delete mode and not dragging
388
+ // This ensures we don't cancel when user is interacting with items
389
+ if (anyItemInDeleteMode.value && !dragMode.value) {
390
+ anyItemInDeleteMode.value = false;
391
+ }
392
+ }, 100); // Small delay to let item interactions complete
393
+ }}
394
+ >
395
+ <View
396
+ style={[
397
+ styles.container,
398
+ {
399
+ padding: containerPadding,
400
+ height: calculatedHeight,
401
+ },
402
+ ]}
403
+ onLayout={onLayoutContent}
404
+ >
405
+ <GestureDetector gesture={composed}>
406
+ <View pointerEvents="box-none" style={StyleSheet.absoluteFill}>
407
+ {orderState.map((key) => {
408
+ const child = childArray.find(
409
+ (c) => c.key && normalizeKey(c.key) === normalizeKey(key)
410
+ );
411
+ if (!child) return null;
412
+ return (
413
+ <ChildWrapper
414
+ key={key}
415
+ position={positions[key]}
416
+ itemWidth={itemWidth}
417
+ itemHeight={itemHeight}
418
+ dragMode={dragMode}
419
+ anyItemInDeleteMode={anyItemInDeleteMode}
420
+ wiggle={wiggle}
421
+ dragSizeIncreaseFactor={dragSizeIncreaseFactor}
422
+ disableHoldToDelete={!!deleteComponent}
423
+ onDelete={() => {
424
+ deleteItem(key);
425
+ if (onDelete) {
426
+ onDelete(normalizeKey(key));
427
+ }
428
+ }}
429
+ >
430
+ {child}
431
+ </ChildWrapper>
432
+ );
433
+ })}
434
+ </View>
435
+ </GestureDetector>
436
+
437
+ {/* Trailing rendered OUTSIDE the GestureDetector */}
438
+ {trailingComponent && showTrailingComponent && (
439
+ <Animated.View
440
+ pointerEvents="box-none"
441
+ collapsable={false}
442
+ style={[
443
+ {
444
+ position: "absolute",
445
+ width: itemWidth,
446
+ height: itemHeight,
447
+ },
448
+ trailingStyle, // 👈 left/top from UI thread
449
+ ]}
450
+ >
451
+ <View pointerEvents="auto" style={{ flex: 1 }}>
452
+ {trailingComponent}
453
+ </View>
454
+ </Animated.View>
455
+ )}
456
+
457
+ {/* Delete component rendered OUTSIDE the GestureDetector - only show when dragging */}
458
+ {deleteComponent && showDeleteComponent && isDragging && (
459
+ <Animated.View
460
+ ref={deleteComponentRef}
461
+ pointerEvents="box-none"
462
+ collapsable={false}
463
+ style={[
464
+ deleteComponentStyleAnimated,
465
+ deleteComponentStyle, // User can override position with custom style
466
+ ]}
467
+ onLayout={(e) => {
468
+ // Update position for drop detection
469
+ const { x, y, width, height } = e.nativeEvent.layout;
470
+ if (deleteComponentPosition) {
471
+ deleteComponentPosition.value = { x, y, width, height };
472
+ }
473
+ }}
474
+ >
475
+ <View pointerEvents="auto" style={{ flex: 1 }}>
476
+ {deleteComponent}
477
+ </View>
478
+ </Animated.View>
479
+ )}
480
+ </View>
481
+ </AnimatedScrollView>
482
+ );
483
+ }
484
+ );
485
+
486
+ const styles = StyleSheet.create({
487
+ container: {
488
+ width: "100%",
489
+ },
490
+ });
491
+
492
+ export default SwappableGrid;
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { default as SwappableGrid } from "./SwappableGrid";
2
+ export type { SwappableGridRef } from "./SwappableGrid";
@@ -0,0 +1,9 @@
1
+ export default function computeMinHeight(
2
+ count: number,
3
+ numColumns: number,
4
+ tileH: number,
5
+ pad: number
6
+ ) {
7
+ const rows = Math.max(1, Math.ceil(count / numColumns));
8
+ return pad * 2 + rows * tileH;
9
+ }