| 8 | } |
| 9 | |
| 10 | export const openFileDialog = ({ |
| 11 | accept = '*', |
| 12 | multiple = false, |
| 13 | onChange, |
| 14 | onError, |
| 15 | }: OpenFileDialogOptions) => { |
| 16 | const input = document.createElement('input') |
| 17 | input.type = 'file' |
| 18 | if (accept !== '*') input.accept = accept |
| 19 | input.style.display = 'none' |
| 20 | document.body.appendChild(input) |
| 21 | input.multiple = multiple |
| 22 | |
| 23 | input.addEventListener('change', e => { |
| 24 | if (onChange) onChange(Array.from(input.files ?? [])) |
| 25 | // remove element |
| 26 | document.body.removeChild(input) |
| 27 | }) |
| 28 | try { |
| 29 | // dispatch a click event to open the file dialog |
| 30 | input.dispatchEvent(new MouseEvent('click')) |
| 31 | } catch (error) { |
| 32 | if (onError) onError(error as Error) |
| 33 | document.body.removeChild(input) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | export const useFilePicker = ( |
| 38 | options: Omit<OpenFileDialogOptions, 'onChange' | 'onError'> = {}, |