@dvcol/common-utils
Version:
Typescript library for common utility functions and constants
51 lines (44 loc) • 1.65 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true});// lib/common/utils/save.utils.ts
var defaultFileHandlerOptions = {
startIn: "downloads",
types: [
{
description: "Json Files",
accept: {
"application/json": [".json"]
}
}
]
};
var getNewFileHandle = (options = {}) => {
if (!("showSaveFilePicker" in window)) throw new Error("File System Access API not supported");
if (options.types === void 0) options.types = defaultFileHandlerOptions.types;
if (options.startIn === void 0) options.startIn = defaultFileHandlerOptions.startIn;
return window.showSaveFilePicker(options);
};
var getJsonWriter = async ({ picker, replacer = null, space = 2, fileHandle, separator } = {}) => {
if (!fileHandle) fileHandle = await getNewFileHandle(picker);
const writable = await fileHandle.createWritable();
let length = 0;
const write = async (newContents) => {
const content = `${length && separator ? separator : ""}${length ? "\n" : ""}${JSON.stringify(newContents, replacer, space)}`;
await writable.write(content);
length += content.length;
};
const close = async () => writable.close();
return {
handle: fileHandle,
writable,
write,
close,
length,
[Symbol.asyncDispose]: close
};
};
var writeJson = async (contents, options) => {
const { write, close, handle } = await getJsonWriter(options);
await write(contents);
await close();
return handle;
};
exports.defaultFileHandlerOptions = defaultFileHandlerOptions; exports.getNewFileHandle = getNewFileHandle; exports.getJsonWriter = getJsonWriter; exports.writeJson = writeJson;