react-native-layout-dnd 0.1.0-alpha.1 → 0.1.0-alpha.3

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 (62) hide show
  1. package/README.md +124 -57
  2. package/lib/module/components/DndProvider.js +44 -5
  3. package/lib/module/components/DndProvider.js.map +1 -1
  4. package/lib/module/components/GridController.js +48 -0
  5. package/lib/module/components/GridController.js.map +1 -1
  6. package/lib/module/components/SortableGrid.js +31 -4
  7. package/lib/module/components/SortableGrid.js.map +1 -1
  8. package/lib/module/components/SortableList.js +15 -1
  9. package/lib/module/components/SortableList.js.map +1 -1
  10. package/lib/module/controller/dndSession.js +8 -1
  11. package/lib/module/controller/dndSession.js.map +1 -1
  12. package/lib/module/engine/index.js +1 -1
  13. package/lib/module/engine/index.js.map +1 -1
  14. package/lib/module/engine/movementPolicy.js +3 -10
  15. package/lib/module/engine/movementPolicy.js.map +1 -1
  16. package/lib/module/engine/spatialInsertion.js +12 -33
  17. package/lib/module/engine/spatialInsertion.js.map +1 -1
  18. package/lib/module/engine/spatialPolicy.js +7 -3
  19. package/lib/module/engine/spatialPolicy.js.map +1 -1
  20. package/lib/module/index.js +1 -1
  21. package/lib/module/index.js.map +1 -1
  22. package/lib/module/pointer/geometry.js +5 -2
  23. package/lib/module/pointer/geometry.js.map +1 -1
  24. package/lib/module/runtime/committedSize.js +42 -0
  25. package/lib/module/runtime/committedSize.js.map +1 -0
  26. package/lib/typescript/src/components/DndProvider.d.ts +1 -1
  27. package/lib/typescript/src/components/DndProvider.d.ts.map +1 -1
  28. package/lib/typescript/src/components/GridController.d.ts +1 -1
  29. package/lib/typescript/src/components/GridController.d.ts.map +1 -1
  30. package/lib/typescript/src/components/SortableGrid.d.ts.map +1 -1
  31. package/lib/typescript/src/components/SortableList.d.ts.map +1 -1
  32. package/lib/typescript/src/components/gridTypes.d.ts +7 -1
  33. package/lib/typescript/src/components/gridTypes.d.ts.map +1 -1
  34. package/lib/typescript/src/controller/dndSession.d.ts +6 -0
  35. package/lib/typescript/src/controller/dndSession.d.ts.map +1 -1
  36. package/lib/typescript/src/engine/index.d.ts +1 -1
  37. package/lib/typescript/src/engine/index.d.ts.map +1 -1
  38. package/lib/typescript/src/engine/movementPolicy.d.ts +3 -5
  39. package/lib/typescript/src/engine/movementPolicy.d.ts.map +1 -1
  40. package/lib/typescript/src/engine/spatialInsertion.d.ts +1 -0
  41. package/lib/typescript/src/engine/spatialInsertion.d.ts.map +1 -1
  42. package/lib/typescript/src/engine/spatialPolicy.d.ts.map +1 -1
  43. package/lib/typescript/src/index.d.ts +1 -1
  44. package/lib/typescript/src/index.d.ts.map +1 -1
  45. package/lib/typescript/src/pointer/geometry.d.ts +1 -1
  46. package/lib/typescript/src/pointer/geometry.d.ts.map +1 -1
  47. package/lib/typescript/src/runtime/committedSize.d.ts +19 -0
  48. package/lib/typescript/src/runtime/committedSize.d.ts.map +1 -0
  49. package/package.json +1 -1
  50. package/src/components/DndProvider.tsx +55 -5
  51. package/src/components/GridController.tsx +57 -0
  52. package/src/components/SortableGrid.tsx +65 -6
  53. package/src/components/SortableList.tsx +38 -1
  54. package/src/components/gridTypes.ts +7 -1
  55. package/src/controller/dndSession.ts +14 -0
  56. package/src/engine/index.ts +0 -1
  57. package/src/engine/movementPolicy.ts +5 -13
  58. package/src/engine/spatialInsertion.ts +13 -41
  59. package/src/engine/spatialPolicy.ts +8 -3
  60. package/src/index.ts +0 -1
  61. package/src/pointer/geometry.ts +4 -0
  62. package/src/runtime/committedSize.ts +65 -0
