Skip to content

Commit

Permalink
fix: handle getAsFileSystemHandle resolving to null and close #106
Browse files Browse the repository at this point in the history
  • Loading branch information
rolandjitsu committed Nov 7, 2024
1 parent f159a4a commit dda503e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
11 changes: 9 additions & 2 deletions src/file-selector.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,13 @@ it('should use getAsFileSystemHandle when available', async () => {
expect(file.path).toBe(`./${name}`);
});

it('should reject when getAsFileSystemHandle resoles to null', async () => {
const evt = dragEvtFromItems([
dataTransferItemWithFsHandle(null, null)
]);
expect(fromEvent(evt)).rejects.toMatch('is not a File');
});

function dragEvtFromItems(items: DataTransferItem | DataTransferItem[], type: string = 'drop'): DragEvent {
return {
type,
Expand Down Expand Up @@ -374,7 +381,7 @@ function dataTransferItemFromEntry(entry: FileEntry | DirEntry, file?: File): Da
} as any;
}

function dataTransferItemWithFsHandle(file?: File, h?: FileSystemFileHandle): DataTransferItem {
function dataTransferItemWithFsHandle(file?: File | null, h?: FileSystemFileHandle | null): DataTransferItem {
return {
kind: 'file',
getAsFile() {
Expand Down Expand Up @@ -482,7 +489,7 @@ function sortFiles<T extends File>(files: T[]) {


interface FileSystemFileHandle {
getFile(): Promise<File>;
getFile(): Promise<File | null>;
}

type FileOrDirEntry = FileEntry | DirEntry
Expand Down
9 changes: 8 additions & 1 deletion src/file-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,19 +124,26 @@ function fromDataTransferItem(item: DataTransferItem, entry?: FileSystemEntry |
if (typeof (item as any).getAsFileSystemHandle === 'function') {
return (item as any).getAsFileSystemHandle()
.then(async (h: any) => {
if (!h) {
return notAFile(item);
}
const file = await h.getFile();
file.handle = h;
return toFileWithPath(file);
});
}
const file = item.getAsFile();
if (!file) {
return Promise.reject(`${item} is not a File`);
return notAFile(item);
}
const fwp = toFileWithPath(file, entry?.fullPath ?? undefined);
return Promise.resolve(fwp);
}

function notAFile(item: DataTransferItem) {
return Promise.reject(`${item} is not a File`);
}

// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry
async function fromEntry(entry: any) {
return entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry);
Expand Down

0 comments on commit dda503e

Please sign in to comment.