-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
70 lines (59 loc) · 1.88 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { defaultDocument, resolveUnref, tryOnMounted, tryOnScopeDispose, unrefElement } from '@vueuse/core'
import type { ConfigurableDocument, MaybeComputedRef } from '@vueuse/core'
import Sortable, { type Options } from 'sortablejs'
import { nextTick } from 'vue-demi'
export interface UseSortableReturn {
/**
* start sortable instance
*/
start: () => void
/**
* destroy sortable instance
*/
stop: () => void
}
export type UseSortableOptions = Options & ConfigurableDocument
export function useSortable<T>(selector: string, list: MaybeComputedRef<T[]>,
options?: UseSortableOptions): UseSortableReturn
export function useSortable<T>(el: MaybeComputedRef<HTMLElement | null | undefined>, list: MaybeComputedRef<T[]>,
options?: UseSortableOptions): UseSortableReturn
/**
* Wrapper for sortablejs.
* @param el
* @param list
* @param options
*/
export function useSortable<T>(
el: MaybeComputedRef<HTMLElement | null | undefined> | string,
list: MaybeComputedRef<T[]>,
options: UseSortableOptions = {},
): UseSortableReturn {
let sortable: Sortable
const { document = defaultDocument, ...resetOptions } = options
const defaultOptions: Options = {
onUpdate: (e) => {
moveArrayElement(list, e.oldIndex!, e.newIndex!)
},
}
const start = () => {
const target = (typeof el === 'string' ? document?.querySelector(el) : unrefElement(el))
if (!target)
return
sortable = new Sortable(target as HTMLElement, { ...defaultOptions, ...resetOptions })
}
const stop = () => sortable?.destroy()
tryOnMounted(start)
tryOnScopeDispose(stop)
return { stop, start }
}
export function moveArrayElement<T>(
list: MaybeComputedRef<T[]>,
from: number,
to: number,
): void {
const array = resolveUnref(list)
if (to >= 0 && to < array.length) {
const element = array.splice(from, 1)[0]
nextTick(() => array.splice(to, 0, element))
}
}