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

281 lines
8.8 KiB
TypeScript
Raw Normal View History

2024-05-02 19:51:08 +02:00
import { writable, get, type Writable } 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';
2024-05-24 22:53:30 +02:00
import { applyToOrderedSelectedItemsFromFile, selectFile, selection } from '$lib/components/file-list/Selection';
2024-06-05 23:37:55 +02:00
import { ListFileItem, 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-06-06 18:11:03 +02:00
import { overlayTree, overlays, stravaHeatmapActivityIds, stravaHeatmapServers } from '$lib/assets/layers';
2024-06-10 20:03:57 +02:00
import { SplitType } from '$lib/components/toolbar/tools/Scissors.svelte';
2024-04-17 11:44:37 +02:00
2024-04-17 16:46:51 +02:00
export const map = writable<mapboxgl.Map | null>(null);
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
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-08 23:01:56 +02:00
}
});
2024-04-30 20:55:47 +02:00
});
2024-05-08 21:31:54 +02:00
const targetMapBounds = writable({
bounds: new mapboxgl.LngLatBounds([180, 90, -180, -90]),
initial: true
});
2024-05-07 12:16:30 +02:00
targetMapBounds.subscribe((bounds) => {
2024-05-07 15:16:32 +02:00
if (bounds.initial) {
2024-05-07 12:16:30 +02:00
return;
}
2024-05-23 12:57:24 +02:00
let currentBounds = get(map)?.getBounds();
if (currentBounds && currentBounds.contains(bounds.bounds.getSouthEast()) && currentBounds.contains(bounds.bounds.getNorthWest())) {
return;
}
2024-05-07 15:16:32 +02:00
get(map)?.fitBounds(bounds.bounds, {
2024-05-07 12:16:30 +02:00
padding: 80,
linear: true,
easing: () => 1
});
});
2024-05-08 21:31:54 +02:00
export function initTargetMapBounds(first: boolean) {
let bounds = new mapboxgl.LngLatBounds([180, 90, -180, -90]);
let mapBounds = new mapboxgl.LngLatBounds([180, 90, -180, -90]);
if (!first) { // Some files are already loaded
mapBounds = get(map)?.getBounds() ?? mapBounds;
bounds.extend(mapBounds);
}
targetMapBounds.set({
bounds: bounds,
initial: true
});
}
export function updateTargetMapBounds(bounds: {
southWest: Coordinates,
northEast: Coordinates
}) {
if (bounds.southWest.lat == 90 && bounds.southWest.lon == 180 && bounds.northEast.lat == -90 && bounds.northEast.lon == -180) { // Avoid update for empty (new) files
return;
}
targetMapBounds.update((target) => {
target.bounds.extend(bounds.southWest);
target.bounds.extend(bounds.northEast);
target.initial = false;
return target;
});
}
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,
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-04-18 10:55:55 +02:00
2024-06-05 21:08:01 +02:00
export function newGPXFile() {
2024-04-27 12:18:40 +02:00
let file = new GPXFile();
file.metadata.name = get(_)("menu.new_filename");
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-04-20 18:47:16 +02:00
export async function loadFiles(list: FileList) {
2024-04-30 20:55:47 +02:00
let files = [];
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
2024-05-07 12:16:30 +02:00
dbUtils.addMultiple(files);
2024-04-30 20:55:47 +02:00
2024-05-03 15:59:34 +02:00
selectFileWhenLoaded(files[0]._data.id);
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 = { name: file.name.split('.').slice(0, -1).join('.') };
} else if (gpx.metadata.name === undefined) {
2024-04-20 18:47:16 +02:00
gpx.metadata['name'] = file.name.split('.').slice(0, -1).join('.');
}
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
}
2024-05-03 15:59:34 +02:00
function selectFileWhenLoaded(fileId: string) {
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-05-03 15:59:34 +02:00
export function exportSelectedFiles() {
2024-05-23 16:46:24 +02:00
get(selection).forEach(async (item) => {
if (item instanceof ListFileItem) {
2024-06-15 18:44:17 +02:00
let file = getFile(item.getFileId());
if (file) {
exportFile(file);
await new Promise(resolve => setTimeout(resolve, 200));
2024-05-03 15:59:34 +02:00
}
}
});
}
export function exportAllFiles() {
get(fileObservers).forEach(async (file) => {
let f = get(file);
if (f) {
2024-05-15 15:30:02 +02:00
exportFile(f.file);
2024-05-03 15:59:34 +02:00
await new Promise(resolve => setTimeout(resolve, 200));
}
});
2024-04-18 15:30:19 +02:00
}
2024-05-03 22:15:47 +02:00
export function exportFile(file: GPXFile) {
2024-04-18 15:30:19 +02:00
let blob = new Blob([buildGPX(file)], { type: 'application/gpx+xml' });
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
}
let stravaCookies: any = null;
function refreshStravaCookies() {
2024-06-06 18:40:08 +02:00
/*
TODO
2024-06-06 18:11:03 +02:00
if (stravaCookies === null) {
return fetch('https://s.gpx.studio')
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to fetch Strava cookies');
}
})
.then(data => {
stravaCookies = data;
console.log('Strava cookies:', stravaCookies);
});
} else {
return Promise.resolve();
}
2024-06-06 18:40:08 +02:00
*/
return Promise.resolve();
2024-06-06 18:11:03 +02:00
}
export function setStravaHeatmapURLs() {
refreshStravaCookies().then(() => {
overlays.stravaHeatmapRun.tiles = [];
overlays.stravaHeatmapTrailRun.tiles = [];
overlays.stravaHeatmapHike.tiles = [];
overlays.stravaHeatmapRide.tiles = [];
overlays.stravaHeatmapGravel.tiles = [];
overlays.stravaHeatmapMTB.tiles = [];
overlays.stravaHeatmapWater.tiles = [];
overlays.stravaHeatmapWinter.tiles = [];
for (let activity of Object.keys(overlayTree.overlays.world.strava)) {
overlays[activity].tiles = [];
for (let server of stravaHeatmapServers) {
2024-06-06 18:40:08 +02:00
overlays[activity].tiles.push(`${server}/${stravaHeatmapActivityIds[activity]}/${get(settings.stravaHeatmapColor)}/{z}/{x}/{y}@2x.png`); //?Signature=${stravaCookies['CloudFront-Signature']}&Key-Pair-Id=${stravaCookies['CloudFront-Key-Pair-Id']}&Policy=${stravaCookies['CloudFront-Policy']}`);
2024-06-06 18:11:03 +02:00
}
}
});
2024-04-18 10:55:55 +02:00
}