@sv-use/core
Version:
A collection of Svelte 5 utilities.
55 lines (54 loc) • 1.57 kB
JavaScript
import { onDestroy } from 'svelte';
import { BROWSER } from 'esm-env';
import { handleEventListener } from '../handle-event-listener/index.svelte.js';
/**
* Creates a file dialog to interact with programatically.
* @param options Additional options to customize the behavior.
* @see https://svelte-librarian.github.io/sv-use/docs/core/create-file-dialog
*/
export function createFileDialog(options = {}) {
const { autoCleanup = true, accept = '*', multiple = false, onChange = () => { }, onCancel = () => { } } = options;
let _files = $state([]);
let _input = $state();
const cleanups = [];
if (BROWSER) {
_input = document.createElement('input');
_input.type = 'file';
_input.accept = accept;
_input.multiple = multiple;
cleanups.push(handleEventListener(_input, 'change', (event) => {
_files = Array.from(event.currentTarget.files ?? []);
onChange(_files);
}), handleEventListener(_input, 'cancel', () => {
onCancel();
}));
}
if (autoCleanup) {
onDestroy(() => {
cleanup();
});
}
function open() {
if (!_input)
return;
_input.click();
}
function reset() {
_files = [];
if (_input) {
_input.value = '';
}
}
function cleanup() {
cleanups.forEach((fn) => fn());
_input?.remove();
}
return {
get files() {
return _files;
},
open,
reset,
cleanup
};
}