Skip to content

Commit

Permalink
✨ Add reject for file select dialog
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelGesenhues committed Dec 17, 2024
1 parent 8aceef4 commit 136c1ec
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions packages/core/src/utils/fileDialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ interface SelectFilesOptions {
}

export const selectFiles = ({
type,
multiple,
maxFileSizeInMB,
}: SelectFilesOptions): Promise<File[]> =>
new Promise((resolve) => {
type,
multiple,
maxFileSizeInMB,
}: SelectFilesOptions): Promise<File[]> =>
new Promise((resolve, reject) => {
const input = document.createElement('input');

input.type = 'file';
Expand All @@ -30,22 +30,23 @@ export const selectFiles = ({

document.body.appendChild(input);

input.addEventListener('change', (event) => {
const abortController = new AbortController();
const { signal } = abortController;

const onChange = (event: Event) => {
document.body.removeChild(input);
abortController.abort();

if (!event.target) {
resolve([]);

return;
}

const target = event.target as HTMLInputElement;

const { files } = target;

if (!files) {
resolve([]);

return;
}

Expand Down Expand Up @@ -73,7 +74,16 @@ export const selectFiles = ({
}

resolve(filteredFileArray);
});
};

const onCancel = () => {
document.body.removeChild(input);
abortController.abort();
reject(new Error('File selection was cancelled.'));
};

input.addEventListener('change', onChange, { signal });
input.addEventListener('focusout', onCancel, { signal });

input.click();
});
Expand Down

0 comments on commit 136c1ec

Please sign in to comment.