Files
gpx.studio/website/src/lib/components/export/utils.svelte.ts
T

62 lines
1.9 KiB
TypeScript
Raw Normal View History

2026-10-08 09:24:15 +02:00
import { engine, type ExportOptions } from '$lib/engine';
2025-06-21 21:07:36 +02:00
import FileSaver from 'file-saver';
import JSZip from 'jszip';
2025-10-17 23:54:45 +02:00
import { get } from 'svelte/store';
2025-06-21 21:07:36 +02:00
export enum ExportState {
NONE,
SELECTION,
ALL,
}
export const exportState = $state({
current: ExportState.NONE,
});
2026-10-08 09:24:15 +02:00
/** The files that contain the selection, in the order of the selection. */
export function selectedFileIds(): string[] {
const selection = get(engine.selection);
switch (selection.type) {
case 'file':
return selection.fileIds;
case 'empty':
return [];
default:
return [selection.fileId];
2025-06-21 21:07:36 +02:00
}
}
2026-10-08 09:24:15 +02:00
export function allFileIds(): string[] {
return get(engine.order);
}
async function exportFiles(fileIds: string[], options: ExportOptions) {
const files = fileIds.flatMap((fileId) => {
const gpx = engine.exportFile(fileId, options);
const name = get(engine.files).get(fileId);
return gpx === undefined || !name ? [] : [{ name: get(name).structure.name, gpx }];
2025-06-21 21:07:36 +02:00
});
2026-10-08 09:24:15 +02:00
if (files.length === 1) {
const blob = new Blob([files[0].gpx], { type: 'application/gpx+xml' });
FileSaver.saveAs(blob, `${files[0].name}.gpx`);
} else if (files.length > 1) {
const zip = new JSZip();
for (const { name, gpx } of files) {
let filename = name;
2025-06-21 21:07:36 +02:00
for (let i = 1; zip.files[filename + '.gpx']; i++) {
2026-10-08 09:24:15 +02:00
filename = name + `-${i}`;
2025-06-21 21:07:36 +02:00
}
zip.file(filename + '.gpx', gpx);
}
const blob = await zip.generateAsync({ type: 'blob' });
FileSaver.saveAs(blob, 'gpx-files.zip');
}
}
2026-10-08 09:24:15 +02:00
export async function exportSelectedFiles(options: ExportOptions) {
await exportFiles(selectedFileIds(), options);
}
export async function exportAllFiles(options: ExportOptions) {
await exportFiles(allFileIds(), options);
}