@pyreon/dnd 0.51.0 → 0.53.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.
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["__pkgName","__pkgVersion"],"sources":["../package.json","../src/use-drag-monitor.ts","../src/use-draggable.ts","../src/use-droppable.ts","../src/use-file-drop.ts","../src/use-sortable.ts","../src/index.ts"],"sourcesContent":["","import { monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData } from './types'\n\nexport interface UseDragMonitorOptions {\n /** Called on any drag start in the page. */\n onDragStart?: (data: DragData) => void\n /** Called on any drop in the page. */\n onDrop?: (sourceData: DragData, targetData: DragData) => void\n /** Filter which drags to monitor. */\n canMonitor?: (data: DragData) => boolean\n}\n\nexport interface UseDragMonitorResult {\n /** Whether any element is currently being dragged. */\n isDragging: () => boolean\n /** Data of the currently dragging element (null if not dragging). */\n dragData: () => DragData | null\n}\n\n/**\n * Monitor all drag operations on the page.\n * Useful for global drag indicators, analytics, or coordination between\n * multiple drag-and-drop areas.\n *\n * @example\n * ```tsx\n * const { isDragging, dragData } = useDragMonitor({\n * canMonitor: (data) => data.type === \"card\",\n * onDrop: (source, target) => logDrop(source, target),\n * })\n *\n * <Show when={isDragging()}>\n * <div class=\"global-drag-overlay\">\n * Dragging: {() => dragData()?.name}\n * </div>\n * </Show>\n * ```\n */\nexport function useDragMonitor(options?: UseDragMonitorOptions): UseDragMonitorResult {\n if (isServer) return { isDragging: () => false, dragData: () => null }\n\n const isDragging = signal(false)\n const dragData = signal<DragData | null>(null)\n\n /* v8 ignore next 4 — opt-in canMonitor predicate; both arms structurally exercised but counted as one */\n const canMonitorFn = options?.canMonitor\n ? ({ source }: { source: { data: Record<string, unknown> } }) =>\n options.canMonitor?.(source.data as DragData) ?? true\n : null\n\n const cleanup = monitorForElements({\n ...(canMonitorFn ? { canMonitor: canMonitorFn } : {}),\n onDragStart: ({ source }) => {\n // batch() so subscribers to isDragging + dragData get notified once,\n // not twice. Drag events fire frequently; doubling subscriber work\n // per event compounds visibly on UIs with many drag-monitor consumers.\n batch(() => {\n isDragging.set(true)\n dragData.set(source.data as DragData)\n })\n options?.onDragStart?.(source.data as DragData)\n },\n onDrop: ({ source, location }) => {\n batch(() => {\n isDragging.set(false)\n dragData.set(null)\n })\n const targetData = location.current.dropTargets[0]?.data ?? {}\n options?.onDrop?.(source.data as DragData, targetData as DragData)\n },\n })\n\n onCleanup(cleanup)\n\n return { isDragging, dragData }\n}\n","import { draggable } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { centerUnderPointer } from '@atlaskit/pragmatic-drag-and-drop/element/center-under-pointer'\nimport { pointerOutsideOfPreview } from '@atlaskit/pragmatic-drag-and-drop/element/pointer-outside-of-preview'\nimport { preserveOffsetOnSource } from '@atlaskit/pragmatic-drag-and-drop/element/preserve-offset-on-source'\nimport { setCustomNativeDragPreview } from '@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview'\nimport { isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData, DragPreviewOptions, UseDraggableOptions, UseDraggableResult } from './types'\n\n/**\n * Resolve a preview `offset` preset to pdnd's `GetOffsetFn`. Split out so\n * the ternary chain is directly unit-testable; `undefined` keeps the\n * browser default (top-left of the preview under the pointer).\n */\nfunction resolvePreviewOffset(\n offset: DragPreviewOptions['offset'],\n source: { element: HTMLElement },\n input: Parameters<typeof preserveOffsetOnSource>[0]['input'],\n): ReturnType<typeof pointerOutsideOfPreview> | undefined {\n if (offset === 'pointer-outside') return pointerOutsideOfPreview({ x: '16px', y: '8px' })\n if (offset === 'center') return centerUnderPointer\n if (offset === 'preserve-offset') {\n return preserveOffsetOnSource({ element: source.element, input })\n }\n return undefined\n}\n\n/**\n * Make an element draggable with signal-driven state.\n *\n * @example\n * ```tsx\n * let cardEl: HTMLElement | null = null\n *\n * const { isDragging } = useDraggable({\n * element: () => cardEl,\n * data: { id: card.id, type: \"card\" },\n * })\n *\n * <div ref={(el) => cardEl = el} class={isDragging() ? \"opacity-50\" : \"\"}>\n * {card.title}\n * </div>\n * ```\n */\nexport function useDraggable<T extends DragData = DragData>(\n options: UseDraggableOptions<T>,\n): UseDraggableResult {\n if (isServer) return { isDragging: () => false }\n\n const isDragging = signal(false)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function setup() {\n // The hook may have unmounted before this deferred (queueMicrotask) setup\n // ran. onCleanup fired with `cleanup` still undefined (a no-op), so a\n // registration created here would never be torn down — bail instead.\n /* v8 ignore next — defensive disposed-during-setup guard; tested implicitly via lifecycle */\n if (disposed) return\n // Defensive re-setup teardown: `setup` is scheduled exactly once\n // (`queueMicrotask(setup)`) and never re-invoked, so `cleanup` is always\n // undefined here — this branch never fires in the current single-shot\n // design. Kept so a future re-setup trigger (element-change re-registration)\n // can't leak a double registration.\n /* v8 ignore next — defensive re-setup teardown; unreachable with single-shot queueMicrotask */\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n const resolveData = () =>\n typeof options.data === 'function' ? (options.data as () => T)() : options.data\n\n const handle = options.handle?.()\n const preview = options.preview\n cleanup = draggable({\n element: el,\n ...(handle ? { dragHandle: handle } : {}),\n // Custom native drag preview — thin pass-through to pdnd's\n // setCustomNativeDragPreview + offset presets. Only wired when the\n // consumer opts in, so the default path is byte-identical.\n ...(preview\n ? {\n onGenerateDragPreview: ({\n nativeSetDragImage,\n source,\n location,\n }: {\n nativeSetDragImage: Parameters<\n typeof setCustomNativeDragPreview\n >[0]['nativeSetDragImage']\n source: { element: HTMLElement }\n location: {\n initial: { input: Parameters<typeof preserveOffsetOnSource>[0]['input'] }\n }\n }) => {\n const getOffset = resolvePreviewOffset(preview.offset, source, location.initial.input)\n setCustomNativeDragPreview({\n render: ({ container }) => preview.render(container),\n nativeSetDragImage,\n ...(getOffset ? { getOffset } : {}),\n })\n },\n }\n : {}),\n getInitialData: resolveData,\n canDrag: () => {\n const disabled = options.disabled\n if (typeof disabled === 'function') return !disabled()\n return !disabled\n },\n onDragStart: () => {\n isDragging.set(true)\n options.onDragStart?.()\n },\n onDrop: () => {\n isDragging.set(false)\n options.onDragEnd?.()\n },\n })\n }\n\n // Defer setup to next microtask so refs are populated\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isDragging }\n}\n","import { dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport {\n attachClosestEdge,\n type Edge,\n extractClosestEdge,\n} from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData, DropEdge, UseDroppableOptions, UseDroppableResult } from './types'\n\n/**\n * Make an element a drop target with signal-driven state.\n *\n * @example\n * ```tsx\n * let zoneEl: HTMLElement | null = null\n *\n * const { isOver, overEdge } = useDroppable({\n * element: () => zoneEl,\n * onDrop: (data) => handleDrop(data),\n * canDrop: (data) => data.type === \"card\",\n * edges: [\"top\", \"bottom\"], // opt-in closest-edge detection\n * })\n *\n * <div ref={(el) => zoneEl = el} class={isOver() ? \"bg-blue-50\" : \"\"}>\n * Drop here\n * </div>\n * ```\n */\nexport function useDroppable<T extends DragData = DragData>(\n options: UseDroppableOptions<T>,\n): UseDroppableResult {\n if (isServer) return { isOver: () => false, overEdge: () => null }\n\n const isOver = signal(false)\n const overEdge = signal<DropEdge | null>(null)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function setup() {\n // Unmounted before this deferred setup ran — don't register a target that\n // onCleanup (already fired with `cleanup` undefined) can never tear down.\n /* v8 ignore next — defensive disposed-during-setup guard */\n if (disposed) return\n // Defensive re-setup teardown: `setup` runs exactly once\n // (`queueMicrotask(setup)`, never re-invoked), so `cleanup` is always\n // undefined here — this branch never fires in the current single-shot\n // design. Kept so a future re-setup trigger can't leak a double target.\n /* v8 ignore next — defensive re-setup teardown; unreachable with single-shot queueMicrotask */\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n const edges = options.edges\n\n const resolveData = (): DragData => {\n if (!options.data) return {}\n return typeof options.data === 'function' ? (options.data as () => T)() : options.data\n }\n\n cleanup = dropTargetForElements({\n element: el,\n getData: ({ input, element }) => {\n const data = resolveData()\n // Opt-in closest-edge detection — wraps the target data with\n // pdnd hitbox metadata so extractClosestEdge can read the live\n // edge on enter/drag.\n if (edges && edges.length > 0) {\n return attachClosestEdge(data, { input, element, allowedEdges: edges as Edge[] })\n }\n return data\n },\n // pdnd stickiness — keep \"held\" drop-target status while the\n // pointer crosses gaps between targets. Pass-through of getIsSticky.\n ...(options.sticky ? { getIsSticky: () => true } : {}),\n canDrop: ({ source }) => {\n if (!options.canDrop) return true\n return options.canDrop(source.data as DragData)\n },\n onDragEnter: ({ source, self }) => {\n // batch — isOver + overEdge settle in ONE notify pass for\n // subscribers reading both (matches useSortable's batching).\n batch(() => {\n isOver.set(true)\n if (edges) overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n })\n options.onDragEnter?.(source.data as DragData)\n },\n // Live edge tracking while the pointer moves over the target —\n // only meaningful (and only wired) when edges are configured.\n ...(edges && edges.length > 0\n ? {\n onDrag: ({ self }: { self: { data: Record<string | symbol, unknown> } }) => {\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n },\n }\n : {}),\n onDragLeave: () => {\n batch(() => {\n isOver.set(false)\n overEdge.set(null)\n })\n options.onDragLeave?.()\n },\n onDrop: ({ source }) => {\n batch(() => {\n isOver.set(false)\n overEdge.set(null)\n })\n options.onDrop?.(source.data as DragData)\n },\n })\n }\n\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isOver, overEdge }\n}\n","import {\n dropTargetForExternal,\n monitorForExternal,\n} from '@atlaskit/pragmatic-drag-and-drop/external/adapter'\nimport { containsFiles, getFiles } from '@atlaskit/pragmatic-drag-and-drop/external/file'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\n\nexport interface UseFileDropOptions {\n /** Element getter for the drop zone. */\n element: () => HTMLElement | null\n /** Called when files are dropped. */\n onDrop: (files: File[]) => void\n /** Filter accepted file types (e.g. [\"image/*\", \".pdf\"]). */\n accept?: string[]\n /** Maximum number of files. */\n maxFiles?: number\n /** Whether drop is disabled. */\n disabled?: boolean | (() => boolean)\n}\n\nexport interface UseFileDropResult {\n /** Whether files are being dragged over the drop zone. */\n isOver: () => boolean\n /** Whether files are being dragged anywhere on the page. */\n isDraggingFiles: () => boolean\n}\n\n/**\n * File drop zone with signal-driven state.\n * Uses the native file drag events via pragmatic-drag-and-drop.\n *\n * @example\n * ```tsx\n * let dropZone: HTMLElement | null = null\n *\n * const { isOver, isDraggingFiles } = useFileDrop({\n * element: () => dropZone,\n * accept: [\"image/*\", \".pdf\"],\n * maxFiles: 5,\n * onDrop: (files) => upload(files),\n * })\n *\n * <div\n * ref={(el) => dropZone = el}\n * class={isOver() ? \"drop-active\" : isDraggingFiles() ? \"drop-ready\" : \"\"}\n * >\n * Drop files here\n * </div>\n * ```\n */\nexport function useFileDrop(options: UseFileDropOptions): UseFileDropResult {\n if (isServer) return { isOver: () => false, isDraggingFiles: () => false }\n\n const isOver = signal(false)\n const isDraggingFiles = signal(false)\n let cleanup: (() => void) | undefined\n let disposed = false\n\n function matchesAccept(file: File, accept: string[]): boolean {\n return accept.some((pattern) => {\n if (pattern.startsWith('.')) {\n return file.name.toLowerCase().endsWith(pattern.toLowerCase())\n }\n if (pattern.endsWith('/*')) {\n return file.type.startsWith(pattern.slice(0, -1))\n }\n return file.type === pattern\n })\n }\n\n function setup() {\n // Unmounted before this deferred setup ran — don't register a drop target\n // that onCleanup (already fired with `cleanup` undefined) can never remove.\n /* v8 ignore next — defensive disposed-during-setup guard */\n if (disposed) return\n if (cleanup) cleanup()\n\n const el = options.element()\n if (!el) return\n\n const cleanups: (() => void)[] = []\n\n // Monitor for file drags anywhere on the page\n cleanups.push(\n monitorForExternal({\n canMonitor: ({ source }) => containsFiles({ source }),\n onDragStart: () => isDraggingFiles.set(true),\n onDrop: () => isDraggingFiles.set(false),\n }),\n )\n\n // Drop target on the specific element\n cleanups.push(\n dropTargetForExternal({\n element: el,\n canDrop: ({ source }) => {\n const disabled = options.disabled\n if (typeof disabled === 'function' ? disabled() : disabled) return false\n return containsFiles({ source })\n },\n onDragEnter: () => isOver.set(true),\n onDragLeave: () => isOver.set(false),\n onDrop: ({ source }) => {\n // batch() so onDrop subscribers don't get notified twice\n // (isOver + isDraggingFiles) per file-drop event.\n batch(() => {\n isOver.set(false)\n isDraggingFiles.set(false)\n })\n\n let files = getFiles({ source })\n\n // Filter by accept\n if (options.accept && options.accept.length > 0) {\n files = files.filter((f) => matchesAccept(f, options.accept as string[]))\n }\n\n // Limit count\n if (options.maxFiles && files.length > options.maxFiles) {\n files = files.slice(0, options.maxFiles)\n }\n\n if (files.length > 0) {\n options.onDrop(files)\n }\n },\n }),\n )\n\n cleanup = () => {\n for (const fn of cleanups) fn()\n }\n }\n\n queueMicrotask(setup)\n\n onCleanup(() => {\n disposed = true\n if (cleanup) cleanup()\n })\n\n return { isOver, isDraggingFiles }\n}\n","import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'\nimport { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'\nimport { autoScrollForElements } from '@atlaskit/pragmatic-drag-and-drop-auto-scroll/element'\nimport {\n attachClosestEdge,\n type Edge,\n extractClosestEdge,\n} from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'\nimport { announce } from '@pyreon/a11y'\nimport { batch, createSelector, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DropEdge, UseSortableOptions, UseSortableResult } from './types'\n\nconst SORT_KEY = '__pyreon_sortable_key'\nconst SORT_ID = '__pyreon_sortable_id'\nconst SORT_GROUP = '__pyreon_sortable_group'\nconst SORT_PAYLOAD = '__pyreon_sortable_payload'\n\n// Same sr-only recipe as @pyreon/a11y's live regions — inline (not a CSS\n// class) so the instructions node needs zero stylesheet wiring.\nconst SR_ONLY =\n 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0'\n\nlet _sortableCounter = 0\n\n// Module-level registry of live sortable instances — used to dispatch\n// cross-list drop notifications from the destination back to the source\n// (W18). Keyed by sortableId.\nconst _sortableRegistry = new Map<\n string,\n {\n groupId: string | undefined\n onCrossListDrop: ((item: unknown) => void) | undefined\n }\n>()\n\n/**\n * Sortable list with signal-driven state, auto-scroll, and edge detection.\n *\n * Features:\n * - Keyed drag items matching `<For by={...}>` pattern\n * - Auto-scroll when dragging near container edges\n * - Closest-edge detection (drop above/below or left/right)\n * - Axis constraint (vertical/horizontal)\n * - Keyboard reordering (Alt+Arrow keys)\n * - Optional cross-list `groupId` for Trello/Notion/Linear board layouts\n * (W18) — share the same `groupId` between two\n * sortable instances and items can be dragged between them. The\n * source's `onCrossListDrop(item)` removes; the destination's\n * `onCrossListReceive(item, index)` inserts.\n *\n * @example\n * ```tsx\n * const items = signal([\n * { id: \"1\", name: \"Alice\" },\n * { id: \"2\", name: \"Bob\" },\n * { id: \"3\", name: \"Charlie\" },\n * ])\n *\n * const { containerRef, itemRef, isActive, isOverKey, overEdge } = useSortable({\n * items,\n * by: (item) => item.id,\n * onReorder: (newItems) => items.set(newItems),\n * label: (item) => item.name, // screen-reader announcements\n * })\n *\n * <ul ref={containerRef}>\n * <For each={items()} by={item => item.id}>\n * {(item) => (\n * <li\n * ref={itemRef(item.id)}\n * class={isActive(item.id) ? \"dragging\" : \"\"}\n * style={isOverKey(item.id) ? `border-${overEdge()}: 2px solid blue` : \"\"}\n * >\n * {item.name}\n * </li>\n * )}\n * </For>\n * </ul>\n * ```\n *\n * Prefer `isActive(key)` / `isOverKey(key)` over `activeId() === key` /\n * `overId() === key` in row templates — the equality read subscribes EVERY\n * row to the id signal (O(N) notifies per change); the selectors notify\n * only the two affected rows (O(2), `createSelector` semantics).\n */\nexport function useSortable<T>(options: UseSortableOptions<T>): UseSortableResult {\n if (isServer) {\n const noop = (_el: HTMLElement | null) => {}\n return {\n containerRef: noop,\n itemRef: () => noop,\n itemHandleRef: () => noop,\n activeId: () => null,\n overId: () => null,\n overEdge: () => null,\n isActive: () => false,\n isOverKey: () => false,\n }\n }\n\n const sortableId = `sortable-${++_sortableCounter}`\n const instructionsId = `${sortableId}-instructions`\n const activeId = signal<string | number | null>(null)\n const overId = signal<string | number | null>(null)\n const overEdge = signal<DropEdge | null>(null)\n // createSelector-backed per-key predicates (the krausest select-row\n // pattern): `activeId() === key` in a row template subscribes EVERY row\n // to activeId (O(N) notifies per change); the selector notifies only\n // the two affected keys (deselected + newly selected) — O(2).\n const isActiveSelector = createSelector<string | number | null>(activeId)\n const isOverSelector = createSelector<string | number | null>(overId)\n const axis = options.axis ?? 'vertical'\n const groupId = options.groupId\n\n /** Resolve the announcement label for an item: `label(item)` else the key. */\n function labelOf(item: T | undefined, key: string | number): string {\n if (item !== undefined && options.label) return options.label(item)\n return String(key)\n }\n\n /** Resolve the announcement label for a key by looking the item up. */\n function labelFor(key: string | number): string {\n const item = options.items().find((i) => options.by(i) === key)\n return labelOf(item, key)\n }\n\n // Register so siblings in the same group can call our onCrossListDrop\n // when they receive one of our items.\n _sortableRegistry.set(sortableId, {\n groupId,\n onCrossListDrop: options.onCrossListDrop as ((item: unknown) => void) | undefined,\n })\n\n // Container-level pdnd teardown (auto-scroll + reorder drop-target + the\n // keydown listener). A SINGLE disposer, replaced on re-register and cleared\n // on unmount — symmetric with the per-item map below. A collapsible board\n // whose `<ul ref={containerRef}>` sits behind a `<Show>` (with the hook in\n // the parent) re-fires `containerRef` on every toggle; without disposal each\n // toggle leaked the auto-scroll + drop-target + keydown listener on the now-\n // detached element (the container sibling of the F3 per-item leak).\n let containerCleanup: (() => void) | undefined\n // Per-item pdnd cleanups, keyed by sort key. Disposed individually on\n // item unmount / re-register so a churning list doesn't accumulate\n // dead registrations for the sortable's whole lifetime.\n const itemCleanups = new Map<string | number, () => void>()\n\n /** Perform the reorder based on current active/over/edge state. */\n function performReorder() {\n const dragId = activeId.peek()\n const dropId = overId.peek()\n const edge = overEdge.peek()\n /* v8 ignore next — defensive null/equal id guards */\n if (dragId == null || dropId == null || dragId === dropId) return\n\n const currentItems = options.items()\n const dragIndex = currentItems.findIndex((item) => options.by(item) === dragId)\n const dropIndex = currentItems.findIndex((item) => options.by(item) === dropId)\n /* v8 ignore next — defensive findIndex-not-found guards; ids come from active drag */\n if (dragIndex === -1 || dropIndex === -1) return\n\n const reordered = [...currentItems]\n const [moved] = reordered.splice(dragIndex, 1)\n /* v8 ignore next — defensive splice fallback; dragIndex was just verified */\n if (!moved) return\n\n // Determine insert position based on closest edge\n /* v8 ignore next 7 — ternary combinatorics; structurally exercised in browser e2e but not unit-coverable per arm */\n const rawInsert =\n edge === 'bottom' || edge === 'right'\n ? dropIndex >= dragIndex\n ? dropIndex\n : dropIndex + 1\n : dropIndex <= dragIndex\n ? dropIndex\n : dropIndex - 1\n const insertAt = Math.max(0, Math.min(rawInsert, reordered.length))\n\n reordered.splice(insertAt, 0, moved)\n options.onReorder(reordered)\n // Screen-reader announcement — position is 1-based for humans.\n announce(`Dropped ${labelOf(moved, dragId)} at position ${insertAt + 1} of ${reordered.length}`)\n }\n\n /** Announce a cross-list receive on THIS (destination) sortable. */\n function announceCrossListReceive(item: T, insertAt: number) {\n // `items()` reflects the post-insert length when the consumer commits\n // synchronously inside onCrossListReceive (the documented shape); the\n // max() keeps the count honest if the commit is deferred.\n const count = Math.max(options.items().length, insertAt + 1)\n const key = options.by(item)\n announce(\n `Dropped ${labelOf(item, key)} at position ${insertAt + 1} of ${count} in the receiving list`,\n )\n }\n\n /** Returns true when `source` belongs to this sortable or to a sibling\n * in the same `groupId`. */\n function acceptsSource(source: { data: Record<string, unknown> }): boolean {\n if (source.data[SORT_ID] === sortableId) return true\n if (groupId && source.data[SORT_GROUP] === groupId) return true\n return false\n }\n\n function containerRef(el: HTMLElement | null) {\n // Dispose the prior container registration on BOTH unmount (el === null,\n // fired by Pyreon's runtime) AND re-register (a new container element) so\n // a toggled/re-mounted container can't leak its auto-scroll + drop-target +\n // keydown listener. Symmetric with the per-item disposal below (F3).\n if (containerCleanup) {\n containerCleanup()\n containerCleanup = undefined\n }\n if (!el) return\n\n const containerCleanups: (() => void)[] = []\n\n // Visually-hidden keyboard instructions, referenced by every item via\n // aria-describedby (the dnd-kit pattern — screen-reader users land on\n // an item and hear how to reorder it). Created once per container\n // mount, removed with the container registration.\n const instructions = document.createElement('div')\n instructions.id = instructionsId\n instructions.setAttribute('data-pyreon-sortable-instructions', '')\n instructions.style.cssText = SR_ONLY\n instructions.textContent = 'Press Alt plus arrow keys to reorder'\n el.appendChild(instructions)\n containerCleanups.push(() => instructions.remove())\n\n // Auto-scroll when dragging near container edges\n containerCleanups.push(\n autoScrollForElements({\n element: el,\n canScroll: ({ source }) => acceptsSource(source),\n }),\n )\n\n // Container is a drop target for reorder finalization OR for\n // appending a cross-list item at the end of this column.\n containerCleanups.push(\n dropTargetForElements({\n element: el,\n getData: () => ({ [SORT_ID]: sortableId, [SORT_GROUP]: groupId }),\n canDrop: ({ source }) => acceptsSource(source),\n onDrop: ({ source }) => {\n // Item-level dropTarget for cross-list drops marks the source\n // data as handled — container skips so we don't insert twice.\n const handled = (source.data as Record<string, unknown>).__pyreon_sortable_handled\n if (source.data[SORT_ID] === sortableId) {\n // Same-list drop on container edge → reorder finalization.\n performReorder()\n } else if (\n !handled &&\n groupId &&\n source.data[SORT_GROUP] === groupId &&\n options.onCrossListReceive\n ) {\n // Cross-list drop on the container itself (not on an item) →\n // append to the end of this column.\n const item = source.data[SORT_PAYLOAD] as T\n const sourceSortableId = source.data[SORT_ID] as string\n const targetIndex = options.items().length\n options.onCrossListReceive(item, targetIndex)\n const sourceInstance = _sortableRegistry.get(sourceSortableId)\n sourceInstance?.onCrossListDrop?.(item)\n announceCrossListReceive(item, targetIndex)\n }\n // batch() the 3-signal reset so subscribers reading any of\n // activeId/overId/overEdge get notified once per drop, not\n // three times. Fires on every container-level drop.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n },\n }),\n )\n\n // Keyboard reordering: Alt+Arrow keys\n const keyHandler = (e: KeyboardEvent) => {\n if (!e.altKey) return\n\n const isUp = axis === 'vertical' ? e.key === 'ArrowUp' : e.key === 'ArrowLeft'\n const isDown = axis === 'vertical' ? e.key === 'ArrowDown' : e.key === 'ArrowRight'\n if (!isUp && !isDown) return\n\n const focused = document.activeElement as HTMLElement | null\n if (!focused || !el.contains(focused)) return\n\n const focusedKey = focused.dataset.pyreonSortKey\n if (!focusedKey) return\n\n e.preventDefault()\n\n const currentItems = options.items()\n const currentIndex = currentItems.findIndex((item) => String(options.by(item)) === focusedKey)\n /* v8 ignore next — defensive findIndex guard; focusedKey is from active item */\n if (currentIndex === -1) return\n\n const targetIndex = isUp ? currentIndex - 1 : currentIndex + 1\n if (targetIndex < 0 || targetIndex >= currentItems.length) return\n\n const reordered = [...currentItems]\n const temp = reordered[currentIndex]\n reordered[currentIndex] = reordered[targetIndex] as T\n reordered[targetIndex] = temp as T\n options.onReorder(reordered)\n // Screen-reader announcement for the keyboard path (1-based).\n announce(\n `Moved ${labelOf(temp, focusedKey)} to position ${targetIndex + 1} of ${currentItems.length}`,\n )\n\n // Restore focus after DOM update\n requestAnimationFrame(() => {\n const items = el.querySelectorAll('[data-pyreon-sort-key]')\n for (const item of items) {\n if ((item as HTMLElement).dataset.pyreonSortKey === focusedKey) {\n ;(item as HTMLElement).focus()\n break\n }\n }\n })\n }\n\n el.addEventListener('keydown', keyHandler)\n containerCleanups.push(() => el.removeEventListener('keydown', keyHandler))\n\n containerCleanup = () => {\n for (const fn of containerCleanups) fn()\n }\n }\n\n // Live item elements + registered drag handles, keyed by sort key.\n // `itemEls` lets the handle registrar re-register an already-mounted\n // item when its handle arrives (child refs fire AFTER the parent's,\n // so the handle is never available at itemRef time).\n const itemEls = new Map<string | number, HTMLElement>()\n const itemHandles = new Map<string | number, HTMLElement>()\n\n function itemRef(key: string | number): (el: HTMLElement | null) => void {\n return (el: HTMLElement | null) => {\n // Per-key disposal. The ref fires with the element on mount and\n // with `null` on unmount. The old code pushed every registration\n // onto the shared `cleanups[]` and made the null branch a pure\n // no-op — so for a `<For>`-rendered sortable (the documented usage:\n // todo list / kanban) every removed item's pdnd `draggable` /\n // `dropTargetForElements` registration (and its pointer/drag\n // listeners on the now-detached node) leaked until the WHOLE\n // sortable unmounted. Dispose the prior registration for this key\n // on BOTH unmount (el === null) and re-registration (same key,\n // new element) so the live set tracks live items, not all-ever.\n const prev = itemCleanups.get(key)\n if (prev) {\n prev()\n itemCleanups.delete(key)\n }\n if (!el) {\n itemEls.delete(key)\n return\n }\n itemEls.set(key, el)\n registerItem(key, el)\n }\n }\n\n /**\n * OPTIONAL drag-handle registrar mirroring `itemRef`. When a handle is\n * (un)registered for an already-mounted item, the item's pdnd\n * registration is torn down and re-created so `dragHandle` takes\n * effect — pdnd captures the handle at registration time.\n */\n function itemHandleRef(key: string | number): (el: HTMLElement | null) => void {\n return (el: HTMLElement | null) => {\n if (el) itemHandles.set(key, el)\n else itemHandles.delete(key)\n const itemEl = itemEls.get(key)\n if (!itemEl) return\n // itemEls and itemCleanups are set together (itemRef → registerItem),\n // so a live itemEl implies a live cleanup — dispose it before the\n // re-registration below replaces it.\n /* v8 ignore next — defensive optional call; a live itemEl implies a live cleanup */\n itemCleanups.get(key)?.()\n itemCleanups.delete(key)\n registerItem(key, itemEl)\n }\n }\n\n function registerItem(key: string | number, el: HTMLElement) {\n el.dataset.pyreonSortKey = String(key)\n if (!el.hasAttribute('tabindex')) el.setAttribute('tabindex', '0')\n el.setAttribute('role', 'listitem')\n el.setAttribute('aria-roledescription', 'sortable item')\n // Link the container's visually-hidden keyboard instructions so a\n // screen-reader user focusing the item hears how to reorder it.\n // A consumer-supplied aria-describedby wins.\n if (!el.hasAttribute('aria-describedby')) {\n el.setAttribute('aria-describedby', instructionsId)\n }\n\n const allowedEdges: Edge[] = axis === 'vertical' ? ['top', 'bottom'] : ['left', 'right']\n const handle = itemHandles.get(key)\n\n const cleanup = combine(\n draggable({\n element: el,\n // Per-item drag handle (pdnd dragHandle) — drag initiation is\n // scoped to the registered handle element when one exists.\n ...(handle ? { dragHandle: handle } : {}),\n getInitialData: () => {\n const currentItems = options.items()\n const item = currentItems.find((i) => options.by(i) === key)\n return {\n [SORT_KEY]: key,\n [SORT_ID]: sortableId,\n [SORT_GROUP]: groupId,\n // Carry the actual item value when groupId is set so a\n // sibling sortable's onDrop can receive it without a\n // separate registry lookup. Plain reference (pdnd doesn't\n // serialize) — safe within a single document.\n [SORT_PAYLOAD]: groupId ? item : undefined,\n }\n },\n onDragStart: () => {\n activeId.set(key)\n announce(`Picked up ${labelFor(key)}`)\n },\n onDrop: () => {\n queueMicrotask(() => {\n // batch() — same 3-signal reset shape as the container\n // onDrop above. Per-item drops fire this branch.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n })\n },\n }),\n dropTargetForElements({\n element: el,\n getData: ({ input, element }) =>\n attachClosestEdge(\n { [SORT_KEY]: key, [SORT_ID]: sortableId, [SORT_GROUP]: groupId },\n { input, element, allowedEdges },\n ),\n canDrop: ({ source }) => acceptsSource(source),\n onDragEnter: ({ self }) => {\n // batch — overId + overEdge settle in ONE notify pass (same\n // shape as every other multi-signal write in this hook).\n batch(() => {\n overId.set(key)\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n })\n },\n onDrag: ({ self }) => {\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n },\n onDragLeave: () => {\n if (overId.peek() === key) {\n batch(() => {\n overId.set(null)\n overEdge.set(null)\n })\n }\n },\n onDrop: ({ source, self }) => {\n // Same-list drops are handled by the container's onDrop via\n // performReorder. Item-level onDrop fires for cross-list\n // shapes — insert at THIS item's index, then propagate to\n // the source to remove.\n if (source.data[SORT_ID] === sortableId) return\n if (!groupId || source.data[SORT_GROUP] !== groupId || !options.onCrossListReceive) {\n return\n }\n const item = source.data[SORT_PAYLOAD] as T\n const edge = extractClosestEdge(self.data) as DropEdge | null\n const currentItems = options.items()\n const targetIndex = currentItems.findIndex((i) => options.by(i) === key)\n /* v8 ignore next — defensive findIndex guard */\n if (targetIndex === -1) return\n /* v8 ignore next 4 — ternary combinatorics */\n const insertAt =\n edge === 'bottom' || edge === 'right' ? targetIndex + 1 : Math.max(0, targetIndex)\n options.onCrossListReceive(item, insertAt)\n const sourceSortableId = source.data[SORT_ID] as string\n const sourceInstance = _sortableRegistry.get(sourceSortableId)\n sourceInstance?.onCrossListDrop?.(item)\n announceCrossListReceive(item, insertAt)\n // Mark so the container's onDrop (which also fires) skips\n // re-inserting at the end of the list.\n ;(source.data as Record<string, unknown>).__pyreon_sortable_handled = true\n },\n }),\n )\n\n itemCleanups.set(key, cleanup)\n }\n\n onCleanup(() => {\n // Drain the live container registration (idempotent — containerRef(null)\n // may already have cleared it) plus every per-item registration.\n if (containerCleanup) {\n containerCleanup()\n containerCleanup = undefined\n }\n for (const cleanup of itemCleanups.values()) cleanup()\n itemCleanups.clear()\n itemEls.clear()\n itemHandles.clear()\n _sortableRegistry.delete(sortableId)\n // Selectors own a source-tracking effect + per-key buckets — release\n // them with the sortable (keys are unbounded across list churn).\n isActiveSelector.dispose()\n isOverSelector.dispose()\n // batch() the final 3-signal reset so any subscriber that survives\n // the dispose order (unusual but possible — e.g. an external store\n // holding refs) sees one notify, not three.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n })\n\n return {\n containerRef,\n itemRef,\n itemHandleRef,\n activeId,\n overId,\n overEdge,\n isActive: (key: string | number) => isActiveSelector(key),\n isOverKey: (key: string | number) => isOverSelector(key),\n }\n}\n","import { name as __pkgName, version as __pkgVersion } from '../package.json' with { type: 'json' }\nimport { registerSingleton } from '@pyreon/reactivity'\n\n// Singleton sentinel — fail-loud detection of duplicate @pyreon/dnd\n// instances in the same heap. See @pyreon/reactivity/singleton-sentinel for\n// full rationale. Hardcoded version is acceptable here — it's a diagnostic\n// aid, not a load-bearing identity check.\nregisterSingleton(__pkgName, __pkgVersion, import.meta.url)\n\nexport type {\n DragData,\n DragPreviewOptions,\n DropEdge,\n DropLocation,\n UseDraggableOptions,\n UseDraggableResult,\n UseDroppableOptions,\n UseDroppableResult,\n UseSortableOptions,\n UseSortableResult,\n} from './types'\n\nexport type { UseDragMonitorOptions, UseDragMonitorResult } from './use-drag-monitor'\nexport { useDragMonitor } from './use-drag-monitor'\n\nexport { useDraggable } from './use-draggable'\nexport { useDroppable } from './use-droppable'\nexport type { UseFileDropOptions, UseFileDropResult } from './use-file-drop'\nexport { useFileDrop } from './use-file-drop'\nexport { useSortable } from './use-sortable'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuCA,SAAgB,eAAe,SAAuD;CACpF,IAAI,UAAU,OAAO;EAAE,kBAAkB;EAAO,gBAAgB;CAAK;CAErE,MAAM,aAAa,OAAO,KAAK;CAC/B,MAAM,WAAW,OAAwB,IAAI;;CAG7C,MAAM,eAAe,SAAS,cACzB,EAAE,aACD,QAAQ,aAAa,OAAO,IAAgB,KAAK,OACnD;CAwBJ,UAtBgB,mBAAmB;EACjC,GAAI,eAAe,EAAE,YAAY,aAAa,IAAI,CAAC;EACnD,cAAc,EAAE,aAAa;GAI3B,YAAY;IACV,WAAW,IAAI,IAAI;IACnB,SAAS,IAAI,OAAO,IAAgB;GACtC,CAAC;GACD,SAAS,cAAc,OAAO,IAAgB;EAChD;EACA,SAAS,EAAE,QAAQ,eAAe;GAChC,YAAY;IACV,WAAW,IAAI,KAAK;IACpB,SAAS,IAAI,IAAI;GACnB,CAAC;GACD,MAAM,aAAa,SAAS,QAAQ,YAAY,EAAE,EAAE,QAAQ,CAAC;GAC7D,SAAS,SAAS,OAAO,MAAkB,UA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Aa,YAAY;IACzC,IAAI,CAAC,WAAW,OAAO,KAAK,gBAAgB,WAAW,CAAC,QAAQ,oBAC9D;IAEF,MAAM,OAAO,OAAO,KAAK;IACzB,MAAM,OAAO,mBAAmB,KAAK,IAAI;IAEzC,MAAM,cADe,QAAQ,MACE,CAAC,CAAC,WAAW,MAAM,QAAQ,GAAG,CAAC,MAAM,GAAG;;IAEvE,IAAI,gBAAgB,IAAI;;IAExB,MAAM,WACJ,SAAS,YAAY,SAAS,UAAU,cAAc,IAAI,KAAK,IAAI,GAAG,WAAW;IACnF,QAAQ,mBAAmB,MAAM,QAAQ;IACzC,MAAM,mBAAmB,OAAO,KAAK;IAErC,AADuB,kBAAkB,IAAI,gBAChC,CAAC,EAAE,kBAAkB,IAAI;IACtC,yBAAyB,MAAM,QAAQ;IAGtC,AAAC,OAAO,KAAiC,4BAA4B;GACxE;EACF,CAAC,CACH;EAEA,aAAa,IAAI,KAAK,OAAO;CAC/B;CAEA,gBAAgB;EAGd,IAAI,kBAAkB;GACpB,iBAAiB;GACjB,mBAAmB;EACrB;EACA,KAAK,MAAM,WAAW,aAAa,OAAO,GAAG,QAAQ;EACrD,aAAa,MAAM;EACnB,QAAQ,MAAM;EACd,YAAY,MAAM;EAClB,kBAAkB,OAAO,UAAU;EAGnC,iBAAiB,QAAQ;EACzB,eAAe,QAAQ;EAIvB,YAAY;GACV,SAAS,IAAI,IAAI;GACjB,OAAO,IAAI,IAAI;GACf,SAAS,IAAI,IAAI;EACnB,CAAC;CACH,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,QAAyB,iBAAiB,GAAG;EACxD,YAAY,QAAyB,eAAe,GAAG;CACzD;AACF;;;;AC/gBA,kBAAkBA,MAAWC,SAAc,OAAO,KAAK,GAAG"}
1
+ {"version":3,"file":"index.js","names":["__pkgName","__pkgVersion"],"sources":["../package.json","../src/use-drag-monitor.ts","../src/element-binding.ts","../src/use-draggable.ts","../src/use-droppable.ts","../src/use-file-drop.ts","../src/use-sortable.ts","../src/index.ts"],"sourcesContent":["","import { monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter'\nimport { batch, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DragData } from './types'\n\nexport interface UseDragMonitorOptions {\n /** Called on any drag start in the page. */\n onDragStart?: (data: DragData) => void\n /** Called on any drop in the page. */\n onDrop?: (sourceData: DragData, targetData: DragData) => void\n /** Filter which drags to monitor. */\n canMonitor?: (data: DragData) => boolean\n}\n\nexport interface UseDragMonitorResult {\n /** Whether any element is currently being dragged. */\n isDragging: () => boolean\n /** Data of the currently dragging element (null if not dragging). */\n dragData: () => DragData | null\n}\n\n/**\n * Monitor all drag operations on the page.\n * Useful for global drag indicators, analytics, or coordination between\n * multiple drag-and-drop areas.\n *\n * @example\n * ```tsx\n * const { isDragging, dragData } = useDragMonitor({\n * canMonitor: (data) => data.type === \"card\",\n * onDrop: (source, target) => logDrop(source, target),\n * })\n *\n * <Show when={isDragging()}>\n * <div class=\"global-drag-overlay\">\n * Dragging: {() => dragData()?.name}\n * </div>\n * </Show>\n * ```\n */\nexport function useDragMonitor(options?: UseDragMonitorOptions): UseDragMonitorResult {\n if (isServer) return { isDragging: () => false, dragData: () => null }\n\n const isDragging = signal(false)\n const dragData = signal<DragData | null>(null)\n\n /* v8 ignore next 4 — opt-in canMonitor predicate; both arms structurally exercised but counted as one */\n const canMonitorFn = options?.canMonitor\n ? ({ source }: { source: { data: Record<string, unknown> } }) =>\n options.canMonitor?.(source.data as DragData) ?? true\n : null\n\n const cleanup = monitorForElements({\n ...(canMonitorFn ? { canMonitor: canMonitorFn } : {}),\n onDragStart: ({ source }) => {\n // batch() so subscribers to isDragging + dragData get notified once,\n // not twice. Drag events fire frequently; doubling subscriber work\n // per event compounds visibly on UIs with many drag-monitor consumers.\n batch(() => {\n isDragging.set(true)\n dragData.set(source.data as DragData)\n })\n options?.onDragStart?.(source.data as DragData)\n },\n onDrop: ({ source, location }) => {\n batch(() => {\n isDragging.set(false)\n dragData.set(null)\n })\n const targetData = location.current.dropTargets[0]?.data ?? {}\n options?.onDrop?.(source.data as DragData, targetData as DragData)\n },\n })\n\n onCleanup(cleanup)\n\n return { isDragging, dragData }\n}\n","import { effect, onCleanup, untrack } from '@pyreon/reactivity'\n\nexport interface ElementBinding {\n /** Ref callback: registers the element, moves the registration on a swap, disposes on `null`. */\n ref: (el: HTMLElement | null) => void\n}\n\n/**\n * Bind a pdnd registration to an element that may mount LATER or be SWAPPED.\n *\n * The hooks used to read `options.element()` exactly once, on a microtask\n * after the hook ran. An element that mounted after that (behind `<Show>`, a\n * lazy branch, a data-dependent render) was never registered, and a swapped\n * element kept the registration on the detached old node — both silently.\n *\n * Two ways in, both re-resolving:\n * - `ref` — attach it as the element's `ref`; every (el | null) call moves\n * the registration, so mount order no longer matters.\n * - the `element` getter — still resolved on a microtask (so a plain\n * `let el` assigned by a ref is populated), but inside an effect, so a\n * getter that reads a SIGNAL re-registers when that signal changes. A\n * getter still `null` at that point (and no ref) gets a dev warning naming\n * the fix, instead of a drop zone that never works.\n *\n * Cleanup contract: identity-based — one live registration, disposed on\n * re-register, on `ref(null)`, and when the owning scope is cleaned up.\n */\nexport function bindElement(\n hookName: string,\n getter: (() => HTMLElement | null) | undefined,\n register: (el: HTMLElement) => () => void,\n): ElementBinding {\n let current: HTMLElement | null = null\n let cleanup: (() => void) | undefined\n let disposed = false\n let refUsed = false\n let stopGetter: (() => void) | undefined\n\n const attach = (el: HTMLElement | null): void => {\n if (disposed || el === current) return\n if (cleanup) {\n cleanup()\n cleanup = undefined\n }\n current = el\n if (el) cleanup = register(el)\n }\n\n const ref = (el: HTMLElement | null): void => {\n if (el) refUsed = true\n attach(el)\n }\n\n if (getter) {\n // Defer to the next microtask so a ref-assigned `let` is populated.\n queueMicrotask(() => {\n // Unmounted before the deferred setup ran — nothing to register.\n if (disposed || refUsed) return\n let first = true\n const e = effect(() => {\n const el = getter()\n untrack(() => {\n if (first && !el && !refUsed && process.env.NODE_ENV !== 'production') {\n console.warn(\n `[Pyreon] ${hookName}: element() returned null when the deferred setup ran, so nothing was registered. If the element mounts later (behind <Show>, a lazy branch), attach the returned \\`ref\\` to it instead (<div ref={ref}>), or read the element from a signal so the getter re-resolves.`,\n )\n }\n first = false\n // The ref wins once it has supplied an element.\n if (!refUsed) attach(el)\n })\n })\n stopGetter = () => e.dispose()\n })\n }\n\n onCleanup(() => {\n disposed = true\n stopGetter?.()\n if (cleanup) cleanup()\n cleanup = undefined\n current = null\n })\n\n return { ref }\n}\n","import { draggable } from '@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter'\nimport { centerUnderPointer } from '@atlaskit/pragmatic-drag-and-drop/utils/center-under-pointer'\nimport { pointerOutsideOfPreview } from '@atlaskit/pragmatic-drag-and-drop/utils/pointer-outside-of-preview'\nimport { preserveOffsetOnSource } from '@atlaskit/pragmatic-drag-and-drop/utils/preserve-offset-on-source'\nimport { setCustomNativeDragPreview } from '@atlaskit/pragmatic-drag-and-drop/utils/set-custom-native-drag-preview'\nimport { isServer, signal } from '@pyreon/reactivity'\nimport { bindElement } from './element-binding'\nimport type { DragData, DragPreviewOptions, UseDraggableOptions, UseDraggableResult } from './types'\n\n/**\n * Resolve a preview `offset` preset to pdnd's `GetOffsetFn`. Split out so\n * the ternary chain is directly unit-testable; `undefined` keeps the\n * browser default (top-left of the preview under the pointer).\n */\nfunction resolvePreviewOffset(\n offset: DragPreviewOptions['offset'],\n source: { element: HTMLElement },\n input: Parameters<typeof preserveOffsetOnSource>[0]['input'],\n): ReturnType<typeof pointerOutsideOfPreview> | undefined {\n if (offset === 'pointer-outside') return pointerOutsideOfPreview({ x: '16px', y: '8px' })\n if (offset === 'center') return centerUnderPointer\n if (offset === 'preserve-offset') {\n return preserveOffsetOnSource({ element: source.element, input })\n }\n return undefined\n}\n\n/**\n * Make an element draggable with signal-driven state.\n *\n * Attach the returned `ref` to the element (works for elements that mount\n * later or get swapped), or pass an `element` getter.\n *\n * @example\n * ```tsx\n * const { ref, isDragging } = useDraggable({\n * data: { id: card.id, type: \"card\" },\n * })\n *\n * <div ref={ref} class={isDragging() ? \"opacity-50\" : \"\"}>\n * {card.title}\n * </div>\n * ```\n */\nexport function useDraggable<T extends DragData = DragData>(\n options: UseDraggableOptions<T>,\n): UseDraggableResult {\n if (isServer) return { isDragging: () => false, ref: () => {} }\n\n const isDragging = signal(false)\n\n const resolveData = () =>\n typeof options.data === 'function' ? (options.data as () => T)() : options.data\n\n function register(el: HTMLElement): () => void {\n const handle = options.handle?.()\n const preview = options.preview\n return draggable({\n element: el,\n ...(handle ? { dragHandle: handle } : {}),\n // Custom native drag preview — thin pass-through to pdnd's\n // setCustomNativeDragPreview + offset presets. Only wired when the\n // consumer opts in, so the default path is byte-identical.\n ...(preview\n ? {\n onGenerateDragPreview: ({\n nativeSetDragImage,\n source,\n location,\n }: {\n nativeSetDragImage: Parameters<\n typeof setCustomNativeDragPreview\n >[0]['nativeSetDragImage']\n source: { element: HTMLElement }\n location: {\n initial: { input: Parameters<typeof preserveOffsetOnSource>[0]['input'] }\n }\n }) => {\n const getOffset = resolvePreviewOffset(preview.offset, source, location.initial.input)\n setCustomNativeDragPreview({\n render: ({ container }) => preview.render(container),\n nativeSetDragImage,\n ...(getOffset ? { getOffset } : {}),\n })\n },\n }\n : {}),\n getInitialData: resolveData,\n canDrag: () => {\n const disabled = options.disabled\n if (typeof disabled === 'function') return !disabled()\n return !disabled\n },\n onDragStart: () => {\n isDragging.set(true)\n options.onDragStart?.()\n },\n onDrop: () => {\n isDragging.set(false)\n options.onDragEnd?.()\n },\n })\n }\n\n const { ref } = bindElement('useDraggable', options.element, register)\n\n return { isDragging, ref }\n}\n","import { dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter'\nimport {\n attachClosestEdge,\n type Edge,\n extractClosestEdge,\n} from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'\nimport { batch, isServer, signal } from '@pyreon/reactivity'\nimport { bindElement } from './element-binding'\nimport type {\n DragData,\n DropEdge,\n DropLocation,\n UseDroppableOptions,\n UseDroppableResult,\n} from './types'\n\n/**\n * Make an element a drop target with signal-driven state.\n *\n * Attach the returned `ref` to the element (works for elements that mount\n * later or get swapped), or pass an `element` getter.\n *\n * @example\n * ```tsx\n * const { ref, isOver, overEdge } = useDroppable({\n * onDrop: (data, { edge }) => handleDrop(data, edge),\n * canDrop: (data) => data.type === \"card\",\n * edges: [\"top\", \"bottom\"], // opt-in closest-edge detection\n * })\n *\n * <div ref={ref} class={isOver() ? \"bg-blue-50\" : \"\"}>\n * Drop here\n * </div>\n * ```\n */\nexport function useDroppable<T extends DragData = DragData, TSource extends DragData = DragData>(\n options: UseDroppableOptions<T, TSource>,\n): UseDroppableResult {\n if (isServer) return { isOver: () => false, overEdge: () => null, ref: () => {} }\n\n const isOver = signal(false)\n const overEdge = signal<DropEdge | null>(null)\n const edges = options.edges\n const hasEdges = !!edges && edges.length > 0\n\n const resolveData = (): DragData => {\n if (!options.data) return {}\n return typeof options.data === 'function' ? (options.data as () => T)() : options.data\n }\n\n function register(el: HTMLElement): () => void {\n return dropTargetForElements({\n element: el,\n getData: ({ input, element }) => {\n const data = resolveData()\n // Opt-in closest-edge detection — wraps the target data with\n // pdnd hitbox metadata so extractClosestEdge can read the live\n // edge on enter/drag.\n if (hasEdges) {\n return attachClosestEdge(data, { input, element, allowedEdges: edges as Edge[] })\n }\n return data\n },\n // pdnd stickiness — keep \"held\" drop-target status while the\n // pointer crosses gaps between targets. Pass-through of getIsSticky.\n ...(options.sticky ? { getIsSticky: () => true } : {}),\n canDrop: ({ source }) => {\n if (!options.canDrop) return true\n return options.canDrop(source.data as TSource)\n },\n onDragEnter: ({ source, self }) => {\n // batch — isOver + overEdge settle in ONE notify pass for\n // subscribers reading both (matches useSortable's batching).\n batch(() => {\n isOver.set(true)\n if (hasEdges) overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n })\n options.onDragEnter?.(source.data as TSource)\n },\n // Live edge tracking while the pointer moves over the target —\n // only meaningful (and only wired) when edges are configured.\n ...(hasEdges\n ? {\n onDrag: ({ self }: { self: { data: Record<string | symbol, unknown> } }) => {\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n },\n }\n : {}),\n onDragLeave: () => {\n batch(() => {\n isOver.set(false)\n overEdge.set(null)\n })\n options.onDragLeave?.()\n },\n onDrop: ({ source, self }) => {\n // Capture WHERE the drop landed before the reset below clears the\n // signal — `onDrop` used to receive only the source, so the edge a\n // consumer needs to insert above/below was already gone.\n const location: DropLocation = {\n edge: hasEdges\n ? ((extractClosestEdge(self.data) as DropEdge | null) ?? overEdge.peek())\n : null,\n data: resolveData(),\n }\n batch(() => {\n isOver.set(false)\n overEdge.set(null)\n })\n options.onDrop?.(source.data as TSource, location)\n },\n })\n }\n\n const { ref } = bindElement('useDroppable', options.element, register)\n\n return { isOver, overEdge, ref }\n}\n","import { dropTargetForExternal } from '@atlaskit/pragmatic-drag-and-drop/adapter/drop-target-for-external'\nimport { monitorForExternal } from '@atlaskit/pragmatic-drag-and-drop/adapter/monitor-for-external'\nimport { containsFiles } from '@atlaskit/pragmatic-drag-and-drop/utils/contains-files'\nimport { getFiles } from '@atlaskit/pragmatic-drag-and-drop/utils/get-files'\nimport { batch, isServer, signal } from '@pyreon/reactivity'\nimport { bindElement } from './element-binding'\n\n/** Why a dropped file was not delivered to `onDrop`. */\nexport type FileRejectReason = 'accept' | 'maxFiles'\n\nexport interface UseFileDropOptions {\n /**\n * Element getter for the drop zone. Optional — attach the returned `ref`\n * instead for an element that mounts later or may be swapped. A getter that\n * reads a signal re-registers when the signal changes.\n */\n element?: () => HTMLElement | null\n /** Called when files are dropped (only the accepted ones). */\n onDrop: (files: File[]) => void\n /**\n * Called with the dropped files that were NOT delivered, and why: `'accept'`\n * (type / extension not in `accept`) or `'maxFiles'` (over the limit). Fired\n * once per reason per drop. Without it a rejected drop is silent.\n */\n onReject?: (rejected: File[], reason: FileRejectReason) => void\n /**\n * Filter accepted file types — MIME types (`\"image/png\"`), MIME wildcards\n * (`\"image/*\"`), extensions (`\".pdf\"`), or `\"*\"` / `\"*\\/*\"` for any file.\n */\n accept?: string[]\n /** Maximum number of files. */\n maxFiles?: number\n /** Whether drop is disabled. */\n disabled?: boolean | (() => boolean)\n}\n\nexport interface UseFileDropResult {\n /** Whether files are being dragged over the drop zone. */\n isOver: () => boolean\n /** Whether files are being dragged anywhere on the page. */\n isDraggingFiles: () => boolean\n /** Ref callback for the drop zone — see `UseFileDropOptions.element`. */\n ref: (el: HTMLElement | null) => void\n}\n\nfunction matchesAccept(file: File, accept: string[]): boolean {\n return accept.some((pattern) => {\n if (pattern === '*' || pattern === '*/*') return true\n if (pattern.startsWith('.')) {\n return file.name.toLowerCase().endsWith(pattern.toLowerCase())\n }\n if (pattern.endsWith('/*')) {\n return file.type.startsWith(pattern.slice(0, -1))\n }\n return file.type === pattern\n })\n}\n\n/**\n * File drop zone with signal-driven state.\n * Uses the native file drag events via pragmatic-drag-and-drop.\n *\n * @example\n * ```tsx\n * const { ref, isOver, isDraggingFiles } = useFileDrop({\n * accept: [\"image/*\", \".pdf\"],\n * maxFiles: 5,\n * onDrop: (files) => upload(files),\n * onReject: (files, reason) => toast(`${files.length} file(s) rejected: ${reason}`),\n * })\n *\n * <div\n * ref={ref}\n * class={isOver() ? \"drop-active\" : isDraggingFiles() ? \"drop-ready\" : \"\"}\n * >\n * Drop files here\n * </div>\n * ```\n */\nexport function useFileDrop(options: UseFileDropOptions): UseFileDropResult {\n if (isServer) return { isOver: () => false, isDraggingFiles: () => false, ref: () => {} }\n\n const isOver = signal(false)\n const isDraggingFiles = signal(false)\n\n function register(el: HTMLElement): () => void {\n const cleanups: (() => void)[] = []\n\n // Monitor for file drags anywhere on the page\n cleanups.push(\n monitorForExternal({\n canMonitor: ({ source }) => containsFiles({ source }),\n onDragStart: () => isDraggingFiles.set(true),\n onDrop: () => isDraggingFiles.set(false),\n }),\n )\n\n // Drop target on the specific element\n cleanups.push(\n dropTargetForExternal({\n element: el,\n canDrop: ({ source }) => {\n const disabled = options.disabled\n if (typeof disabled === 'function' ? disabled() : disabled) return false\n return containsFiles({ source })\n },\n onDragEnter: () => isOver.set(true),\n onDragLeave: () => isOver.set(false),\n onDrop: ({ source }) => {\n // batch() so onDrop subscribers don't get notified twice\n // (isOver + isDraggingFiles) per file-drop event.\n batch(() => {\n isOver.set(false)\n isDraggingFiles.set(false)\n })\n\n let files = getFiles({ source })\n\n // Filter by accept\n const accept = options.accept\n if (accept && accept.length > 0) {\n const rejected = files.filter((f) => !matchesAccept(f, accept))\n if (rejected.length > 0) {\n files = files.filter((f) => matchesAccept(f, accept))\n options.onReject?.(rejected, 'accept')\n }\n }\n\n // Limit count\n if (options.maxFiles && files.length > options.maxFiles) {\n options.onReject?.(files.slice(options.maxFiles), 'maxFiles')\n files = files.slice(0, options.maxFiles)\n }\n\n if (files.length > 0) {\n options.onDrop(files)\n }\n },\n }),\n )\n\n return () => {\n for (const fn of cleanups) fn()\n }\n }\n\n const { ref } = bindElement('useFileDrop', options.element, register)\n\n return { isOver, isDraggingFiles, ref }\n}\n","import { combine } from '@atlaskit/pragmatic-drag-and-drop/utils/combine'\nimport { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter'\nimport { autoScrollForElements } from '@atlaskit/pragmatic-drag-and-drop-auto-scroll/element'\nimport {\n attachClosestEdge,\n type Edge,\n extractClosestEdge,\n} from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'\nimport { announce } from '@pyreon/a11y'\nimport { batch, createSelector, isServer, onCleanup, signal } from '@pyreon/reactivity'\nimport type { DropEdge, UseSortableOptions, UseSortableResult } from './types'\n\nconst SORT_KEY = '__pyreon_sortable_key'\nconst SORT_ID = '__pyreon_sortable_id'\nconst SORT_GROUP = '__pyreon_sortable_group'\nconst SORT_PAYLOAD = '__pyreon_sortable_payload'\n\n// Same sr-only recipe as @pyreon/a11y's live regions — inline (not a CSS\n// class) so the instructions node needs zero stylesheet wiring.\nconst SR_ONLY =\n 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0'\n\nlet _sortableCounter = 0\n\n// Visually-hidden keyboard instructions live in ONE shared host on\n// document.body — NOT inside the consumer's container. Appending a <div> into\n// the container put an invalid child inside a <ul>/<ol> AND broke `<For>`'s\n// owns-parent bulk clear (its markers were no longer the container's first\n// child, so every clear fell back to the per-node walk). Cleanup contract:\n// each sortable removes its OWN node by identity; the host is removed when its\n// last node goes (refcount = host.childElementCount).\nconst INSTRUCTIONS =\n 'To reorder, press Space or Enter to pick up an item, use the arrow keys to move it, then Space or Enter to drop it, or Escape to cancel. Alt plus an arrow key moves an item directly.'\nlet _instructionsHost: HTMLElement | null = null\n\nfunction mountInstructions(id: string): () => void {\n /* v8 ignore next — callers run client-side only (containerRef is a DOM ref) */\n if (isServer) return () => {}\n if (!_instructionsHost || !_instructionsHost.isConnected) {\n _instructionsHost = document.createElement('div')\n _instructionsHost.setAttribute('data-pyreon-sortable-instructions-host', '')\n _instructionsHost.style.cssText = SR_ONLY\n document.body.appendChild(_instructionsHost)\n }\n const host = _instructionsHost\n const node = document.createElement('div')\n node.id = id\n node.setAttribute('data-pyreon-sortable-instructions', '')\n node.textContent = INSTRUCTIONS\n host.appendChild(node)\n return () => {\n node.remove()\n if (host.childElementCount === 0) {\n host.remove()\n if (_instructionsHost === host) _instructionsHost = null\n }\n }\n}\n\n// Module-level registry of live sortable instances — used to dispatch\n// cross-list drop notifications from the destination back to the source\n// (W18). Keyed by sortableId.\nconst _sortableRegistry = new Map<\n string,\n {\n groupId: string | undefined\n onCrossListDrop: ((item: unknown) => void) | undefined\n }\n>()\n\n/**\n * Sortable list with signal-driven state, auto-scroll, and edge detection.\n *\n * Features:\n * - Keyed drag items matching `<For by={...}>` pattern\n * - Auto-scroll when dragging near container edges\n * - Closest-edge detection (drop above/below or left/right)\n * - Axis constraint (vertical/horizontal)\n * - Keyboard reordering: Space/Enter picks an item up, arrows move it,\n * Space/Enter drops, Escape cancels (restores the original position);\n * Alt+Arrow moves directly. Every step is announced to screen readers.\n * - Optional cross-list `groupId` for Trello/Notion/Linear board layouts\n * (W18) — share the same `groupId` between two\n * sortable instances and items can be dragged between them. The\n * source's `onCrossListDrop(item)` removes; the destination's\n * `onCrossListReceive(item, index)` inserts.\n *\n * @example\n * ```tsx\n * const items = signal([\n * { id: \"1\", name: \"Alice\" },\n * { id: \"2\", name: \"Bob\" },\n * { id: \"3\", name: \"Charlie\" },\n * ])\n *\n * const { containerRef, itemRef, isActive, isOverKey, overEdge } = useSortable({\n * items,\n * by: (item) => item.id,\n * onReorder: (newItems) => items.set(newItems),\n * label: (item) => item.name, // screen-reader announcements\n * })\n *\n * <ul ref={containerRef}>\n * <For each={items()} by={item => item.id}>\n * {(item) => (\n * <li\n * ref={itemRef(item.id)}\n * class={isActive(item.id) ? \"dragging\" : \"\"}\n * style={isOverKey(item.id) ? `border-${overEdge()}: 2px solid blue` : \"\"}\n * >\n * {item.name}\n * </li>\n * )}\n * </For>\n * </ul>\n * ```\n *\n * Prefer `isActive(key)` / `isOverKey(key)` over `activeId() === key` /\n * `overId() === key` in row templates — the equality read subscribes EVERY\n * row to the id signal (O(N) notifies per change); the selectors notify\n * only the two affected rows (O(2), `createSelector` semantics).\n */\nexport function useSortable<T>(options: UseSortableOptions<T>): UseSortableResult {\n if (isServer) {\n const noop = (_el: HTMLElement | null) => {}\n return {\n containerRef: noop,\n itemRef: () => noop,\n itemHandleRef: () => noop,\n activeId: () => null,\n overId: () => null,\n overEdge: () => null,\n isActive: () => false,\n isOverKey: () => false,\n }\n }\n\n const sortableId = `sortable-${++_sortableCounter}`\n const instructionsId = `${sortableId}-instructions`\n const activeId = signal<string | number | null>(null)\n const overId = signal<string | number | null>(null)\n const overEdge = signal<DropEdge | null>(null)\n // createSelector-backed per-key predicates (the krausest select-row\n // pattern): `activeId() === key` in a row template subscribes EVERY row\n // to activeId (O(N) notifies per change); the selector notifies only\n // the two affected keys (deselected + newly selected) — O(2).\n const isActiveSelector = createSelector<string | number | null>(activeId)\n const isOverSelector = createSelector<string | number | null>(overId)\n const axis = options.axis ?? 'vertical'\n const groupId = options.groupId\n const isDisabled = (): boolean => {\n const d = options.disabled\n return typeof d === 'function' ? d() : !!d\n }\n\n /** Resolve the announcement label for an item: `label(item)` else the key. */\n function labelOf(item: T | undefined, key: string | number): string {\n if (item !== undefined && options.label) return options.label(item)\n return String(key)\n }\n\n /** Resolve the announcement label for a key by looking the item up. */\n function labelFor(key: string | number): string {\n const item = options.items().find((i) => options.by(i) === key || String(options.by(i)) === key)\n return labelOf(item, key)\n }\n\n // Register so siblings in the same group can call our onCrossListDrop\n // when they receive one of our items.\n _sortableRegistry.set(sortableId, {\n groupId,\n onCrossListDrop: options.onCrossListDrop as ((item: unknown) => void) | undefined,\n })\n\n // Container-level pdnd teardown (auto-scroll + reorder drop-target + the\n // keydown listener). A SINGLE disposer, replaced on re-register and cleared\n // on unmount — symmetric with the per-item map below. A collapsible board\n // whose `<ul ref={containerRef}>` sits behind a `<Show>` (with the hook in\n // the parent) re-fires `containerRef` on every toggle; without disposal each\n // toggle leaked the auto-scroll + drop-target + keydown listener on the now-\n // detached element (the container sibling of the F3 per-item leak).\n let containerCleanup: (() => void) | undefined\n // Per-item pdnd cleanups, keyed by sort key. Disposed individually on\n // item unmount / re-register so a churning list doesn't accumulate\n // dead registrations for the sortable's whole lifetime.\n const itemCleanups = new Map<string | number, () => void>()\n\n /** Perform the reorder based on current active/over/edge state. */\n function performReorder() {\n const dragId = activeId.peek()\n const dropId = overId.peek()\n const edge = overEdge.peek()\n /* v8 ignore next — defensive null/equal id guards */\n if (dragId == null || dropId == null || dragId === dropId) return\n\n const currentItems = options.items()\n const dragIndex = currentItems.findIndex((item) => options.by(item) === dragId)\n const dropIndex = currentItems.findIndex((item) => options.by(item) === dropId)\n /* v8 ignore next — defensive findIndex-not-found guards; ids come from active drag */\n if (dragIndex === -1 || dropIndex === -1) return\n\n const reordered = [...currentItems]\n const [moved] = reordered.splice(dragIndex, 1)\n /* v8 ignore next — defensive splice fallback; dragIndex was just verified */\n if (!moved) return\n\n // Determine insert position based on closest edge\n /* v8 ignore next 7 — ternary combinatorics; structurally exercised in browser e2e but not unit-coverable per arm */\n const rawInsert =\n edge === 'bottom' || edge === 'right'\n ? dropIndex >= dragIndex\n ? dropIndex\n : dropIndex + 1\n : dropIndex <= dragIndex\n ? dropIndex\n : dropIndex - 1\n const insertAt = Math.max(0, Math.min(rawInsert, reordered.length))\n\n reordered.splice(insertAt, 0, moved)\n options.onReorder(reordered)\n // Screen-reader announcement — position is 1-based for humans.\n announce(`Dropped ${labelOf(moved, dragId)} at position ${insertAt + 1} of ${reordered.length}`)\n }\n\n /** Announce a cross-list receive on THIS (destination) sortable. */\n function announceCrossListReceive(item: T, insertAt: number) {\n // `items()` reflects the post-insert length when the consumer commits\n // synchronously inside onCrossListReceive (the documented shape); the\n // max() keeps the count honest if the commit is deferred.\n const count = Math.max(options.items().length, insertAt + 1)\n const key = options.by(item)\n announce(\n `Dropped ${labelOf(item, key)} at position ${insertAt + 1} of ${count} in the receiving list`,\n )\n }\n\n /** Returns true when `source` belongs to this sortable or to a sibling\n * in the same `groupId`. */\n function acceptsSource(source: { data: Record<string, unknown> }): boolean {\n if (source.data[SORT_ID] === sortableId) return true\n if (groupId && source.data[SORT_GROUP] === groupId) return true\n return false\n }\n\n function containerRef(el: HTMLElement | null) {\n // Dispose the prior container registration on BOTH unmount (el === null,\n // fired by Pyreon's runtime) AND re-register (a new container element) so\n // a toggled/re-mounted container can't leak its auto-scroll + drop-target +\n // keydown listener. Symmetric with the per-item disposal below (F3).\n if (containerCleanup) {\n containerCleanup()\n containerCleanup = undefined\n }\n if (!el) return\n\n const containerCleanups: (() => void)[] = []\n\n // Visually-hidden keyboard instructions, referenced by every item via\n // aria-describedby (the dnd-kit pattern — screen-reader users land on\n // an item and hear how to reorder it). Lives in a shared host OUTSIDE\n // the container (see mountInstructions), removed with the container\n // registration.\n containerCleanups.push(mountInstructions(instructionsId))\n\n // A non-list container gets `role=\"list\"` so its `listitem` children are\n // valid; a <ul>/<ol> (implicit list) or a consumer-set role is left alone.\n if (!el.hasAttribute('role') && el.tagName !== 'UL' && el.tagName !== 'OL') {\n el.setAttribute('role', 'list')\n containerCleanups.push(() => {\n if (el.getAttribute('role') === 'list') el.removeAttribute('role')\n })\n }\n\n // Auto-scroll when dragging near container edges\n containerCleanups.push(\n autoScrollForElements({\n element: el,\n canScroll: ({ source }) => acceptsSource(source),\n }),\n )\n\n // Container is a drop target for reorder finalization OR for\n // appending a cross-list item at the end of this column.\n containerCleanups.push(\n dropTargetForElements({\n element: el,\n getData: () => ({ [SORT_ID]: sortableId, [SORT_GROUP]: groupId }),\n canDrop: ({ source }) => acceptsSource(source),\n onDrop: ({ source }) => {\n // Item-level dropTarget for cross-list drops marks the source\n // data as handled — container skips so we don't insert twice.\n const handled = (source.data as Record<string, unknown>).__pyreon_sortable_handled\n if (source.data[SORT_ID] === sortableId) {\n // Same-list drop on container edge → reorder finalization.\n performReorder()\n } else if (\n !handled &&\n groupId &&\n source.data[SORT_GROUP] === groupId &&\n options.onCrossListReceive\n ) {\n // Cross-list drop on the container itself (not on an item) →\n // append to the end of this column.\n const item = source.data[SORT_PAYLOAD] as T\n const sourceSortableId = source.data[SORT_ID] as string\n const targetIndex = options.items().length\n options.onCrossListReceive(item, targetIndex)\n const sourceInstance = _sortableRegistry.get(sourceSortableId)\n sourceInstance?.onCrossListDrop?.(item)\n announceCrossListReceive(item, targetIndex)\n }\n // batch() the 3-signal reset so subscribers reading any of\n // activeId/overId/overEdge get notified once per drop, not\n // three times. Fires on every container-level drop.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n },\n }),\n )\n\n // ── Keyboard reordering ────────────────────────────────────────────\n // Pickup mode (WAI-ARIA / dnd-kit model): Space or Enter on a focused\n // item picks it up, the axis arrows move it one slot per press, Space or\n // Enter drops it, Escape cancels and restores the original index. The\n // Alt+Arrow direct move is kept. Every step is announced.\n let picked: { key: string; origin: number } | null = null\n let focusFrame = 0\n\n const indexOf = (key: string): number =>\n options.items().findIndex((item) => String(options.by(item)) === key)\n\n const restoreFocus = (key: string) => {\n if (focusFrame) cancelAnimationFrame(focusFrame)\n focusFrame = requestAnimationFrame(() => {\n focusFrame = 0\n const items = el.querySelectorAll('[data-pyreon-sort-key]')\n for (const item of items) {\n if ((item as HTMLElement).dataset.pyreonSortKey === key) {\n ;(item as HTMLElement).focus()\n break\n }\n }\n })\n }\n\n /** Move the item with `key` from its index to `to`; returns false when out of range. */\n const moveTo = (key: string, to: number): boolean => {\n const currentItems = options.items()\n const from = indexOf(key)\n /* v8 ignore next — defensive findIndex guard; the key comes from a live item */\n if (from === -1) return false\n if (to < 0 || to >= currentItems.length || to === from) return false\n const reordered = [...currentItems]\n const [moved] = reordered.splice(from, 1)\n reordered.splice(to, 0, moved as T)\n options.onReorder(reordered)\n restoreFocus(key)\n return true\n }\n\n const endPickup = () => {\n picked = null\n activeId.set(null)\n }\n\n const keyHandler = (e: KeyboardEvent) => {\n const focused = document.activeElement as HTMLElement | null\n if (!focused || !el.contains(focused)) return\n const focusedKey = focused.dataset.pyreonSortKey\n if (!focusedKey) return\n\n const isSpaceOrEnter = e.key === ' ' || e.key === 'Enter'\n const isUp = axis === 'vertical' ? e.key === 'ArrowUp' : e.key === 'ArrowLeft'\n const isDown = axis === 'vertical' ? e.key === 'ArrowDown' : e.key === 'ArrowRight'\n\n if (picked) {\n if (isUp || isDown) {\n e.preventDefault()\n const from = indexOf(picked.key)\n const to = isUp ? from - 1 : from + 1\n if (moveTo(picked.key, to)) {\n announce(\n `Moved ${labelFor(picked.key)} to position ${to + 1} of ${options.items().length}`,\n )\n }\n return\n }\n if (isSpaceOrEnter) {\n e.preventDefault()\n const key = picked.key\n endPickup()\n announce(\n `Dropped ${labelFor(key)} at position ${indexOf(key) + 1} of ${options.items().length}`,\n )\n return\n }\n if (e.key === 'Escape') {\n e.preventDefault()\n const { key, origin } = picked\n moveTo(key, origin)\n endPickup()\n announce(\n `Reorder cancelled. ${labelFor(key)} returned to position ${origin + 1} of ${options.items().length}`,\n )\n }\n return\n }\n\n if (isDisabled()) return\n\n // Pickup starts only from the ITEM's own keystroke: a button / input\n // inside an item keeps its native Space / Enter behaviour.\n if (\n isSpaceOrEnter &&\n e.target === focused &&\n !e.altKey &&\n !e.ctrlKey &&\n !e.metaKey &&\n !e.shiftKey\n ) {\n e.preventDefault()\n const origin = indexOf(focusedKey)\n /* v8 ignore next — defensive findIndex guard; the key comes from a live item */\n if (origin === -1) return\n picked = { key: focusedKey, origin }\n // Real key type (number keys stay numbers) so isActive(key) matches.\n activeId.set(options.by(options.items()[origin] as T))\n announce(\n `Picked up ${labelFor(focusedKey)}. Current position ${origin + 1} of ${options.items().length}. Use the arrow keys to move, Space or Enter to drop, Escape to cancel.`,\n )\n return\n }\n\n if (!e.altKey || (!isUp && !isDown)) return\n e.preventDefault()\n const from = indexOf(focusedKey)\n const to = isUp ? from - 1 : from + 1\n if (moveTo(focusedKey, to)) {\n // Screen-reader announcement for the keyboard path (1-based).\n announce(`Moved ${labelFor(focusedKey)} to position ${to + 1} of ${options.items().length}`)\n }\n }\n\n el.addEventListener('keydown', keyHandler)\n containerCleanups.push(() => el.removeEventListener('keydown', keyHandler))\n // A pending focus-restore frame must not run against a torn-down list.\n containerCleanups.push(() => {\n if (focusFrame) cancelAnimationFrame(focusFrame)\n focusFrame = 0\n if (picked) endPickup()\n })\n\n containerCleanup = () => {\n for (const fn of containerCleanups) fn()\n }\n }\n\n // Live item elements + registered drag handles, keyed by sort key.\n // `itemEls` lets the handle registrar re-register an already-mounted\n // item when its handle arrives (child refs fire AFTER the parent's,\n // so the handle is never available at itemRef time).\n const itemEls = new Map<string | number, HTMLElement>()\n const itemHandles = new Map<string | number, HTMLElement>()\n\n function itemRef(key: string | number): (el: HTMLElement | null) => void {\n // The element THIS ref callback registered. A keyed re-render mounts the\n // replacement row (same key) BEFORE the old row's ref(null) fires; when\n // this callback registered an element that is no longer the live one for\n // the key, its null is stale and must not tear down the live row's\n // registration. (A callback that never registered anything — an\n // imperative `itemRef(key)(null)` — still disposes the key.)\n let mine: HTMLElement | null = null\n return (el: HTMLElement | null) => {\n if (!el) {\n const stale = mine !== null && itemEls.get(key) !== mine\n mine = null\n if (stale) return\n }\n // Per-key disposal. The ref fires with the element on mount and\n // with `null` on unmount. The old code pushed every registration\n // onto the shared `cleanups[]` and made the null branch a pure\n // no-op — so for a `<For>`-rendered sortable (the documented usage:\n // todo list / kanban) every removed item's pdnd `draggable` /\n // `dropTargetForElements` registration (and its pointer/drag\n // listeners on the now-detached node) leaked until the WHOLE\n // sortable unmounted. Dispose the prior registration for this key\n // on BOTH unmount (el === null) and re-registration (same key,\n // new element) so the live set tracks live items, not all-ever.\n const prev = itemCleanups.get(key)\n if (prev) {\n prev()\n itemCleanups.delete(key)\n }\n if (!el) {\n itemEls.delete(key)\n return\n }\n mine = el\n itemEls.set(key, el)\n registerItem(key, el)\n }\n }\n\n /**\n * OPTIONAL drag-handle registrar mirroring `itemRef`. When a handle is\n * (un)registered for an already-mounted item, the item's pdnd\n * registration is torn down and re-created so `dragHandle` takes\n * effect — pdnd captures the handle at registration time.\n */\n function itemHandleRef(key: string | number): (el: HTMLElement | null) => void {\n // Same ownership rule as itemRef: a stale handle's null must not drop a\n // replacement row's handle.\n let mine: HTMLElement | null = null\n return (el: HTMLElement | null) => {\n if (el) {\n mine = el\n itemHandles.set(key, el)\n } else {\n const stale = mine !== null && itemHandles.get(key) !== mine\n mine = null\n if (stale) return\n itemHandles.delete(key)\n }\n const itemEl = itemEls.get(key)\n if (!itemEl) return\n // itemEls and itemCleanups are set together (itemRef → registerItem),\n // so a live itemEl implies a live cleanup — dispose it before the\n // re-registration below replaces it.\n /* v8 ignore next — defensive optional call; a live itemEl implies a live cleanup */\n itemCleanups.get(key)?.()\n itemCleanups.delete(key)\n registerItem(key, itemEl)\n }\n }\n\n function registerItem(key: string | number, el: HTMLElement) {\n el.dataset.pyreonSortKey = String(key)\n if (!el.hasAttribute('tabindex')) el.setAttribute('tabindex', '0')\n // A consumer-supplied role (option, row, treeitem, …) wins.\n if (!el.hasAttribute('role')) el.setAttribute('role', 'listitem')\n el.setAttribute('aria-roledescription', 'sortable item')\n // Link the container's visually-hidden keyboard instructions so a\n // screen-reader user focusing the item hears how to reorder it.\n // A consumer-supplied aria-describedby wins.\n if (!el.hasAttribute('aria-describedby')) {\n el.setAttribute('aria-describedby', instructionsId)\n }\n\n const allowedEdges: Edge[] = axis === 'vertical' ? ['top', 'bottom'] : ['left', 'right']\n const handle = itemHandles.get(key)\n\n const cleanup = combine(\n draggable({\n element: el,\n // Per-item drag handle (pdnd dragHandle) — drag initiation is\n // scoped to the registered handle element when one exists.\n ...(handle ? { dragHandle: handle } : {}),\n canDrag: () => !isDisabled(),\n getInitialData: () => {\n const currentItems = options.items()\n const item = currentItems.find((i) => options.by(i) === key)\n return {\n [SORT_KEY]: key,\n [SORT_ID]: sortableId,\n [SORT_GROUP]: groupId,\n // Carry the actual item value when groupId is set so a\n // sibling sortable's onDrop can receive it without a\n // separate registry lookup. Plain reference (pdnd doesn't\n // serialize) — safe within a single document.\n [SORT_PAYLOAD]: groupId ? item : undefined,\n }\n },\n onDragStart: () => {\n activeId.set(key)\n announce(`Picked up ${labelFor(key)}`)\n },\n onDrop: () => {\n queueMicrotask(() => {\n // batch() — same 3-signal reset shape as the container\n // onDrop above. Per-item drops fire this branch.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n })\n },\n }),\n dropTargetForElements({\n element: el,\n getData: ({ input, element }) =>\n attachClosestEdge(\n { [SORT_KEY]: key, [SORT_ID]: sortableId, [SORT_GROUP]: groupId },\n { input, element, allowedEdges },\n ),\n canDrop: ({ source }) => acceptsSource(source),\n onDragEnter: ({ self }) => {\n // batch — overId + overEdge settle in ONE notify pass (same\n // shape as every other multi-signal write in this hook).\n batch(() => {\n overId.set(key)\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n })\n },\n onDrag: ({ self }) => {\n overEdge.set(extractClosestEdge(self.data) as DropEdge | null)\n },\n onDragLeave: () => {\n if (overId.peek() === key) {\n batch(() => {\n overId.set(null)\n overEdge.set(null)\n })\n }\n },\n onDrop: ({ source, self }) => {\n // Same-list drops are handled by the container's onDrop via\n // performReorder. Item-level onDrop fires for cross-list\n // shapes — insert at THIS item's index, then propagate to\n // the source to remove.\n if (source.data[SORT_ID] === sortableId) return\n if (!groupId || source.data[SORT_GROUP] !== groupId || !options.onCrossListReceive) {\n return\n }\n const item = source.data[SORT_PAYLOAD] as T\n const edge = extractClosestEdge(self.data) as DropEdge | null\n const currentItems = options.items()\n const targetIndex = currentItems.findIndex((i) => options.by(i) === key)\n /* v8 ignore next — defensive findIndex guard */\n if (targetIndex === -1) return\n /* v8 ignore next 4 — ternary combinatorics */\n const insertAt =\n edge === 'bottom' || edge === 'right' ? targetIndex + 1 : Math.max(0, targetIndex)\n options.onCrossListReceive(item, insertAt)\n const sourceSortableId = source.data[SORT_ID] as string\n const sourceInstance = _sortableRegistry.get(sourceSortableId)\n sourceInstance?.onCrossListDrop?.(item)\n announceCrossListReceive(item, insertAt)\n // Mark so the container's onDrop (which also fires) skips\n // re-inserting at the end of the list.\n ;(source.data as Record<string, unknown>).__pyreon_sortable_handled = true\n },\n }),\n )\n\n itemCleanups.set(key, cleanup)\n }\n\n onCleanup(() => {\n // Drain the live container registration (idempotent — containerRef(null)\n // may already have cleared it) plus every per-item registration.\n if (containerCleanup) {\n containerCleanup()\n containerCleanup = undefined\n }\n for (const cleanup of itemCleanups.values()) cleanup()\n itemCleanups.clear()\n itemEls.clear()\n itemHandles.clear()\n _sortableRegistry.delete(sortableId)\n // Selectors own a source-tracking effect + per-key buckets — release\n // them with the sortable (keys are unbounded across list churn).\n isActiveSelector.dispose()\n isOverSelector.dispose()\n // batch() the final 3-signal reset so any subscriber that survives\n // the dispose order (unusual but possible — e.g. an external store\n // holding refs) sees one notify, not three.\n batch(() => {\n activeId.set(null)\n overId.set(null)\n overEdge.set(null)\n })\n })\n\n return {\n containerRef,\n itemRef,\n itemHandleRef,\n activeId,\n overId,\n overEdge,\n isActive: (key: string | number) => isActiveSelector(key),\n isOverKey: (key: string | number) => isOverSelector(key),\n }\n}\n","import { name as __pkgName, version as __pkgVersion } from '../package.json' with { type: 'json' }\nimport { registerSingleton } from '@pyreon/reactivity'\n\n// Singleton sentinel — fail-loud detection of duplicate @pyreon/dnd\n// instances in the same heap. See @pyreon/reactivity/singleton-sentinel for\n// full rationale. Hardcoded version is acceptable here — it's a diagnostic\n// aid, not a load-bearing identity check.\nregisterSingleton(__pkgName, __pkgVersion, import.meta.url)\n\nexport type {\n DragData,\n DragPreviewOptions,\n DropEdge,\n DropLocation,\n UseDraggableOptions,\n UseDraggableResult,\n UseDroppableOptions,\n UseDroppableResult,\n UseSortableOptions,\n UseSortableResult,\n} from './types'\n\nexport type { UseDragMonitorOptions, UseDragMonitorResult } from './use-drag-monitor'\nexport { useDragMonitor } from './use-drag-monitor'\n\nexport { useDraggable } from './use-draggable'\nexport { useDroppable } from './use-droppable'\nexport type { FileRejectReason, UseFileDropOptions, UseFileDropResult } from './use-file-drop'\nexport { useFileDrop } from './use-file-drop'\nexport { useSortable } from './use-sortable'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACuCA,SAAgB,eAAe,SAAuD;CACpF,IAAI,UAAU,OAAO;EAAE,kBAAkB;EAAO,gBAAgB;CAAK;CAErE,MAAM,aAAa,OAAO,KAAK;CAC/B,MAAM,WAAW,OAAwB,IAAI;;CAG7C,MAAM,eAAe,SAAS,cACzB,EAAE,aACD,QAAQ,aAAa,OAAO,IAAgB,KAAK,OACnD;CAEJ,MAAM,UAAU,mBAAmB;EACjC,GAAI,eAAe,EAAE,YAAY,aAAa,IAAI,CAAC;EAC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CACH,CAAC;CAED,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,WAAW,QAAyB,iBAAiB,GAAG;EACxD,YAAY,QAAyB,eAAe,GAAG;CACzD;AACF;;;;ACxqBA,kBAAkBA,MAAWC,SAAc,YAAY,GAAG"}
@@ -0,0 +1,269 @@
1
+ import { staticPropKey, unwrapTypeLayers } from "@pyreon/native-compiler/plugin-api";
2
+
3
+ //#region src/native-plugin/stubs.ts
4
+ const DND_SWIFT_STUBS = `// @pyreon/dnd — the PyreonSortableState engine + its two View modifiers.
5
+ // Mirrors PyreonSortable.swift EXACTLY (minus @Observable/@available, which are
6
+ // runtime-reactivity/availability macros rather than type-level contract — the
7
+ // same omission PyreonTableState/PyreonNetworkStatus document).
8
+ public enum PyreonSortAxis: String, Equatable { case vertical, horizontal }
9
+ public enum PyreonDropEdge: String, Equatable { case top, bottom, left, right }
10
+ public final class PyreonSortableState<T> {
11
+ public init(axis: PyreonSortAxis = .vertical) {}
12
+ public func bind(
13
+ items: @escaping () -> [T],
14
+ by: @escaping (T) -> String,
15
+ onReorder: @escaping ([T]) -> Void
16
+ ) {}
17
+ public func isActive(_ key: String) -> Bool { false }
18
+ public func isOverKey(_ key: String) -> Bool { false }
19
+ public func activeId() -> String? { nil }
20
+ public func overId() -> String? { nil }
21
+ public func overEdge() -> String? { nil }
22
+ public func pickUp(_ key: String) {}
23
+ public func dragOver(_ key: String, edge: PyreonDropEdge) {}
24
+ public func dragLeave(_ key: String) {}
25
+ public func cancel() {}
26
+ @discardableResult
27
+ public func drop(source: String, on target: String, edge: PyreonDropEdge) -> Bool { false }
28
+ public static func moveIndex(_ list: [T], from: Int, to: Int) -> [T] { list }
29
+ public func reordered(dragKey: String, dropKey: String, edge: PyreonDropEdge) -> [T]? { nil }
30
+ public func edgeAt(_ point: CGPoint, in size: CGSize) -> PyreonDropEdge { .top }
31
+ public private(set) var activeKey: String?
32
+ public private(set) var overKey: String?
33
+ public private(set) var currentEdge: PyreonDropEdge?
34
+ public let axis: PyreonSortAxis = .vertical
35
+ }
36
+ extension View {
37
+ public func pyreonSortableItem<T>(
38
+ _ state: PyreonSortableState<T>,
39
+ key: String
40
+ ) -> some View { self }
41
+ public func pyreonSortableContainer<T>(
42
+ _ state: PyreonSortableState<T>
43
+ ) -> some View { self }
44
+ }
45
+ `;
46
+ const DND_KOTLIN_STUBS = `// @pyreon/dnd — the PyreonSortableState engine. Mirrors PyreonSortable.kt.
47
+ // The Modifier extensions it pairs with (PyreonSortableModifier.kt) are top-level
48
+ // extensions on Modifier in the real runtime, and are declared the same way here.
49
+ enum class PyreonSortAxis { VERTICAL, HORIZONTAL }
50
+ enum class PyreonDropEdge { TOP, BOTTOM, LEFT, RIGHT }
51
+ class PyreonSortableState<T>(
52
+ val axis: PyreonSortAxis = PyreonSortAxis.VERTICAL,
53
+ ) {
54
+ fun bind(items: () -> List<T>, by: (T) -> String, onReorder: (List<T>) -> Unit) {}
55
+ fun isActive(key: String): Boolean = false
56
+ fun isOverKey(key: String): Boolean = false
57
+ fun activeId(): String? = null
58
+ fun overId(): String? = null
59
+ fun overEdge(): String? = null
60
+ fun pickUp(key: String) {}
61
+ fun dragBy(delta: Float, extent: Float) {}
62
+ fun drop(): Boolean = false
63
+ fun cancel() {}
64
+ fun reordered(dragKey: String, dropKey: String, edge: PyreonDropEdge): List<T>? = null
65
+ val activeKey: String? get() = null
66
+ val overKey: String? get() = null
67
+ val currentEdge: PyreonDropEdge? get() = null
68
+ companion object {
69
+ fun <T> moveIndex(list: List<T>, from: Long, to: Long): List<T> = list
70
+ }
71
+ }
72
+ @Suppress("UNUSED_PARAMETER")
73
+ fun <T> Modifier.pyreonSortableItem(state: PyreonSortableState<T>, key: String): Modifier = this
74
+ @Suppress("UNUSED_PARAMETER")
75
+ fun <T> Modifier.pyreonSortableContainer(state: PyreonSortableState<T>): Modifier = this
76
+ `;
77
+ /** The `PyreonSortableState` compile-gate stubs, appended only to an emit that names the engine or its modifiers. */
78
+ const dndStubs = {
79
+ swift: (source) => /\bPyreonSort(?:ableState|Axis)\b|\bpyreonSortable(?:Item|Container)\b/.test(source) ? DND_SWIFT_STUBS : "",
80
+ kotlin: (source) => /\bPyreonSort(?:ableState|Axis)\b|\bpyreonSortable(?:Item|Container)\b/.test(source) ? DND_KOTLIN_STUBS : ""
81
+ };
82
+
83
+ //#endregion
84
+ //#region src/native-plugin/plugin.ts
85
+ const SORTABLE_TYPE = "sortable";
86
+ const DND_PLUGIN_NAME = "@pyreon/dnd";
87
+ const payloadOf = (decl) => decl.payload;
88
+ const recognizeSortable = (_call, ctx) => {
89
+ const name = ctx.declName;
90
+ const configArg = unwrapTypeLayers(ctx.args[0]);
91
+ if (!configArg || configArg.type !== "ObjectExpression") {
92
+ ctx.report(`useSortable declaration \`${name}\`: argument must be an object literal { items, by, onReorder } to lower natively. Falling back to silent-drop.`);
93
+ return;
94
+ }
95
+ let itemsBody;
96
+ let keyParam;
97
+ let keyBody;
98
+ let reorderParam;
99
+ let reorderBody;
100
+ let axis = "vertical";
101
+ for (const prop of configArg.properties ?? []) {
102
+ if (prop?.type !== "Property" && prop?.type !== "ObjectProperty") continue;
103
+ if (ctx.hasDynamicKey(prop)) {
104
+ ctx.warnDynamicKey(prop, `useSortable declaration \`${name}\`: config`);
105
+ continue;
106
+ }
107
+ const keyName = staticPropKey(prop);
108
+ if (!keyName) continue;
109
+ const valueNode = unwrapTypeLayers(prop.value);
110
+ if (keyName === "items") {
111
+ if ((valueNode?.type === "ArrowFunctionExpression" || valueNode?.type === "FunctionExpression") && valueNode.body?.type !== "BlockStatement") itemsBody = ctx.expr(valueNode.body);
112
+ } else if (keyName === "by") {
113
+ if (valueNode?.type === "ArrowFunctionExpression" && valueNode.params?.length === 1 && valueNode.body?.type !== "BlockStatement") {
114
+ const p = valueNode.params[0]?.name;
115
+ if (p !== void 0) {
116
+ keyParam = p;
117
+ keyBody = ctx.expr(valueNode.body);
118
+ }
119
+ }
120
+ } else if (keyName === "onReorder") {
121
+ if (valueNode?.type === "ArrowFunctionExpression") {
122
+ reorderParam = (valueNode.params?.[0])?.name ?? "next";
123
+ reorderBody = valueNode.body?.type === "BlockStatement" ? ctx.statements(valueNode.body) : [{
124
+ kind: "expr",
125
+ expr: ctx.expr(valueNode.body)
126
+ }];
127
+ }
128
+ } else if (keyName === "axis") {
129
+ if (valueNode?.type === "Literal" && valueNode.value === "horizontal") axis = "horizontal";
130
+ } else if (keyName === "groupId" || keyName === "onCrossListDrop" || keyName === "onCrossListReceive") ctx.report(`useSortable declaration \`${name}\`: \`${keyName}\` (cross-list boards) has NO native lowering — the native engine reorders WITHIN one list only, so a drag between two lists will not fire on iOS/Android. Keep a cross-list board behind a \`<Web>\` escape hatch, or model the move explicitly (remove from one signal, insert into the other).`);
131
+ else if (keyName === "label") ctx.report(`useSortable declaration \`${name}\`: \`label\` (screen-reader announcement text) is not used natively — VoiceOver/TalkBack announce the item's own accessibility label instead. Set \`accessibilityLabel\` on the row for a native-friendly announcement.`);
132
+ }
133
+ if (!itemsBody) {
134
+ ctx.report(`useSortable declaration \`${name}\`: \`items\` must be an expression-body getter (\`() => rows()\`) to lower natively. Falling back to silent-drop.`);
135
+ return;
136
+ }
137
+ if (keyParam === void 0 || !keyBody) {
138
+ ctx.report(`useSortable declaration \`${name}\`: \`by\` must be a single-param expression-body arrow (\`(item) => item.id\`) to lower natively. Falling back to silent-drop.`);
139
+ return;
140
+ }
141
+ if (reorderParam === void 0 || !reorderBody) {
142
+ ctx.report(`useSortable declaration \`${name}\`: \`onReorder\` must be an arrow function (\`(next) => items.set(next)\`) to lower natively. Falling back to silent-drop.`);
143
+ return;
144
+ }
145
+ return {
146
+ type: SORTABLE_TYPE,
147
+ payload: {
148
+ itemsBody,
149
+ keyParam,
150
+ keyBody,
151
+ reorderParam,
152
+ reorderBody,
153
+ axis
154
+ }
155
+ };
156
+ };
157
+ const rowElement = (type) => type.kind === "array" ? type.element : { kind: "unknown" };
158
+ /**
159
+ * The `by` key, coerced to `String`. The web `by` returns `string | number` (both are valid `<For by>` keys), but
160
+ * the native engine keys on `String` so one drag payload type serves every row type — `String` already conforms
161
+ * to `Transferable`, which is what lets a consumer's row type stay conformance-free. A string-typed key passes
162
+ * through unchanged; anything else is interpolated (total, and identical to `String(describing:)` for the scalar
163
+ * keys this accepts).
164
+ */
165
+ const swiftKey = (ctx, key, at) => {
166
+ const emitted = ctx.expr(key, at);
167
+ return ctx.inferType(key).kind === "string" ? emitted : `"\\(${emitted})"`;
168
+ };
169
+ const kotlinKey = (ctx, key, at) => {
170
+ const emitted = ctx.expr(key, at);
171
+ return ctx.inferType(key).kind === "string" ? emitted : `(${emitted}).toString()`;
172
+ };
173
+ const sortableDecl = {
174
+ legacyKind: SORTABLE_TYPE,
175
+ lifecycle: {
176
+ stableHost: true,
177
+ midOrder: 20,
178
+ swift(decl, ctx) {
179
+ const { itemsBody, keyParam, keyBody, reorderParam, reorderBody } = payloadOf(decl);
180
+ const name = ctx.ident(decl.name);
181
+ const body = reorderBody.length === 0 ? [""] : ctx.statements(reorderBody, 10).map((st) => ` ${st}`);
182
+ return [
183
+ `.onAppear {`,
184
+ ` ${name}.bind(`,
185
+ ` items: { ${ctx.expr(itemsBody, 10)} },`,
186
+ ` by: { ${ctx.ident(keyParam)} in ${swiftKey(ctx, keyBody, 10)} },`,
187
+ ` onReorder: { ${ctx.ident(reorderParam)} in`,
188
+ ...body,
189
+ ` }`,
190
+ ` )`,
191
+ `}`
192
+ ];
193
+ },
194
+ kotlin(decl, ctx) {
195
+ const { itemsBody, keyParam, keyBody, reorderParam, reorderBody } = payloadOf(decl);
196
+ const body = reorderBody.length === 0 ? [""] : ctx.statements(reorderBody, 4).map((st) => ` ${st}`);
197
+ return [
198
+ `${ctx.ident(decl.name)}.bind({ ${ctx.expr(itemsBody, 2)} }, { ${ctx.ident(keyParam)} -> ${kotlinKey(ctx, keyBody, 2)} }) { ${ctx.ident(reorderParam)} ->`,
199
+ ...body,
200
+ `}`
201
+ ];
202
+ }
203
+ },
204
+ swift(decl, ctx) {
205
+ const { itemsBody, axis } = payloadOf(decl);
206
+ const element = rowElement(ctx.inferType(itemsBody));
207
+ const axisArg = axis === "horizontal" ? "axis: .horizontal" : "";
208
+ return `@State private var ${ctx.ident(decl.name)} = PyreonSortableState<${ctx.rowType(element)}>(${axisArg})`;
209
+ },
210
+ kotlin(decl, ctx) {
211
+ const { itemsBody, axis } = payloadOf(decl);
212
+ const element = rowElement(ctx.inferType(itemsBody));
213
+ const axisArg = axis === "horizontal" ? "PyreonSortAxis.HORIZONTAL" : "";
214
+ return `val ${ctx.ident(decl.name)} = remember { PyreonSortableState<${ctx.rowType(element)}>(${axisArg}) }`;
215
+ }
216
+ };
217
+ function classifyRef(value, isSortable) {
218
+ if (value.kind === "member" && value.property === "containerRef" && value.object.kind === "identifier" && isSortable(value.object.name)) return {
219
+ kind: "container",
220
+ state: value.object.name
221
+ };
222
+ if (value.kind === "call" && value.callee.kind === "member" && value.callee.property === "itemRef" && value.callee.object.kind === "identifier" && isSortable(value.callee.object.name) && value.args.length === 1) return {
223
+ kind: "item",
224
+ state: value.callee.object.name,
225
+ key: value.args[0]
226
+ };
227
+ return null;
228
+ }
229
+ const bindsSortable = (ctx) => (name) => ctx.decls(DND_PLUGIN_NAME, SORTABLE_TYPE).some((d) => d.name === name);
230
+ /**
231
+ * `ref={s.containerRef}` / `ref={s.itemRef(key)}` → the sortable modifiers. Appended LAST so the drag wrapper sits
232
+ * outside the element's own padding / background, which is what an author writing the SwiftUI by hand would do
233
+ * (the lifted row carries its styling with it).
234
+ */
235
+ const sortableRefs = {
236
+ swift(ref, _el, ctx) {
237
+ const binding = classifyRef(ref, bindsSortable(ctx));
238
+ if (binding === null) return void 0;
239
+ const state = ctx.ident(binding.state);
240
+ return binding.kind === "container" ? `.pyreonSortableContainer(${state})` : `.pyreonSortableItem(${state}, key: ${swiftKey(ctx, binding.key, 0)})`;
241
+ },
242
+ kotlin(ref, _el, ctx) {
243
+ const binding = classifyRef(ref, bindsSortable(ctx));
244
+ if (binding === null) return void 0;
245
+ const state = ctx.ident(binding.state);
246
+ return binding.kind === "container" ? `.pyreonSortableContainer(${state})` : `.pyreonSortableItem(${state}, ${kotlinKey(ctx, binding.key, 0)})`;
247
+ }
248
+ };
249
+ /**
250
+ * The `@pyreon/dnd` native plugin. Shipped by `@pyreon/dnd` itself and discovered from its manifest
251
+ * (`pyreon.native.plugin`) when a source file imports the package.
252
+ */
253
+ const dndPlugin = {
254
+ name: DND_PLUGIN_NAME,
255
+ apiVersion: 2,
256
+ modules: ["@pyreon/dnd"],
257
+ calls: { useSortable: recognizeSortable },
258
+ decls: { [SORTABLE_TYPE]: sortableDecl },
259
+ refModifiers: sortableRefs,
260
+ unlowered: { "@pyreon/dnd": {
261
+ supported: ["useSortable"],
262
+ advice: "`useSortable({ items, by, onReorder })` DOES lower — it emits the native PyreonSortableState engine, and `ref={s.containerRef}` / `ref={s.itemRef(key)}` become SwiftUI .draggable/.dropDestination + Compose long-press drag modifiers. The element-getter hooks (useDraggable/useDroppable) are imperative DOM registration, useDragMonitor is a page-global drag bus, and useFileDrop is OS-level file DnD — none of the three has a native analogue"
263
+ } },
264
+ stubs: dndStubs
265
+ };
266
+
267
+ //#endregion
268
+ export { dndPlugin as default, dndPlugin, dndStubs };
269
+ //# sourceMappingURL=native-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native-plugin.js","names":[],"sources":["../src/native-plugin/stubs.ts","../src/native-plugin/plugin.ts"],"sourcesContent":["/**\n * The compile-gate stubs the `@pyreon/dnd` lowering's emit needs beyond the SwiftUI / Compose stub bundle: the\n * `PyreonSortableState` engine a `useSortable` declaration emits and the two modifiers `ref={s.containerRef}` /\n * `ref={s.itemRef(key)}` lower to. They mirror the REAL runtimes (`@pyreon/dnd/native`) exactly — a superset stub\n * masks real breakage, a narrower one manufactures it.\n *\n * Appended to the bundle only for an emit that names the engine (see {@link dndStubs}); the compiler never reads them.\n */\n\nimport type { StubAugmentation } from '@pyreon/native-compiler/plugin-api'\n\nexport const DND_SWIFT_STUBS = `// @pyreon/dnd — the PyreonSortableState engine + its two View modifiers.\n// Mirrors PyreonSortable.swift EXACTLY (minus @Observable/@available, which are\n// runtime-reactivity/availability macros rather than type-level contract — the\n// same omission PyreonTableState/PyreonNetworkStatus document).\npublic enum PyreonSortAxis: String, Equatable { case vertical, horizontal }\npublic enum PyreonDropEdge: String, Equatable { case top, bottom, left, right }\npublic final class PyreonSortableState<T> {\n public init(axis: PyreonSortAxis = .vertical) {}\n public func bind(\n items: @escaping () -> [T],\n by: @escaping (T) -> String,\n onReorder: @escaping ([T]) -> Void\n ) {}\n public func isActive(_ key: String) -> Bool { false }\n public func isOverKey(_ key: String) -> Bool { false }\n public func activeId() -> String? { nil }\n public func overId() -> String? { nil }\n public func overEdge() -> String? { nil }\n public func pickUp(_ key: String) {}\n public func dragOver(_ key: String, edge: PyreonDropEdge) {}\n public func dragLeave(_ key: String) {}\n public func cancel() {}\n @discardableResult\n public func drop(source: String, on target: String, edge: PyreonDropEdge) -> Bool { false }\n public static func moveIndex(_ list: [T], from: Int, to: Int) -> [T] { list }\n public func reordered(dragKey: String, dropKey: String, edge: PyreonDropEdge) -> [T]? { nil }\n public func edgeAt(_ point: CGPoint, in size: CGSize) -> PyreonDropEdge { .top }\n public private(set) var activeKey: String?\n public private(set) var overKey: String?\n public private(set) var currentEdge: PyreonDropEdge?\n public let axis: PyreonSortAxis = .vertical\n}\nextension View {\n public func pyreonSortableItem<T>(\n _ state: PyreonSortableState<T>,\n key: String\n ) -> some View { self }\n public func pyreonSortableContainer<T>(\n _ state: PyreonSortableState<T>\n ) -> some View { self }\n}\n`\n\nexport const DND_KOTLIN_STUBS = `// @pyreon/dnd — the PyreonSortableState engine. Mirrors PyreonSortable.kt.\n// The Modifier extensions it pairs with (PyreonSortableModifier.kt) are top-level\n// extensions on Modifier in the real runtime, and are declared the same way here.\nenum class PyreonSortAxis { VERTICAL, HORIZONTAL }\nenum class PyreonDropEdge { TOP, BOTTOM, LEFT, RIGHT }\nclass PyreonSortableState<T>(\n val axis: PyreonSortAxis = PyreonSortAxis.VERTICAL,\n) {\n fun bind(items: () -> List<T>, by: (T) -> String, onReorder: (List<T>) -> Unit) {}\n fun isActive(key: String): Boolean = false\n fun isOverKey(key: String): Boolean = false\n fun activeId(): String? = null\n fun overId(): String? = null\n fun overEdge(): String? = null\n fun pickUp(key: String) {}\n fun dragBy(delta: Float, extent: Float) {}\n fun drop(): Boolean = false\n fun cancel() {}\n fun reordered(dragKey: String, dropKey: String, edge: PyreonDropEdge): List<T>? = null\n val activeKey: String? get() = null\n val overKey: String? get() = null\n val currentEdge: PyreonDropEdge? get() = null\n companion object {\n fun <T> moveIndex(list: List<T>, from: Long, to: Long): List<T> = list\n }\n}\n@Suppress(\"UNUSED_PARAMETER\")\nfun <T> Modifier.pyreonSortableItem(state: PyreonSortableState<T>, key: String): Modifier = this\n@Suppress(\"UNUSED_PARAMETER\")\nfun <T> Modifier.pyreonSortableContainer(state: PyreonSortableState<T>): Modifier = this\n`\n\n/** The `PyreonSortableState` compile-gate stubs, appended only to an emit that names the engine or its modifiers. */\nexport const dndStubs: StubAugmentation = {\n swift: (source) => (/\\bPyreonSort(?:ableState|Axis)\\b|\\bpyreonSortable(?:Item|Container)\\b/.test(source) ? DND_SWIFT_STUBS : ''),\n kotlin: (source) => (/\\bPyreonSort(?:ableState|Axis)\\b|\\bpyreonSortable(?:Item|Container)\\b/.test(source) ? DND_KOTLIN_STUBS : ''),\n}\n","// How `@pyreon/dnd` crosses to native: `const s = useSortable({ items, by, onReorder, axis? })` lowers to the\n// `PyreonSortableState` engine both runtimes ship (list REORDER within one list). The web hook returns ref\n// callbacks the author attaches to DOM nodes; on native `ref={s.containerRef}` / `ref={s.itemRef(key)}` become\n// SwiftUI `.draggable` / `.dropDestination` and Compose long-press drag modifiers. The engine reads its source\n// and reorder sink through closures over the component's own state, so they are bound where the compiler binds\n// containers (`midOrder`): `.onAppear` on SwiftUI (a `@State` initializer cannot capture `self`), a `bind` call\n// in the composable body on Compose.\n//\n// v1 lowers the four load-bearing options. Options that would silently do NOTHING natively — `groupId` /\n// `onCrossListDrop` / `onCrossListReceive` (cross-list boards) and `label` (screen-reader announcement text) —\n// WARN by name rather than being dropped without a word, because a board that quietly stops accepting\n// cross-list drops on device is the worst possible failure.\n\nimport {\n staticPropKey,\n unwrapTypeLayers,\n type CallRecognizer,\n type CompilerPlugin,\n type DeclEmitter,\n type EmitContext,\n type ExprIR,\n type ExtDecl,\n type RefModifierLowering,\n type StatementIR,\n type TypeIR,\n} from '@pyreon/native-compiler/plugin-api'\nimport { dndStubs } from './stubs'\n\n// biome-ignore lint/suspicious/noExplicitAny: ESTree nodes are read structurally, as in the compiler.\ntype AnyNode = any\n\nconst SORTABLE_TYPE = 'sortable'\nexport const DND_PLUGIN_NAME = '@pyreon/dnd'\n\ninterface SortablePayload {\n readonly itemsBody: ExprIR\n readonly keyParam: string\n readonly keyBody: ExprIR\n readonly reorderParam: string\n readonly reorderBody: readonly StatementIR[]\n readonly axis: 'vertical' | 'horizontal'\n}\n\nconst payloadOf = (decl: ExtDecl): SortablePayload => decl.payload as unknown as SortablePayload\n\nconst recognizeSortable: CallRecognizer = (_call, ctx) => {\n const name = ctx.declName\n const configArg = unwrapTypeLayers(ctx.args[0] as AnyNode | undefined)\n if (!configArg || configArg.type !== 'ObjectExpression') {\n ctx.report(\n `useSortable declaration \\`${name}\\`: argument must be an object literal { items, by, onReorder } to lower natively. Falling back to silent-drop.`,\n )\n return undefined\n }\n\n let itemsBody: ExprIR | undefined\n let keyParam: string | undefined\n let keyBody: ExprIR | undefined\n let reorderParam: string | undefined\n let reorderBody: StatementIR[] | undefined\n let axis: 'vertical' | 'horizontal' = 'vertical'\n\n for (const prop of (configArg.properties as AnyNode[] | undefined) ?? []) {\n if (prop?.type !== 'Property' && prop?.type !== 'ObjectProperty') continue\n if (ctx.hasDynamicKey(prop)) {\n ctx.warnDynamicKey(prop, `useSortable declaration \\`${name}\\`: config`)\n continue\n }\n const keyName = staticPropKey(prop)\n if (!keyName) continue\n const valueNode = unwrapTypeLayers(prop.value as AnyNode | undefined)\n\n if (keyName === 'items') {\n // `items: () => rows()` — an expression-body getter, the same contract as createTableState's `data`.\n if ((valueNode?.type === 'ArrowFunctionExpression' || valueNode?.type === 'FunctionExpression') && valueNode.body?.type !== 'BlockStatement') {\n itemsBody = ctx.expr(valueNode.body as AnyNode)\n }\n } else if (keyName === 'by') {\n if (valueNode?.type === 'ArrowFunctionExpression' && (valueNode.params as AnyNode[] | undefined)?.length === 1 && valueNode.body?.type !== 'BlockStatement') {\n const p = ((valueNode.params as AnyNode[])[0] as AnyNode | undefined)?.name as string | undefined\n if (p !== undefined) {\n keyParam = p\n keyBody = ctx.expr(valueNode.body as AnyNode)\n }\n }\n } else if (keyName === 'onReorder') {\n // A VOID callback, so an expression body must lower to a bare expression statement — NOT a function declaration,\n // whose `return <expr>` is invalid inside a Kotlin lambda (`return` there targets the enclosing function, and an\n // assignment is not an expression).\n if (valueNode?.type === 'ArrowFunctionExpression') {\n const p = ((valueNode.params as AnyNode[] | undefined)?.[0] as AnyNode | undefined)?.name as string | undefined\n reorderParam = p ?? 'next'\n reorderBody =\n valueNode.body?.type === 'BlockStatement'\n ? ctx.statements(valueNode.body as AnyNode)\n : [{ kind: 'expr' as const, expr: ctx.expr(valueNode.body as AnyNode) }]\n }\n } else if (keyName === 'axis') {\n if (valueNode?.type === 'Literal' && valueNode.value === 'horizontal') axis = 'horizontal'\n } else if (keyName === 'groupId' || keyName === 'onCrossListDrop' || keyName === 'onCrossListReceive') {\n ctx.report(\n `useSortable declaration \\`${name}\\`: \\`${keyName}\\` (cross-list boards) has NO native lowering — the native engine reorders WITHIN one list only, so a drag between two lists will not fire on iOS/Android. Keep a cross-list board behind a \\`<Web>\\` escape hatch, or model the move explicitly (remove from one signal, insert into the other).`,\n )\n } else if (keyName === 'label') {\n ctx.report(\n `useSortable declaration \\`${name}\\`: \\`label\\` (screen-reader announcement text) is not used natively — VoiceOver/TalkBack announce the item's own accessibility label instead. Set \\`accessibilityLabel\\` on the row for a native-friendly announcement.`,\n )\n }\n }\n\n if (!itemsBody) {\n ctx.report(\n `useSortable declaration \\`${name}\\`: \\`items\\` must be an expression-body getter (\\`() => rows()\\`) to lower natively. Falling back to silent-drop.`,\n )\n return undefined\n }\n if (keyParam === undefined || !keyBody) {\n ctx.report(\n `useSortable declaration \\`${name}\\`: \\`by\\` must be a single-param expression-body arrow (\\`(item) => item.id\\`) to lower natively. Falling back to silent-drop.`,\n )\n return undefined\n }\n if (reorderParam === undefined || !reorderBody) {\n ctx.report(\n `useSortable declaration \\`${name}\\`: \\`onReorder\\` must be an arrow function (\\`(next) => items.set(next)\\`) to lower natively. Falling back to silent-drop.`,\n )\n return undefined\n }\n return { type: SORTABLE_TYPE, payload: { itemsBody, keyParam, keyBody, reorderParam, reorderBody, axis } as never }\n}\n\nconst rowElement = (type: TypeIR): TypeIR => (type.kind === 'array' ? type.element : { kind: 'unknown' })\n\n/**\n * The `by` key, coerced to `String`. The web `by` returns `string | number` (both are valid `<For by>` keys), but\n * the native engine keys on `String` so one drag payload type serves every row type — `String` already conforms\n * to `Transferable`, which is what lets a consumer's row type stay conformance-free. A string-typed key passes\n * through unchanged; anything else is interpolated (total, and identical to `String(describing:)` for the scalar\n * keys this accepts).\n */\nconst swiftKey = (ctx: EmitContext, key: ExprIR, at: number): string => {\n const emitted = ctx.expr(key, at)\n return ctx.inferType(key).kind === 'string' ? emitted : `\"\\\\(${emitted})\"`\n}\nconst kotlinKey = (ctx: EmitContext, key: ExprIR, at: number): string => {\n const emitted = ctx.expr(key, at)\n return ctx.inferType(key).kind === 'string' ? emitted : `(${emitted}).toString()`\n}\n\nconst sortableDecl: DeclEmitter = {\n // The declaration was a closed `sortable` compiler kind before it moved here; the struct names the compiler\n // derives from a declaration's shape hash it under that name, so emitted names did not move.\n legacyKind: SORTABLE_TYPE,\n lifecycle: {\n // A `.onAppear` on a transparent conditional would restart with every branch flip (see `DeclLifecycle.stableHost`).\n stableHost: true,\n midOrder: 20,\n swift(decl, ctx) {\n const { itemsBody, keyParam, keyBody, reorderParam, reorderBody } = payloadOf(decl)\n const name = ctx.ident(decl.name)\n // An empty callback body is ONE blank line (the statements joined), which a caller leaves unindented.\n const body = reorderBody.length === 0 ? [''] : ctx.statements(reorderBody, 10).map((st) => ` ${st}`)\n return [\n `.onAppear {`,\n ` ${name}.bind(`,\n ` items: { ${ctx.expr(itemsBody, 10)} },`,\n ` by: { ${ctx.ident(keyParam)} in ${swiftKey(ctx, keyBody, 10)} },`,\n ` onReorder: { ${ctx.ident(reorderParam)} in`,\n ...body,\n ` }`,\n ` )`,\n `}`,\n ]\n },\n kotlin(decl, ctx) {\n const { itemsBody, keyParam, keyBody, reorderParam, reorderBody } = payloadOf(decl)\n const body = reorderBody.length === 0 ? [''] : ctx.statements(reorderBody, 4).map((st) => ` ${st}`)\n return [\n `${ctx.ident(decl.name)}.bind({ ${ctx.expr(itemsBody, 2)} }, { ${ctx.ident(keyParam)} -> ${kotlinKey(ctx, keyBody, 2)} }) { ${ctx.ident(reorderParam)} ->`,\n ...body,\n `}`,\n ]\n },\n },\n swift(decl, ctx) {\n const { itemsBody, axis } = payloadOf(decl)\n const element = rowElement(ctx.inferType(itemsBody))\n const axisArg = axis === 'horizontal' ? 'axis: .horizontal' : ''\n return `@State private var ${ctx.ident(decl.name)} = PyreonSortableState<${ctx.rowType(element)}>(${axisArg})`\n },\n kotlin(decl, ctx) {\n const { itemsBody, axis } = payloadOf(decl)\n const element = rowElement(ctx.inferType(itemsBody))\n const axisArg = axis === 'horizontal' ? 'PyreonSortAxis.HORIZONTAL' : ''\n return `val ${ctx.ident(decl.name)} = remember { PyreonSortableState<${ctx.rowType(element)}>(${axisArg}) }`\n },\n}\n\n/** What a `ref` value binds: the sortable's container, or one item by key. `null` for every other ref, which keeps its existing behaviour. */\ntype SortableRefBinding = { readonly kind: 'container'; readonly state: string } | { readonly kind: 'item'; readonly state: string; readonly key: ExprIR }\n\nfunction classifyRef(value: ExprIR, isSortable: (name: string) => boolean): SortableRefBinding | null {\n // `ref={s.containerRef}` — a bare member read.\n if (value.kind === 'member' && value.property === 'containerRef' && value.object.kind === 'identifier' && isSortable(value.object.name)) {\n return { kind: 'container', state: value.object.name }\n }\n // `ref={s.itemRef(key)}` — a one-argument call on the member.\n if (\n value.kind === 'call' &&\n value.callee.kind === 'member' &&\n value.callee.property === 'itemRef' &&\n value.callee.object.kind === 'identifier' &&\n isSortable(value.callee.object.name) &&\n value.args.length === 1\n ) {\n return { kind: 'item', state: value.callee.object.name, key: value.args[0] as ExprIR }\n }\n return null\n}\n\nconst bindsSortable = (ctx: EmitContext) => (name: string) => ctx.decls(DND_PLUGIN_NAME, SORTABLE_TYPE).some((d) => d.name === name)\n\n/**\n * `ref={s.containerRef}` / `ref={s.itemRef(key)}` → the sortable modifiers. Appended LAST so the drag wrapper sits\n * outside the element's own padding / background, which is what an author writing the SwiftUI by hand would do\n * (the lifted row carries its styling with it).\n */\nconst sortableRefs: RefModifierLowering = {\n swift(ref, _el, ctx) {\n const binding = classifyRef(ref, bindsSortable(ctx))\n if (binding === null) return undefined\n const state = ctx.ident(binding.state)\n return binding.kind === 'container' ? `.pyreonSortableContainer(${state})` : `.pyreonSortableItem(${state}, key: ${swiftKey(ctx, binding.key, 0)})`\n },\n kotlin(ref, _el, ctx) {\n const binding = classifyRef(ref, bindsSortable(ctx))\n if (binding === null) return undefined\n const state = ctx.ident(binding.state)\n return binding.kind === 'container' ? `.pyreonSortableContainer(${state})` : `.pyreonSortableItem(${state}, ${kotlinKey(ctx, binding.key, 0)})`\n },\n}\n\n/**\n * The `@pyreon/dnd` native plugin. Shipped by `@pyreon/dnd` itself and discovered from its manifest\n * (`pyreon.native.plugin`) when a source file imports the package.\n */\nexport const dndPlugin: CompilerPlugin = {\n name: DND_PLUGIN_NAME,\n apiVersion: 2,\n modules: ['@pyreon/dnd'],\n calls: { useSortable: recognizeSortable },\n decls: { [SORTABLE_TYPE]: sortableDecl },\n refModifiers: sortableRefs,\n // `useSortable` lowers; the rest do not, and the reasons differ per hook rather than per package — so name the one\n // that crosses instead of letting the blanket \"web-only\" line imply none do.\n //\n // useDraggable / useDroppable take `element: () => HTMLElement | null` — an imperative DOM-registration shape with no\n // declarative analogue on either target. useDragMonitor is a page-global drag bus neither SwiftUI nor Compose\n // exposes. useFileDrop is an OS-level file drag between apps (iPad multitasking / Android multi-window), a different\n // model entirely.\n unlowered: {\n '@pyreon/dnd': {\n supported: ['useSortable'],\n advice:\n '`useSortable({ items, by, onReorder })` DOES lower — it emits the native PyreonSortableState engine, and `ref={s.containerRef}` / `ref={s.itemRef(key)}` become SwiftUI .draggable/.dropDestination + Compose long-press drag modifiers. The element-getter hooks (useDraggable/useDroppable) are imperative DOM registration, useDragMonitor is a page-global drag bus, and useFileDrop is OS-level file DnD — none of the three has a native analogue',\n },\n },\n stubs: dndStubs,\n}\n"],"mappings":";;;AAWA,MAAa,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2C/B,MAAa,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiChC,MAAa,WAA6B;CACxC,QAAQ,WAAY,wEAAwE,KAAK,MAAM,IAAI,kBAAkB;CAC7H,SAAS,WAAY,wEAAwE,KAAK,MAAM,IAAI,mBAAmB;AACjI;;;;AC3DA,MAAM,gBAAgB;AACtB,MAAa,kBAAkB;AAW/B,MAAM,aAAa,SAAmC,KAAK;AAE3D,MAAM,qBAAqC,OAAO,QAAQ;CACxD,MAAM,OAAO,IAAI;CACjB,MAAM,YAAY,iBAAiB,IAAI,KAAK,EAAyB;CACrE,IAAI,CAAC,aAAa,UAAU,SAAS,oBAAoB;EACvD,IAAI,OACF,6BAA6B,KAAK,gHACpC;EACA;CACF;CAEA,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,OAAkC;CAEtC,KAAK,MAAM,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