2023-08-02 16:23:17 -07:00
|
|
|
import { isTauri } from './isTauri'
|
|
|
|
import { deserialize_files } from '../wasm-lib/pkg/wasm_lib'
|
|
|
|
import { browserSaveFile } from './browserSaveFile'
|
2024-04-09 08:04:36 -04:00
|
|
|
import { save } from '@tauri-apps/plugin-dialog'
|
|
|
|
import { writeFile } from '@tauri-apps/plugin-fs'
|
2023-08-02 16:23:17 -07:00
|
|
|
|
2024-03-14 11:50:46 -04:00
|
|
|
import JSZip from 'jszip'
|
|
|
|
|
|
|
|
interface ModelingAppFile {
|
|
|
|
name: string
|
|
|
|
contents: number[]
|
|
|
|
}
|
|
|
|
|
|
|
|
const save_ = async (file: ModelingAppFile) => {
|
2023-08-02 16:23:17 -07:00
|
|
|
try {
|
2024-03-14 11:50:46 -04:00
|
|
|
if (isTauri()) {
|
|
|
|
// Open a dialog to save the file.
|
|
|
|
const filePath = await save({
|
|
|
|
defaultPath: file.name,
|
|
|
|
})
|
|
|
|
|
|
|
|
if (filePath === null) {
|
|
|
|
// The user canceled the save.
|
|
|
|
// Return early.
|
|
|
|
return
|
2023-08-02 16:23:17 -07:00
|
|
|
}
|
2024-03-14 11:50:46 -04:00
|
|
|
|
|
|
|
// Write the file.
|
2024-04-09 08:04:36 -04:00
|
|
|
await writeFile(filePath, new Uint8Array(file.contents))
|
2024-03-14 11:50:46 -04:00
|
|
|
} else {
|
|
|
|
// Download the file to the user's computer.
|
|
|
|
// Now we need to download the files to the user's downloads folder.
|
|
|
|
// Or the destination they choose.
|
|
|
|
// Iterate over the files.
|
|
|
|
// Create a new blob.
|
|
|
|
const blob = new Blob([new Uint8Array(file.contents)])
|
|
|
|
// Save the file.
|
|
|
|
await browserSaveFile(blob, file.name)
|
2023-08-02 16:23:17 -07:00
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
// TODO: do something real with the error.
|
2023-09-25 17:28:03 +10:00
|
|
|
console.log('export error', e)
|
2023-08-02 16:23:17 -07:00
|
|
|
}
|
|
|
|
}
|
2024-03-14 11:50:46 -04:00
|
|
|
|
|
|
|
// Saves files locally from an export call.
|
|
|
|
export async function exportSave(data: ArrayBuffer) {
|
|
|
|
// This converts the ArrayBuffer to a Rust equivalent Vec<u8>.
|
|
|
|
let uintArray = new Uint8Array(data)
|
|
|
|
|
|
|
|
const files: ModelingAppFile[] = deserialize_files(uintArray)
|
|
|
|
|
|
|
|
if (files.length > 1) {
|
|
|
|
let zip = new JSZip()
|
|
|
|
for (const file of files) {
|
|
|
|
zip.file(file.name, new Uint8Array(file.contents), { binary: true })
|
|
|
|
}
|
|
|
|
return zip.generateAsync({ type: 'array' }).then((contents) => {
|
|
|
|
return save_({ name: 'output.zip', contents })
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
return save_(files[0])
|
|
|
|
}
|
|
|
|
}
|