-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
82 lines (71 loc) · 1.77 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
71
72
73
74
75
76
77
78
79
80
81
82
import { type Ref, readonly, ref } from 'vue-demi'
import type { ConfigurableDocument } from '../_configurable'
import { defaultDocument } from '../_configurable'
export interface UseFileDialogOptions extends ConfigurableDocument {
/**
* @default true
*/
multiple?: boolean
/**
* @default '*'
*/
accept?: string
/**
* Select the input source for the capture file.
* @see [HTMLInputElement Capture](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/capture)
*/
capture?: string
}
const DEFAULT_OPTIONS: UseFileDialogOptions = {
multiple: true,
accept: '*',
}
export interface UseFileDialogReturn {
files: Ref<FileList | null>
open: (localOptions?: Partial<UseFileDialogOptions>) => void
reset: () => void
}
/**
* Open file dialog with ease.
*
* @see https://vueuse.org/useFileDialog
* @param options
*/
export function useFileDialog(options: UseFileDialogOptions = {}): UseFileDialogReturn {
const {
document = defaultDocument,
} = options
const files = ref<FileList | null>(null)
let input: HTMLInputElement | undefined
if (document) {
input = document.createElement('input')
input.type = 'file'
input.onchange = (event: Event) => {
const result = event.target as HTMLInputElement
files.value = result.files
}
}
const open = (localOptions?: Partial<UseFileDialogOptions>) => {
if (!input)
return
const _options = {
...DEFAULT_OPTIONS,
...options,
...localOptions,
}
input.multiple = _options.multiple!
input.accept = _options.accept!
input.capture = _options.capture!
input.click()
}
const reset = () => {
files.value = null
if (input)
input.value = ''
}
return {
files: readonly(files),
open,
reset,
}
}