"use client"; import { type CollisionDetection, closestCenter, DndContext, type DragEndEvent, type DragMoveEvent, type DragOverEvent, DragOverlay, type DragStartEvent, type DropAnimation, getClientRect, getFirstCollision, KeyboardSensor, MeasuringStrategy, PointerSensor, pointerWithin, rectIntersection, type UniqueIdentifier, useDroppable, useSensor, useSensors, } from "@dnd-kit/core"; import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { Button } from "@suphark/ui/components/shared/button/button"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { hotkeyKeyOf } from "@suphark/ui/hooks/use-hotkeys"; import { useMounted } from "@suphark/ui/hooks/use-mounted"; import { errorMessage } from "@suphark/ui/lib/action-result"; import { flatItems, gatherItems, groupOfItem, moveItemToGroup, moveItemToRoot, moveRootEntry, reorderItems, rootEntries, type SortableOrder, sameOrder, UNGROUPED, } from "@suphark/ui/lib/sortable-order"; import { cn } from "@suphark/ui/lib/utils"; import { GripVerticalIcon } from "lucide-react"; import { type CSSProperties, createContext, type KeyboardEvent, type MouseEvent, type ReactNode, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, } from "react"; import { createPortal } from "react-dom"; import { toast } from "sonner"; export type SortableKind = "group" | "item"; // id ของ dnd-kit ต้องไม่ชนกันข้ามชนิด: กลุ่ม / รายการ / หัวกลุ่มที่ใช้เป็นที่วาง const dndId = (kind: SortableKind | "zone", id: string) => `${kind === "group" ? "g" : kind === "item" ? "i" : "z"}:${id}`; const kindOf = (id: UniqueIdentifier) => String(id).slice(0, 1); const rawOf = (id: UniqueIdentifier) => String(id).slice(2); /** ตำแหน่ง y ของเมาส์ตอนนี้ = จุดที่กดเริ่มลาก + ระยะที่ลากมา (คีย์บอร์ด = null) */ function pointerYOf(activator: Event | null, delta: { y: number }): number | null { if (activator && "clientY" in activator && typeof activator.clientY === "number") { return activator.clientY + delta.y; } return null; } /** จังหวะเดียวกันทั้งแถวที่เลื่อนหลบและตอนปล่อย — ease-out สั้น ๆ แบบบอร์ดงาน (Trello/Todoist) */ const EASING = "cubic-bezier(0.25, 1, 0.5, 1)"; const SORT_TRANSITION = { duration: 200, easing: EASING }; const DROP_ANIMATION: DropAnimation = { duration: 200, easing: EASING, // ช่องจาง ๆ ของแถวต้นทางเราใส่ผ่าน style ของ React เองแล้ว — side effect ของ dnd-kit จะจำค่า 0.4 นั้น // ไว้เป็น "ค่าเดิม" แล้วเขียนคืนหลังปล่อย ทำให้แถวจางค้าง (เจอกับหัวกลุ่ม) sideEffects: null, }; /** สิ่งที่กำลังลาก — `ids` = ทุกรายการที่ลากไปด้วยกัน (ลากแบบ bulk; ลากตัวเดียว = `[id]`) */ export interface SortableDrag { kind: SortableKind; id: string; ids: string[]; } type SelectMode = "toggle" | "range" | "all" | "clear"; /** ระยะเลื่อนของหัวกลุ่มแต่ละกลุ่มระหว่างลากกลุ่ม — แถวรายการในกลุ่มอ่านไปเลื่อนตาม (ทั้งก้อนขยับพร้อมกัน) */ interface GroupShift { transform: string | undefined; transition: string | undefined; } function createShiftStore() { const shifts = new Map(); const listeners = new Set<() => void>(); return { get: (id: string) => shifts.get(id), set(id: string, shift: GroupShift | undefined) { const prev = shifts.get(id); if (prev?.transform === shift?.transform && prev?.transition === shift?.transition) return; if (shift) shifts.set(id, shift); else shifts.delete(id); for (const listener of listeners) listener(); }, clear() { if (shifts.size === 0) return; shifts.clear(); for (const listener of listeners) listener(); }, subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; }, }; } type ShiftStore = ReturnType; interface SortableState { /** กำลังลากชนิดไหนอยู่ (null = ไม่ได้ลาก) — ใช้ปิดที่วางของอีกชนิด */ dragging: SortableKind | null; disabled: boolean; handleLabel: string; /** มี `renderOverlay` = แถวต้นทางเป็นที่ว่างจาง ๆ ส่วนของที่ลอยตามเมาส์คือ overlay */ overlay: boolean; /** กลุ่มที่กำลังถูกลาก (แถวรายการของกลุ่มนี้จางตามหัวกลุ่ม) */ activeGroup: string | null; /** กำลังลากของในชั้นบนสุด (กลุ่ม หรือรายการไม่มีกลุ่มเมื่อ `freeLayout`) — ระยะเลื่อนมาจาก provider */ rootDrag: boolean; freeLayout: boolean; /** รายการอื่นที่ลากไปพร้อมกันแบบ bulk (ไม่รวมตัวที่จับ) — แสดงจาง ๆ ระหว่างลาก */ carried: ReadonlySet; multiSelect: boolean; selected: ReadonlySet; select: (id: string, mode: SelectMode) => void; groupOf: (itemId: string) => string | undefined; register: (kind: SortableKind, id: string, node: HTMLElement | null) => void; shifts: ShiftStore; } const EMPTY = new Set(); const SortableStateContext = createContext({ dragging: null, disabled: true, handleLabel: "ลากเพื่อจัดลำดับ", overlay: false, activeGroup: null, rootDrag: false, freeLayout: false, carried: EMPTY, multiSelect: false, selected: EMPTY, select: () => {}, groupOf: () => undefined, register: () => {}, shifts: createShiftStore(), }); /** * สถานะการลากตอนนี้ — ใช้ตัดสินใจเรนเดอร์ที่วางเอง เช่นแถว "ลากมาที่นี่เพื่อเอาออกจากกลุ่ม" * ที่ควรโผล่เฉพาะตอน `dragging === "item"` (กลุ่มที่ไม่มีหัวกลุ่มต้องมีที่วางของตัวเอง) * `selected`/`clearSelection` ใช้ทำแถบ "เลือก N รายการ" เมื่อเปิด `multiSelect` */ export function useSortableState(): { dragging: SortableKind | null; disabled: boolean; selected: string[]; clearSelection: () => void; } { const state = useContext(SortableStateContext); return { dragging: state.dragging, disabled: state.disabled, selected: [...state.selected], clearSelection: () => state.select("", "clear"), }; } /** ข้อมูลของสิ่งที่กำลังลาก ส่งให้แอปประกอบข้อความเอง (แอปรู้ชื่อคีย์/ชื่อกลุ่ม แพ็กเกจไม่รู้) */ export interface SortableAnnouncementContext { id: string; kind: SortableKind; /** กลุ่มที่อยู่ตอนนี้ (เฉพาะ kind = "item") */ groupId?: string; /** ตำแหน่งในกลุ่ม/ในลำดับกลุ่ม เริ่มที่ 1 */ index: number; total: number; /** จำนวนรายการที่ลากไปด้วยกัน (ลากแบบ bulk > 1) */ count: number; } export interface SortableAnnouncements { onDragStart?: (context: SortableAnnouncementContext) => string | undefined; onDragOver?: (context: SortableAnnouncementContext) => string | undefined; onDragEnd?: (context: SortableAnnouncementContext) => string | undefined; onDragCancel?: (context: SortableAnnouncementContext) => string | undefined; } export interface SortableProviderProps { order: SortableOrder; /** ลำดับเปลี่ยนระหว่างลาก (ย้ายข้ามกลุ่ม) และตอนปล่อย — แอปเก็บไว้ใน state ของตัวเอง */ onOrderChange: (order: SortableOrder) => void; /** * บันทึกลำดับใหม่ตอนปล่อย — throw หรือคืน `{ ok: false, error }` = ล้มเหลว * ล้มเหลวแล้ว provider คืนลำดับเดิมให้เองและขึ้น toast (ไม่ต้องจัดการใน call site) */ onCommit?: (order: SortableOrder) => void | Promise; /** ปิดการลากทั้งชุด (เช่นระหว่างค้นหา หรือผู้ใช้ไม่มีสิทธิ์แก้) */ disabled?: boolean; /** aria-label ของที่จับ (ค่าเริ่มต้นจาก `UiText.sortable.handle`) */ handleLabel?: string; /** * `onCommit` ล้มเหลวแล้วทำอะไรต่อ — ไม่ส่ง = ขึ้น toast ข้อความของ error ให้เอง * ส่งมา = แพ็กเกจไม่ขึ้น toast แต่ส่ง error ดิบให้แอปจัดการ (คืนลำดับเดิมให้เสมอทั้งสองทาง) */ onCommitError?: (error: unknown) => void; /** คำอธิบายวิธีลากด้วยคีย์บอร์ด (ไม่ส่ง = `UiText.sortable.instructions`) */ screenReaderInstructions?: string; /** * ข้อความประกาศระหว่างลากสำหรับ screen reader — แอปประกอบเองจากชื่อจริงของข้อมูล * ไม่ส่ง = แม่แบบจาก `UiText.sortable` (`{index}` / `{total}`) */ announcements?: SortableAnnouncements; /** * id ของ `DndContext` — ต้องคงที่ระหว่าง SSR กับ client ไม่งั้น `aria-describedby="DndDescribedBy-N"` * ที่ dnd-kit สร้างจากตัวนับจะไม่ตรงกัน (hydration mismatch ที่ React ไม่ซ่อมให้ → screen reader * ไม่ได้ยินคำอธิบายวิธีลาก) · ไม่ส่ง = `useId()` ซึ่งตรงกันทั้งสองฝั่งอยู่แล้ว · ส่ง id ที่สื่อความหมาย * (เช่น `values-${environmentId}`) ช่วยตอนไล่ปัญหา */ id?: string; /** * สิ่งที่ลอยตามเมาส์ระหว่างลาก (แบบการ์ดใน Trello/Todoist) — ไม่ส่ง = ลากตัวแถวเองเหมือนเดิม * ส่งมา = แถวต้นทางกลายเป็นช่องว่างจาง ๆ บอกตำแหน่งที่จะวาง และมีแอนิเมชันตอนปล่อย * วาดใน portal ที่ `body` จึงคืน `
` ได้แม้รายการจริงเป็นแถว `` ของตาราง */ renderOverlay?: (drag: SortableDrag) => ReactNode; /** * เลือกหลายรายการแล้วลากไปพร้อมกัน: ⌘/Ctrl+คลิก = เลือกทีละตัว, Shift+คลิก = เลือกเป็นช่วง, * คลิกเฉย ๆ = ล้าง · ที่จับ (คีย์บอร์ด): `x` = เลือก/ไม่เลือก, ⌘/Ctrl+A = ทั้งหมด, Esc = ล้าง * แถวต้องกระจาย `selectProps` จาก `useSortableRow` (มี `data-selected` ไว้ทำสีแถวที่เลือก) * ลากตัวที่เลือกอยู่ = ลากทุกตัวที่เลือกไปรวมที่จุดวาง เรียงตามลำดับเดิม */ multiSelect?: boolean; /** * ชั้นบนสุดจัดได้อิสระ: กลุ่มกับรายการที่ไม่มีกลุ่มสลับที่กันได้ทุกแบบ (กลุ่มขึ้นไปเหนือรายการ / * รายการไปอยู่ระหว่างกลุ่ม / เอารายการออกจากกลุ่มไปวางก่อนกลุ่มไหนก็ได้) — แอปต้องเรนเดอร์ตาม * `rootEntries(order)` และบันทึก `sortableOrderToPayload(order).root` · ชี้ครึ่งบนของหัวกลุ่ม = วางก่อนกลุ่ม, * ครึ่งล่าง = เข้ากลุ่มเป็นตัวแรก · ไม่เปิด = รายการไม่มีกลุ่มอยู่บนสุดเสมอ (แบบเดิม) */ freeLayout?: boolean; /** รายการที่เลือก (ควบคุมจากภายนอก) — ไม่ส่ง = provider เก็บเอง */ selected?: string[]; onSelectedChange?: (ids: string[]) => void; children: ReactNode; } /** * บริบทการลากจัดลำดับ 2 ระดับ (กลุ่ม + รายการในกลุ่ม) — ยกสมองส่วนลากออกมาจากแอป * การเรนเดอร์ยังเป็นของแอป (แถวตาราง/การ์ด/รายการ) ผ่าน `useSortableRow` * ย้ายข้ามกลุ่มได้ระหว่างลาก และกลุ่มที่ย่ออยู่ก็ยังรับการวางได้ด้วย `useSortableDropZone` * * * … * */ export function SortableProvider({ order, onOrderChange, onCommit, disabled = false, handleLabel, onCommitError, screenReaderInstructions, announcements, id, renderOverlay, multiSelect = false, freeLayout = false, selected: selectedProp, onSelectedChange, children, }: SortableProviderProps) { const fallbackId = useId(); const text = useUiText(); const mounted = useMounted(); const [dragging, setDragging] = useState(null); const [activeDrag, setActiveDrag] = useState(null); const draggingRef = useRef(null); // รายการที่ลากไปด้วยกันแบบ bulk (รวมตัวที่จับ เรียงตามลำดับที่แสดง) — null = ลากตัวเดียว const bulk = useRef(null); const nodes = useRef({ groups: new Map(), items: new Map(), groupOfNode: new WeakMap(), }); const shifts = useMemo(createShiftStore, []); // กันกระพริบตอนย้ายข้ามกลุ่ม: จำเป้าหมายล่าสุดไว้ใช้ตอนที่ layout กำลังขยับแล้วหาเป้าหมายไม่เจอ const lastOverId = useRef(null); const movedAcross = useRef(false); // เป้าหมายตอนย้ายข้ามกลุ่มครั้งล่าสุด — ตำแหน่งถูกจัดไว้แล้ว (ก่อน/หลังตามครึ่งแถว) ถ้าปล่อยตอนยังชี้ตัวเดิม // ห้าม reorderItems ซ้ำ (arrayMove ไปแทนที่ตัวนั้น = วาง "หลัง" กลายเป็น "ก่อน") const crossedAt = useRef(null); const beforeDrag = useRef(null); // อ่านลำดับล่าสุดตอนปล่อย (onDragOver เปลี่ยนไปหลายรอบแล้ว prop ยังไม่ทัน) const latest = useRef(order); latest.current = order; // ลำดับของการบันทึก — การบันทึกที่ล้มย้อนลำดับได้เฉพาะเมื่อเป็นครั้งล่าสุด const commitSeq = useRef(0); // ---------- เลือกหลายรายการ ---------- const [ownSelected, setOwnSelected] = useState([]); const selectedList = selectedProp ?? ownSelected; const selected = useMemo>(() => { if (!multiSelect || selectedList.length === 0) return EMPTY; const present = new Set(flatItems(order)); return new Set(selectedList.filter((x) => present.has(x))); }, [multiSelect, selectedList, order]); const selectedRef = useRef(selected); selectedRef.current = selected; const anchor = useRef(null); const onSelectedChangeRef = useRef(onSelectedChange); onSelectedChangeRef.current = onSelectedChange; const controlled = selectedProp !== undefined; const setSelected = useCallback( (ids: string[]) => { if (!controlled) setOwnSelected(ids); onSelectedChangeRef.current?.(ids); }, [controlled], ); const select = useCallback( (itemId: string, mode: SelectMode) => { const all = flatItems(latest.current); // เลือกเป็นช่วง/ทั้งหมด = เฉพาะแถวที่แสดงอยู่ (ไม่หยิบของในกลุ่มที่ย่อไว้โดยไม่รู้ตัว) const visible = all.filter((x) => nodes.current.items.get(x)?.isConnected); const current = selectedRef.current; let next: Set; if (mode === "clear") next = new Set(); else if (mode === "all") next = new Set(visible); else if (mode === "toggle") { next = new Set(current); if (next.has(itemId)) next.delete(itemId); else next.add(itemId); anchor.current = itemId; } else { const from = visible.indexOf(anchor.current ?? itemId); const to = visible.indexOf(itemId); next = new Set(current); if (from >= 0 && to >= 0) { for (const x of visible.slice(Math.min(from, to), Math.max(from, to) + 1)) next.add(x); } else next.add(itemId); if (anchor.current === null) anchor.current = itemId; } if (mode === "clear" || mode === "all") anchor.current = null; if (next.size === current.size && [...next].every((x) => current.has(x))) return; setSelected(all.filter((x) => next.has(x))); }, [setSelected], ); // Esc ที่ไหนก็ได้ = ล้างการเลือก (ระหว่างลาก Esc เป็นของการยกเลิกลาก) const hasSelection = selected.size > 0; useEffect(() => { if (!hasSelection) return; function onKey(event: globalThis.KeyboardEvent) { if (event.key === "Escape" && draggingRef.current === null) select("", "clear"); } document.addEventListener("keydown", onKey); return () => document.removeEventListener("keydown", onKey); }, [hasSelection, select]); const register = useCallback((kind: SortableKind, rowId: string, node: HTMLElement | null) => { const map = kind === "group" ? nodes.current.groups : nodes.current.items; if (node) { map.set(rowId, node); if (kind === "group") nodes.current.groupOfNode.set(node, rowId); } else map.delete(rowId); }, []); /** * กรอบของทั้งก้อน: หัวกลุ่ม + แถวรายการที่แสดงอยู่ (ไม่สนใจ transform ระหว่างลาก) * หัวกลุ่มกับแถวรายการต้องเป็นพี่น้องกัน (`` ใน `` เดียวกัน / การ์ดในลิสต์เดียวกัน) * ห้ามให้ node ของกลุ่มครอบแถวรายการไว้ ไม่งั้นกรอบนี้นับซ้ำและแถวลูกจะเลื่อนสองชั้น */ const blockRect = useCallback((groupId: string, header: HTMLElement) => { let { top, bottom, left, right } = getClientRect(header, { ignoreTransform: true }); for (const itemId of latest.current.items[groupId] ?? []) { const node = nodes.current.items.get(itemId); if (!node?.isConnected) continue; const r = getClientRect(node, { ignoreTransform: true }); top = Math.min(top, r.top); bottom = Math.max(bottom, r.bottom); left = Math.min(left, r.left); right = Math.max(right, r.right); } return { top, bottom, left, right, width: right - left, height: bottom - top }; }, []); /** * ขนาดของที่วางตอนลากกลุ่ม = หัวกลุ่ม "รวมแถวรายการของกลุ่มนั้น" ทั้งก้อน * (เดิมวัดแค่หัวกลุ่ม กลุ่มอื่นจึงเลื่อนหลบแค่ความสูงหัวกลุ่มเดียว แถวรายการไม่ขยับ) */ const measureDroppable = useCallback( (element: HTMLElement) => { const groupId = draggingRef.current === "group" ? nodes.current.groupOfNode.get(element) : undefined; return groupId ? blockRect(groupId, element) : getClientRect(element, { ignoreTransform: true }); }, [blockRect], ); // ---------- เลื่อนทั้งก้อนในชั้นบนสุด (แบบรายการ: ตัวอื่นหลบ ช่องว่างของตัวที่ลากเลื่อนไปจุดวาง) ---------- const freeRef = useRef(freeLayout); freeRef.current = freeLayout; const overlayOn = Boolean(renderOverlay); /** * ลำดับที่ตัวที่ลากเรียงอยู่ด้วย (เป็น dnd id) — `freeLayout` = ชั้นบนสุดทั้งหมด, * ไม่เปิด = เฉพาะกลุ่ม (รายการไม่มีกลุ่มเรียงกันเองด้วย dnd-kit) · null = ไม่ใช่การลากในชั้นบนสุด */ const entryKeys = useCallback((current: SortableOrder, activeKey: string): string[] | null => { if (freeRef.current) { const keys = rootEntries(current).map((e) => dndId(e.kind, e.id)); return keys.includes(activeKey) ? keys : null; } return kindOf(activeKey) === "g" ? current.groups.map((g) => dndId("group", g)) : null; }, []); /** กรอบของสิ่งหนึ่งในชั้นบนสุด: กลุ่ม = ทั้งก้อน, รายการ = แถวเดียว */ const measureKey = useCallback( (key: string) => { const raw = rawOf(key); if (kindOf(key) === "g") { const header = nodes.current.groups.get(raw); return header?.isConnected ? blockRect(raw, header) : null; } const node = nodes.current.items.get(raw); return node?.isConnected ? getClientRect(node, { ignoreTransform: true }) : null; }, [blockRect], ); /** จะวาง "ก่อน" อะไร (dnd id; null = ท้ายสุดของลำดับ) — null ทั้ง object = ไม่ใช่เป้าหมายในชั้นบนสุด */ const [target, setTargetState] = useState<{ before: string | null } | null>(null); const targetRef = useRef(target); const setTarget = useCallback((next: { before: string | null } | null) => { const prev = targetRef.current; if (prev === next || (prev && next && prev.before === next.before)) return; targetRef.current = next; setTargetState(next); }, []); useEffect(() => { if (!activeDrag) return; const activeKey = dndId(activeDrag.kind, activeDrag.id); const keys = entryKeys(order, activeKey); if (!keys) { // รายการที่ลากเข้าไปอยู่ในกลุ่มแล้ว → dnd-kit ของกลุ่มนั้นคุมต่อ shifts.clear(); return; } const rest = keys.filter((k) => k !== activeKey); const at = target ? target.before === null ? rest.length : rest.indexOf(target.before) : keys.indexOf(activeKey); const final = [...rest.slice(0, Math.max(0, at)), activeKey, ...rest.slice(Math.max(0, at))]; const rects = new Map(keys.map((k) => [k, measureKey(k)] as const)); const first = rects.get(keys[0] ?? ""); const second = rects.get(keys[1] ?? ""); if (!first) return; // ช่องไฟระหว่างก้อน (ตาราง = 0, การ์ดมีระยะห่าง) — ใช้ระยะจริงระหว่างสองก้อนแรก const gap = second ? Math.max(0, second.top - first.bottom) : 0; const transition = `transform ${SORT_TRANSITION.duration}ms ${EASING}`; let cursor = first.top; for (const key of final) { const rect = rects.get(key); if (!rect) continue; const dy = cursor - rect.top; cursor += rect.height + gap; // ไม่มี overlay = ตัวที่ลากลอยตามเมาส์เอง (กลุ่ม: onDragMove, รายการ: dnd-kit) if (key === activeKey && !overlayOn) continue; shifts.set(key, { transform: `translate3d(0px, ${dy}px, 0)`, transition }); } }, [activeDrag, target, order, overlayOn, shifts, entryKeys, measureKey]); /** ตั้งเป้าหมายในชั้นบนสุดจากสิ่งที่ชี้อยู่ + ตัวที่ลากเลยครึ่งของมันหรือยัง */ function updateTarget( active: DragMoveEvent["active"], over: DragMoveEvent["over"], keyboard: boolean, pointerY: number | null, ) { const activeKey = String(active.id); const keys = entryKeys(latest.current, activeKey); if (!keys) { setTarget(null); return; } if (!over) return; const overKey = String(over.id); const nextAfter = (index: number) => keys.slice(index + 1).find((k) => k !== activeKey) ?? null; if (kindOf(overKey) === "z" && rawOf(overKey) === UNGROUPED) { setTarget({ before: null }); } else if (overKey === activeKey) { setTarget({ before: nextAfter(keys.indexOf(activeKey)) }); } else if (keys.includes(overKey)) { if (kindOf(activeKey) === "i" && kindOf(overKey) === "g") { // รายการชี้ครึ่งบนของหัวกลุ่ม = วางก่อนกลุ่มนั้น setTarget({ before: overKey }); return; } const a = keys.indexOf(activeKey); const o = keys.indexOf(overKey); const rect = measureKey(overKey); // ตัดสินด้วยตำแหน่งเมาส์ ไม่ใช่กลางของสิ่งที่ลาก: แอปที่แปะ ref ของกลุ่มที่ ทั้งก้อน // กลางของก้อนสูง ๆ ไม่เคยเลยครึ่งของกลุ่มเป้าหมาย → ได้ "ที่เดิม" เสมอ กลุ่มอื่นไม่เลื่อนหลบ (Pi Config) const dragged = active.rect.current.translated; const y = pointerY ?? (dragged ? dragged.top + dragged.height / 2 : null); // คีย์บอร์ดขยับทีละตำแหน่งไปทับกลางเป้าหมายพอดี → ใช้ทิศทางแทน const after = keyboard || !rect || y === null ? o > a : y > (rect.top + rect.bottom) / 2; setTarget({ before: after ? nextAfter(o) : overKey }); } else { setTarget(null); } } const measuring = useMemo( () => ({ droppable: { strategy: MeasuringStrategy.Always, measure: measureDroppable } }), [measureDroppable], ); // ย้ายข้ามกลุ่มเสร็จแล้ว (render ลำดับใหม่ไปแล้ว) ค่อยปลดธงในเฟรมถัดไป useEffect(() => { const frame = requestAnimationFrame(() => { movedAcross.current = false; }); return () => cancelAnimationFrame(frame); }, [order]); /** * เลือกเป้าหมายแบบบอร์ดงาน (สูตรเดียวกับตัวอย่าง multiple containers ของ dnd-kit): * - ลากกลุ่ม → เทียบกับกลุ่มด้วยกันเท่านั้น * - ลากรายการ → ใช้ "สิ่งที่อยู่ใต้เมาส์จริง" ก่อน (pointerWithin) ไม่ใช่ตัวที่ใกล้ที่สุดทั้งตาราง * (เดิมใช้ closestCenter ทั้งตาราง ทำให้แถวรับวางท้ายตารางแย่งเป้าหมาย รายการกระโดดไปไกลจากเมาส์) * - ชี้หัวกลุ่มที่เปิดอยู่ → เลือกรายการในกลุ่มที่ใกล้ที่สุดแทน (วางลงในกลุ่มตรงตำแหน่ง) * - หาไม่เจอชั่วขณะตอน layout ขยับ → ใช้เป้าหมายล่าสุด ไม่ให้แถวสั่นไปมา */ const collisionDetection: CollisionDetection = useCallback((args) => { if (kindOf(args.active.id) === "g") { // freeLayout: กลุ่มเรียงปนกับรายการไม่มีกลุ่ม → เทียบกับทั้งสองอย่าง (สิ่งที่อยู่ใต้เมาส์ก่อน) const loose = new Set(latest.current.items[UNGROUPED] ?? []); const rootLevel = args.droppableContainers.filter( (c) => kindOf(c.id) === "g" || (freeRef.current && kindOf(c.id) === "i" && loose.has(rawOf(c.id))), ); const scoped = { ...args, droppableContainers: rootLevel }; const under = freeRef.current ? pointerWithin(scoped) : []; return under.length > 0 ? under.slice(0, 1) : closestCenter(scoped); } const candidates = args.droppableContainers.filter((c) => kindOf(c.id) !== "g"); const scoped = { ...args, droppableContainers: candidates }; const underPointer = pointerWithin(scoped); const hits = underPointer.length > 0 ? underPointer : rectIntersection(scoped); let overId = getFirstCollision(hits, "id"); if (overId != null) { const header = kindOf(overId) === "z" ? args.droppableRects.get(overId) : undefined; const pointer = args.pointerCoordinates; if ( freeRef.current && header && pointer && rawOf(overId) !== UNGROUPED && pointer.y < header.top + header.height / 2 ) { // freeLayout: ครึ่งบนของหัวกลุ่ม = วาง "ก่อนกลุ่ม" ในชั้นบนสุด (ครึ่งล่าง = เข้ากลุ่มเป็นตัวแรก) overId = dndId("group", rawOf(overId)); } else if (kindOf(overId) === "z" && rawOf(overId) !== UNGROUPED) { // (โซนของ UNGROUPED = ที่วาง "ท้ายสุด" ไม่ใช่หัวกลุ่ม — ห้ามเปลี่ยนเป็นรายการแรก) // ชี้หัวกลุ่ม = "บนสุดของกลุ่ม" → เป้าหมายคือรายการแรกที่แสดงอยู่ "รวมตัวที่ลากเอง" // (เดิมเลือกตัวที่ใกล้ที่สุดที่ไม่ใช่ตัวที่ลาก: ลากเข้ากลุ่มแล้วขึ้นเป็นตัวแรกถูก แต่พอปล่อย // onDragEnd ย้ายไปแทนที่ตัวแรกเดิม → กลายเป็นตัวที่สอง วางเป็นรายการแรกไม่ได้) const rendered = new Set( candidates.filter((c) => kindOf(c.id) === "i").map((c) => rawOf(c.id)), ); const first = (latest.current.items[rawOf(overId)] ?? []).find((x) => rendered.has(x)); if (first !== undefined) overId = dndId("item", first); } lastOverId.current = overId; return [{ id: overId }]; } if (movedAcross.current) lastOverId.current = args.active.id; return lastOverId.current != null ? [{ id: lastOverId.current }] : []; }, []); const sensors = useSensors( useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), ); const containerOf = useCallback((id: UniqueIdentifier, current: SortableOrder) => { if (kindOf(id) === "z") return rawOf(id); return groupOfItem(current, rawOf(id)); }, []); function onDragStart({ active }: DragStartEvent) { beforeDrag.current = latest.current; crossedAt.current = null; lastOverId.current = null; const kind: SortableKind = kindOf(active.id) === "g" ? "group" : "item"; const raw = rawOf(active.id); const chosen = selectedRef.current; bulk.current = null; if (kind === "item" && chosen.has(raw) && chosen.size > 1) { bulk.current = flatItems(latest.current).filter((x) => chosen.has(x)); } else if (kind === "item" && chosen.size > 0 && !chosen.has(raw)) { // ลากตัวที่ไม่ได้เลือก = ลากตัวนั้นตัวเดียว และล้างการเลือกเดิม (แบบ Finder) select("", "clear"); } draggingRef.current = kind; setTarget(null); setDragging(kind); setActiveDrag({ kind, id: raw, ids: bulk.current ?? [raw] }); } function onDragMove({ active, over, delta, activatorEvent }: DragMoveEvent) { updateTarget( active, over, activatorEvent instanceof KeyboardEvent, pointerYOf(activatorEvent, delta), ); // ไม่มี overlay: ก้อนของกลุ่มที่ลากลอยตามเมาส์ทั้งก้อน (หัวกลุ่ม + แถวรายการ) if (overlayOn || kindOf(active.id) !== "g") return; shifts.set(String(active.id), { transform: `translate3d(${delta.x}px, ${delta.y}px, 0)`, transition: undefined, }); } function endDrag() { draggingRef.current = null; bulk.current = null; setTarget(null); // ล้างระยะเลื่อนพร้อมกับที่ลำดับใหม่ render (รอ effect = มีเฟรมที่แถวใหม่ยังติด transform เก่า → กระพริบ) shifts.clear(); setDragging(null); setActiveDrag(null); } function onDragOver({ active, over, activatorEvent, delta }: DragOverEvent) { const keyboard = activatorEvent instanceof KeyboardEvent; const pointerY = pointerYOf(activatorEvent, delta); if (!over || kindOf(active.id) !== "i") { updateTarget(active, over, keyboard, pointerY); return; } const current = latest.current; const raw = rawOf(active.id); const apply = (next: SortableOrder) => { if (next === current) return; crossedAt.current = over.id; movedAcross.current = true; latest.current = next; onOrderChange(next); }; // ครึ่งบนของหัวกลุ่ม (freeLayout) = ออกมาวางก่อนกลุ่มนั้นในชั้นบนสุด if (kindOf(over.id) === "g") { if (groupOfItem(current, raw) !== UNGROUPED) { apply(moveItemToRoot(current, raw, { kind: "group", id: rawOf(over.id) })); } updateTarget(active, over, keyboard, pointerY); return; } const from = containerOf(active.id, current); const to = containerOf(over.id, current); if (!from || !to || from === to) { // ชี้ตัวอื่นในกลุ่มเดียวกันแล้ว = เรียงต่อแบบปกติ (ไม่ใช่ตำแหน่งที่จัดไว้ตอนข้ามกลุ่ม) if (over.id !== crossedAt.current) crossedAt.current = null; updateTarget(active, over, keyboard, pointerY); return; } if (to === UNGROUPED) { // ออกจากกลุ่มมาชั้นบนสุด: ก่อน/หลังรายการที่ชี้ตามครึ่งแถว (ถัดไปอาจเป็นกลุ่ม) หรือท้ายสุด const root = rootEntries(current); let before: (typeof root)[number] | null = null; if (kindOf(over.id) === "i") { const at = root.findIndex((e) => e.kind === "item" && e.id === rawOf(over.id)); const dragged = active.rect.current.translated; const below = dragged != null && dragged.top > over.rect.top + over.rect.height / 2; before = root[at + (below ? 1 : 0)] ?? null; } apply(moveItemToRoot(current, raw, before)); return; } // วางก่อนหรือหลังแถวเป้าหมาย ตามว่าตัวที่ลากเลยครึ่งแถวนั้นลงมาหรือยัง // (เดิมแทรก "ก่อน" เสมอ — ลากเข้าจากด้านล่างแล้วรายการกระโดดข้ามขึ้นไป) let before: string | null = null; if (kindOf(over.id) === "i") { const list = current.items[to] ?? []; const at = list.indexOf(rawOf(over.id)); const dragged = active.rect.current.translated; const below = dragged != null && dragged.top > over.rect.top + over.rect.height / 2; before = list[at + (below ? 1 : 0)] ?? null; } else { // วางบนหัวโฟลเดอร์ = ขึ้นบนสุดของโฟลเดอร์ (ตรงกับตำแหน่งที่เห็น และไม่กระโดดตอนโฟลเดอร์ที่ย่อไว้เปิดออก) // ส่วนโซน "ไม่มีกลุ่ม" อยู่ท้ายตาราง จึงต่อท้าย before = current.items[to]?.[0] ?? null; } apply(moveItemToGroup(current, raw, to, before)); } /** ล้มเหลว = คืนลำดับเดิมเสมอ แล้วส่ง error ต่อให้แอป (ไม่มี `onCommitError` = ขึ้น toast ให้) */ function failed(error: unknown, snapshot: SortableOrder, seq: number) { // คืนลำดับเดิมเฉพาะเมื่อยังไม่มีการลากครั้งใหม่ทับ — ไม่งั้นลำดับที่บันทึกสำเร็จทีหลังจะถูกย้อนทิ้ง if (commitSeq.current === seq) { onOrderChange(snapshot); latest.current = snapshot; } if (onCommitError) onCommitError(error); else toast.error(errorMessage(error, text.actionFailed ?? "ดำเนินการไม่สำเร็จ")); } async function commit(next: SortableOrder, snapshot: SortableOrder) { if (!onCommit) return; commitSeq.current += 1; const seq = commitSeq.current; try { const result = await onCommit(next); // server action ที่คืน { ok: false, error } ถือว่าล้มเหลวเหมือน throw if (result && typeof result === "object" && "ok" in result && result.ok === false) { failed("error" in result ? result.error : undefined, snapshot, seq); } } catch (err) { failed(err, snapshot, seq); } } function onDragEnd({ active, over }: DragEndEvent) { const snapshot = beforeDrag.current; const carried = bulk.current; // อ่านเป้าหมายก่อน endDrag (endDrag ล้างทิ้ง) const finalTarget = targetRef.current; beforeDrag.current = null; endDrag(); const current = latest.current; let next = current; const activeKey = String(active.id); const keys = entryKeys(current, activeKey); if (keys && finalTarget) { // ชั้นบนสุด: แปลง "ก่อน X / ท้ายลำดับ" เป็นตำแหน่งใน root (ลำดับที่ไม่รวมตัวที่ลาก) const rootRest = rootEntries(current) .map((e) => dndId(e.kind, e.id)) .filter((k) => k !== activeKey); const last = keys.filter((k) => k !== activeKey).at(-1); const index = finalTarget.before !== null ? rootRest.indexOf(finalTarget.before) : last ? rootRest.indexOf(last) + 1 : rootRest.length; if (index >= 0) { next = moveRootEntry( current, { kind: kindOf(activeKey) === "g" ? "group" : "item", id: rawOf(activeKey) }, index, ); } } else if ( over && kindOf(active.id) === "i" && kindOf(over.id) === "i" && over.id !== crossedAt.current ) { next = reorderItems(current, rawOf(active.id), rawOf(over.id)); } // bulk: ตัวที่เลือกไว้ตัวอื่นตามมารวมที่จุดวางของตัวที่จับ (เรียงตามลำดับเดิม) if (carried) next = gatherItems(next, rawOf(active.id), carried); if (next !== current) { latest.current = next; onOrderChange(next); } if (snapshot && !sameOrder(snapshot, next)) void commit(next, snapshot); } function onDragCancel() { const snapshot = beforeDrag.current; beforeDrag.current = null; endDrag(); if (snapshot) { latest.current = snapshot; onOrderChange(snapshot); } } const instructions = screenReaderInstructions ?? text.sortable?.instructions ?? "กด Space เพื่อเริ่มลาก ใช้ปุ่มลูกศรเลื่อน แล้วกด Space อีกครั้งเพื่อวาง (Esc = ยกเลิก)"; /** เหตุการณ์ของ dnd-kit → บริบทที่แอปอ่านง่าย (ตำแหน่งเริ่มที่ 1) */ const describe = useCallback((id: UniqueIdentifier): SortableAnnouncementContext => { const current = latest.current; const raw = rawOf(id); if (kindOf(id) === "g") { return { id: raw, kind: "group", index: current.groups.indexOf(raw) + 1, total: current.groups.length, count: 1, }; } const group = groupOfItem(current, raw); const list = group ? (current.items[group] ?? []) : []; return { id: raw, kind: "item", groupId: group, index: list.indexOf(raw) + 1, total: list.length, count: bulk.current?.length ?? 1, }; }, []); /** * ตำแหน่งที่ "จะไปวาง" ระหว่างลาก — ในกลุ่มเดียวกันลำดับจริงยังไม่เปลี่ยนจนกว่าจะปล่อย * (เดิมประกาศตำแหน่งเดิมซ้ำ เช่น "ตำแหน่งที่ 1" ทั้งที่เลื่อนลงมาแล้ว) จึงใช้ตำแหน่งของเป้าหมายแทน * ข้ามกลุ่มไม่ต้องทำอะไร — onDragOver ย้ายเข้ากลุ่มใหม่ใน order ไปแล้ว */ const describeTarget = useCallback( (activeId: UniqueIdentifier, overId: UniqueIdentifier | null): SortableAnnouncementContext => { const base = describe(activeId); if (overId === null || overId === activeId) return base; const current = latest.current; if (base.kind === "group" && kindOf(overId) === "g") { const at = current.groups.indexOf(rawOf(overId)); return at >= 0 ? { ...base, index: at + 1 } : base; } if (base.kind === "item" && kindOf(overId) === "i") { const group = groupOfItem(current, rawOf(overId)); if (!group || group !== base.groupId) return base; const at = (current.items[group] ?? []).indexOf(rawOf(overId)); return at >= 0 ? { ...base, index: at + 1 } : base; } return base; }, [describe], ); const dndAnnouncements = useMemo(() => { const fill = ( template: string | undefined, fallback: string, ctx: SortableAnnouncementContext, ) => (template ?? fallback) .replace("{index}", String(ctx.index)) .replace("{total}", String(ctx.total)) .replace("{count}", String(ctx.count)); const announce = ( own: ((context: SortableAnnouncementContext) => string | undefined) | undefined, template: string | undefined, fallback: string, // ประโยคแทนเมื่อลากหลายรายการพร้อมกัน many: { template: string | undefined; fallback: string } | null, // ระหว่างลาก = ตำแหน่งของเป้าหมาย; ตอนปล่อย order อัปเดตแล้ว จึงใช้ตำแหน่งจริงของตัวที่ลาก useTarget = false, ) => ({ active, over, }: { active: { id: UniqueIdentifier }; over?: { id: UniqueIdentifier } | null; }) => { const context = useTarget ? describeTarget(active.id, over?.id ?? null) : describe(active.id); if (own) { const said = own(context); if (said !== undefined) return said; } return many && context.count > 1 ? fill(many.template, many.fallback, context) : fill(template, fallback, context); }; return { onDragStart: announce( announcements?.onDragStart, text.sortable?.started, "เริ่มลากรายการที่ {index} จาก {total}", { template: text.sortable?.startedMany, fallback: "เริ่มลาก {count} รายการที่เลือกไว้" }, ), onDragOver: announce( announcements?.onDragOver, text.sortable?.moved, "ย้ายไปตำแหน่งที่ {index} จาก {total}", null, true, ), onDragEnd: announce( announcements?.onDragEnd, text.sortable?.dropped, "วางที่ตำแหน่งที่ {index} จาก {total}", null, ), onDragCancel: announce( announcements?.onDragCancel, text.sortable?.cancelled, "ยกเลิกการลาก", null, ), }; }, [announcements, describeTarget, text.sortable]); const groupIds = useMemo(() => order.groups.map((id) => dndId("group", id)), [order.groups]); const groupOf = useCallback((itemId: string) => groupOfItem(order, itemId), [order]); const rootDrag = activeDrag !== null && (activeDrag.kind === "group" || (freeLayout && groupOfItem(order, activeDrag.id) === UNGROUPED)); const carried = useMemo>( () => activeDrag && activeDrag.ids.length > 1 ? new Set(activeDrag.ids.filter((x) => x !== activeDrag.id)) : EMPTY, [activeDrag], ); const state = useMemo( () => ({ dragging, disabled, handleLabel: handleLabel ?? text.sortable?.handle ?? "ลากเพื่อจัดลำดับ", overlay: Boolean(renderOverlay), activeGroup: activeDrag?.kind === "group" ? activeDrag.id : null, rootDrag, freeLayout, carried, multiSelect, selected, select, groupOf, register, shifts, }), [ dragging, disabled, handleLabel, text.sortable?.handle, renderOverlay, activeDrag, rootDrag, freeLayout, carried, multiSelect, selected, select, groupOf, register, shifts, ], ); return ( {/* ชั้นนอก = ลำดับของกลุ่ม (provider รู้ `order.groups` อยู่แล้ว แอปจึงไม่ต้องสร้างเอง และลำดับใน context หลุดจากลำดับจริงไม่ได้) · ชั้นใน = `SortableGroup` ของแต่ละกลุ่ม */} {children} {renderOverlay && mounted && createPortal( {activeDrag ? (
{renderOverlay(activeDrag)}
) : null}
, document.body, )}
); } /** ขอบเขตการเรียงของกลุ่มหนึ่ง — ครอบแถวของกลุ่มนั้น (ลำดับ id ต้องตรงกับที่เรนเดอร์) */ export function SortableGroup({ itemIds, children, }: { itemIds: ReadonlyArray; children: ReactNode; }) { const ids = useMemo(() => itemIds.map((id) => dndId("item", id)), [itemIds]); return ( {children} ); } export interface SortableRow { /** แปะที่ element ของแถว */ ref: (node: HTMLElement | null) => void; style: CSSProperties; /** props ที่ต้องแปะที่ "ที่จับ" — ส่งต่อให้ `` */ handleProps: Record; isDragging: boolean; /** รายการนี้ถูกเลือกอยู่ (`multiSelect`) */ selected: boolean; /** เลือก/ไม่เลือกแถวนี้ (สำหรับช่องติ๊กในแถว) — ไม่ได้เปิด `multiSelect` = ไม่ทำอะไร */ toggleSelected: () => void; /** * กระจายลงแถวเมื่อเปิด `multiSelect`: คลิกพร้อม ⌘/Ctrl/Shift เพื่อเลือก + `data-selected` * สำหรับทำสี (`data-[selected]:bg-primary/10`) — ปิด `multiSelect` หรือเป็นแถวกลุ่ม = object ว่าง */ selectProps: Record; } const INTERACTIVE = "a,button,input,select,textarea,label,[contenteditable=''],[contenteditable='true'],[role=button],[role=checkbox],[role=switch],[role=combobox]"; /** * ทำให้แถวหนึ่งลากได้ — แอปเอา `ref`/`style` ไปแปะที่ `` และ `handleProps` ที่ `` * `type: "group"` = ลากทั้งกลุ่ม, `"item"` = ลากรายการในกลุ่ม */ export function useSortableRow({ type, id, disabled, }: { type: SortableKind; id: string; /** ปิดเฉพาะแถวนี้ (ทั้งชุดปิดที่ `SortableProvider disabled`) */ disabled?: boolean; }): SortableRow { const state = useContext(SortableStateContext); const sortable = useSortable({ id: dndId(type, id), disabled: disabled || state.disabled, transition: SORT_TRANSITION, }); const { register, shifts, select } = state; const { setNodeRef } = sortable; const ref = useCallback( (node: HTMLElement | null) => { setNodeRef(node); register(type, id, node); }, [setNodeRef, register, type, id], ); const transform = CSS.Translate.toString(sortable.transform); // ระหว่างลากกลุ่ม provider คำนวณระยะเลื่อนของแต่ละกลุ่มเอง — หัวกลุ่มและแถวรายการของกลุ่มอ่านค่าเดียวกัน // (หัวกลุ่มมักอยู่ใน `SortableGroup` ซึ่งเป็น context ของรายการ dnd-kit จึงคำนวณให้หัวกลุ่มไม่ได้) const groupId = type === "item" ? state.groupOf(id) : id; const loose = type === "item" && groupId === UNGROUPED; // ระยะเลื่อนในชั้นบนสุด: กลุ่ม/รายการไม่มีกลุ่ม อ่านของตัวเอง, รายการในกลุ่มอ่านของกลุ่ม const shiftKey = type === "group" || loose ? dndId(type, id) : groupId ? dndId("group", groupId) : undefined; const shift = useSyncExternalStore( shifts.subscribe, () => (shiftKey ? shifts.get(shiftKey) : undefined), () => undefined, ); let style: CSSProperties = { transform, transition: sortable.transition }; if (loose && state.freeLayout && state.rootDrag) { style = sortable.isDragging && !state.overlay ? { ...style, position: "relative", zIndex: 1, opacity: 0.85 } : { transform: shift?.transform, transition: shift?.transition, ...(sortable.isDragging || state.carried.has(id) ? { opacity: 0.4 } : {}), }; } else if (type === "group" && state.rootDrag) { const own = state.activeGroup === id; style = { transform: shift?.transform, transition: shift?.transition, ...(own ? state.overlay ? { opacity: 0.4 } : { position: "relative", zIndex: 1, opacity: 0.85 } : {}), }; } else if (sortable.isDragging) { style = state.overlay ? // มี overlay ลอยตามเมาส์แล้ว แถวต้นทางเหลือเป็นช่องจาง ๆ บอกตำแหน่งที่จะวาง { ...style, opacity: 0.4 } : { ...style, position: "relative", zIndex: 1, opacity: 0.85 }; } else if (type === "item" && state.rootDrag && shift) { const own = state.activeGroup !== null && state.activeGroup === groupId; style = { transform: shift.transform, transition: shift.transition, ...(own ? state.overlay ? { opacity: 0.4 } : { position: "relative", zIndex: 1, opacity: 0.85 } : {}), }; } else if (type === "item" && state.carried.has(id)) { // ลากแบบ bulk: ตัวที่ตามไปด้วยจางลงตรงที่เดิม แล้วไปรวมที่จุดวางตอนปล่อย style = { ...style, opacity: 0.4 }; } const selectable = type === "item" && state.multiSelect; const isSelected = selectable && state.selected.has(id); const listeners = sortable.listeners; const handleProps: Record = { ...sortable.attributes, ...listeners }; if (selectable) { handleProps.onKeyDown = (event: KeyboardEvent) => { const mod = event.metaKey || event.ctrlKey; // เทียบแป้นจริง — แป้นภาษาไทยกด X ได้ "ป", A ได้ "ฟ" const key = hotkeyKeyOf(event); if (!mod && !event.altKey && key === "x") { event.preventDefault(); select(id, "toggle"); return; } if (mod && !event.altKey && key === "a") { event.preventDefault(); select(id, "all"); return; } listeners?.onKeyDown?.(event); }; } const selectProps: Record = selectable ? { "data-selected": isSelected ? "" : undefined, onMouseDown: (event: MouseEvent) => { // Shift+คลิก ไม่ให้เบราว์เซอร์ลากคลุมข้อความทั้งแถว if (event.shiftKey) event.preventDefault(); }, onClick: (event: MouseEvent) => { const target = event.target as Element; const control = target.closest(INTERACTIVE); if (control && !control.closest("[data-sortable-handle]")) return; if (event.metaKey || event.ctrlKey) select(id, "toggle"); else if (event.shiftKey) select(id, "range"); else if (state.selected.size > 0) select(id, "clear"); }, } : {}; return { ref, style, handleProps, isDragging: sortable.isDragging, selected: isSelected, toggleSelected: () => { if (selectable) select(id, "toggle"); }, selectProps, }; } /** * ทำให้หัวกลุ่ม (หรือพื้นที่ว่างของกลุ่ม) รับการวางรายการได้ — กลุ่มที่ย่ออยู่ก็ยังรับได้ * ปิดเองเมื่อกำลังลากกลุ่ม (ไม่ใช่รายการ) */ export function useSortableDropZone( groupId: string | null, options?: { /** * ลากรายการค้างไว้เหนือที่วางนี้นานพอ — ใช้เปิดกลุ่มที่ย่ออยู่ให้เองแบบโฟลเดอร์ใน Finder/Todoist * (ไม่ส่ง = ไม่ทำอะไร) */ onDwell?: () => void; /** นานเท่าไรถึงนับว่าค้าง (ms) — ค่าเริ่มต้น 600 */ dwellMs?: number; }, ): { ref: (node: HTMLElement | null) => void; isOver: boolean; } { const state = useContext(SortableStateContext); const droppable = useDroppable({ // `null` = กลุ่มของรายการที่ยังไม่มีกลุ่ม (เขียน `useSortableDropZone(null)` ได้เลย) id: dndId("zone", groupId ?? UNGROUPED), disabled: state.disabled || state.dragging !== "item", }); const onDwell = options?.onDwell; const dwellMs = options?.dwellMs ?? 600; const hovering = droppable.isOver && state.dragging === "item"; // เก็บ callback ล่าสุดไว้ใน ref — แอปส่งฟังก์ชันใหม่ทุก render ก็ไม่ทำให้นับเวลาใหม่ const dwellRef = useRef(onDwell); dwellRef.current = onDwell; useEffect(() => { if (!hovering || !dwellRef.current) return; const timer = setTimeout(() => dwellRef.current?.(), dwellMs); return () => clearTimeout(timer); }, [hovering, dwellMs]); return { ref: droppable.setNodeRef, isOver: droppable.isOver }; } /** * ปุ่มที่จับสำหรับลาก — ใช้ `Button` ของแพ็กเกจ จึงได้ tooltip จาก `aria-label` อัตโนมัติ * ต้องกระจาย `handleProps` จาก `useSortableRow` ลงไปด้วยเสมอ */ export function DragHandle({ label, className, disabled, hideWhenDisabled = false, reveal = false, ...handleProps }: { label?: string; className?: string; disabled?: boolean; /** ปิดการลากแล้วไม่ต้องแสดงที่จับเลย (ค่าเริ่มต้นคือแสดงแบบจาง ๆ ให้รู้ว่ามีแต่ตอนนี้ลากไม่ได้) */ hideWhenDisabled?: boolean; /** * "สงบจนกว่าจะแตะ": ซ่อนที่จับไว้ โผล่เมื่อชี้แถว / โฟกัสในแถว (คีย์บอร์ด) / แถวถูกเลือก · จอสัมผัส (ไม่มี hover) เห็นตลอด * ต้องใส่ `group/row` ที่แถว (``) · ที่จับยังโฟกัสด้วย Tab ได้เสมอ */ reveal?: boolean; } & Record) { const state = useContext(SortableStateContext); const off = disabled ?? state.disabled; if (off && hideWhenDisabled) return null; return ( ); } export type { SortableOrder }; export { UNGROUPED };