feat: native filesystem api integration WIP

This commit is contained in:
Tienson Qin
2020-11-22 01:17:47 +08:00
parent 8b5719e1fd
commit 6c3da67f6b
17 changed files with 436 additions and 139 deletions

View File

@@ -71,4 +71,68 @@ export var getSelectionText = function() {
}
return '';
// Modified from https://github.com/GoogleChromeLabs/browser-nativefs
// because shadow-cljs doesn't handle this babel transform
const getFiles = async function (dirHandle, recursive) {
const dirs = [];
const files = [];
const path = dirHandle.name;
for await (const entry of dirHandle.values()) {
const nestedPath = `${path}/${entry.name}`;
if (entry.kind === 'file') {
files.push(
entry.getFile().then((file) => {
Object.defineProperty(file, 'webkitRelativePath', {
configurable: true,
enumerable: true,
get: () => nestedPath,
});
Object.defineProperty(file, 'handle', {
configurable: true,
enumerable: true,
get: () => entry,
});
return file;
}
)
);
} else if (entry.kind === 'directory' && recursive) {
dirs.push(getFiles(entry, recursive, nestedPath));
}
}
return [(await Promise.all(dirs)), (await Promise.all(files))];
};
export var openDirectory = async function (options = {}) {
options.recursive = options.recursive || false;
const handle = await window.showDirectoryPicker({ mode: 'readwrite' });
return [handle, getFiles(handle, options.recursive)];
};
export var writeFile = async function (fileHandle, contents) {
// Create a FileSystemWritableFileStream to write to.
const writable = await fileHandle.createWritable();
// Write the contents of the file to the stream.
await writable.write(contents);
// Close the file and write the contents to disk.
await writable.close();
};
export var verifyPermission = async function (handle, readWrite) {
const options = {};
if (readWrite) {
options.mode = 'readwrite';
}
// Check if permission was already granted. If so, return true.
if ((await handle.queryPermission(options)) === 'granted') {
return true;
}
// Request permission. If the user grants permission, return true.
if ((await handle.requestPermission(options)) === 'granted') {
return true;
}
// The user didn't grant permission, so return false.
return false;
}