@pyreon/dnd 0.24.5 → 0.25.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.
@@ -1,110 +0,0 @@
1
- import { effect, signal } from '@pyreon/reactivity'
2
- import { describe, expect, it, vi } from 'vitest'
3
-
4
- // F3 — useSortable per-item registration leak.
5
- //
6
- // pdnd is mocked here so the test isolates ONE thing: that useSortable
7
- // disposes each item's `combine(...)` cleanup on unmount (ref called with
8
- // `null`) and on re-register of the same key — instead of pushing every
9
- // registration onto a shared array drained only when the WHOLE sortable
10
- // unmounts. The real pdnd uses document-level listeners + a registry, so
11
- // there is no robust per-element DOM observable; mocking `combine` to
12
- // return a tracked spy is the deterministic, version-agnostic proxy.
13
- //
14
- // Scoped to its own file: vi.mock is module-global, and the rest of the
15
- // dnd suite needs the real pdnd.
16
-
17
- const combineCleanups: Array<ReturnType<typeof vi.fn>> = []
18
-
19
- vi.mock('@atlaskit/pragmatic-drag-and-drop/combine', () => ({
20
- combine: (..._fns: Array<() => void>) => {
21
- const cleanup = vi.fn()
22
- combineCleanups.push(cleanup)
23
- return cleanup
24
- },
25
- }))
26
- vi.mock('@atlaskit/pragmatic-drag-and-drop/element/adapter', () => ({
27
- draggable: () => () => {},
28
- dropTargetForElements: () => () => {},
29
- }))
30
- vi.mock('@atlaskit/pragmatic-drag-and-drop-auto-scroll/element', () => ({
31
- autoScrollForElements: () => () => {},
32
- }))
33
- vi.mock('@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge', () => ({
34
- attachClosestEdge: (data: unknown) => data,
35
- extractClosestEdge: () => null,
36
- }))
37
-
38
- describe('useSortable — per-item registration disposal (F3 leak)', () => {
39
- it('disposes the item cleanup on unmount and on re-register; no accumulation under churn', async () => {
40
- const { useSortable } = await import('../use-sortable')
41
- const items = signal([{ id: '1' }])
42
- const { itemRef } = useSortable({ items, by: (i) => i.id, onReorder: () => {} })
43
-
44
- combineCleanups.length = 0
45
-
46
- // Register one item.
47
- const ref = itemRef('1')
48
- ref(document.createElement('div'))
49
- expect(combineCleanups).toHaveLength(1)
50
- expect(combineCleanups[0]).not.toHaveBeenCalled()
51
-
52
- // Unmount (ref(null)) MUST run that registration's cleanup. Pre-fix
53
- // the null branch was a no-op → cleanup never ran → leak.
54
- ref(null)
55
- expect(combineCleanups[0]).toHaveBeenCalledTimes(1)
56
-
57
- // Re-register the SAME key with a new element: a fresh registration,
58
- // and the prior one stays disposed (not double-registered).
59
- itemRef('1')(document.createElement('div'))
60
- expect(combineCleanups).toHaveLength(2)
61
- expect(combineCleanups[1]).not.toHaveBeenCalled()
62
- ;(itemRef('1') as (el: HTMLElement | null) => void)(null)
63
- expect(combineCleanups[1]).toHaveBeenCalledTimes(1)
64
-
65
- // Churn: 200 register/unmount cycles for the same key. Every
66
- // registration's cleanup must have been called exactly once — the
67
- // live set never accumulates dead registrations.
68
- const base = combineCleanups.length
69
- for (let i = 0; i < 200; i++) {
70
- const r = itemRef(`k${i}`)
71
- r(document.createElement('div'))
72
- r(null)
73
- }
74
- const churned = combineCleanups.slice(base)
75
- expect(churned).toHaveLength(200)
76
- for (const c of churned) expect(c).toHaveBeenCalledTimes(1)
77
- })
78
-
79
- it('component onCleanup drains BOTH container and per-item registrations (F3)', async () => {
80
- // Covers the `onCleanup` block: when the sortable's owner is
81
- // disposed, the shared container `cleanups[]` AND the per-key
82
- // `itemCleanups` map are both drained (F3 added the itemCleanups
83
- // drain). Runs inside a disposable `effect` so useSortable's
84
- // `onCleanup` actually registers + fires.
85
- const { useSortable } = await import('../use-sortable')
86
- combineCleanups.length = 0
87
-
88
- let itemRefFn: ((el: HTMLElement | null) => void) | null = null
89
- let containerRefFn: ((el: HTMLElement | null) => void) | null = null
90
- const owner = effect(() => {
91
- const items = signal([{ id: '1' }])
92
- const s = useSortable({ items, by: (i) => i.id, onReorder: () => {} })
93
- containerRefFn = s.containerRef
94
- itemRefFn = s.itemRef('1')
95
- })
96
-
97
- // Populate the container cleanups (dropTarget + autoScroll + keydown)
98
- // and one per-item registration so BOTH drain paths execute.
99
- containerRefFn!(document.createElement('div'))
100
- itemRefFn!(document.createElement('div'))
101
- const itemCleanup = combineCleanups[combineCleanups.length - 1]!
102
- expect(itemCleanup).not.toHaveBeenCalled()
103
-
104
- // Dispose the owner → useSortable's onCleanup runs.
105
- owner.dispose()
106
-
107
- // The per-item registration was disposed via the itemCleanups drain.
108
- expect(itemCleanup).toHaveBeenCalledTimes(1)
109
- })
110
- })
package/src/types.ts DELETED
@@ -1,92 +0,0 @@
1
- /** Data attached to a draggable item. */
2
- export type DragData = Record<string, unknown>
3
-
4
- /** Position of a drop relative to the target element. */
5
- export type DropEdge = 'top' | 'bottom' | 'left' | 'right'
6
-
7
- /** Drop location information. */
8
- export interface DropLocation {
9
- /** The edge closest to the drop point. */
10
- edge: DropEdge | null
11
- /** Custom data attached to the drop target. */
12
- data: DragData
13
- }
14
-
15
- // ─── useDraggable ───────────────────────────────────────────────────────────
16
-
17
- export interface UseDraggableOptions<T extends DragData = DragData> {
18
- /** Ref callback or element getter for the draggable element. */
19
- element: () => HTMLElement | null
20
- /** Data to transfer on drag. Can be a function for dynamic data. */
21
- data: T | (() => T)
22
- /** Optional drag handle element (subset of the draggable). */
23
- handle?: () => HTMLElement | null
24
- /** Whether dragging is disabled. Reactive. */
25
- disabled?: boolean | (() => boolean)
26
- /** Called when drag starts. */
27
- onDragStart?: () => void
28
- /** Called when drag ends (drop or cancel). */
29
- onDragEnd?: () => void
30
- }
31
-
32
- export interface UseDraggableResult {
33
- /** Whether this element is currently being dragged. */
34
- isDragging: () => boolean
35
- }
36
-
37
- // ─── useDroppable ───────────────────────────────────────────────────────────
38
-
39
- export interface UseDroppableOptions<T extends DragData = DragData> {
40
- /** Ref callback or element getter for the drop target. */
41
- element: () => HTMLElement | null
42
- /** Data to attach to the drop target. */
43
- data?: T | (() => T)
44
- /** Filter what can be dropped. Return false to reject. */
45
- canDrop?: (sourceData: DragData) => boolean
46
- /** Called when a draggable enters this target. */
47
- onDragEnter?: (sourceData: DragData) => void
48
- /** Called when a draggable leaves this target. */
49
- onDragLeave?: () => void
50
- /** Called when an item is dropped on this target. */
51
- onDrop?: (sourceData: DragData) => void
52
- }
53
-
54
- export interface UseDroppableResult {
55
- /** Whether something is currently being dragged over this target. */
56
- isOver: () => boolean
57
- }
58
-
59
- // ─── useSortable ────────────────────────────────────────────────────────────
60
-
61
- export interface UseSortableOptions<T> {
62
- /** Reactive list of items to sort. */
63
- items: () => T[]
64
- /** Key extractor — matches Pyreon's <For by={...}> pattern. */
65
- by: (item: T) => string | number
66
- /** Called with the reordered items after a drop. */
67
- onReorder: (items: T[]) => void
68
- /** Sort axis. Default: "vertical". */
69
- axis?: 'vertical' | 'horizontal'
70
- }
71
-
72
- export interface UseSortableResult {
73
- /**
74
- * Attach to the scroll container. Pyreon's runtime invokes refs with
75
- * `T | null` (called with `null` on unmount), so the parameter widens
76
- * accordingly. The hook ignores `null` calls — they're a no-op
77
- * because the underlying pdnd cleanup is registered via `onCleanup`.
78
- */
79
- containerRef: (el: HTMLElement | null) => void
80
- /**
81
- * Attach to each sortable item. Call with the item's key — the
82
- * returned callback accepts `T | null` for the same Pyreon `RefProp`
83
- * compatibility reason as `containerRef` above.
84
- */
85
- itemRef: (key: string | number) => (el: HTMLElement | null) => void
86
- /** The key of the currently dragging item. */
87
- activeId: () => string | number | null
88
- /** The key of the item being hovered over. */
89
- overId: () => string | number | null
90
- /** The closest edge of the hovered item ("top"/"bottom" or "left"/"right"). */
91
- overEdge: () => DropEdge | null
92
- }
@@ -1,69 +0,0 @@
1
- import { monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
2
- import { onCleanup, signal } from '@pyreon/reactivity'
3
- import type { DragData } from './types'
4
-
5
- export interface UseDragMonitorOptions {
6
- /** Called on any drag start in the page. */
7
- onDragStart?: (data: DragData) => void
8
- /** Called on any drop in the page. */
9
- onDrop?: (sourceData: DragData, targetData: DragData) => void
10
- /** Filter which drags to monitor. */
11
- canMonitor?: (data: DragData) => boolean
12
- }
13
-
14
- export interface UseDragMonitorResult {
15
- /** Whether any element is currently being dragged. */
16
- isDragging: () => boolean
17
- /** Data of the currently dragging element (null if not dragging). */
18
- dragData: () => DragData | null
19
- }
20
-
21
- /**
22
- * Monitor all drag operations on the page.
23
- * Useful for global drag indicators, analytics, or coordination between
24
- * multiple drag-and-drop areas.
25
- *
26
- * @example
27
- * ```tsx
28
- * const { isDragging, dragData } = useDragMonitor({
29
- * canMonitor: (data) => data.type === "card",
30
- * onDrop: (source, target) => logDrop(source, target),
31
- * })
32
- *
33
- * <Show when={isDragging()}>
34
- * <div class="global-drag-overlay">
35
- * Dragging: {() => dragData()?.name}
36
- * </div>
37
- * </Show>
38
- * ```
39
- */
40
- export function useDragMonitor(options?: UseDragMonitorOptions): UseDragMonitorResult {
41
- if (typeof document === 'undefined') return { isDragging: () => false, dragData: () => null }
42
-
43
- const isDragging = signal(false)
44
- const dragData = signal<DragData | null>(null)
45
-
46
- const canMonitorFn = options?.canMonitor
47
- ? ({ source }: { source: { data: Record<string, unknown> } }) =>
48
- options.canMonitor?.(source.data as DragData) ?? true
49
- : null
50
-
51
- const cleanup = monitorForElements({
52
- ...(canMonitorFn ? { canMonitor: canMonitorFn } : {}),
53
- onDragStart: ({ source }) => {
54
- isDragging.set(true)
55
- dragData.set(source.data as DragData)
56
- options?.onDragStart?.(source.data as DragData)
57
- },
58
- onDrop: ({ source, location }) => {
59
- isDragging.set(false)
60
- dragData.set(null)
61
- const targetData = location.current.dropTargets[0]?.data ?? {}
62
- options?.onDrop?.(source.data as DragData, targetData as DragData)
63
- },
64
- })
65
-
66
- onCleanup(cleanup)
67
-
68
- return { isDragging, dragData }
69
- }
@@ -1,68 +0,0 @@
1
- import { draggable } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
2
- import { onCleanup, signal } from '@pyreon/reactivity'
3
- import type { DragData, UseDraggableOptions, UseDraggableResult } from './types'
4
-
5
- /**
6
- * Make an element draggable with signal-driven state.
7
- *
8
- * @example
9
- * ```tsx
10
- * let cardEl: HTMLElement | null = null
11
- *
12
- * const { isDragging } = useDraggable({
13
- * element: () => cardEl,
14
- * data: { id: card.id, type: "card" },
15
- * })
16
- *
17
- * <div ref={(el) => cardEl = el} class={isDragging() ? "opacity-50" : ""}>
18
- * {card.title}
19
- * </div>
20
- * ```
21
- */
22
- export function useDraggable<T extends DragData = DragData>(
23
- options: UseDraggableOptions<T>,
24
- ): UseDraggableResult {
25
- if (typeof document === 'undefined') return { isDragging: () => false }
26
-
27
- const isDragging = signal(false)
28
- let cleanup: (() => void) | undefined
29
-
30
- function setup() {
31
- if (cleanup) cleanup()
32
-
33
- const el = options.element()
34
- if (!el) return
35
-
36
- const resolveData = () =>
37
- typeof options.data === 'function' ? (options.data as () => T)() : options.data
38
-
39
- const handle = options.handle?.()
40
- cleanup = draggable({
41
- element: el,
42
- ...(handle ? { dragHandle: handle } : {}),
43
- getInitialData: resolveData,
44
- canDrag: () => {
45
- const disabled = options.disabled
46
- if (typeof disabled === 'function') return !disabled()
47
- return !disabled
48
- },
49
- onDragStart: () => {
50
- isDragging.set(true)
51
- options.onDragStart?.()
52
- },
53
- onDrop: () => {
54
- isDragging.set(false)
55
- options.onDragEnd?.()
56
- },
57
- })
58
- }
59
-
60
- // Defer setup to next microtask so refs are populated
61
- queueMicrotask(setup)
62
-
63
- onCleanup(() => {
64
- if (cleanup) cleanup()
65
- })
66
-
67
- return { isDragging }
68
- }
@@ -1,69 +0,0 @@
1
- import { dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
2
- import { onCleanup, signal } from '@pyreon/reactivity'
3
- import type { DragData, UseDroppableOptions, UseDroppableResult } from './types'
4
-
5
- /**
6
- * Make an element a drop target with signal-driven state.
7
- *
8
- * @example
9
- * ```tsx
10
- * let zoneEl: HTMLElement | null = null
11
- *
12
- * const { isOver } = useDroppable({
13
- * element: () => zoneEl,
14
- * onDrop: (data) => handleDrop(data),
15
- * canDrop: (data) => data.type === "card",
16
- * })
17
- *
18
- * <div ref={(el) => zoneEl = el} class={isOver() ? "bg-blue-50" : ""}>
19
- * Drop here
20
- * </div>
21
- * ```
22
- */
23
- export function useDroppable<T extends DragData = DragData>(
24
- options: UseDroppableOptions<T>,
25
- ): UseDroppableResult {
26
- if (typeof document === 'undefined') return { isOver: () => false }
27
-
28
- const isOver = signal(false)
29
- let cleanup: (() => void) | undefined
30
-
31
- function setup() {
32
- if (cleanup) cleanup()
33
-
34
- const el = options.element()
35
- if (!el) return
36
-
37
- cleanup = dropTargetForElements({
38
- element: el,
39
- getData: () => {
40
- if (!options.data) return {}
41
- return typeof options.data === 'function' ? (options.data as () => T)() : options.data
42
- },
43
- canDrop: ({ source }) => {
44
- if (!options.canDrop) return true
45
- return options.canDrop(source.data as DragData)
46
- },
47
- onDragEnter: ({ source }) => {
48
- isOver.set(true)
49
- options.onDragEnter?.(source.data as DragData)
50
- },
51
- onDragLeave: () => {
52
- isOver.set(false)
53
- options.onDragLeave?.()
54
- },
55
- onDrop: ({ source }) => {
56
- isOver.set(false)
57
- options.onDrop?.(source.data as DragData)
58
- },
59
- })
60
- }
61
-
62
- queueMicrotask(setup)
63
-
64
- onCleanup(() => {
65
- if (cleanup) cleanup()
66
- })
67
-
68
- return { isOver }
69
- }
@@ -1,148 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
- import { useFileDrop } from './use-file-drop'
3
-
4
- // Real-Chromium browser test for `useFileDrop`'s drop pathway. The
5
- // happy-dom unit suite (`src/tests/dnd.test.ts`) covers the signal
6
- // surface — `isOver`, `isDraggingFiles`, accept-filter wiring — but
7
- // can't drive pragmatic-drag-and-drop's external/file adapter end-to-
8
- // end because happy-dom's `DataTransfer` polyfill is incomplete enough
9
- // that the adapter's window-level dragenter activation rejects the
10
- // synthetic event.
11
- //
12
- // This test uses pdnd's official Playwright pattern (window-level
13
- // `dragenter` + element-level `dragover` + `drop`, all sharing one
14
- // DataTransfer) — same shape as the app-showcase `/dnd` e2e file-drop
15
- // spec — but at the package level so a regression in `useFileDrop`'s
16
- // `onDrop` wiring surfaces in `bun run test:browser` against
17
- // @pyreon/dnd directly, before any consumer-app e2e runs.
18
- //
19
- // Why both this AND the e2e spec: the e2e exercises the FULL stack
20
- // (Pyreon JSX → ref-callback → element resolution → pdnd → onDrop →
21
- // signal write → DOM update). This unit-level test isolates the
22
- // PDND-bridge layer — if pdnd updates and breaks `getFiles({source})`
23
- // or the `onDrop` callback signature, this test fails BEFORE the e2e
24
- // (which depends on a 100+ ms dev-server boot).
25
-
26
- describe('useFileDrop — real-Chromium drop flow', () => {
27
- it('fires onDrop with the dropped File when the full pdnd sequence runs', async () => {
28
- const dropZone = document.createElement('div')
29
- dropZone.style.cssText = 'width: 200px; height: 200px'
30
- document.body.appendChild(dropZone)
31
-
32
- let received: File[] | null = null
33
- const result = useFileDrop({
34
- element: () => dropZone,
35
- onDrop: (files) => {
36
- received = files
37
- },
38
- })
39
-
40
- // pdnd registers its drop target asynchronously via `queueMicrotask`
41
- // (see `use-file-drop.ts` setup function). Yield a microtask so the
42
- // adapter is wired before we dispatch.
43
- await Promise.resolve()
44
- await new Promise<void>((r) => setTimeout(r, 0))
45
-
46
- const file = new File(['<bytes>'], 'avatar.png', { type: 'image/png' })
47
- const dataTransfer = new DataTransfer()
48
- dataTransfer.items.add(file)
49
-
50
- // 1. `dragenter` on `window` activates pdnd's external adapter.
51
- // Bubbling a zone-targeted dragenter is platform-fragile (works
52
- // on macOS Chromium, fails on Linux Chromium under headless);
53
- // dispatching directly on window is the deterministic path
54
- // documented in pdnd's own Playwright suite.
55
- window.dispatchEvent(new DragEvent('dragenter', { dataTransfer }))
56
-
57
- // 2. `dragover` + `drop` on the zone with the same DataTransfer
58
- // instance — pdnd reads the file list from the event's transfer
59
- // at drop time.
60
- dropZone.dispatchEvent(new DragEvent('dragover', { dataTransfer }))
61
- dropZone.dispatchEvent(new DragEvent('drop', { dataTransfer }))
62
-
63
- // pdnd's onDrop fires synchronously off the drop event, but the
64
- // signal write is wrapped in our cleanup-aware effect — yield once
65
- // more to let any pending microtasks flush.
66
- await Promise.resolve()
67
-
68
- expect(received).not.toBeNull()
69
- expect(received).toHaveLength(1)
70
- expect(received![0]!.name).toBe('avatar.png')
71
- expect(received![0]!.type).toBe('image/png')
72
- expect(result.isOver()).toBe(false)
73
-
74
- dropZone.remove()
75
- })
76
-
77
- it('filters out files that fail the `accept` pattern', async () => {
78
- const dropZone = document.createElement('div')
79
- dropZone.style.cssText = 'width: 200px; height: 200px'
80
- document.body.appendChild(dropZone)
81
-
82
- let received: File[] | null = null
83
- useFileDrop({
84
- element: () => dropZone,
85
- // PDF-only accept — image file should be rejected.
86
- accept: ['application/pdf'],
87
- onDrop: (files) => {
88
- received = files
89
- },
90
- })
91
-
92
- await Promise.resolve()
93
- await new Promise<void>((r) => setTimeout(r, 0))
94
-
95
- const file = new File(['<bytes>'], 'avatar.png', { type: 'image/png' })
96
- const dataTransfer = new DataTransfer()
97
- dataTransfer.items.add(file)
98
-
99
- window.dispatchEvent(new DragEvent('dragenter', { dataTransfer }))
100
- dropZone.dispatchEvent(new DragEvent('dragover', { dataTransfer }))
101
- dropZone.dispatchEvent(new DragEvent('drop', { dataTransfer }))
102
-
103
- await Promise.resolve()
104
-
105
- // The hook filters BEFORE invoking `onDrop` — when zero files
106
- // survive the filter, `onDrop` is never called.
107
- expect(received).toBeNull()
108
-
109
- dropZone.remove()
110
- })
111
-
112
- it('respects maxFiles by truncating the dropped list', async () => {
113
- const dropZone = document.createElement('div')
114
- dropZone.style.cssText = 'width: 200px; height: 200px'
115
- document.body.appendChild(dropZone)
116
-
117
- let received: File[] | null = null
118
- useFileDrop({
119
- element: () => dropZone,
120
- accept: ['image/*'],
121
- maxFiles: 2,
122
- onDrop: (files) => {
123
- received = files
124
- },
125
- })
126
-
127
- await Promise.resolve()
128
- await new Promise<void>((r) => setTimeout(r, 0))
129
-
130
- const dataTransfer = new DataTransfer()
131
- dataTransfer.items.add(new File(['a'], 'a.png', { type: 'image/png' }))
132
- dataTransfer.items.add(new File(['b'], 'b.png', { type: 'image/png' }))
133
- dataTransfer.items.add(new File(['c'], 'c.png', { type: 'image/png' }))
134
-
135
- window.dispatchEvent(new DragEvent('dragenter', { dataTransfer }))
136
- dropZone.dispatchEvent(new DragEvent('dragover', { dataTransfer }))
137
- dropZone.dispatchEvent(new DragEvent('drop', { dataTransfer }))
138
-
139
- await Promise.resolve()
140
-
141
- expect(received).not.toBeNull()
142
- expect(received).toHaveLength(2) // truncated from 3
143
- expect(received![0]!.name).toBe('a.png')
144
- expect(received![1]!.name).toBe('b.png')
145
-
146
- dropZone.remove()
147
- })
148
- })
@@ -1,133 +0,0 @@
1
- import {
2
- dropTargetForExternal,
3
- monitorForExternal,
4
- } from '@atlaskit/pragmatic-drag-and-drop/external/adapter'
5
- import { containsFiles, getFiles } from '@atlaskit/pragmatic-drag-and-drop/external/file'
6
- import { onCleanup, signal } from '@pyreon/reactivity'
7
-
8
- export interface UseFileDropOptions {
9
- /** Element getter for the drop zone. */
10
- element: () => HTMLElement | null
11
- /** Called when files are dropped. */
12
- onDrop: (files: File[]) => void
13
- /** Filter accepted file types (e.g. ["image/*", ".pdf"]). */
14
- accept?: string[]
15
- /** Maximum number of files. */
16
- maxFiles?: number
17
- /** Whether drop is disabled. */
18
- disabled?: boolean | (() => boolean)
19
- }
20
-
21
- export interface UseFileDropResult {
22
- /** Whether files are being dragged over the drop zone. */
23
- isOver: () => boolean
24
- /** Whether files are being dragged anywhere on the page. */
25
- isDraggingFiles: () => boolean
26
- }
27
-
28
- /**
29
- * File drop zone with signal-driven state.
30
- * Uses the native file drag events via pragmatic-drag-and-drop.
31
- *
32
- * @example
33
- * ```tsx
34
- * let dropZone: HTMLElement | null = null
35
- *
36
- * const { isOver, isDraggingFiles } = useFileDrop({
37
- * element: () => dropZone,
38
- * accept: ["image/*", ".pdf"],
39
- * maxFiles: 5,
40
- * onDrop: (files) => upload(files),
41
- * })
42
- *
43
- * <div
44
- * ref={(el) => dropZone = el}
45
- * class={isOver() ? "drop-active" : isDraggingFiles() ? "drop-ready" : ""}
46
- * >
47
- * Drop files here
48
- * </div>
49
- * ```
50
- */
51
- export function useFileDrop(options: UseFileDropOptions): UseFileDropResult {
52
- if (typeof document === 'undefined') return { isOver: () => false, isDraggingFiles: () => false }
53
-
54
- const isOver = signal(false)
55
- const isDraggingFiles = signal(false)
56
- let cleanup: (() => void) | undefined
57
-
58
- function matchesAccept(file: File, accept: string[]): boolean {
59
- return accept.some((pattern) => {
60
- if (pattern.startsWith('.')) {
61
- return file.name.toLowerCase().endsWith(pattern.toLowerCase())
62
- }
63
- if (pattern.endsWith('/*')) {
64
- return file.type.startsWith(pattern.slice(0, -1))
65
- }
66
- return file.type === pattern
67
- })
68
- }
69
-
70
- function setup() {
71
- if (cleanup) cleanup()
72
-
73
- const el = options.element()
74
- if (!el) return
75
-
76
- const cleanups: (() => void)[] = []
77
-
78
- // Monitor for file drags anywhere on the page
79
- cleanups.push(
80
- monitorForExternal({
81
- canMonitor: ({ source }) => containsFiles({ source }),
82
- onDragStart: () => isDraggingFiles.set(true),
83
- onDrop: () => isDraggingFiles.set(false),
84
- }),
85
- )
86
-
87
- // Drop target on the specific element
88
- cleanups.push(
89
- dropTargetForExternal({
90
- element: el,
91
- canDrop: ({ source }) => {
92
- const disabled = options.disabled
93
- if (typeof disabled === 'function' ? disabled() : disabled) return false
94
- return containsFiles({ source })
95
- },
96
- onDragEnter: () => isOver.set(true),
97
- onDragLeave: () => isOver.set(false),
98
- onDrop: ({ source }) => {
99
- isOver.set(false)
100
- isDraggingFiles.set(false)
101
-
102
- let files = getFiles({ source })
103
-
104
- // Filter by accept
105
- if (options.accept && options.accept.length > 0) {
106
- files = files.filter((f) => matchesAccept(f, options.accept as string[]))
107
- }
108
-
109
- // Limit count
110
- if (options.maxFiles && files.length > options.maxFiles) {
111
- files = files.slice(0, options.maxFiles)
112
- }
113
-
114
- if (files.length > 0) {
115
- options.onDrop(files)
116
- }
117
- },
118
- }),
119
- )
120
-
121
- cleanup = () => {
122
- for (const fn of cleanups) fn()
123
- }
124
- }
125
-
126
- queueMicrotask(setup)
127
-
128
- onCleanup(() => {
129
- if (cleanup) cleanup()
130
- })
131
-
132
- return { isOver, isDraggingFiles }
133
- }