File size: 12,135 Bytes
71174bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import { FileInfo } from "@/FileSystem/FileInfo";
import { dynamicImports } from "../DynamicImports";
import { DataFormat, IData } from "./FSInterfaces";

/**
 * Adds an extension if missing.
 *
 * @param  {FileInfo} params   The parameters describing the text file.
 * @param  {string} defaultExt The default extension to use.
 * @returns {FileInfo} The parameters with the extension added to the filename
 *     field.
 */
// function _addExt(params: FileInfo, defaultExt: string): FileInfo {
//     // Get the extension from the filename
//     // *****

//     // Set some default values.
//     params.ext = params.ext || defaultExt;
//     // params.compress = params.compress || false;

//     // If ext doesn't start with a period, add one.
//     if (params.ext.charAt(0) !== ".") {
//         params.ext = "." + params.ext;
//     }

//     // If fileName doesn't end in the string contained in params.ext (case
//     // insensitive), add it. Use endsWith
//     if (!params.name.toLowerCase().endsWith(params.ext.toLowerCase())) {
//         params.name += params.ext;
//     }

//     return params;
// }

/**
 * Saves a text file.
 *
 * @param  {FileInfo} params The parameters describing the text file.
 * @returns {Promise<any>} A promise that resolves after saving the file.
 */
export function saveTxt(params: FileInfo): Promise<any> {
    // Add .txt extension if
    // params = _addExt(params, ".txt");

    // If doesn't end in ".zip" (case insensitive), add it.
    const validCompressedExts = [".zip", ".molmoda", ".biotite"];
    if (
        params.compressedName &&
        !validCompressedExts.some((ext) =>
            params.compressedName?.toLowerCase().endsWith(ext)
        )
    ) {
        params.compressedName += ".zip";
    }

    if (params.compressedName) {
        return saveZipWithTxtFiles(params.compressedName, [params]);
    }

    // Don't compress the output
    return dynamicImports.fileSaver.module.then((fileSaver: any) => {
        const blob = new Blob([params.contents as string], {
            type: "text/plain;charset=utf-8",
        });
        fileSaver.saveAs(blob, params.name);
        return;
    });

    // const promises: Promise<any>[] = [dynamicImports.fileSaver.module];
    // if (params.compress) {
    //  promises.push(dynamicImports.jsZip.module);
    // }
}

/**
 * Saves an SVG file.
 *
 * @param  {FileInfo} params The parameters describing the SVG file.
 *              The `contents` should be the SVG string.
 *              The `name` should be the desired filename (e.g., "image.svg").
 * @returns {Promise<any>} A promise that resolves after saving the file.
 */
export function saveSvg(params: FileInfo): Promise<any> {
    // Ensure the filename ends with .svg
    if (!params.name.toLowerCase().endsWith(".svg")) {
        params.name += ".svg";
    }

    // If a compressedName is provided, save as a zip containing the SVG file.
    // This part remains consistent with saveTxt for compressed outputs.
    const validCompressedExts = [".zip", ".molmoda", ".biotite"];
    if (
        params.compressedName &&
        !validCompressedExts.some((ext) =>
            params.compressedName?.toLowerCase().endsWith(ext)
        )
    ) {
        params.compressedName += ".zip";
    }

    if (params.compressedName) {
        // To save as a zip, we need to ensure the FileInfo for the SVG
        // within the zip has the correct .svg extension.
        // The saveZipWithTxtFiles function expects FileInfo objects.
        // We'll create a new FileInfo for the SVG content to be zipped.
        const svgFileInfoForZip = new FileInfo({
            name: params.name, // Already ensured to end with .svg
            contents: params.contents,
            // No compressedName for the file *inside* the zip
        });
        return saveZipWithTxtFiles(params.compressedName, [svgFileInfoForZip]);
    }

    // Save directly as an SVG file (not compressed)
    return dynamicImports.fileSaver.module.then((fileSaver: any) => {
        const blob = new Blob([params.contents as string], {
            type: "image/svg+xml", // Correct MIME type for SVG
        });
        fileSaver.saveAs(blob, params.name);
        return;
    });
}

/**
 * Creates a zip file blob from a list of FileInfo objects.
 *
 * @param {FileInfo[]} files An array of FileInfo objects to include in the zip.
 * @returns {Promise<Blob>} A promise that resolves with the zip file as a Blob.
 */
export function createZipBlob(files: FileInfo[]): Promise<Blob> {
    return dynamicImports.jsZip.module.then((JSZip: any) => {
        const zip = new JSZip();
        files.forEach((file) => {
            zip.file(file.name, file.contents, {
                compression: "DEFLATE",
                // Note: Below doesn't seem to improve compression, so
                // comment out.
                // compressionOptions: {
                //     compressionOptions: 9
                // }
            });
        });
        return zip.generateAsync({ type: "blob" });
    });
}

/**
 * Saves a zip file containing one or more text files.
 *
 * @param  {string} compressedName The parameters describing the zip file.
 * @param  {FileInfo[]} files      A list of parameters describing the text
 *                                 files to add to the zip file.
 * @returns {Promise<any>} A promise that resolves after saving the zip file.
 */
