Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle getFile returning null and close #106 #107

Merged
merged 2 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions src/file-selector.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,35 @@ 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.toThrow('[object Object] is not a File');
});

it('should fallback to getAsFile when getAsFileSystemHandle resolves to undefined', async () => {
const name = 'test.nosec.json';
const mockFile = createFile(name, {ping: false}, {
type: 'application/json'
});
const evt = dragEvtFromItems([
dataTransferItemWithFsHandle(mockFile, undefined)
]);

const files = await fromEvent(evt);
expect(files).toHaveLength(1);
expect(files.every(file => file instanceof File)).toBe(true);

const [file] = files as FileWithPath[];

expect(file.name).toBe(mockFile.name);
expect(file.type).toBe(mockFile.type);
expect(file.size).toBe(mockFile.size);
expect(file.lastModified).toBe(mockFile.lastModified);
expect(file.path).toBe(`./${name}`);
});

function dragEvtFromItems(items: DataTransferItem | DataTransferItem[], type: string = 'drop'): DragEvent {
return {
type,
Expand Down Expand Up @@ -403,7 +432,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 +539,7 @@ function sortFiles<T extends File>(files: T[]) {


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

type FileOrDirEntry = FileEntry | DirEntry
Expand Down
23 changes: 14 additions & 9 deletions src/file-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,27 +120,32 @@ function flatten<T>(items: any[]): T[] {
], []);
}

function fromDataTransferItem(item: DataTransferItem, entry?: FileSystemEntry | null) {
async function fromDataTransferItem(item: DataTransferItem, entry?: FileSystemEntry | null) {
// Check if we're in a secure context; due to a bug in Chrome (as far as we know)
// the browser crashes when calling this API (yet to be confirmed as a consistent behaviour).
//
// See:
// - https://issues.chromium.org/issues/40186242
// - https://github.com/react-dropzone/react-dropzone/issues/1397
if (globalThis.isSecureContext && typeof (item as any).getAsFileSystemHandle === 'function') {
return (item as any).getAsFileSystemHandle()
.then(async (h: any) => {
const file = await h.getFile();
file.handle = h;
return toFileWithPath(file);
});
const h = await (item as any).getAsFileSystemHandle();
if (h === null) {
throw new Error(`${item} is not a File`);
}
// It seems that the handle can be `undefined` (see https://github.com/react-dropzone/file-selector/issues/120),
// so we check if it isn't; if it is, the code path continues to the next API (`getAsFile`).
if (h !== undefined) {
const file = await h.getFile();
file.handle = h;
return toFileWithPath(file);
}
Comment on lines +131 to +141

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't this be a safer fallback? Isn't it nice to try getFile if getAsFileSystemHandle does not return the expected data for some other unknown reason?

Suggested change
const h = await (item as any).getAsFileSystemHandle();
if (h === null) {
throw new Error(`${item} is not a File`);
}
// It seems that the handle can be `undefined` (see https://github.com/react-dropzone/file-selector/issues/120),
// so we check if it isn't; if it is, the code path continues to the next API (`getAsFile`).
if (h !== undefined) {
const file = await h.getFile();
file.handle = h;
return toFileWithPath(file);
}
const h = await (item as any).getAsFileSystemHandle();
if(!h) {
const file = await h.getFile();
if(!file) {
throw new Error(`${item} is not a File`);
}
file.handle = h;
return toFileWithPath(file);
}

And then you can skip the

	const file = item.getAsFile(); 
    if (!file) {
        throw new Error(`${item} is not a File`);
    }

below, because it will always try getFile?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if(!h) {
	        const file = await h.getFile();

That will essentially throw an exception because it will evaluate if h is undefined or null. We want the opposite of that. Note that getFile and getAsFile are 2 different APIs that exist on different objects.

}
const file = item.getAsFile();
if (!file) {
return Promise.reject(`${item} is not a File`);
throw new Error(`${item} is not a File`);
}
const fwp = toFileWithPath(file, entry?.fullPath ?? undefined);
return Promise.resolve(fwp);
return fwp;
}

// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry
Expand Down