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

code refactoring #119

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
36 changes: 15 additions & 21 deletions src/fs-access/file-open.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,33 +26,27 @@ const getFileWithHandle = async (handle) => {
* @type { typeof import("../../index").fileOpen }
*/
export default async (options = [{}]) => {
if (!Array.isArray(options)) {
options = [options];
}
const types = [];
options.forEach((option, i) => {
types[i] = {
description: option.description || 'Files',
accept: {},
};
if (option.mimeTypes) {
option.mimeTypes.map((mimeType) => {
types[i].accept[mimeType] = option.extensions || [];
});
const opts = Array.isArray(options) ? options : [options];
const types = opts.map(({ description = 'Files', extensions = [], mimeTypes }) => {
const accept = {};
if (mimeTypes) {
for (const mimeType of mimeTypes) {
accept[mimeType] = extensions;
}
} else {
types[i].accept['*/*'] = option.extensions || [];
accept['*/*'] = extensions;
}
return { description, accept };
});
const [{ id, startIn, multiple = false, excludeAcceptAllOption = false }] = opts;
const handleOrHandles = await window.showOpenFilePicker({
id: options[0].id,
startIn: options[0].startIn,
id,
startIn,
types,
multiple: options[0].multiple || false,
excludeAcceptAllOption: options[0].excludeAcceptAllOption || false,
multiple,
excludeAcceptAllOption,
});
const files = await Promise.all(handleOrHandles.map(getFileWithHandle));
if (options[0].multiple) {
return files;
}
if (multiple) return files;
return files[0];
};
99 changes: 48 additions & 51 deletions src/fs-access/file-save.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,29 @@
*/
// @license © 2020 Google LLC. Licensed under the Apache License, Version 2.0.

const tryExistingHandle = async (handle, discontinue) => {
try {
await handle.getFile();
return handle;
} catch (error) {
if (discontinue) throw error;
return null;
}
}

const getHandle = async (handle, options) => {
if (handle) return handle;
return await window.showSaveFilePicker(options)
};

const getType = (blob, response) => {
const { type } = blob;
if (type) return type;
const { headers } = response;
if (headers) return headers.get('content-type');
return '';
};

/**
* Saves a file to disk using the File System Access API.
* @type { typeof import("../../index").fileSave }
Expand All @@ -26,64 +49,37 @@ export default async (
throwIfExistingHandleNotGood = false,
filePickerShown = null
) => {
if (!Array.isArray(options)) {
options = [options];
}
options[0].fileName = options[0].fileName || 'Untitled';
const types = [];
let type = null;
if (
blobOrPromiseBlobOrResponse instanceof Blob &&
blobOrPromiseBlobOrResponse.type
) {
type = blobOrPromiseBlobOrResponse.type;
} else if (
blobOrPromiseBlobOrResponse.headers &&
blobOrPromiseBlobOrResponse.headers.get('content-type')
) {
type = blobOrPromiseBlobOrResponse.headers.get('content-type');
}
options.forEach((option, i) => {
types[i] = {
description: option.description || 'Files',
accept: {},
};
if (option.mimeTypes) {
if (i === 0 && type) {
option.mimeTypes.push(type);
const opts = Array.isArray(options) ? options : [options];
const blob = blobOrPromiseBlobOrResponse instanceof Blob ? blobOrPromiseBlobOrResponse : {};
const response = blobOrPromiseBlobOrResponse;
const type = getType(blob, response);
const types = opts.map(({ description = 'Files', extensions = [], mimeTypes }) => {
const accept = {};
if (mimeTypes) {
for (const mimeType of mimeTypes) {
accept[mimeType] = extensions;
}
option.mimeTypes.map((mimeType) => {
types[i].accept[mimeType] = option.extensions || [];
});
} else if (type) {
types[i].accept[type] = option.extensions || [];
accept[type] = extensions;
} else {
types[i].accept['*/*'] = option.extensions || [];
accept['*/*'] = extensions;
}
return { description, accept }
});
if (existingHandle) {
try {
// Check if the file still exists.
await existingHandle.getFile();
} catch (err) {
existingHandle = null;
if (throwIfExistingHandleNotGood) {
throw err;
}
}
const [{ mimeTypes, extentions = [] }] = opts;
const [{ accept }] = types;
if (mimeTypes && type) {
accept[type] = extentions;
}
const handle =
existingHandle ||
(await window.showSaveFilePicker({
suggestedName: options[0].fileName,
id: options[0].id,
startIn: options[0].startIn,
types,
excludeAcceptAllOption: options[0].excludeAcceptAllOption || false,
}));
if (!existingHandle && filePickerShown) {

const prevHandle = await tryExistingHandle(existingHandle, throwIfExistingHandleNotGood)
const [{ fileName = 'Untitled', id, startIn, excludeAcceptAllOption = false }] = opts;
const handleOptions = { suggestedName: fileName, id, startIn, types, excludeAcceptAllOption };
const handle = await getHandle(prevHandle, handleOptions);
if (!prevHandle && filePickerShown) {
filePickerShown(handle);
}

const writable = await handle.createWritable();
// Use streaming on the `Blob` if the browser supports it.
if ('stream' in blobOrPromiseBlobOrResponse) {
Expand All @@ -96,7 +92,8 @@ export default async (
return handle;
}
// Default case of `Blob` passed and `Blob.stream()` not supported.
await writable.write(await blobOrPromiseBlobOrResponse);
const contents = await blobOrPromiseBlobOrResponse;
await writable.write(contents);
await writable.close();
return handle;
};