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 26, 2024
1 parent 5ec58b2 commit 8ca297f
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 @@ -333,6 +333,13 @@ it('should not use getAsFileSystemHandle when not in a secure context', async ()
window.isSecureContext = true;
});

it('should reject when getAsFileSystemHandle resolves 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 @@ -403,7 +410,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 @@ -510,7 +517,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 @@ -130,19 +130,26 @@ function fromDataTransferItem(item: DataTransferItem, entry?: FileSystemEntry |
if (globalThis.isSecureContext && 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 8ca297f

Please sign in to comment.