Files
gpx.studio/website/src/lib/stores.ts

513 lines
16 KiB
TypeScript
Raw Normal View History

2024-07-17 10:23:04 +02:00
import { writable, get, type Writable, derived } from 'svelte/store';
2024-04-17 11:44:37 +02:00
import mapboxgl from 'mapbox-gl';
2024-05-08 21:31:54 +02:00
import { GPXFile, buildGPX, parseGPX, GPXStatistics, type Coordinates } from 'gpx';
2024-04-27 12:18:40 +02:00
import { tick } from 'svelte';
import { _ } from 'svelte-i18n';
import type { GPXLayer } from '$lib/components/gpx-layer/GPXLayer';
2024-06-15 18:44:17 +02:00
import { dbUtils, fileObservers, getFile, getStatistics, settings } from './db';
import {
addSelectItem,
applyToOrderedSelectedItemsFromFile,
selectFile,
selectItem,
selection
} from '$lib/components/file-list/Selection';
import {
ListFileItem,
ListItem,
ListTrackItem,
ListTrackSegmentItem,
ListWaypointItem,
ListWaypointsItem
} from '$lib/components/file-list/FileList';
2024-05-24 20:23:49 +02:00
import type { RoutingControls } from '$lib/components/toolbar/tools/routing/RoutingControls';
2024-07-25 16:15:44 +02:00
import { SplitType } from '$lib/components/toolbar/tools/scissors/Scissors.svelte';
2025-01-24 19:57:08 +01:00
import JSZip from 'jszip';
2024-04-17 11:44:37 +02:00
2024-06-19 18:51:26 +02:00
const { fileOrder } = settings;
2024-04-17 16:46:51 +02:00
export const map = writable<mapboxgl.Map | null>(null);
2024-07-11 18:42:49 +02:00
export const embedding = writable(false);
2024-04-30 20:55:47 +02:00
export const selectFiles = writable<{ [key: string]: (fileId?: string) => void }>({});
2024-05-03 22:15:47 +02:00
export const gpxStatistics: Writable<GPXStatistics> = writable(new GPXStatistics());
export const slicedGPXStatistics: Writable<[GPXStatistics, number, number] | undefined> =
writable(undefined);
2024-04-30 20:55:47 +02:00
2024-07-13 11:42:21 +02:00
export function updateGPXData() {
2024-05-22 16:05:31 +02:00
let statistics = new GPXStatistics();
2024-05-24 22:53:30 +02:00
applyToOrderedSelectedItemsFromFile((fileId, level, items) => {
2024-06-15 18:44:17 +02:00
let stats = getStatistics(fileId);
if (stats) {
let first = true;
items.forEach((item) => {
if (!(item instanceof ListWaypointItem || item instanceof ListWaypointsItem) || first) {
statistics.mergeWith(stats.getStatisticsFor(item));
first = false;
}
});
2024-05-07 10:37:24 +02:00
}
2024-05-24 22:53:30 +02:00
}, false);
2024-05-22 16:05:31 +02:00
gpxStatistics.set(statistics);
2024-04-30 20:55:47 +02:00
}
2024-05-22 16:05:31 +02:00
let unsubscribes: Map<string, () => void> = new Map();
selection.subscribe(($selection) => {
// Maintain up-to-date statistics for the current selection
2024-04-30 20:55:47 +02:00
updateGPXData();
2024-05-08 23:01:56 +02:00
2024-05-22 16:05:31 +02:00
while (unsubscribes.size > 0) {
let [fileId, unsubscribe] = unsubscribes.entries().next().value;
unsubscribe();
unsubscribes.delete(fileId);
2024-05-08 23:01:56 +02:00
}
2024-05-22 16:05:31 +02:00
$selection.forEach((item) => {
let fileId = item.getFileId();
if (!unsubscribes.has(fileId)) {
let fileObserver = get(fileObservers).get(fileId);
if (fileObserver) {
let first = true;
unsubscribes.set(
fileId,
fileObserver.subscribe(() => {
if (first) first = false;
else updateGPXData();
})
);
2024-05-22 16:05:31 +02:00
}
2024-05-08 23:01:56 +02:00
}
});
2024-04-30 20:55:47 +02:00
});
2024-06-18 12:35:24 +02:00
gpxStatistics.subscribe(() => {
slicedGPXStatistics.set(undefined);
});
const targetMapBounds = writable<{
bounds: mapboxgl.LngLatBounds;
ids: string[];
total: number;
}>({
2024-05-08 21:31:54 +02:00
bounds: new mapboxgl.LngLatBounds([180, 90, -180, -90]),
ids: [],
total: 0,
2024-05-08 21:31:54 +02:00
});
derived([targetMapBounds, map], (x) => x).subscribe(([bounds, $map]) => {
if (
$map === null ||
bounds.ids.length > 0 ||
(bounds.bounds.getSouth() === 90 &&
bounds.bounds.getWest() === 180 &&
bounds.bounds.getNorth() === -90 &&
bounds.bounds.getEast() === -180)
) {
2024-05-07 12:16:30 +02:00
return;
}
let currentZoom = $map.getZoom();
2024-07-17 10:23:04 +02:00
let currentBounds = $map.getBounds();
if (bounds.total !== get(fileObservers).size &&
currentBounds &&
currentZoom > 2 // Extend current bounds only if the map is zoomed in
) {
2024-07-17 10:23:04 +02:00
// There are other files on the map
if (
currentBounds.contains(bounds.bounds.getSouthEast()) &&
currentBounds.contains(bounds.bounds.getNorthWest())
) {
2024-07-17 10:23:04 +02:00
return;
2024-07-12 18:25:52 +02:00
}
2024-07-17 10:23:04 +02:00
bounds.bounds.extend(currentBounds.getSouthWest());
bounds.bounds.extend(currentBounds.getNorthEast());
}
$map.fitBounds(bounds.bounds, { padding: 80, linear: true, easing: () => 1 });
2024-05-07 12:16:30 +02:00
});
export function initTargetMapBounds(ids: string[]) {
2024-05-08 21:31:54 +02:00
targetMapBounds.set({
2024-07-17 10:23:04 +02:00
bounds: new mapboxgl.LngLatBounds([180, 90, -180, -90]),
ids,
total: ids.length,
2024-05-08 21:31:54 +02:00
});
}
export function updateTargetMapBounds(id: string, bounds: { southWest: Coordinates; northEast: Coordinates }) {
if (get(targetMapBounds).ids.indexOf(id) === -1) {
2024-05-08 21:31:54 +02:00
return;
}
targetMapBounds.update((target) => {
target.ids = target.ids.filter((x) => x !== id);
if (
bounds.southWest.lat !== 90 ||
bounds.southWest.lon !== 180 ||
bounds.northEast.lat !== -90 ||
bounds.northEast.lon !== -180
) {
// Avoid update for empty (new) files
target.bounds.extend(bounds.southWest);
target.bounds.extend(bounds.northEast);
}
2024-05-08 21:31:54 +02:00
return target;
});
}
export function centerMapOnSelection(
) {
let selected = get(selection).getSelected();
let bounds = new mapboxgl.LngLatBounds();
if (selected.find((item) => item instanceof ListWaypointItem)) {
applyToOrderedSelectedItemsFromFile((fileId, level, items) => {
let file = getFile(fileId);
if (file) {
items.forEach((item) => {
if (item instanceof ListWaypointItem) {
let waypoint = file.wpt[item.getWaypointIndex()];
if (waypoint) {
bounds.extend([waypoint.getLongitude(), waypoint.getLatitude()]);
}
}
});
}
});
} else {
let selectionBounds = get(gpxStatistics).global.bounds;
bounds.setNorthEast(selectionBounds.northEast);
bounds.setSouthWest(selectionBounds.southWest);
}
get(map)?.fitBounds(bounds, {
padding: 80,
easing: () => 1,
maxZoom: 15
});
}
2024-05-24 20:23:49 +02:00
export const gpxLayers: Map<string, GPXLayer> = new Map();
export const routingControls: Map<string, RoutingControls> = new Map();
export enum Tool {
ROUTING,
2024-05-24 20:23:49 +02:00
WAYPOINT,
2024-06-06 11:44:53 +02:00
SCISSORS,
TIME,
MERGE,
EXTRACT,
2024-07-19 13:18:38 +02:00
ELEVATION,
REDUCE,
2024-06-12 15:40:26 +02:00
CLEAN
}
export const currentTool = writable<Tool | null>(null);
2024-06-10 20:03:57 +02:00
export const splitAs = writable(SplitType.FILES);
2024-06-24 19:41:44 +02:00
export const streetViewEnabled = writable(false);
2024-04-18 10:55:55 +02:00
2024-06-05 21:08:01 +02:00
export function newGPXFile() {
const newFileName = get(_)('menu.new_file');
2024-06-19 16:15:21 +02:00
2024-04-27 12:18:40 +02:00
let file = new GPXFile();
2024-06-19 16:15:21 +02:00
let maxNewFileNumber = 0;
get(fileObservers).forEach((f) => {
let file = get(f)?.file;
2024-06-20 15:18:21 +02:00
if (file && file.metadata.name && file.metadata.name.startsWith(newFileName)) {
2024-06-19 16:15:21 +02:00
let number = parseInt(file.metadata.name.split(' ').pop() ?? '0');
if (!isNaN(number) && number > maxNewFileNumber) {
maxNewFileNumber = number;
}
}
});
file.metadata.name = `${newFileName} ${maxNewFileNumber + 1}`;
2024-06-05 21:08:01 +02:00
return file;
}
export function createFile() {
let file = newGPXFile();
2024-04-30 20:55:47 +02:00
2024-05-02 19:51:08 +02:00
dbUtils.add(file);
2024-04-30 20:55:47 +02:00
2024-05-03 15:59:34 +02:00
selectFileWhenLoaded(file._data.id);
2024-05-06 17:56:07 +02:00
currentTool.set(Tool.ROUTING);
2024-04-27 12:18:40 +02:00
}
2024-04-18 10:55:55 +02:00
export function triggerFileInput() {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.gpx';
input.multiple = true;
input.className = 'hidden';
input.onchange = () => {
if (input.files) {
loadFiles(input.files);
}
};
input.click();
}
2024-07-11 18:42:49 +02:00
export async function loadFiles(list: FileList | File[]) {
let files: GPXFile[] = [];
2024-04-20 18:47:16 +02:00
for (let i = 0; i < list.length; i++) {
2024-04-22 17:22:21 +02:00
let file = await loadFile(list[i]);
2024-04-25 13:48:31 +02:00
if (file) {
2024-04-30 20:55:47 +02:00
files.push(file);
2024-04-20 18:47:16 +02:00
}
2024-04-18 10:55:55 +02:00
}
2024-04-30 20:55:47 +02:00
let ids = dbUtils.addMultiple(files);
2024-04-30 20:55:47 +02:00
initTargetMapBounds(ids);
selectFileWhenLoaded(ids[0]);
2024-04-18 10:55:55 +02:00
}
2024-04-30 20:55:47 +02:00
export async function loadFile(file: File): Promise<GPXFile | null> {
let result = await new Promise<GPXFile | null>((resolve) => {
2024-04-20 18:47:16 +02:00
const reader = new FileReader();
reader.onload = () => {
let data = reader.result?.toString() ?? null;
if (data) {
let gpx = parseGPX(data);
2024-05-08 23:01:56 +02:00
if (gpx.metadata === undefined) {
gpx.metadata = {};
}
if (gpx.metadata.name === undefined || gpx.metadata.name.trim() === '') {
gpx.metadata.name = file.name.split('.').slice(0, -1).join('.');
2024-04-20 18:47:16 +02:00
}
2024-04-30 20:55:47 +02:00
resolve(gpx);
2024-04-22 17:22:21 +02:00
} else {
resolve(null);
2024-04-18 10:55:55 +02:00
}
2024-04-20 18:47:16 +02:00
};
reader.readAsText(file);
});
return result;
2024-04-18 15:30:19 +02:00
}
export function selectFileWhenLoaded(fileId: string) {
2024-05-03 15:59:34 +02:00
const unsubscribe = fileObservers.subscribe((files) => {
if (files.has(fileId)) {
tick().then(() => {
2024-05-24 20:23:49 +02:00
selectFile(fileId);
2024-05-03 15:59:34 +02:00
});
unsubscribe();
2024-04-18 15:30:19 +02:00
}
2024-05-03 15:59:34 +02:00
});
2024-04-18 15:30:19 +02:00
}
2024-06-19 18:51:26 +02:00
export function updateSelectionFromKey(down: boolean, shift: boolean) {
let selected = get(selection).getSelected();
if (selected.length === 0) {
return;
}
let next: ListItem | undefined = undefined;
if (selected[0] instanceof ListFileItem) {
let order = get(fileOrder);
let limitIndex: number | undefined = undefined;
selected.forEach((item) => {
let index = order.indexOf(item.getFileId());
if (
limitIndex === undefined ||
(down && index > limitIndex) ||
(!down && index < limitIndex)
) {
2024-06-19 18:51:26 +02:00
limitIndex = index;
}
});
if (limitIndex !== undefined) {
let nextIndex = down ? limitIndex + 1 : limitIndex - 1;
while (true) {
if (nextIndex < 0) {
nextIndex = order.length - 1;
} else if (nextIndex >= order.length) {
nextIndex = 0;
}
if (nextIndex === limitIndex) {
break;
}
next = new ListFileItem(order[nextIndex]);
if (!get(selection).has(next)) {
break;
}
nextIndex += down ? 1 : -1;
}
}
} else if (
selected[0] instanceof ListTrackItem &&
selected[selected.length - 1] instanceof ListTrackItem
) {
2024-06-19 18:51:26 +02:00
let fileId = selected[0].getFileId();
let file = getFile(fileId);
if (file) {
let numberOfTracks = file.trk.length;
let trackIndex = down
? selected[selected.length - 1].getTrackIndex()
: selected[0].getTrackIndex();
2024-06-19 18:51:26 +02:00
if (down && trackIndex < numberOfTracks - 1) {
next = new ListTrackItem(fileId, trackIndex + 1);
} else if (!down && trackIndex > 0) {
next = new ListTrackItem(fileId, trackIndex - 1);
}
}
} else if (
selected[0] instanceof ListTrackSegmentItem &&
selected[selected.length - 1] instanceof ListTrackSegmentItem
) {
2024-06-19 18:51:26 +02:00
let fileId = selected[0].getFileId();
let file = getFile(fileId);
if (file) {
let trackIndex = selected[0].getTrackIndex();
let numberOfSegments = file.trk[trackIndex].trkseg.length;
let segmentIndex = down
? selected[selected.length - 1].getSegmentIndex()
: selected[0].getSegmentIndex();
2024-06-19 18:51:26 +02:00
if (down && segmentIndex < numberOfSegments - 1) {
next = new ListTrackSegmentItem(fileId, trackIndex, segmentIndex + 1);
} else if (!down && segmentIndex > 0) {
next = new ListTrackSegmentItem(fileId, trackIndex, segmentIndex - 1);
}
}
} else if (
selected[0] instanceof ListWaypointItem &&
selected[selected.length - 1] instanceof ListWaypointItem
) {
2024-06-19 18:51:26 +02:00
let fileId = selected[0].getFileId();
let file = getFile(fileId);
if (file) {
let numberOfWaypoints = file.wpt.length;
let waypointIndex = down
? selected[selected.length - 1].getWaypointIndex()
: selected[0].getWaypointIndex();
2024-06-19 18:51:26 +02:00
if (down && waypointIndex < numberOfWaypoints - 1) {
next = new ListWaypointItem(fileId, waypointIndex + 1);
} else if (!down && waypointIndex > 0) {
next = new ListWaypointItem(fileId, waypointIndex - 1);
}
}
}
if (next && (!get(selection).has(next) || !shift)) {
if (shift) {
addSelectItem(next);
} else {
selectItem(next);
}
}
}
2025-01-24 19:57:08 +01:00
async function exportFilesAsZip(fileIds: string[], exclude: string[]) {
const zip = new JSZip();
for (const fileId of fileIds) {
const file = getFile(fileId);
2024-06-28 15:43:57 +02:00
if (file) {
2025-01-24 19:57:08 +01:00
const gpx = buildGPX(file, exclude);
zip.file(file.metadata.name + '.gpx', gpx);
}
}
if (Object.keys(zip.files).length > 0) {
const content = await zip.generateAsync({ type: 'blob' });
const link = document.createElement('a');
link.href = URL.createObjectURL(content);
link.download = 'gpx-export.zip';
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
}
}
async function exportFiles(fileIds: string[], exclude: string[]) {
if (fileIds.length > 1) {
await exportFilesAsZip(fileIds, exclude)
} else {
const firstFileId = fileIds.at(0);
if (firstFileId != null) {
const file = getFile(firstFileId);
if (file) {
exportFile(file, exclude);
}
2024-05-03 15:59:34 +02:00
}
2024-06-28 15:43:57 +02:00
}
}
2025-01-24 19:57:08 +01:00
export async function exportSelectedFiles(exclude: string[]) {
const fileIds: string[] = [];
2024-06-28 15:43:57 +02:00
applyToOrderedSelectedItemsFromFile(async (fileId, level, items) => {
fileIds.push(fileId);
2024-05-03 15:59:34 +02:00
});
2025-01-24 19:57:08 +01:00
await exportFiles(fileIds, exclude);
2024-05-03 15:59:34 +02:00
}
2025-01-24 19:57:08 +01:00
export async function exportAllFiles(exclude: string[]) {
await exportFiles(get(fileOrder), exclude);
2024-04-18 15:30:19 +02:00
}
2024-07-23 11:20:31 +02:00
export function exportFile(file: GPXFile, exclude: string[]) {
let blob = new Blob([buildGPX(file, exclude)], { type: 'application/gpx+xml' });
2024-04-18 15:30:19 +02:00
let url = URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = file.metadata.name + '.gpx';
a.click();
URL.revokeObjectURL(url);
2024-06-06 18:11:03 +02:00
}
2024-07-02 20:04:17 +02:00
export const allHidden = writable(false);
2024-06-27 18:23:11 +02:00
2024-07-02 20:04:17 +02:00
export function updateAllHidden() {
let hidden = true;
applyToOrderedSelectedItemsFromFile((fileId, level, items) => {
let file = getFile(fileId);
if (file) {
for (let item of items) {
if (!hidden) {
return;
}
2024-06-27 17:14:35 +02:00
2024-07-02 20:04:17 +02:00
if (item instanceof ListFileItem) {
hidden = hidden && file._data.hidden === true;
2024-07-02 20:04:17 +02:00
} else if (item instanceof ListTrackItem && item.getTrackIndex() < file.trk.length) {
hidden = hidden && file.trk[item.getTrackIndex()]._data.hidden === true;
} else if (
item instanceof ListTrackSegmentItem &&
item.getTrackIndex() < file.trk.length &&
item.getSegmentIndex() < file.trk[item.getTrackIndex()].trkseg.length
) {
hidden =
hidden &&
file.trk[item.getTrackIndex()].trkseg[item.getSegmentIndex()]._data.hidden === true;
2024-07-02 20:04:17 +02:00
} else if (item instanceof ListWaypointsItem) {
hidden = hidden && file._data.hiddenWpt === true;
2024-07-02 20:04:17 +02:00
} else if (item instanceof ListWaypointItem && item.getWaypointIndex() < file.wpt.length) {
hidden = hidden && file.wpt[item.getWaypointIndex()]._data.hidden === true;
2024-07-02 20:04:17 +02:00
}
}
2024-06-27 17:14:35 +02:00
}
});
2024-07-02 20:04:17 +02:00
allHidden.set(hidden);
2024-06-27 17:14:35 +02:00
}
2024-07-02 20:04:17 +02:00
selection.subscribe(updateAllHidden);
2024-06-27 17:14:35 +02:00
2024-06-27 18:23:11 +02:00
export const editMetadata = writable(false);
export const editStyle = writable(false);
2024-06-28 15:43:57 +02:00
export enum ExportState {
NONE,
SELECTION,
ALL
}
export const exportState = writable<ExportState>(ExportState.NONE);