torch-glare 2.4.4 → 2.5.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 (147) hide show
  1. package/apps/lib/components/DataViews/{badgeAdapter.ts → badge.ts} +2 -2
  2. package/apps/lib/components/DataViews/cell.tsx +324 -0
  3. package/apps/lib/components/DataViews/context.ts +144 -0
  4. package/apps/lib/components/DataViews/data-views.tsx +383 -0
  5. package/apps/lib/components/DataViews/filters/children.tsx +98 -0
  6. package/apps/lib/components/DataViews/filters/custom.tsx +34 -0
  7. package/apps/lib/components/DataViews/filters/filters.tsx +163 -0
  8. package/apps/lib/components/DataViews/filters/index.ts +4 -0
  9. package/apps/lib/components/DataViews/filters/labelled.tsx +20 -0
  10. package/apps/lib/components/DataViews/filters/presets.tsx +65 -0
  11. package/apps/lib/components/DataViews/filters/summary.tsx +65 -0
  12. package/apps/lib/components/DataViews/filters/sync.tsx +35 -0
  13. package/apps/lib/components/DataViews/filters/values.ts +173 -0
  14. package/apps/lib/components/DataViews/header.tsx +217 -0
  15. package/apps/lib/components/DataViews/hooks/index.ts +5 -0
  16. package/apps/lib/components/DataViews/hooks/useActiveRow.ts +22 -0
  17. package/apps/lib/components/DataViews/hooks/useControllable.ts +52 -0
  18. package/apps/lib/components/DataViews/index.ts +74 -26
  19. package/apps/lib/components/DataViews/panel/columns.tsx +153 -0
  20. package/apps/lib/components/DataViews/panel/controls.tsx +106 -0
  21. package/apps/lib/components/DataViews/panel/index.ts +3 -0
  22. package/apps/lib/components/DataViews/panel/panel.tsx +164 -0
  23. package/apps/lib/components/DataViews/panel/saved-views.tsx +67 -0
  24. package/apps/lib/components/DataViews/panel/section.tsx +79 -0
  25. package/apps/lib/components/DataViews/panel/sort.tsx +42 -0
  26. package/apps/lib/components/DataViews/panel/tab.tsx +31 -0
  27. package/apps/lib/components/DataViews/slots.ts +63 -0
  28. package/apps/lib/components/DataViews/states.tsx +38 -0
  29. package/apps/lib/components/DataViews/types.ts +485 -178
  30. package/apps/lib/components/DataViews/views/board-view.tsx +379 -0
  31. package/apps/lib/components/DataViews/views/card-rows.tsx +36 -0
  32. package/apps/lib/components/DataViews/views/inbox-view.tsx +257 -0
  33. package/apps/lib/components/DataViews/views/pane-views.tsx +192 -0
  34. package/apps/lib/components/DataViews/views/table-view.tsx +426 -0
  35. package/apps/lib/components/DataViews/views/tree-view.tsx +365 -0
  36. package/apps/lib/components/FormBuilder/context.ts +20 -6
  37. package/apps/lib/components/FormBuilder/field-kind.ts +28 -0
  38. package/apps/lib/components/FormBuilder/fields/DateField.tsx +3 -3
  39. package/apps/lib/components/FormBuilder/fields/FieldShell.tsx +7 -6
  40. package/apps/lib/components/FormBuilder/fields/PhoneField.tsx +30 -4
  41. package/apps/lib/components/FormBuilder/fields/SelectField.tsx +7 -7
  42. package/apps/lib/components/FormBuilder/fields/TableField.tsx +80 -52
  43. package/apps/lib/components/FormBuilder/fields/TextField.tsx +9 -9
  44. package/apps/lib/components/FormBuilder/form-builder.tsx +66 -6
  45. package/apps/lib/components/FormBuilder/index.ts +3 -1
  46. package/apps/lib/components/FormBuilder/types.ts +40 -0
  47. package/apps/lib/components/Input.tsx +3 -0
  48. package/apps/lib/components/SearchableTable.tsx +5 -4
  49. package/apps/lib/components/SectionBlock.tsx +58 -11
  50. package/apps/lib/components/Select.tsx +3 -1
  51. package/apps/lib/components/TabSwitch.tsx +16 -4
  52. package/apps/lib/components/Table.tsx +265 -67
  53. package/apps/lib/components/TreeFolder/TreeFolder.tsx +6 -3
  54. package/apps/lib/components/TreeFolder/TreeFolderRow.tsx +16 -14
  55. package/apps/lib/components/TreeFolder/index.ts +1 -1
  56. package/apps/lib/components/TreeFolder/useTreeFolderDnD.ts +70 -207
  57. package/apps/lib/hooks/useDragDrop.tsx +365 -0
  58. package/apps/lib/hooks/useInfiniteScroll.ts +108 -0
  59. package/apps/lib/registry.json +159 -4
  60. package/apps/lib/tsconfig.tsbuildinfo +1 -1
  61. package/apps/lib/utils/dataViews/path.ts +67 -0
  62. package/apps/lib/utils/dataViews/query.ts +73 -0
  63. package/apps/lib/utils/dataViews/types.ts +187 -0
  64. package/docs/components/breadcrumb.md +1 -1
  65. package/docs/components/button-group.md +1 -1
  66. package/docs/components/button.md +1 -1
  67. package/docs/components/card.md +1 -1
  68. package/docs/components/checkbox.md +1 -1
  69. package/docs/components/data-views/backend-response.md +324 -0
  70. package/docs/components/data-views/examples/a11y-rtl.md +250 -0
  71. package/docs/components/data-views/examples/api-orders-route.md +130 -0
  72. package/docs/components/data-views/examples/fields.md +362 -0
  73. package/docs/components/data-views/examples/filters.md +308 -0
  74. package/docs/components/data-views/examples/inbox-routing.md +218 -0
  75. package/docs/components/data-views/examples/index.md +29 -0
  76. package/docs/components/data-views/examples/overview.md +244 -0
  77. package/docs/components/data-views/examples/panel.md +212 -0
  78. package/docs/components/data-views/examples/scale.md +231 -0
  79. package/docs/components/data-views/examples/server-side.md +210 -0
  80. package/docs/components/data-views/examples/state.md +250 -0
  81. package/docs/components/data-views/examples/tree-custom.md +388 -0
  82. package/docs/components/data-views/examples/view-registry.md +313 -0
  83. package/docs/components/data-views/examples/views.md +534 -0
  84. package/docs/components/data-views/guide.md +405 -0
  85. package/docs/components/data-views/index.md +1504 -0
  86. package/docs/components/data-views/migration.md +79 -0
  87. package/docs/components/date-picker.md +0 -1
  88. package/docs/components/form-builder.md +19 -8
  89. package/docs/components/form-renderer.md +2 -1
  90. package/docs/components/form.md +1 -1
  91. package/docs/components/input-field.md +1 -1
  92. package/docs/components/input-otp.md +1 -1
  93. package/docs/components/input.md +1 -1
  94. package/docs/components/labeled-check-box.md +1 -1
  95. package/docs/components/labeled-radio.md +1 -1
  96. package/docs/components/radio-card.md +1 -1
  97. package/docs/components/radio.md +1 -1
  98. package/docs/components/search-field.md +1 -1
  99. package/docs/components/section-block.md +79 -3
  100. package/docs/components/select.md +1 -1
  101. package/docs/components/simple-select.md +1 -1
  102. package/docs/components/switch.md +1 -1
  103. package/docs/components/tab-switch.md +1 -1
  104. package/docs/components/table.md +45 -8
  105. package/docs/components/text-editor.md +1 -1
  106. package/docs/components/textarea.md +1 -1
  107. package/docs/components/toggle-button.md +1 -1
  108. package/docs/components/toggle.md +1 -1
  109. package/docs/components/tree-folder.md +110 -0
  110. package/docs/how-to/forms-with-form-builder.md +6 -4
  111. package/docs/reference/components.md +16 -6
  112. package/docs/tutorials/component-composition.md +11 -13
  113. package/package.json +3 -2
  114. package/apps/lib/components/DataViews/DataViewRadio.tsx +0 -49
  115. package/apps/lib/components/DataViews/DataViewsConfigPanel.tsx +0 -393
  116. package/apps/lib/components/DataViews/DataViewsHeader.tsx +0 -207
  117. package/apps/lib/components/DataViews/DataViewsLayout.tsx +0 -332
  118. package/apps/lib/components/DataViews/FilterPanel.tsx +0 -493
  119. package/apps/lib/components/DataViews/HeaderSearch.tsx +0 -93
  120. package/apps/lib/components/DataViews/InboxView.tsx +0 -463
  121. package/apps/lib/components/DataViews/InboxViewCard.tsx +0 -127
  122. package/apps/lib/components/DataViews/KanbanView.tsx +0 -336
  123. package/apps/lib/components/DataViews/PanelControls.tsx +0 -39
  124. package/apps/lib/components/DataViews/SettingsPanel.tsx +0 -279
  125. package/apps/lib/components/DataViews/TableView.tsx +0 -212
  126. package/apps/lib/components/DataViews/TreeView.tsx +0 -364
  127. package/apps/lib/components/DataViews/fieldRenderers.tsx +0 -299
  128. package/apps/lib/components/DataViews/filters/DatePickerRangeFilter.tsx +0 -87
  129. package/apps/lib/components/DataViews/filters/DateRangePopover.tsx +0 -120
  130. package/apps/lib/components/DataViews/filters/PresetChips.tsx +0 -45
  131. package/apps/lib/components/DataViews/filters/RangeSliderWithInputs.tsx +0 -165
  132. package/apps/lib/components/DataViews/tree/TreeDrawer.tsx +0 -50
  133. package/apps/lib/components/DataViews/tree/TreeSidebar.tsx +0 -74
  134. package/apps/lib/hooks/useDataViewsState.ts +0 -175
  135. package/apps/lib/utils/dataViews/columnUtils.ts +0 -132
  136. package/apps/lib/utils/dataViews/fieldUtils.ts +0 -197
  137. package/apps/lib/utils/dataViews/nestedDataUtils.tsx +0 -371
  138. package/apps/lib/utils/dataViews/pathUtils.ts +0 -139
  139. package/apps/lib/utils/dataViews/rangeUtils.ts +0 -234
  140. package/apps/lib/utils/dataViews/treeUtils.ts +0 -396
  141. package/docs/components/data-views-config-panel.md +0 -208
  142. package/docs/components/data-views-layout.md +0 -291
  143. package/docs/components/inbox-view.md +0 -170
  144. package/docs/components/kanban-view.md +0 -135
  145. package/docs/components/table-view.md +0 -141
  146. package/docs/components/tree-view.md +0 -147
  147. package/docs/how-to/data-views-from-backend-response.md +0 -194