export function saveZipWithTxtFiles(
    compressedName: string,
    files: FileInfo[]
): Promise<any> {
    // compressedName = _addExt(compressedName, ".zip");
    // files = files.map((file) => _addExt(file, ".txt"));
    const makeZipPromise = createZipBlob(files);

    const promises: Promise<any>[] = [
        dynamicImports.fileSaver.module,
        makeZipPromise,
    ];

    return Promise.all(promises).then((payload: any[]) => {
        const fileSaver = payload[0];
        const zipBlob = payload[1];
        fileSaver.saveAs(zipBlob, compressedName);
        return;
    });
}

/**
 * Converts a dataURI to a Blob.
 *
 * @param  {string} dataURI The dataURI to convert.
 * @returns {Blob} The Blob representing the dataURI.
 */
function _dataURIToBlob(dataURI: string): Blob {
    // see https://stackoverflow.com/questions/12168909/blob-from-dataurl

    // convert base64 to raw binary data held in a string doesn't handle
    // URLEncoded DataURIs - see SO answer #6850276 for code that does this
    const byteString = atob(dataURI.split(",")[1]);

    // separate out the mime component
    const mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];

    // write the bytes of the string to an ArrayBuffer
    const ab = new ArrayBuffer(byteString.length);

    // create a view into the buffer
    const ia = new Uint8Array(ab);

    // set the bytes of the buffer to the correct values
    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    return new Blob([ab], { type: mimeString });
}

/**
 * Saves a dataURI representing a PNG image to a file.
 *
 * @param  {string} fileName The name of the file to save.
 * @param  {string} pngUri   The dataURI representing the PNG image.
 */
export function savePngUri(fileName: string, pngUri: string) {
    dynamicImports.fileSaver.module
        .then((fileSaver) => {
            const blob = _dataURIToBlob(pngUri);
            fileSaver.saveAs(blob, fileName);
            return;
        })
        .catch((err: any) => {
            throw err;
        });
}

/**
 * Given a string of compressed data (representing a zip file), get the contents
 * of a text file in it.
 *
 * @param  {string} s          The compressed data.
 * @returns {Promise<FileInfo[]>} A promise that resolves to the contents of the
 *     file(s). Always an array, even if only one file is returned.
 */
export function uncompress(s: string): Promise<FileInfo[]> {
    const getZipObjPromise = dynamicImports.jsZip.module.then((JSZip) => {
        return JSZip.loadAsync(s);
    });

    // if (fileName !== undefined) {
    //     return getZipObjPromise.then((zip: any) => {
    //         return [zip.file(fileName).async("string")];
    //     });
    // } else {
    let fileNames: string[];
    // let fileSizes: number[];
    return getZipObjPromise
        .then((zip: any) => {
            fileNames = Object.keys(zip.files);
            // fileSizes = zip.files.map((file: any) => file.size);
            const promises = fileNames.map((f) => zip.files[f].async("string"));
            return Promise.all(promises);
        })
        .then((fileContents: string[]) => {
            const fileInfos: FileInfo[] = [];
            for (let i = 0; i < fileNames.length; i++) {
                const fileName = fileNames[i];
                if (fileName.startsWith("__MACOSX")) {
                    continue;
                }
                if (fileName.startsWith(".")) {
                    continue;
                }

                const contents = fileContents[i];

                fileInfos.push(
                    new FileInfo({
                        name: fileName.split("/").pop() as string, // basename
                        // Getting file size not supported with zip. You could
                        // implement, though.
                        // size: 0,
                        contents: contents,
                        // type: type,
                    })
                );
            }
            return fileInfos;
        });
    // }
}

/**
 * Saves tabular data to a file.
 *
 * @param {IData}  data      The data to save.
 * @param {string} filename  The name of the file to save.
 * @param {DataFormat | string} format   The format to save the data in.
 */
export function saveData(
    data: IData,
    filename: string,
    format: DataFormat | string
) {
    if (format === DataFormat.JSON) {
        saveTxt(
            new FileInfo({
                name: filename,
                contents: JSON.stringify(data.rows, null, 2),
            })
        );
    } else {
        Promise.all([
            dynamicImports.exceljs.module,
            dynamicImports.fileSaver.module,
        ])
            .then(async ([ExcelJS, fileSaver]) => {
                const workbook = new ExcelJS.Workbook();
                const worksheet = workbook.addWorksheet("Sheet1");

                worksheet.columns = data.headers.map((header) => ({
                    header: header,
                    key: header,
                }));

                worksheet.addRows(data.rows);

                const fileExtension = filename.split(".").pop()?.toLowerCase();
                let buffer: ArrayBuffer;
                let blobType: string;

                if (fileExtension === "xlsx") {
                    buffer = await workbook.xlsx.writeBuffer();
                    blobType =
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                } else if (fileExtension === "csv") {
                    buffer = await workbook.csv.writeBuffer();
                    blobType = "text/csv;charset=utf-8;";
                } else {
                    // Fallback for when format is passed but not in filename
                    if (format === DataFormat.XLSX) {
                        buffer = await workbook.xlsx.writeBuffer();
                        blobType =
                            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    } else if (format === DataFormat.CSV) {
                        buffer = await workbook.csv.writeBuffer();
                        blobType = "text/csv;charset=utf-8;";
                    } else {
                        console.error("Unsupported format for saving:", format);
                        return;
                    }
                }
                const blob = new Blob([buffer], { type: blobType });
                fileSaver.saveAs(blob, filename);
                return;
            })
            .catch((err: any) => {
                throw err;
            });
    }
}