@@ -50,6 +50,11 @@ import {
50
50
  type DndZonePresentation,
51
51
  } from '../runtime/dndPresentation';
52
52
  import type { RetainSlotsRule } from '../runtime/dndRenderStore';
53
+ import {
54
+ readCommittedSize,
55
+ sameViewSize,
56
+ type ViewSize,
57
+ } from '../runtime/committedSize';
53
58
  import type { ListItemRenderArgs, SortableListProps } from './dndTypes';
54
59
  import { useListCellMotion } from '../pointer/listCellMotion';
55
60
 
@@ -447,7 +452,12 @@ export function SortableList<T>({
447
452
  typeof itemSize === 'function' ? false : virtualized ? retainSlots : true,
448
453
  );
449
454
  const identity = useRef({}).current;
450
- const [viewportSize, setViewportSize] = useState({ width: 0, height: 0 });
455
+ // Last known native viewport: onLayout, or the committed layout read below.
456
+ const [viewportSize, setViewportSize] = useState<ViewSize>({
457
+ width: 0,
458
+ height: 0,
459
+ });
460
+ const committedViewport = useRef<ViewSize | null>(null);
451
461
  const [measurementVersion, setMeasurementVersion] = useState(0);
452
462
  const zone = snapshot.zone;
453
463
  const displayZone = snapshot.display;
@@ -520,6 +530,26 @@ export function SortableList<T>({
520
530
  // frame. Its newer version must not be acknowledged by this older render.
521
531
  }, [measurements, renderedMeasurementVersion]);
522
532
  const scrollRef = useAnimatedRef<ScrollView>();
533
+ useLayoutEffect(() => {
534
+ // Fabric has laid out this commit already. A viewport newer than the last
535
+ // onLayout event re-renders synchronously, before paint, so cells never
536
+ // combine new props with the previous cross size. Other commits, such as
537
+ // drag previews, skip the native read.
538
+ const next = readCommittedSize(scrollRef.current);
539
+ committedViewport.current = next;
540
+ if (next && !sameViewSize(next, viewportSize)) setViewportSize(next);
541
+ }, [
542
+ scrollRef,
543
+ viewportSize,
544
+ style,
545
+ orientation,
546
+ virtualized,
547
+ itemSize,
548
+ estimatedItemSize,
549
+ gap,
550
+ paddingStart,
551
+ paddingEnd,
552
+ ]);
523
553
  const offset = useSharedValue(0);
524
554
  const { motion, animation, presentation, committedRevision } = runtime;
525
555
  // Virtual cells position their content with a React-committed slot offset
@@ -728,6 +758,12 @@ export function SortableList<T>({
728
758
  );
729
759
  });
