-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
component.ts
74 lines (69 loc) · 1.97 KB
/
component.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
71
72
73
74
import { computed, defineComponent, h, reactive, ref } from 'vue-demi'
import type { UseDraggableOptions } from '@vueuse/core'
import { isClient, useDraggable, useStorage } from '@vueuse/core'
import { toValue } from '@vueuse/shared'
import type { Position, RenderableComponent } from '../types'
export interface UseDraggableProps extends UseDraggableOptions, RenderableComponent {
/**
* When provided, use `useStorage` to preserve element's position
*/
storageKey?: string
/**
* Storage type
*
* @default 'local'
*/
storageType?: 'local' | 'session'
}
export const UseDraggable = /* #__PURE__ */ defineComponent<UseDraggableProps>({
name: 'UseDraggable',
props: [
'storageKey',
'storageType',
'initialValue',
'exact',
'preventDefault',
'stopPropagation',
'pointerTypes',
'as',
'handle',
'axis',
'onStart',
'onMove',
'onEnd',
'disabled',
] as unknown as undefined,
setup(props, { slots }) {
const target = ref()
const handle = computed(() => props.handle ?? target.value)
const disabled = computed(() => !!props.disabled)
const storageValue = props.storageKey && useStorage(
props.storageKey,
toValue(props.initialValue) || { x: 0, y: 0 },
isClient
? props.storageType === 'session'
? sessionStorage
: localStorage
: undefined,
)
const initialValue = storageValue || props.initialValue || { x: 0, y: 0 }
const onEnd = (position: Position, event: PointerEvent) => {
props.onEnd?.(position, event)
if (!storageValue)
return
storageValue.value.x = position.x
storageValue.value.y = position.y
}
const data = reactive(useDraggable(target, {
...props,
handle,
initialValue,
onEnd,
disabled,
}))
return () => {
if (slots.default)
return h(props.as || 'div', { ref: target, style: `touch-action:none;${data.style}` }, slots.default(data))
}
},
})