@@ -1,25 +1,16 @@
1
1
  "use client";
2
2
 
3
- import { useCallback, useEffect, useRef, useState } from "react";
3
+ import { useCallback, useMemo } from "react";
4
+ import { useDragDrop, type DragMove } from "../../hooks/useDragDrop";
4
5
  import { isAncestor } from "./treeFolderUtils";
5
- import type {
6
- TreeFolderDropPosition,
7
- TreeFolderDropTarget,
8
- TreeFolderMoveArgs,
9
- TreeFolderNode,
10
- TreeFolderVisibleRow,
11
- } from "./types";
6
+ import type { TreeFolderDropTarget, TreeFolderMoveArgs, TreeFolderNode } from "./types";
7
+ import type { TreeFolderVisibleRow } from "./types";
12
8
 
13
9
  type RowLookup = Map<string, TreeFolderVisibleRow>;
14
10
 
15
- const SCROLL_EDGE_PX = 32;
16
- const SCROLL_SPEED_PX_PER_FRAME = 8;
17
- const DRAG_DATA_MIME = "application/x-treefolder-ids";
18
-
19
11
  export type UseTreeFolderDnDOptions = {
20
12
  data: TreeFolderNode[];
21
13
  rowsById: RowLookup;
22
- scrollContainerRef: React.RefObject<HTMLDivElement | null>;
23
14
  enabled: boolean;
24
15
  onMove?: (args: TreeFolderMoveArgs) => void;
25
16
  /**
@@ -29,227 +20,99 @@ export type UseTreeFolderDnDOptions = {
29
20
  canDrop?: (args: { dragIds: string[]; parentId: string | null; index: number }) => boolean;
30
21
  };
31
22
 
32
- export type UseTreeFolderDnDResult = {
33
- dragIds: string[];
34
- dropTarget: TreeFolderDropTarget | null;
35
- getRowDragHandlers: (rowId: string) => {
36
- draggable: boolean;
37
- onDragStart: (e: React.DragEvent<HTMLElement>) => void;
38
- onDragEnd: (e: React.DragEvent<HTMLElement>) => void;
39
- onDragOver: (e: React.DragEvent<HTMLElement>) => void;
40
- onDragLeave: (e: React.DragEvent<HTMLElement>) => void;
41
- onDrop: (e: React.DragEvent<HTMLElement>) => void;
42
- };
43
- };
44
-
23
+ /**
24
+ * The tree's drag, expressed as a translation.
25
+ *
26
+ * All this does is turn one `DragMove` — an id, a target row and whether the pointer sat above,
27
+ * on or below it — into the `{dragIds, parentId, index}` a tree move is written in. Picking the
28
+ * item up, following the pointer, deciding which row is underneath, scrolling when the drag nears
29
+ * an edge and answering the keyboard all belong to `useDragDrop`, which every other draggable
30
+ * surface in the library now shares.
31
+ *
32
+ * What stays here is the part only a tree knows: that "inside" means the end of the target's
33
+ * children, that "before" and "after" are indices in the target's parent, and that a branch
34
+ * dropped into its own descendant would detach itself from the root.
35
+ */
45
36
  export function useTreeFolderDnD({
46
37
  data,
47
38
  rowsById,
48
- scrollContainerRef,
49
39
  enabled,
50
40
  onMove,
51
41
  canDrop,
52
- }: UseTreeFolderDnDOptions): UseTreeFolderDnDResult {
53
- const [dragIds, setDragIds] = useState<string[]>([]);
54
- const [dropTarget, setDropTarget] = useState<TreeFolderDropTarget | null>(null);
55
-
56
- // Auto-scroll loop while the user is dragging near a container edge.
57
- const autoScrollDeltaRef = useRef(0);
58
- const autoScrollRafRef = useRef<number | null>(null);
59
-
60
- const stopAutoScroll = useCallback(() => {
61
- autoScrollDeltaRef.current = 0;
62
- if (autoScrollRafRef.current != null) {
63
- cancelAnimationFrame(autoScrollRafRef.current);
64
- autoScrollRafRef.current = null;
65
- }
66
- }, []);
67
-
68
- const tickAutoScroll = useCallback(() => {
69
- const el = scrollContainerRef.current;
70
- const delta = autoScrollDeltaRef.current;
71
- if (!el || delta === 0) {
72
- autoScrollRafRef.current = null;
73
- return;
74
- }
75
- el.scrollTop += delta;
76
- autoScrollRafRef.current = requestAnimationFrame(tickAutoScroll);
77
- }, [scrollContainerRef]);
78
-
79
- const maybeAutoScroll = useCallback(
80
- (clientY: number) => {
81
- const el = scrollContainerRef.current;
82
- if (!el) return;
83
- const rect = el.getBoundingClientRect();
84
- let delta = 0;
85
- if (clientY - rect.top < SCROLL_EDGE_PX) delta = -SCROLL_SPEED_PX_PER_FRAME;
86
- else if (rect.bottom - clientY < SCROLL_EDGE_PX) delta = SCROLL_SPEED_PX_PER_FRAME;
87
- autoScrollDeltaRef.current = delta;
88
- if (delta !== 0 && autoScrollRafRef.current == null) {
89
- autoScrollRafRef.current = requestAnimationFrame(tickAutoScroll);
90
- } else if (delta === 0) {
91
- stopAutoScroll();
92
- }
93
- },
94
- [scrollContainerRef, stopAutoScroll, tickAutoScroll],
95
- );
96
-
97
- useEffect(() => stopAutoScroll, [stopAutoScroll]);
98
-
99
- const computePosition = useCallback(
100
- (target: HTMLElement, clientY: number, isInternal: boolean): TreeFolderDropPosition => {
101
- const rect = target.getBoundingClientRect();
102
- const offset = clientY - rect.top;
103
- const ratio = offset / rect.height;
104
- // Leaves can't accept "inside" drops — squash that zone into before/after.
105
- if (!isInternal) return ratio < 0.5 ? "before" : "after";
106
- if (ratio < 0.25) return "before";
107
- if (ratio > 0.75) return "after";
108
- return "inside";
109
- },
110
- [],
42
+ }: UseTreeFolderDnDOptions) {
43
+ /** A row can only take children if it is a folder; a file's middle band is not a drop zone. */
44
+ const canNestInto = useCallback(
45
+ (id: string) => rowsById.get(id)?.isInternal ?? false,
46
+ [rowsById],
111
47
  );
112
48
 
113
- const resolveMoveArgs = useCallback(
114
- (drag: string[], drop: TreeFolderDropTarget): TreeFolderMoveArgs | null => {
115
- const targetRow = rowsById.get(drop.rowId);
49
+ /** `{row, position}` → `{parentId, index}`, or null if the move is impossible or pointless. */
50
+ const resolve = useCallback(
51
+ (dragIds: string[], move: DragMove): TreeFolderMoveArgs | null => {
52
+ const targetRow = move.to ? rowsById.get(move.to) : undefined;
116
53
  if (!targetRow) return null;
117
54
 
118
- let parentId: string | null;
119
- let index: number;
120
-
121
- if (drop.position === "inside") {
122
- parentId = targetRow.node.id;
123
- // Drop at the end of the target's children.
124
- index = targetRow.node.children?.length ?? 0;
125
- } else {
126
- parentId = targetRow.parentId;
127
- index = drop.position === "before" ? targetRow.childIndex : targetRow.childIndex + 1;
128
- }
129
-
130
- // Reject: dropping into self or any descendant.
131
- for (const id of drag) {
55
+ const position = move.position ?? "after";
56
+ const parentId = position === "inside" ? targetRow.node.id : targetRow.parentId;
57
+ const index =
58
+ position === "inside"
59
+ ? // Dropped onto a folder: land at the end of what it already holds.
60
+ (targetRow.node.children?.length ?? 0)
61
+ : position === "before"
62
+ ? targetRow.childIndex
63
+ : targetRow.childIndex + 1;
64
+
65
+ // A node cannot become its own descendant's child — that severs the branch from the root.
66
+ for (const id of dragIds) {
132
67
  const node = rowsById.get(id)?.node;
133
68
  if (!node) continue;
134
69
  if (parentId && (node.id === parentId || isAncestor(node, parentId))) return null;
135
70
  }
136
71
 
137
- if (canDrop && !canDrop({ dragIds: drag, parentId, index })) return null;
72
+ if (canDrop && !canDrop({ dragIds, parentId, index })) return null;
138
73
 
139
- // No-op safety: skipping the equivalent of "drop where you already are".
140
- if (drag.length === 1) {
141
- const onlyDrag = rowsById.get(drag[0]);
74
+ // "Drop where you already are" is not a move; reporting it would churn the caller's data.
75
+ if (dragIds.length === 1) {
76
+ const only = rowsById.get(dragIds[0]);
142
77
  if (
143
- onlyDrag &&
144
- onlyDrag.parentId === parentId &&
145
- (onlyDrag.childIndex === index || onlyDrag.childIndex + 1 === index)
78
+ only &&
79
+ only.parentId === parentId &&
80
+ (only.childIndex === index || only.childIndex + 1 === index)
146
81
  ) {
147
82
  return null;
148
83
  }
149
84
  }
150
85
 
151
- return { dragIds: drag, parentId, index };
86
+ return { dragIds, parentId, index };
152
87
  },
153
88
  [rowsById, canDrop],
154
89
  );
155
90
 
156
- const getRowDragHandlers = useCallback(
157
- (rowId: string) => {
158
- if (!enabled) {
159
- return {
160
- draggable: false,
161
- onDragStart: () => {},
162
- onDragEnd: () => {},
163
- onDragOver: () => {},
164
- onDragLeave: () => {},
165
- onDrop: () => {},
166
- };
167
- }
168
- return {
169
- draggable: true,
170
- onDragStart: (e: React.DragEvent<HTMLElement>) => {
171
- const ids = [rowId];
172
- setDragIds(ids);
173
- e.dataTransfer.effectAllowed = "move";
174
- try {
175
- e.dataTransfer.setData(DRAG_DATA_MIME, ids.join(","));
176
- // Required for Firefox to initiate the drag at all.
177
- e.dataTransfer.setData("text/plain", ids.join(","));
178
- } catch {
179
- // setData can throw in some sandboxed contexts; ignore.
180
- }
181
- },
182
- onDragEnd: () => {
183
- setDragIds([]);
184
- setDropTarget(null);
185
- stopAutoScroll();
186
- },
187
- onDragOver: (e: React.DragEvent<HTMLElement>) => {
188
- if (dragIds.length === 0) return;
189
- // Reject self-drops upfront so the cursor reflects "no drop" outside the tree.
190
- if (dragIds.includes(rowId)) {
191
- e.dataTransfer.dropEffect = "none";
192
- return;
193
- }
194
- const row = rowsById.get(rowId);
195
- if (!row) return;
196
- // Reject dropping onto a descendant of any dragged node.
197
- for (const dragId of dragIds) {
198
- const dragNode = rowsById.get(dragId)?.node;
199
- if (dragNode && isAncestor(dragNode, rowId)) {
200
- e.dataTransfer.dropEffect = "none";
201
- return;
202
- }
203
- }
204
- e.preventDefault();
205
- e.dataTransfer.dropEffect = "move";
206
- const position = computePosition(e.currentTarget, e.clientY, row.isInternal);
207
- // Only setState when something actually changed (avoids re-render storms).
208
- setDropTarget((prev) =>
209
- prev && prev.rowId === rowId && prev.position === position ? prev : { rowId, position },
210
- );
211
- maybeAutoScroll(e.clientY);
212
- },
213
- onDragLeave: () => {
214
- // No-op: onDragOver on the next row will overwrite dropTarget. Clearing
215
- // here would flicker the indicator during normal row-to-row hovering.
216
- },
217
- onDrop: (e: React.DragEvent<HTMLElement>) => {
218
- if (dragIds.length === 0) return;
219
- e.preventDefault();
220
- const row = rowsById.get(rowId);
221
- if (!row) {
222
- setDragIds([]);
223
- setDropTarget(null);
224
- stopAutoScroll();
225
- return;
226
- }
227
- const position = computePosition(e.currentTarget, e.clientY, row.isInternal);
228
- const moveArgs = resolveMoveArgs(dragIds, { rowId, position });
229
- if (moveArgs) onMove?.(moveArgs);
230
- setDragIds([]);
231
- setDropTarget(null);
232
- stopAutoScroll();
233
- },
234
- };
91
+ const { contextProps, activeId, overId, position } = useDragDrop({
92
+ mode: "tree",
93
+ disabled: !enabled,
94
+ canNestInto,
95
+ onMove: (move) => {
96
+ const args = resolve([move.id], move);
97
+ if (args) onMove?.(args);
235
98
  },
236
- [
237
- enabled,
238
- dragIds,
239
- rowsById,
240
- computePosition,
241
- resolveMoveArgs,
242
- onMove,
243
- maybeAutoScroll,
244
- stopAutoScroll,
245
- ],
246
- );
99
+ });
100
+
101
+ /**
102
+ * Kept as a list because a move is defined over a set of nodes: a tree that gains multi-select
103
+ * drag changes what fills this, and nothing downstream — the guard, the resolver, `onMove` — has
104
+ * to change with it.
105
+ */
106
+ const dragIds = useMemo(() => (activeId ? [activeId] : []), [activeId]);
107
+
108
+ /** Where the indicator is painted. Null while nothing is over a valid row. */
109
+ const dropTarget: TreeFolderDropTarget | null =
110
+ activeId && overId && position && overId !== activeId
111
+ ? { rowId: overId, position }
112
+ : null;
247
113
 
248
- // If the data tree changes mid-drag, clear stale targets.
249
- useEffect(() => {
250
- if (dragIds.length === 0) return;
251
- setDropTarget((prev) => (prev && rowsById.has(prev.rowId) ? prev : null));
252
- }, [data, rowsById, dragIds.length]);
114
+ /** The rows the tree can drop on, in painted order — `data` is what changes them. */
115
+ const ids = useMemo(() => [...rowsById.keys()], [rowsById, data]); // eslint-disable-line react-hooks/exhaustive-deps
253
116
 
254
- return { dragIds, dropTarget, getRowDragHandlers };
117
+ return { dragIds, dropTarget, contextProps, ids, enabled };
255
118
  }
@@ -0,0 +1,365 @@
1
+ "use client";
2
+
3
+ import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
4
+ import {
5
+ DndContext,
6
+ DragOverlay,
7
+ useDroppable,
8
+ KeyboardSensor,
9
+ MouseSensor,
10
+ TouchSensor,
11
+ closestCenter,
12
+ closestCorners,
13
+ useSensor,
14
+ useSensors,
15
+ type DragEndEvent,
16
+ type DragMoveEvent,
17
+ type DragOverEvent,
18
+ type DragStartEvent,
19
+ } from "@dnd-kit/core";
20
+ import {
21
+ SortableContext,
22
+ sortableKeyboardCoordinates,
23
+ useSortable,
24
+ verticalListSortingStrategy,
25
+ } from "@dnd-kit/sortable";
26
+ import { CSS } from "@dnd-kit/utilities";
27
+
28
+ /**
29
+ * Drag and drop, once, for every surface that needs it.
30
+ *
31
+ * It exists because the same thing was written three times — the board, the config rail's column
32
+ * list and the tree each had their own — all three on the **HTML5 drag and drop API**, which
33
+ * mobile browsers do not drive from touch. A finger never fires `dragstart`, so on a phone none of
34
+ * it worked at all, and there was no keyboard path either.
35
+ *
36
+ * This is built on `@dnd-kit`, already used by `DataTable` and `FormBuilder.Table`. Its pointer
37
+ * sensor speaks Pointer Events, which cover mouse, touch and pen alike, and its keyboard sensor
38
+ * makes a drag reachable without a pointing device.
39
+ *
40
+ * The hook does not move anything. It reports a `DragMove` and the caller decides — the same
41
+ * contract the rest of DataViews keeps, and the reason a failed save leaves the UI showing the
42
+ * truth rather than a lie.
43
+ */
44
+
45
+ // Re-exported so a surface can render the provider without also importing @dnd-kit directly —
46
+ // the point of this file is that it is the only place that does.
47
+ export { DndContext };
48
+
49
+ /**
50
+ * The thing that follows the pointer.
51
+ *
52
+ * A list does not need one: its items slide apart, so the gap says where the drop will land. A
53
+ * board does. Once a card is dragged over a *different* column, dnd-kit stops transforming it —
54
+ * it has left the list that was arranging it — and without an overlay the card just sits faded in
55
+ * its old column while the pointer moves off alone.
56
+ *
57
+ * Render whatever the item looks like inside; it is drawn above everything, at the pointer.
58
+ */
59
+ export function DragGhost({ children }: { children: ReactNode }) {
60
+ return (
61
+ <DragOverlay dropAnimation={null}>
62
+ {children ? <div data-dnd-overlay>{children}</div> : null}
63
+ </DragOverlay>
64
+ );
65
+ }
66
+
67
+ export type DropPosition = "before" | "inside" | "after";
68
+
69
+ export interface DragMove {
70
+ /** The item being dragged. */
71
+ id: string;
72
+ /** The container it started in. `null` for a flat list, which has only one. */
73
+ from: string | null;
74
+ /** The container it was dropped on. */
75
+ to: string | null;
76
+ /** Its position within `to`, when the surface has an order. */
77
+ index?: number;
78
+ /** Trees only: dropped above the target, into it, or below it. */
79
+ position?: DropPosition;
80
+ }
81
+
82
+ export type DragMode =
83
+ /** Items move between containers — a kanban board. */
84
+ | "board"
85
+ /** One ordered list — the column rail, table rows. */
86
+ | "list"
87
+ /** A hierarchy, where a drop can also mean "inside". */
88
+ | "tree";
89
+
90
+ export interface UseDragDropOptions {
91
+ mode: DragMode;
92
+ /** Called on drop. Nothing has moved yet; that is your job. */
93
+ onMove: (move: DragMove) => void;
94
+ disabled?: boolean;
95
+ /**
96
+ * Veto a drop before it is reported — a tree uses this to refuse a node dropped into its own
97
+ * descendant, which would detach the branch from the root.
98
+ */
99
+ canDrop?: (move: DragMove) => boolean;
100
+ /**
101
+ * Which container an item currently belongs to. Board mode needs it to report `from`, since the
102
+ * drop target only knows where the item landed.
103
+ */
104
+ containerOf?: (id: string) => string | null;
105
+ /** Where in `to` the item landed. Supplied by the caller, which knows its own ordering. */
106
+ indexOf?: (id: string) => number;
107
+ /**
108
+ * Tree mode: can this row hold children? A leaf has no inside, so its middle band collapses and
109
+ * the whole row reads as before-or-after — otherwise a drop on a file would silently do nothing.
110
+ */
111
+ canNestInto?: (id: string) => boolean;
112
+ }
113
+
114
+ /** How far the mouse travels before a press becomes a drag, so a click stays a click. */
115
+ const MOUSE_DISTANCE = 8;
116
+
117
+ /**
118
+ * Touch is deliberately *not* handled by the pointer sensor.
119
+ *
120
+ * A finger has one gesture for two intentions: dragging an item and scrolling the list it is in.
121
+ * A distance threshold cannot separate them — whichever wins, the other becomes impossible. So
122
+ * touch drags start on a long press instead, which is the convention every mobile list uses: hold
123
+ * to pick up, swipe to scroll.
124
+ *
125
+ * `tolerance` is how far the finger may wander during the hold before it is treated as a scroll
126
+ * rather than an impatient drag.
127
+ */
128
+ const TOUCH_DELAY_MS = 200;
129
+ const TOUCH_TOLERANCE = 8;
130
+
131
+ /** Within this fraction of a row's top or bottom edge, a tree drop means "beside", not "into". */
132
+ const EDGE_BAND = 0.25;
133
+
134
+ /**
135
+ * Where the pointer is, in viewport coordinates.
136
+ *
137
+ * dnd-kit reports a *delta* from wherever the drag was activated, so the absolute position is the
138
+ * activator plus that delta. A touch activator carries its coordinates on `touches`, a keyboard
139
+ * activator carries none at all — hence the null, which the caller reads as "aim at the middle".
140
+ */
141
+ function pointerY(activator: Event | null, delta: number): number | null {
142
+ const e = activator as (MouseEvent & TouchEvent) | null;
143
+ const start = e?.clientY ?? e?.touches?.[0]?.clientY;
144
+ return typeof start === "number" ? start + delta : null;
145
+ }
146
+
147
+ /**
148
+ * `CSS.escape`, reached through `window` because `CSS` in this file is dnd-kit's transform helper.
149
+ * The fallback covers environments without it (jsdom, older Safari).
150
+ */
151
+ const escapeId = (v: string) =>
152
+ typeof window !== "undefined" && window.CSS?.escape
153
+ ? window.CSS.escape(v)
154
+ : v.replace(/["\\]/g, "\\$&");
155
+
156
+ export function useDragDrop({
157
+ mode,
158
+ onMove,
159
+ disabled = false,
160
+ canDrop,
161
+ containerOf,
162
+ indexOf,
163
+ canNestInto,
164
+ }: UseDragDropOptions) {
165
+ const [activeId, setActiveId] = useState<string | null>(null);
166
+ const [overId, setOverId] = useState<string | null>(null);
167
+ const [position, setPosition] = useState<DropPosition | null>(null);
168
+ // The state paints the drop indicator; the ref is what the drop itself reads. See `onDragEnd`.
169
+ const positionRef = useRef<DropPosition | null>(null);
170
+ const setPositionState = useCallback((next: DropPosition | null) => {
171
+ positionRef.current = next;
172
+ setPosition((prev) => (prev === next ? prev : next));
173
+ }, []);
174
+
175
+ const sensors = useSensors(
176
+ useSensor(MouseSensor, { activationConstraint: { distance: MOUSE_DISTANCE } }),
177
+ useSensor(TouchSensor, {
178
+ activationConstraint: { delay: TOUCH_DELAY_MS, tolerance: TOUCH_TOLERANCE },
179
+ }),
180
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
181
+ );
182
+
183
+ const onDragStart = useCallback((event: DragStartEvent) => {
184
+ setActiveId(String(event.active.id));
185
+ }, []);
186
+
187
+ const onDragOver = useCallback((event: DragOverEvent) => {
188
+ setOverId(event.over ? String(event.over.id) : null);
189
+ }, []);
190
+
191
+ /**
192
+ * A tree's drop position changes *within* one row — top edge means "before", middle means
193
+ * "inside" — and `onDragOver` fires only when the row underneath changes. So the position is
194
+ * tracked on every move instead.
195
+ */
196
+ const onDragMove = useCallback(
197
+ (event: DragMoveEvent) => {
198
+ if (mode !== "tree") return;
199
+ const over = event.over;
200
+ setOverId(over ? String(over.id) : null);
201
+ if (!over) {
202
+ setPositionState(null);
203
+ return;
204
+ }
205
+ // Measured live off the row itself: dnd-kit's cached rect predates any scrolling the drag
206
+ // has caused, and near a scrolling edge is exactly where a tree drop is hardest to aim.
207
+ const el = document.querySelector(`[data-dnd-item="${escapeId(String(over.id))}"]`);
208
+ const rect = el?.getBoundingClientRect() ?? over.rect;
209
+ const y = pointerY(event.activatorEvent, event.delta.y) ?? rect.top + rect.height / 2;
210
+ const offset = (y - rect.top) / (rect.height || 1);
211
+
212
+ const nests = canNestInto ? canNestInto(String(over.id)) : true;
213
+ setPositionState(
214
+ !nests
215
+ ? offset < 0.5
216
+ ? "before"
217
+ : "after"
218
+ : offset < EDGE_BAND
219
+ ? "before"
220
+ : offset > 1 - EDGE_BAND
221
+ ? "after"
222
+ : "inside",
223
+ );
224
+ },
225
+ [mode, canNestInto, setPositionState],
226
+ );
227
+
228
+ const reset = useCallback(() => {
229
+ setActiveId(null);
230
+ setOverId(null);
231
+ setPositionState(null);
232
+ }, [setPositionState]);
233
+
234
+ const onDragEnd = useCallback(
235
+ (event: DragEndEvent) => {
236
+ const { active, over } = event;
237
+ // Read before resetting: `reset` clears this, and it is the whole answer to "before, inside
238
+ // or after".
239
+ const dropped = positionRef.current;
240
+ reset();
241
+ if (!over) return;
242
+
243
+ const id = String(active.id);
244
+ const to = String(over.id);
245
+ if (id === to && mode !== "list") return;
246
+
247
+ const move: DragMove = {
248
+ id,
249
+ from: containerOf?.(id) ?? null,
250
+ to,
251
+ ...(indexOf ? { index: indexOf(to) } : null),
252
+ // From the ref, not the state: the drop lands in the same tick as the last move, and the
253
+ // handler dnd-kit is holding was built before that move could re-render.
254
+ ...(mode === "tree" && dropped ? { position: dropped } : null),
255
+ };
256
+
257
+ if (canDrop && !canDrop(move)) return;
258
+ onMove(move);
259
+ },
260
+ [canDrop, containerOf, indexOf, mode, onMove, reset],
261
+ );
262
+
263
+ const contextProps = useMemo(
264
+ () => ({
265
+ sensors,
266
+ // A board's columns are large targets, so the *corner* nearest the pointer identifies the
267
+ // intended one better than its centre; a list wants the centre.
268
+ collisionDetection: mode === "board" ? closestCorners : closestCenter,
269
+ onDragStart,
270
+ onDragOver,
271
+ onDragMove,
272
+ onDragEnd,
273
+ onDragCancel: reset,
274
+ }),
275
+ [sensors, mode, onDragStart, onDragOver, onDragMove, onDragEnd, reset],
276
+ );
277
+
278
+ return {
279
+ /** Spread onto `<DndContext>`. */
280
+ contextProps,
281
+ DndContext,
282
+ activeId,
283
+ overId,
284
+ position,
285
+ disabled,
286
+ };
287
+ }
288
+
289
+ /**
290
+ * The ordered part of a surface — a column list, a table body, a tree's visible rows.
291
+ *
292
+ * `ids` must be in the order they are painted; that is how a drop position is worked out.
293
+ *
294
+ * `makeRoom` is the list's answer to "where will this land?". A flat list answers by sliding its
295
+ * items apart to open a gap. A tree cannot: its rows have to stay put for a drop to mean *inside*
296
+ * one of them rather than between two, and the gap would move the very row the pointer is being
297
+ * measured against. It draws an indicator line instead.
298
+ */
299
+ export function DragList({
300
+ ids,
301
+ children,
302
+ makeRoom = true,
303
+ }: {
304
+ ids: string[];
305
+ children: ReactNode;
306
+ makeRoom?: boolean;
307
+ }) {
308
+ return (
309
+ <SortableContext items={ids} strategy={makeRoom ? verticalListSortingStrategy : NO_SHIFT}>
310
+ {children}
311
+ </SortableContext>
312
+ );
313
+ }
314
+
315
+ /** A sorting strategy that moves nothing. */
316
+ const NO_SHIFT = () => null;
317
+
318
+ /**
319
+ * One draggable item.
320
+ *
321
+ * `handleProps` go on whatever should start the drag — spread them on the row for a
322
+ * drag-anywhere feel, or on a grip so the rest of the row stays clickable.
323
+ */
324
+ export function useDragItem(id: string, disabled = false, { follow = true } = {}) {
325
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
326
+ id,
327
+ disabled,
328
+ });
329
+
330
+ // `follow` is whether the item travels with the pointer. A card should — it is the thing being
331
+ // moved and there is nothing else to look at. A tree row should not: the drop indicator is
332
+ // painted on the *target* row, and a ghost sliding over it hides the very answer it is giving.
333
+ const moving = follow ? transform : null;
334
+
335
+ return {
336
+ ref: setNodeRef,
337
+ handleProps: {
338
+ ...attributes,
339
+ ...listeners,
340
+ // A stable hook for styling and for tests. dnd-kit sets no `draggable` attribute — it
341
+ // works on pointer events — so there is otherwise nothing in the DOM saying "this drags".
342
+ "data-dnd-item": id,
343
+ },
344
+ style: {
345
+ transform: CSS.Transform.toString(moving),
346
+ transition: follow ? transition : undefined,
347
+ // `manipulation` keeps panning and scrolling working while suppressing the double-tap
348
+ // zoom delay. `none` would kill scrolling on the item entirely, which is the usual
349
+ // mistake — the long-press constraint above is what separates drag from scroll.
350
+ touchAction: "manipulation" as const,
351
+ },
352
+ isDragging,
353
+ };
354
+ }
355
+
356
+ /**
357
+ * A container an item can be dropped into — one board column.
358
+ *
359
+ * A list does not need this: its items are their own drop targets. A board does, or dropping on
360
+ * an empty column would have nothing to hit.
361
+ */
362
+ export function useDropContainer(id: string, disabled = false) {
363
+ const { setNodeRef, isOver } = useDroppable({ id, disabled });
364
+ return { ref: setNodeRef, isOver, containerProps: { "data-dnd-container": id } };
365
+ }