730
760
  useLayoutEffect(() => {
761
+ // The re-render scheduled with this commit's viewport registers instead.
762
+ if (
763
+ committedViewport.current &&
764
+ !sameViewSize(committedViewport.current, viewportSize)
765
+ )
766
+ return;
731
767
  if (!base?.valid || !display?.valid || !validScroll || !windowing.valid) {
732
768
  unregisterZone(zoneId, identity);
733
769
  return;
@@ -771,6 +807,7 @@ export function SortableList<T>({
771
807
  virtualized,
772
808
  prepareDisplay,
773
809
  items,
810
+ viewportSize,
774
811
  ]);
775
812
  useLayoutEffect(
776
813
  () => () => {
@@ -63,14 +63,20 @@ export type GridControllerProps<T> = Omit<ViewProps, 'children'> & {
63
63
  onDragStart?(event: DragStartEvent): void;
64
64
  /** Fires once the drag preview has settled into its cell, or at once when nothing animates. */
65
65
  onDragEnd?(event: DragEndEvent): void;
66
+ /** New issues only; it is not called when issues are resolved. */
66
67
  onValidationError?(issues: ValidationIssue[]): void;
68
+ /**
69
+ * The complete current issue list whenever it changes, `[]` once every
70
+ * issue is resolved. Not called while the list stays empty.
71
+ */
72
+ onValidationChange?(issues: ValidationIssue[]): void;
67
73
  /** Optional JS-only observation. Exceptions are ignored; omit to disable timing. */
68
74
  onDiagnostic?(event: GridDiagnosticEvent): void;
69
75
  /** Defaults to 10,000 bounded search steps. */
70
76
  searchBudget?: number;
71
77
  /** Defaults to a 250ms long press. */
72
78
  activation?: { delayMs: number };
73
- /** Generic rules by default; opt into HOME_GRID_MOVEMENT_POLICY for home compatibility. */
79
+ /** Omitted rules use DEFAULT_GRID_MOVEMENT_POLICY; each rule can be disabled. */
74
80
  movementPolicy?: GridMovementPolicy;
75
81
  motion?: GridMotionConfig;
76
82
  responseTimeoutMs?: number;
@@ -104,7 +104,13 @@ export type DndSessionOptions<T> = {
104
104
  canDrop?(proposal: DndProposal<T>): DropDecision;
105
105
  onDragStart?(event: DragStartEvent): void;
106
106
  onDragEnd?(event: DndDragEndEvent<T>): void;
107
+ /** New issues only; it is not called when issues are resolved. */
107
108
  onValidationError?(issues: LayoutValidationIssue[]): void;
109
+ /**
110
+ * The complete current issue list whenever it changes, `[]` once every
111
+ * issue is resolved. Not called while the list stays empty.
112
+ */
113
+ onValidationChange?(issues: LayoutValidationIssue[]): void;
108
114
  /** Optional JS-only observation. Exceptions are ignored; omit to disable timing. */
109
115
  onDiagnostic?(event: GridDiagnosticEvent): void;
110
116
  responseTimeoutMs?: number;
@@ -324,6 +330,7 @@ function checkOptions<T>(options: DndSessionOptions<T>) {
324
330
  'onDragStart',
325
331
  'onDragEnd',
326
332
  'onValidationError',
333
+ 'onValidationChange',
327
334
  'getGridItemLayout',
328
335
  ].some(key => {
329
336
  const callback = options[key as keyof DndSessionOptions<T>];
@@ -558,6 +565,13 @@ export class DndSessionCoordinator<T> extends SessionCore<
558
565
  reportCallbackError(error);
559
566
  }
560
567
  }
568
+ if (typeof options.onValidationChange === 'function') {
569
+ try {
570
+ options.onValidationChange(checked.issues);
571
+ } catch (error) {
572
+ reportCallbackError(error);
573
+ }
574
+ }
561
575
  }
562
576
  });
563
577
  }
@@ -64,7 +64,6 @@ export type { GridProposal, RevisionedGridValue } from '../types';
64
64
  export { computeMove } from './move';
65
65
  export {
66
66
  DEFAULT_GRID_MOVEMENT_POLICY,
67
- HOME_GRID_MOVEMENT_POLICY,
68
67
  resolveGridMovementPolicy,
69
68
  validateGridMovementPolicy,
70
69
  } from './movementPolicy';
@@ -4,9 +4,9 @@ export type GridMoveCandidate = 'row-rotation' | 'insert' | 'exchange';
4
4
 
5
5
  /** Declarative configuration shared by the JS engine and UI worklets. */
6
6
  export type GridMovementPolicy = {
7
- /** Full-width exchange items may rotate every item in their vertical corridor. */
7
+ /** Full-width exchange items rotate every item in their vertical corridor. Default full-width. */
8
8
  rowRotation?: 'disabled' | 'full-width';
9
- /** Home compatibility: a one-cell insert item can pull an adjacent exchange item. */
9
+ /** A one-cell insert item pulls an adjacent exchange item one cell. Default single-cell. */
10
10
  adjacentInsertExchange?: 'disabled' | 'single-cell';
11
11
  /** First applicable rule wins. Rejection never falls through to another rule. */
12
12
  candidateOrder?: readonly GridMoveCandidate[];
@@ -35,11 +35,11 @@ const DEFAULT_CANDIDATES: readonly GridMoveCandidate[] = Object.freeze([
35
35
  'exchange',
36
36
  ]);
37
37
 
38
- /** Neutral placement rules; caller data and item size never imply home behavior. */
38
+ /** Launcher-style rules, each switchable; caller data never selects a rule. */
39
39
  export const DEFAULT_GRID_MOVEMENT_POLICY: ResolvedGridMovementPolicy =
40
40
  Object.freeze({
41
- rowRotation: 'disabled',
42
- adjacentInsertExchange: 'disabled',
41
+ rowRotation: 'full-width',
42
+ adjacentInsertExchange: 'single-cell',
43
43
  candidateOrder: DEFAULT_CANDIDATES,
44
44
  pointer: Object.freeze({
45
45
  cellHysteresis: 0.12,
@@ -48,14 +48,6 @@ export const DEFAULT_GRID_MOVEMENT_POLICY: ResolvedGridMovementPolicy =
48
48
  }),
49
49
  });
50
50
 
51
- /** Explicit compatibility with the extracted home grid's reversible movements. */
52
- export const HOME_GRID_MOVEMENT_POLICY: ResolvedGridMovementPolicy =
53
- Object.freeze({
54
- ...DEFAULT_GRID_MOVEMENT_POLICY,
55
- rowRotation: 'full-width',
56
- adjacentInsertExchange: 'single-cell',
57
- });
58
-
59
51
  /** Copy configuration when starting a session so later caller edits cannot change it. */
60
52
  export function resolveGridMovementPolicy(
61
53
  policy?: GridMovementPolicy,
@@ -37,50 +37,23 @@ function applyInsertion<T>(
37
37
  };
38
38
  }
39
39
 
40
- /** Shift intervening occupied slots; keep the requested target even when it was empty. */
41
- function insertWithinZone<T>(
40
+ /** Trade places with the occupant of the target slot; no other item moves. */
41
+ function exchangeSlotsWithinZone<T>(
42
42
  {
43
43
  items,
44
44
  active,
45
45
  origin,
46
- }: SpatialMoveInput<T> & {
47
- origin: PositionedItem<T>;
48
- },
49
- vacantTarget = false,
46
+ }: SpatialMoveInput<T> & { origin: PositionedItem<T> },
47
+ occupant: PositionedItem<T>,
50
48
  ): PlacementSearchResult<T> {
51
- const forward = comparePositions(origin.position, active.position) < 0;
52
- const start = forward ? origin.position : active.position;
53
- const end = forward ? active.position : origin.position;
54
- const displaced = items
55
- .filter(
56
- item =>
57
- item.placement === 'insert' &&
58
- comparePositions(item.position, start) >= 0 &&
59
- comparePositions(item.position, end) <= 0,
60
- )
61
- .sort((left, right) =>
62
- forward
63
- ? comparePositions(left.position, right.position)
64
- : comparePositions(right.position, left.position),
65
- );
66
- if (
67
- !isSlotAligned(active, active.span) ||
68
- !isSlotAligned(origin, active.span) ||
69
- displaced.some(item => !isSlotAligned(item, active.span))
70
- ) {
71
- // An empty target remains usable even when larger insertion items do not
72
- // share aligned slots. Only compatible slots participate in insertion.
73
- if (vacantTarget)
74
- return { status: 'ok', placements: [...items, active], attempts: 0 };
49
+ if (!isSlotAligned(origin, active.span))
75
50
  return { status: 'impossible', attempts: 1 };
76
- }
77
- let vacant = origin.position;
78
- const moved = new Map<string, PositionedItem<T>>();
79
- for (const item of displaced) {
80
- moved.set(item.id, withPosition(item, vacant));
81
- vacant = item.position;
82
- }
83
- return applyInsertion(items, active, moved, 1);
51
+ return applyInsertion(
52
+ items,
53
+ active,
54
+ new Map([[occupant.id, withPosition(occupant, origin.position)]]),
55
+ 1,
56
+ );
84
57
  }
85
58
 
86
59
  /** An incoming item shifts insertion slots forward until a free slot is reached. */
@@ -137,13 +110,12 @@ function insertFromAnotherZone<T>({
137
110
  return { status: 'impossible', attempts };
138
111
  }
139
112
 
113
+ /** Internal: rule selection sends only occupied targets here. */
140
114
  export function insertSpatialItem<T>(
141
115
  input: SpatialMoveInput<T>,
142
116
  colliders: readonly PositionedItem<T>[],
143
117
  ): PlacementSearchResult<T> {
144
118
  const { active, origin } = input;
145
- if (origin && colliders.length === 0)
146
- return insertWithinZone({ ...input, origin }, true);
147
119
  if (
148
120
  colliders.length !== 1 ||
149
121
  !isSlotAligned(active, active.span) ||
@@ -152,6 +124,6 @@ export function insertSpatialItem<T>(
152
124
  )
153
125
  return { status: 'impossible', attempts: 0 };
154
126
  return origin
155
- ? insertWithinZone({ ...input, origin })
127
+ ? exchangeSlotsWithinZone({ ...input, origin }, colliders[0])
156
128
  : insertFromAnotherZone(input);
157
129
  }
@@ -7,9 +7,13 @@ import { normalizeAppWidgetMove } from './spatialAppRotation';
7
7
  /** Shared rule selection only: no packing, search, or caller callbacks on the UI thread. */
8
8
  export function selectSpatialMove<T>(input: SpatialMoveInput<T>) {
9
9
  'worklet';
10
+ // Callers may pass a partial policy: every omitted rule takes its default.
10
11
  const policy = input.movementPolicy ?? DEFAULT_GRID_MOVEMENT_POLICY;
12
+ const rowRotation =
13
+ policy.rowRotation ?? DEFAULT_GRID_MOVEMENT_POLICY.rowRotation;
11
14
  const move =
12
- policy.adjacentInsertExchange === 'single-cell'
15
+ (policy.adjacentInsertExchange ??
16
+ DEFAULT_GRID_MOVEMENT_POLICY.adjacentInsertExchange) === 'single-cell'
13
17
  ? (normalizeAppWidgetMove(input) ?? input)
14
18
  : input;
15
19
  const { active, origin, items, columns } = move;
@@ -20,7 +24,7 @@ export function selectSpatialMove<T>(input: SpatialMoveInput<T>) {
20
24
  DEFAULT_GRID_MOVEMENT_POLICY.candidateOrder) {
21
25
  if (
22
26
  candidate === 'row-rotation' &&
23
- policy.rowRotation === 'full-width' &&
27
+ rowRotation === 'full-width' &&
24
28
  origin &&
25
29
  active.placement !== 'insert' &&
26
30
  active.span.cols === columns &&
@@ -33,7 +37,8 @@ export function selectSpatialMove<T>(input: SpatialMoveInput<T>) {
33
37
  if (
34
38
  candidate === 'insert' &&
35
39
  active.placement === 'insert' &&
36
- (origin !== undefined || colliders.length > 0) &&
40
+ // An empty target is a vacancy for every placement: nothing else moves.
41
+ colliders.length > 0 &&
37
42
  colliders.every(item => item.placement === 'insert')
38
43
  ) {
39
44
  kind = candidate;
package/src/index.ts CHANGED
@@ -87,7 +87,6 @@ export type { HandleViewProps } from './components/handleViewProps';
87
87
  export { DEFAULT_ACTIVATION_DELAY_MS, DEFAULT_SEARCH_BUDGET } from './defaults';
88
88
  export {
89
89
  DEFAULT_GRID_MOVEMENT_POLICY,
90
- HOME_GRID_MOVEMENT_POLICY,
91
90
  resolveGridMovementPolicy,
92
91
  validateGridMovementPolicy,
93
92
  } from './engine/movementPolicy';
@@ -108,6 +108,9 @@ export function getCellGeometry(
108
108
  width: number,
109
109
  height: number,
110
110
  pixelRatio = 1,
111
+ // false: fixed cells even when they overflow the viewport. Renderers use it
112
+ // to keep cells mounted until a misfit is confirmed against native layout.
113
+ requireFit = true,
111
114
  ): CellGeometry | null {
112
115
  'worklet';
113
116
  if (
@@ -170,6 +173,7 @@ export function getCellGeometry(
170
173
  return Number.isFinite(requiredWidth) &&
171
174
  Number.isFinite(requiredHeight) &&
172
175
  (geometry.mode !== 'fixed' ||
176
+ !requireFit ||
173
177
  (requiredWidth - width < pixelSize &&
174
178
  requiredHeight - height < pixelSize)) &&
175
179
  Number.isFinite(cellWidth) &&
@@ -0,0 +1,65 @@
1
+ export type ViewSize = { width: number; height: number };
2
+
3
+ type MeasurableHost = {
4
+ measureLayout(
5
+ relativeTo: unknown,
6
+ onSuccess: (x: number, y: number, width: number, height: number) => void,
7
+ onFail?: () => void,
8
+ ): void;
9
+ getNativeScrollRef?(): unknown;
10
+ };
11
+
12
+ function hostOf(instance: unknown): MeasurableHost | null {
13
+ const candidate = instance as Partial<MeasurableHost> | null | undefined;
14
+ const host =
15
+ typeof candidate?.getNativeScrollRef === 'function'
16
+ ? (candidate.getNativeScrollRef() as Partial<MeasurableHost> | null)
17
+ : candidate;
18
+ return host && typeof host.measureLayout === 'function'
19
+ ? (host as MeasurableHost)
20
+ : null;
21
+ }
22
+
23
+ /**
24
+ * The size the latest React commit gave a host view, read from a layout
25
+ * effect. Fabric commits and lays out the shadow tree before layout effects
26
+ * run and answers a self-relative `measureLayout` synchronously, with the
27
+ * same untransformed frame that onLayout later reports. Props that change in
28
+ * the same commit as the view size can therefore be validated against that
29
+ * size instead of the previous onLayout event.
30
+ *
31
+ * Returns null when no answer arrives synchronously or the view has no
32
+ * layout (unmounted, `display: 'none'`, a renderer without the API); callers
33
+ * keep their onLayout size then.
34
+ */
35
+ export function readCommittedSize(instance: unknown): ViewSize | null {
36
+ const host = hostOf(instance);
37
+ if (!host) return null;
38
+ let size = null as ViewSize | null;
39
+ try {
40
+ host.measureLayout(
41
+ host,
42
+ (_x, _y, width, height) => {
43
+ size = { width, height };
44
+ },
45
+ () => {},
46
+ );
47
+ } catch {
48
+ return null;
49
+ }
50
+ // An answer that arrives after this returns is ignored.
51
+ const result = size;
52
+ return result &&
53
+ Number.isFinite(result.width) &&
54
+ Number.isFinite(result.height) &&
55
+ result.width >= 0 &&
56
+ result.height >= 0
57
+ ? result
58
+ : null;
59
+ }
60
+
61
+ export function sameViewSize(a: ViewSize | null, b: ViewSize | null): boolean {
62
+ return (
63
+ a === b || (!!a && !!b && a.width === b.width && a.height === b.height)
64
+ );
65
+ }