UNPKG

@dvcol/common-utils

Version:

Typescript library for common utility functions and constants

51 lines (49 loc) 1.49 kB
// 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; }; export { defaultFileHandlerOptions, getNewFileHandle, getJsonWriter, writeJson };