patches with immer (not working atm)

This commit is contained in:
vcoppe
2024-04-30 20:55:47 +02:00
parent 0db9f46c05
commit 667c94a4c4
14 changed files with 428 additions and 321 deletions

View File

@@ -13,6 +13,7 @@
"chart.js": "^4.4.2",
"clsx": "^2.1.0",
"gpx": "file:../gpx",
"immer": "^10.1.1",
"lucide-svelte": "^0.365.0",
"mapbox-gl": "^3.2.0",
"mode-watcher": "^0.3.0",
@@ -3356,6 +3357,15 @@
"node": ">= 4"
}
},
"node_modules/immer": {
"version": "10.1.1",
"resolved": "https://registry.npmjs.org/immer/-/immer-10.1.1.tgz",
"integrity": "sha512-s2MPrmjovJcoMaHtx6K11Ra7oD05NT97w1IC5zpMkT6Atjr7H8LjaDd81iIxUYpMKSRRNMJE703M1Fhr/TctHw==",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
}
},
"node_modules/import-fresh": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz",

View File

@@ -46,6 +46,7 @@
"chart.js": "^4.4.2",
"clsx": "^2.1.0",
"gpx": "file:../gpx",
"immer": "^10.1.1",
"lucide-svelte": "^0.365.0",
"mapbox-gl": "^3.2.0",
"mode-watcher": "^0.3.0",

View File

@@ -6,8 +6,7 @@
import Chart from 'chart.js/auto';
import mapboxgl from 'mapbox-gl';
import { map, fileOrder, selectedFiles, settings } from '$lib/stores';
import { get } from 'svelte/store';
import { map, settings, gpxData } from '$lib/stores';
import { onDestroy, onMount } from 'svelte';
import {
@@ -19,7 +18,6 @@
Thermometer,
Zap
} from 'lucide-svelte';
import { GPXFiles } from 'gpx';
import { surfaceColors } from '$lib/assets/surfaces';
import { _ } from 'svelte-i18n';
@@ -32,7 +30,6 @@
getConvertedVelocity,
getDistanceUnits,
getDistanceWithUnits,
getElevationUnits,
getElevationWithUnits,
getHeartRateUnits,
getHeartRateWithUnits,
@@ -236,8 +233,7 @@
});
$: if (chart && $settings) {
let gpxFiles = new GPXFiles(get(fileOrder).filter((f) => $selectedFiles.has(f)));
let data = gpxFiles.getTrackPointsAndStatistics();
let data = $gpxData;
// update data
chart.data.datasets[0] = {

View File

@@ -1,52 +1,50 @@
<script lang="ts">
import { fileOrder, files, getFileIndex, selectedFiles, selectFiles } from '$lib/stores';
import { filestore, fileOrder, selectedFiles, selectFiles } from '$lib/stores';
import { ScrollArea } from '$lib/components/ui/scroll-area/index';
import Sortable from 'sortablejs/Sortable';
import type { GPXFile } from 'gpx';
import { afterUpdate, onMount } from 'svelte';
import { get } from 'svelte/store';
import FileListItem from './FileListItem.svelte';
let container: HTMLDivElement;
let buttons: HTMLDivElement[] = [];
let buttons: { [id: string]: HTMLElement } = {};
let sortable: Sortable;
function selectFile(file: GPXFile) {
function selectFile(fileId: string) {
selectedFiles.update((selectedFiles) => {
selectedFiles.clear();
selectedFiles.add(file);
selectedFiles.add(fileId);
return selectedFiles;
});
}
function addSelectFile(file: GPXFile) {
function addSelectFile(fileId: string) {
selectedFiles.update((selectedFiles) => {
selectedFiles.add(file);
selectedFiles.add(fileId);
return selectedFiles;
});
}
function selectAllFiles() {
selectedFiles.update((selectedFiles) => {
get(files).forEach((file) => {
selectedFiles.add(get(file));
get(filestore).forEach((file) => {
selectedFiles.add(file._data.id);
});
return selectedFiles;
});
}
function deselectFile(file: GPXFile) {
function deselectFile(fileId: string) {
selectedFiles.update((selectedFiles) => {
selectedFiles.delete(file);
selectedFiles.delete(fileId);
return selectedFiles;
});
}
function updateFileOrder() {
let newFileOrder = sortable.toArray().map((index: string) => get(get(files)[parseInt(index)]));
let newFileOrder = sortable.toArray();
if (newFileOrder.length !== get(fileOrder).length) {
fileOrder.set(newFileOrder);
return;
@@ -68,21 +66,19 @@
selectedClass: 'sortable-selected',
avoidImplicitDeselect: true,
onSelect: (e) => {
const index = parseInt(e.item.getAttribute('data-id'));
addSelectFile(get($files[index]));
let selectedId = e.item.getAttribute('data-id');
addSelectFile(selectedId);
if (!e.originalEvent.shiftKey && $selectedFiles.size > 1) {
$selectedFiles.forEach((file) => {
if (file !== get($files[index])) {
deselectFile(file);
const index = getFileIndex(file);
Sortable.utils.deselect(buttons[index]);
$selectedFiles.forEach((fileId) => {
if (fileId !== selectedId) {
deselectFile(fileId);
Sortable.utils.deselect(buttons[fileId]);
}
});
}
},
onDeselect: (e) => {
const index = parseInt(e.item.getAttribute('data-id'));
deselectFile(get($files[index]));
deselectFile(e.item.getAttribute('data-id'));
},
onSort: () => {
updateFileOrder();
@@ -92,48 +88,50 @@
selectFiles.update(() => {
return {
select: (file: GPXFile) => {
buttons.forEach((button) => {
if (button) {
Sortable.utils.deselect(button);
}
select: (fileId: string) => {
Object.values(buttons).forEach((button) => {
Sortable.utils.deselect(button);
});
const index = getFileIndex(file);
Sortable.utils.select(buttons[index]);
selectFile(file);
Sortable.utils.select(buttons[fileId]);
selectFile(fileId);
},
addSelect: (file: GPXFile) => {
const index = getFileIndex(file);
Sortable.utils.select(buttons[index]);
addSelectFile(file);
addSelect: (fileId: string) => {
Sortable.utils.select(buttons[fileId]);
addSelectFile(fileId);
},
selectAllFiles: () => {
$files.forEach((file, index) => {
Sortable.utils.select(buttons[index]);
Object.values(buttons).forEach((button) => {
Sortable.utils.select(button);
});
selectAllFiles();
},
removeSelect: (file: GPXFile) => {
const index = getFileIndex(file);
Sortable.utils.deselect(buttons[index]);
deselectFile(file);
removeSelect: (fileId: string) => {
Sortable.utils.deselect(buttons[fileId]);
deselectFile(fileId);
}
};
});
afterUpdate(updateFileOrder);
afterUpdate(() => {
updateFileOrder();
Object.keys(buttons).forEach((fileId) => {
if (!get(filestore).find((file) => file._data.id === fileId)) {
delete buttons[fileId];
}
});
});
</script>
<div class="h-10 -translate-y-10 w-full pointer-events-none">
<ScrollArea orientation="horizontal" class="w-full h-full" scrollbarXClasses="h-2">
<div bind:this={container} class="flex flex-row gap-1">
{#each $files as file, index}
{#each $filestore as file}
<div
bind:this={buttons[index]}
data-id={index}
bind:this={buttons[file._data.id]}
data-id={file._data.id}
class="pointer-events-auto first:ml-1 last:mr-1 mb-1 bg-transparent"
>
<FileListItem {file} />
<FileListItem file={filestore.getFileStore(file._data.id)} />
</div>
{/each}
</div>

View File

@@ -4,43 +4,38 @@
import Shortcut from './Shortcut.svelte';
import { Copy, Trash2 } from 'lucide-svelte';
import type { GPXFile } from 'gpx';
import { get, type Writable } from 'svelte/store';
import {
duplicateSelectedFiles,
removeSelectedFiles,
selectedFiles,
selectFiles
} from '$lib/stores';
import { filestore, selectedFiles, selectFiles } from '$lib/stores';
import { _ } from 'svelte-i18n';
import type { GPXFile } from 'gpx';
import type { Immutable } from 'immer';
export let file: Writable<GPXFile>;
export let file: Writable<Immutable<GPXFile>> | undefined;
</script>
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div
on:contextmenu={() => {
if (!get(selectedFiles).has(get(file))) {
get(selectFiles).select(get(file));
if (!get(selectedFiles).has($file?._data.id)) {
get(selectFiles).select($file?._data.id);
}
}}
>
<ContextMenu.Root>
<ContextMenu.Trigger>
<Button variant="outline" class="h-9 px-1.5 py-1 border-none shadow-md">
{$file.metadata.name}
{$file?.metadata.name}
</Button>
</ContextMenu.Trigger>
<ContextMenu.Content>
<ContextMenu.Item on:click={duplicateSelectedFiles}>
<ContextMenu.Item on:click={filestore.duplicateSelectedFiles}>
<Copy size="16" class="mr-1" />
{$_('menu.duplicate')}
<Shortcut key="D" ctrl={true} /></ContextMenu.Item
>
<ContextMenu.Separator />
<ContextMenu.Item on:click={removeSelectedFiles}
<ContextMenu.Item on:click={filestore.deleteSelectedFiles}
><Trash2 size="16" class="mr-1" />
{$_('menu.delete')}
<Shortcut key="⌫" ctrl={true} /></ContextMenu.Item

View File

@@ -3,24 +3,17 @@
import Tooltip from '$lib/components/Tooltip.svelte';
import WithUnits from '$lib/components/WithUnits.svelte';
import { GPXFiles, GPXStatistics } from 'gpx';
import { GPXStatistics } from 'gpx';
import { selectedFiles, settings } from '$lib/stores';
import { get } from 'svelte/store';
import { gpxData, settings } from '$lib/stores';
import { MoveDownRight, MoveUpRight, Ruler, Timer, Zap } from 'lucide-svelte';
import { _ } from 'svelte-i18n';
let gpxData: GPXStatistics = new GPXStatistics();
let data: GPXStatistics;
function updateGPXData() {
gpxData = new GPXFiles(Array.from(get(selectedFiles))).getStatistics();
}
$: if ($selectedFiles) {
updateGPXData();
}
$: data = $gpxData.statistics;
</script>
<Card.Root class="h-full overflow-hidden border-none shadow-none min-w-48 pl-4">
@@ -28,25 +21,25 @@
<Tooltip>
<span slot="data" class="flex flex-row items-center">
<Ruler size="18" class="mr-1" />
<WithUnits value={gpxData.distance.total} type="distance" />
<WithUnits value={data.distance.total} type="distance" />
</span>
<span slot="tooltip">{$_('quantities.distance')}</span>
</Tooltip>
<Tooltip>
<span slot="data" class="flex flex-row items-center">
<MoveUpRight size="18" class="mr-1" />
<WithUnits value={gpxData.elevation.gain} type="elevation" />
<WithUnits value={data.elevation.gain} type="elevation" />
<MoveDownRight size="18" class="mx-1" />
<WithUnits value={gpxData.elevation.loss} type="elevation" />
<WithUnits value={data.elevation.loss} type="elevation" />
</span>
<span slot="tooltip">{$_('quantities.elevation')}</span>
</Tooltip>
<Tooltip>
<span slot="data" class="flex flex-row items-center">
<Zap size="18" class="mr-1" />
<WithUnits value={gpxData.speed.total} type="speed" showUnits={false} />
<WithUnits value={data.speed.total} type="speed" showUnits={false} />
<span class="mx-1">/</span>
<WithUnits value={gpxData.speed.moving} type="speed" />
<WithUnits value={data.speed.moving} type="speed" />
</span>
<span slot="tooltip"
>{$settings.velocityUnits === 'speed' ? $_('quantities.speed') : $_('quantities.pace')} ({$_(
@@ -57,9 +50,9 @@
<Tooltip>
<span slot="data" class="flex flex-row items-center">
<Timer size="18" class="mr-1" />
<WithUnits value={gpxData.time.total} type="time" />
<WithUnits value={data.time.total} type="time" />
<span class="mx-1">/</span>
<WithUnits value={gpxData.time.moving} type="time" />
<WithUnits value={data.time.moving} type="time" />
</span>
<span slot="tooltip"
>{$_('quantities.time')} ({$_('quantities.total')} / {$_('quantities.moving')})</span

View File

@@ -6,13 +6,10 @@
import { Plus, Copy, Download, Undo2, Redo2, Trash2, Upload, Cloud, Heart } from 'lucide-svelte';
import {
files,
filestore,
selectedFiles,
duplicateSelectedFiles,
exportAllFiles,
exportSelectedFiles,
removeAllFiles,
removeSelectedFiles,
triggerFileInput,
selectFiles,
settings,
@@ -69,7 +66,10 @@
{$_('menu.load_drive')}</Menubar.Item
>
<Menubar.Separator />
<Menubar.Item on:click={duplicateSelectedFiles} disabled={$selectedFiles.size == 0}>
<Menubar.Item
on:click={filestore.duplicateSelectedFiles}
disabled={$selectedFiles.size == 0}
>
<Copy size="16" class="mr-1" />
{$_('menu.duplicate')}
<Shortcut key="D" ctrl={true} />
@@ -80,7 +80,7 @@
{$_('menu.export')}
<Shortcut key="S" ctrl={true} />
</Menubar.Item>
<Menubar.Item on:click={exportAllFiles} disabled={$files.length == 0}>
<Menubar.Item on:click={exportAllFiles} disabled={$filestore.length == 0}>
<Download size="16" class="mr-1" />
{$_('menu.export_all')}
<Shortcut key="S" ctrl={true} shift={true} />
@@ -107,15 +107,18 @@
<Shortcut key="A" ctrl={true} />
</Menubar.Item>
<Menubar.Separator />
<Menubar.Item on:click={removeSelectedFiles} disabled={$selectedFiles.size == 0}>
<Menubar.Item
on:click={filestore.deleteSelectedFiles}
disabled={$selectedFiles.size == 0}
>
<Trash2 size="16" class="mr-1" />
{$_('menu.delete')}
<Shortcut key="⌫" ctrl={true} />
</Menubar.Item>
<Menubar.Item
class="text-destructive data-[highlighted]:text-destructive"
on:click={removeAllFiles}
disabled={$files.length == 0}
on:click={filestore.deleteAllFiles}
disabled={$filestore.length == 0}
>
<Trash2 size="16" class="mr-1" />
{$_('menu.delete_all')}
@@ -199,7 +202,7 @@
triggerFileInput();
e.preventDefault();
} else if (e.key === 'd' && (e.metaKey || e.ctrlKey)) {
duplicateSelectedFiles();
filestore.duplicateSelectedFiles();
e.preventDefault();
} else if ((e.key === 's' || e.key == 'S') && (e.metaKey || e.ctrlKey)) {
if (e.shiftKey) {
@@ -210,9 +213,9 @@
e.preventDefault();
} else if ((e.key === 'Backspace' || e.key === 'Delete') && (e.metaKey || e.ctrlKey)) {
if (e.shiftKey) {
removeAllFiles();
filestore.deleteAllFiles();
} else {
removeSelectedFiles();
filestore.deleteSelectedFiles();
}
e.preventDefault();
} else if (e.key === 'a' && (e.metaKey || e.ctrlKey)) {

View File

@@ -1,13 +1,8 @@
import type { GPXFile, Waypoint } from "gpx";
import type { GPXFile } from "gpx";
import { map, selectFiles, currentTool, Tool } from "$lib/stores";
import { get, type Writable } from "svelte/store";
import mapboxgl from "mapbox-gl";
let id = 0;
function getLayerId() {
return `gpx-${id++}`;
}
let defaultWeight = 6;
let defaultOpacity = 1;
@@ -44,7 +39,7 @@ function decrementColor(color: string) {
export class GPXLayer {
map: mapboxgl.Map;
file: Writable<GPXFile>;
layerId: string;
fileId: string;
layerColor: string;
popup: mapboxgl.Popup;
popupElement: HTMLElement;
@@ -57,36 +52,33 @@ export class GPXLayer {
constructor(map: mapboxgl.Map, file: Writable<GPXFile>, popup: mapboxgl.Popup, popupElement: HTMLElement) {
this.map = map;
this.file = file;
this.layerId = getLayerId();
this.fileId = get(file)._data.id;
this.layerColor = getColor();
this.popup = popup;
this.popupElement = popupElement;
this.unsubscribe = file.subscribe(this.updateData.bind(this));
get(this.file)._data = {
layerId: this.layerId,
layerColor: this.layerColor
};
get(this.file)._data.layerColor = this.layerColor;
this.add();
this.map.on('style.load', this.addBinded);
}
add() {
if (!this.map.getSource(this.layerId)) {
if (!this.map.getSource(this.fileId)) {
let data = this.getGeoJSON();
this.map.addSource(this.layerId, {
this.map.addSource(this.fileId, {
type: 'geojson',
data
});
}
if (!this.map.getLayer(this.layerId)) {
if (!this.map.getLayer(this.fileId)) {
this.map.addLayer({
id: this.layerId,
id: this.fileId,
type: 'line',
source: this.layerId,
source: this.fileId,
layout: {
'line-join': 'round',
'line-cap': 'round'
@@ -98,14 +90,14 @@ export class GPXLayer {
}
});
this.map.on('click', this.layerId, this.selectOnClickBinded);
this.map.on('mouseenter', this.layerId, toPointerCursor);
this.map.on('mouseleave', this.layerId, toDefaultCursor);
this.map.on('click', this.fileId, this.selectOnClickBinded);
this.map.on('mouseenter', this.fileId, toPointerCursor);
this.map.on('mouseleave', this.fileId, toDefaultCursor);
}
}
updateData() {
let source = this.map.getSource(this.layerId);
let source = this.map.getSource(this.fileId);
if (source) {
source.setData(this.getGeoJSON());
}
@@ -137,13 +129,13 @@ export class GPXLayer {
}
remove() {
this.map.off('click', this.layerId, this.selectOnClickBinded);
this.map.off('mouseenter', this.layerId, toPointerCursor);
this.map.off('mouseleave', this.layerId, toDefaultCursor);
this.map.off('click', this.fileId, this.selectOnClickBinded);
this.map.off('mouseenter', this.fileId, toPointerCursor);
this.map.off('mouseleave', this.fileId, toDefaultCursor);
this.map.off('style.load', this.addBinded);
this.map.removeLayer(this.layerId);
this.map.removeSource(this.layerId);
this.map.removeLayer(this.fileId);
this.map.removeSource(this.fileId);
this.markers.forEach((marker) => {
marker.remove();
@@ -155,7 +147,7 @@ export class GPXLayer {
}
moveToFront() {
this.map.moveLayer(this.layerId);
this.map.moveLayer(this.fileId);
}
selectOnClick(e: any) {
@@ -163,9 +155,9 @@ export class GPXLayer {
return;
}
if (e.originalEvent.shiftKey) {
get(selectFiles).addSelect(get(this.file));
get(selectFiles).addSelect(this.fileId);
} else {
get(selectFiles).select(get(this.file));
get(selectFiles).select(this.fileId);
}
}

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import { map, files, selectedFiles, getFileStore, gpxLayers } from '$lib/stores';
import { map, filestore, selectedFiles, gpxLayers } from '$lib/stores';
import { GPXLayer } from './GPXLayer';
import { get } from 'svelte/store';
import { onMount } from 'svelte';
@@ -12,26 +12,26 @@
$: if ($map) {
gpxLayers.update(($layers) => {
// remove layers for deleted files
$layers.forEach((layer, file) => {
if (!get(files).includes(file)) {
$layers.forEach((layer, fileId) => {
if (!get(filestore).find((file) => file._data.id === fileId)) {
layer.remove();
$layers.delete(file);
$layers.delete(fileId);
}
});
// add layers for new files
$files.forEach((file) => {
if (!$layers.has(file)) {
$layers.set(file, new GPXLayer(get(map), file, popup, popupElement));
$filestore.forEach((file) => {
if (!$layers.has(file._data.id)) {
let fileStore = filestore.getFileStore(file._data.id);
$layers.set(file._data.id, new GPXLayer(get(map), fileStore, popup, popupElement));
}
});
return $layers;
});
}
$: $selectedFiles.forEach((file) => {
let fileStore = getFileStore(file);
if ($gpxLayers.has(fileStore)) {
$gpxLayers.get(fileStore)?.moveToFront();
$: $selectedFiles.forEach((fileId) => {
if ($gpxLayers.has(fileId)) {
$gpxLayers.get(fileId)?.moveToFront();
}
});

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import { reverseSelectedFiles, Tool } from '$lib/stores';
import { Tool, filestore } from '$lib/stores';
import Routing from '$lib/components/toolbar/tools/routing/Routing.svelte';
import Waypoint from '$lib/components/toolbar/tools/waypoint/Waypoint.svelte';
import ToolbarItem from './ToolbarItem.svelte';
@@ -32,7 +32,10 @@
<CalendarClock slot="icon" size="18" />
<span slot="tooltip">{$_('toolbar.time_tooltip')}</span>
</ToolbarItem>
<ToolbarItem tool={Tool.REVERSE} on:click={reverseSelectedFiles}>
<ToolbarItem
tool={Tool.REVERSE}
on:click={() => filestore.applyToSelectedFiles((file) => file.reverse())}
>
<ArrowRightLeft slot="icon" size="18" />
<span slot="tooltip">{$_('toolbar.reverse_tooltip')}</span>
</ToolbarItem>

View File

@@ -6,29 +6,28 @@
import * as Alert from '$lib/components/ui/alert';
import { CircleHelp } from 'lucide-svelte';
import { files, getFileStore, map, selectedFiles, Tool } from '$lib/stores';
import { filestore, map, selectedFiles, Tool } from '$lib/stores';
import { brouterProfiles, privateRoads, routing, routingProfile } from './Routing';
import { _ } from 'svelte-i18n';
import { get, type Writable } from 'svelte/store';
import type { GPXFile } from 'gpx';
import { get } from 'svelte/store';
import { RoutingControls } from './RoutingControls';
import RoutingControlPopup from './RoutingControlPopup.svelte';
import { onMount } from 'svelte';
import mapboxgl from 'mapbox-gl';
let routingControls: Map<Writable<GPXFile>, RoutingControls> = new Map();
let routingControls: Map<string, RoutingControls> = new Map();
let popupElement: HTMLElement;
let popup: mapboxgl.Popup | null = null;
let selectedFile: Writable<GPXFile> | null = null;
let selectedId: string | null = null;
let active = false;
$: if ($map && $files) {
$: if ($map && $filestore) {
// remove controls for deleted files
routingControls.forEach((controls, file) => {
if (!get(files).includes(file)) {
routingControls.forEach((controls, fileId) => {
if (!get(filestore).find((file) => file._data.id === fileId)) {
controls.remove();
routingControls.delete(file);
routingControls.delete(fileId);
}
});
}
@@ -36,30 +35,32 @@
$: if ($map && $selectedFiles) {
// update selected file
if ($selectedFiles.size == 0 || $selectedFiles.size > 1 || !active) {
if (selectedFile) {
routingControls.get(selectedFile)?.remove();
if (selectedId) {
routingControls.get(selectedId)?.remove();
}
selectedFile = null;
selectedId = null;
} else {
let newSelectedFile = get(selectedFiles).values().next().value;
let newSelectedFileStore = getFileStore(newSelectedFile);
if (selectedFile !== newSelectedFileStore) {
if (selectedFile) {
routingControls.get(selectedFile)?.remove();
let newSelectedId = get(selectedFiles).values().next().value;
if (selectedId !== newSelectedId) {
if (selectedId) {
routingControls.get(selectedId)?.remove();
}
selectedFile = newSelectedFileStore;
selectedId = newSelectedId;
}
}
}
$: if ($map && selectedFile) {
if (!routingControls.has(selectedFile)) {
routingControls.set(
selectedFile,
new RoutingControls(get(map), selectedFile, popup, popupElement)
);
$: if ($map && selectedId) {
if (!routingControls.has(selectedId)) {
let selectedFileStore = filestore.getFileStore(selectedId);
if (selectedFileStore) {
routingControls.set(
selectedId,
new RoutingControls(get(map), selectedFileStore, popup, popupElement)
);
}
} else {
routingControls.get(selectedFile)?.add();
routingControls.get(selectedId)?.add();
}
}

View File

@@ -3,11 +3,11 @@ import { get, type Writable } from "svelte/store";
import { computeAnchorPoints } from "./Simplify";
import mapboxgl from "mapbox-gl";
import { route } from "./Routing";
import { applyToFileElement } from "$lib/stores";
import { toast } from "svelte-sonner";
import { _ } from "svelte-i18n";
import { filestore } from "$lib/stores";
export class RoutingControls {
map: mapboxgl.Map;
@@ -36,7 +36,7 @@ export class RoutingControls {
lon: 0
}
});
this.temporaryAnchor = this.createAnchor(point, new TrackSegment());
this.temporaryAnchor = this.createAnchor(point, new TrackSegment(), 0);
this.temporaryAnchor.marker.getElement().classList.remove('z-10'); // Show below the other markers
this.add();
@@ -46,14 +46,18 @@ export class RoutingControls {
this.map.on('zoom', this.toggleAnchorsForZoomLevelAndBoundsBinded);
this.map.on('move', this.toggleAnchorsForZoomLevelAndBoundsBinded);
this.map.on('click', this.appendAnchorBinded);
this.map.on('mousemove', get(this.file)._data.layerId, this.showTemporaryAnchorBinded);
this.map.on('mousemove', get(this.file)._data.id, this.showTemporaryAnchorBinded);
this.unsubscribe = this.file.subscribe(this.updateControls.bind(this));
}
updateControls() { // Update the markers when the file changes
let segments = get(this.file).getSegments();
let anchorIndex = 0;
for (let segment of get(this.file).getSegments()) {
for (let segmentIndex = 0; segmentIndex < segments.length; segmentIndex++) {
let segment = segments[segmentIndex];
if (segment.trkpt.length === 0) { // Empty segment, skip
continue;
}
@@ -79,7 +83,7 @@ export class RoutingControls {
this.anchors[anchorIndex].segment = segment;
this.anchors[anchorIndex].marker.setLngLat(point.getCoordinates());
} else {
this.anchors.push(this.createAnchor(point, segment));
this.anchors.push(this.createAnchor(point, segment, segmentIndex));
}
anchorIndex++;
}
@@ -100,13 +104,13 @@ export class RoutingControls {
this.map.off('zoom', this.toggleAnchorsForZoomLevelAndBoundsBinded);
this.map.off('move', this.toggleAnchorsForZoomLevelAndBoundsBinded);
this.map.off('click', this.appendAnchorBinded);
this.map.off('mousemove', get(this.file)._data.layerId, this.showTemporaryAnchorBinded);
this.map.off('mousemove', get(this.file)._data.id, this.showTemporaryAnchorBinded);
this.map.off('mousemove', this.updateTemporaryAnchorBinded);
this.unsubscribe();
}
createAnchor(point: TrackPoint, segment: TrackSegment): AnchorWithMarker {
createAnchor(point: TrackPoint, segment: TrackSegment, segmentIndex: number): AnchorWithMarker {
let element = document.createElement('div');
element.className = `h-3 w-3 rounded-full bg-white border-2 border-black cursor-pointer`;
@@ -119,6 +123,7 @@ export class RoutingControls {
let anchor = {
point,
segment,
segmentIndex,
marker,
inZoom: false
};
@@ -254,28 +259,25 @@ export class RoutingControls {
getPermanentAnchor(): Anchor {
// Find the closest point closest to the temporary anchor
let segments = get(this.file).getSegments();
let minDistance = Number.MAX_VALUE;
let minPoint: TrackPoint | null = null;
let minSegment: TrackSegment | null = null;
for (let segment of get(this.file).getSegments()) {
let minAnchor = this.temporaryAnchor as Anchor;
for (let segmentIndex = 0; segmentIndex < segments.length; segmentIndex++) {
let segment = segments[segmentIndex];
for (let point of segment.trkpt) {
let dist = distance(point.getCoordinates(), this.temporaryAnchor.point.getCoordinates());
if (dist < minDistance) {
minDistance = dist;
minPoint = point;
minSegment = segment;
minAnchor = {
point,
segment,
segmentIndex,
};
}
}
}
if (!minPoint || !minSegment) {
return this.temporaryAnchor;
}
return {
segment: minSegment,
point: minPoint,
};
return minAnchor;
}
getDeleteAnchor(anchor: Anchor) {
@@ -288,17 +290,20 @@ export class RoutingControls {
let [previousAnchor, nextAnchor] = this.getNeighbouringAnchors(anchor);
if (previousAnchor === null && nextAnchor === null) { // Only one point, remove it
applyToFileElement(this.file, anchor.segment, (segment) => {
filestore.applyToFile(get(this.file)._data.id, (file) => {
let segment = file.getSegments()[anchor.segmentIndex];
segment.replace(0, 0, []);
}, true);
});
} else if (previousAnchor === null) { // First point, remove trackpoints until nextAnchor
applyToFileElement(this.file, anchor.segment, (segment) => {
filestore.applyToFile(get(this.file)._data.id, (file) => {
let segment = file.getSegments()[anchor.segmentIndex];
segment.replace(0, nextAnchor.point._data.index - 1, []);
}, true);
});
} else if (nextAnchor === null) { // Last point, remove trackpoints from previousAnchor
applyToFileElement(this.file, anchor.segment, (segment) => {
filestore.applyToFile(get(this.file)._data.id, (file) => {
let segment = file.getSegments()[anchor.segmentIndex];
segment.replace(previousAnchor.point._data.index + 1, segment.trkpt.length - 1, []);
}, true);
});
} else { // Route between previousAnchor and nextAnchor
this.routeBetweenAnchors([previousAnchor, nextAnchor], [previousAnchor.point.getCoordinates(), nextAnchor.point.getCoordinates()]);
}
@@ -318,16 +323,18 @@ export class RoutingControls {
if (!lastAnchor) {
// TODO, create segment if it does not exist
applyToFileElement(this.file, get(this.file).getSegments()[0], (segment) => {
filestore.applyToFile(get(this.file)._data.id, (file) => {
let segment = file.getSegments()[0];
segment.replace(0, 0, [newPoint]);
}, true);
});
return;
}
newPoint._data.index = lastAnchor.segment.trkpt.length - 1; // Do as if the point was the last point in the segment
let newAnchor = {
point: newPoint,
segment: lastAnchor.segment
segment: lastAnchor.segment,
segmentIndex: lastAnchor.segmentIndex
};
await this.routeBetweenAnchors([lastAnchor, newAnchor], [lastAnchor.point.getCoordinates(), newAnchor.point.getCoordinates()]);
@@ -358,11 +365,12 @@ export class RoutingControls {
let segment = anchors[0].segment;
if (anchors.length === 1) { // Only one anchor, update the point in the segment
applyToFileElement(this.file, segment, (segment) => {
filestore.applyToFile(get(this.file)._data.id, (file) => {
let segment = file.getSegments()[anchors[0].segmentIndex];
segment.replace(0, 0, [new TrackPoint({
attributes: targetCoordinates[0],
})]);
}, true);
});
return true;
}
@@ -417,9 +425,10 @@ export class RoutingControls {
anchor.point._data.zoom = 0; // Make these anchors permanent
});
applyToFileElement(this.file, segment, (segment) => {
filestore.applyToFile(get(this.file)._data.id, (file) => {
let segment = file.getSegments()[anchors[0].segmentIndex];
segment.replace(start, end, response);
}, true);
});
return true;
}
@@ -427,6 +436,7 @@ export class RoutingControls {
type Anchor = {
segment: TrackSegment;
segmentIndex: number;
point: TrackPoint;
};

View File

@@ -0,0 +1,159 @@
import { writable, get, type Readable, type Writable } from "svelte/store";
import { GPXFile } from "gpx";
import { produceWithPatches, enableMapSet, enablePatches, type Immutable } from "immer";
import { fileOrder, selectedFiles } from "./stores";
enableMapSet();
enablePatches();
export type GPXFileStore = Readable<GPXFile[]> & {
add: (file: GPXFile) => void;
addMultiple: (files: GPXFile[]) => void;
applyToFile: (id: string, callback: (file: GPXFile) => void) => void;
applyToSelectedFiles: (callback: (file: GPXFile) => void) => void;
duplicateSelectedFiles: () => void;
deleteSelectedFiles: () => void;
deleteAllFiles: () => void;
getFileStore: (id: string) => Writable<Immutable<GPXFile>> | undefined;
}
export function createGPXFileStore(): GPXFileStore {
let files: Immutable<Map<string, GPXFile>> = new Map();
let subscribers: Set<Function> = new Set();
let filestores = new Map<string, Writable<Immutable<GPXFile>>>();
let patches = [];
function notifySubscriber(run: Function) {
run(Array.from(files.values()));
}
function notify() {
subscribers.forEach((run) => {
notifySubscriber(run);
});
}
function applyToGlobalStore(callback: (files: Map<string, GPXFile>) => void) {
const [newFiles, patch, inversePatch] = produceWithPatches(files, callback);
files = newFiles;
patches.push({
patch,
inversePatch,
global: true
});
console.log(patches[patches.length - 1]);
notify();
}
function applyToFiles(fileIds: string[], callback: (file: GPXFile) => void) {
const [newFiles, patch, inversePatch] = produceWithPatches(files, (draft) => {
fileIds.forEach((fileId) => {
if (draft.has(fileId)) {
callback(draft.get(fileId));
}
});
});
files = newFiles;
patches.push({
patch,
inversePatch,
global: false
});
console.log(patches[patches.length - 1]);
fileIds.forEach((fileId) => {
let filestore = filestores.get(fileId), newFile = newFiles.get(fileId);
if (filestore && newFile) {
filestore.set(newFile);
}
});
}
subscribers.add(() => {
// remove filestores that are no longer in the files map
filestores.forEach((_, fileId) => {
if (!files.has(fileId)) {
filestores.delete(fileId);
}
});
// add filestores that are in the files map but not in the filestores map
files.forEach((file, fileId) => {
if (!filestores.has(fileId)) {
filestores.set(fileId, writable(file));
}
});
});
return {
subscribe: (run) => {
subscribers.add(run);
notifySubscriber(run);
return () => {
subscribers.delete(run);
}
},
add: (file: GPXFile) => {
file._data.id = getLayerId();
applyToGlobalStore((draft) => {
draft.set(file._data.id, file);
});
},
addMultiple: (files: GPXFile[]) => {
applyToGlobalStore((draft) => {
files.forEach((file) => {
file._data.id = getLayerId();
draft.set(file._data.id, file);
});
});
},
applyToFile: (id: string, callback: (file: GPXFile) => void) => {
applyToFiles([id], callback);
},
applyToSelectedFiles: (callback: (file: GPXFile) => void) => {
applyToFiles(get(fileOrder).filter(fileId => get(selectedFiles).has(fileId)), callback);
},
duplicateSelectedFiles: () => {
applyToGlobalStore((draft) => {
get(fileOrder).forEach((fileId) => {
if (get(selectedFiles).has(fileId)) {
let file = draft.get(fileId);
if (file) {
let clone = file.clone();
clone._data.id = getLayerId();
draft.set(clone._data.id, clone);
}
}
});
});
},
deleteSelectedFiles: () => {
applyToGlobalStore((draft) => {
get(selectedFiles).forEach((fileId) => {
draft.delete(fileId);
});
});
selectedFiles.update($selected => {
$selected.clear();
return $selected;
});
},
deleteAllFiles: () => {
applyToGlobalStore((draft) => {
draft.clear();
});
selectedFiles.update($selected => {
$selected.clear();
return $selected;
});
},
getFileStore: (id: string) => {
return filestores.get(id);
}
}
}
let id = 0;
function getLayerId() {
return `gpx-${id++}`;
}

View File

@@ -1,23 +1,52 @@
import { writable, get, type Writable } from 'svelte/store';
import { writable, get, type Writable, derived } from 'svelte/store';
import mapboxgl from 'mapbox-gl';
import { GPXFile, buildGPX, parseGPX, type AnyGPXTreeElement } from 'gpx';
import { GPXFile, buildGPX, parseGPX, type AnyGPXTreeElement, GPXFiles } from 'gpx';
import { tick } from 'svelte';
import { _ } from 'svelte-i18n';
import type { GPXLayer } from '$lib/components/gpx-layer/GPXLayer';
import { createGPXFileStore } from './filestore';
export const map = writable<mapboxgl.Map | null>(null);
export const files = writable<Writable<GPXFile>[]>([]);
export const fileOrder = writable<GPXFile[]>([]);
export const selectedFiles = writable<Set<GPXFile>>(new Set());
export const selectFiles = writable<{ [key: string]: (file?: GPXFile) => void }>({});
export const filestore = createGPXFileStore();
export const fileOrder = writable<string[]>([]);
export const selectedFiles = writable<Set<string>>(new Set());
export const selectFiles = writable<{ [key: string]: (fileId?: string) => void }>({});
export const gpxData = writable(new GPXFiles([]).getTrackPointsAndStatistics());
function updateGPXData() {
let fileIds: string[] = get(fileOrder).filter((f) => get(selectedFiles).has(f));
let files: GPXFile[] = fileIds
.map((id) => get(filestore).find((f) => f._data.id === id))
.filter((f) => f) as GPXFile[];
let gpxFiles = new GPXFiles(files);
gpxData.set(gpxFiles.getTrackPointsAndStatistics());
}
let selectedFilesUnsubscribe: Function[] = [];
selectedFiles.subscribe((selectedFiles) => {
selectedFilesUnsubscribe.forEach((unsubscribe) => unsubscribe());
selectedFiles.forEach((fileId) => {
let fileStore = filestore.getFileStore(fileId);
if (fileStore) {
let unsubscribe = fileStore.subscribe(() => {
updateGPXData();
});
selectedFilesUnsubscribe.push(unsubscribe);
}
});
updateGPXData();
});
export const settings = writable<{ [key: string]: any }>({
distanceUnits: 'metric',
velocityUnits: 'speed',
temperatureUnits: 'celsius',
mode: 'system'
});
export const gpxLayers: Writable<Map<Writable<GPXFile>, GPXLayer>> = writable(new Map());
export const gpxLayers: Writable<Map<string, GPXLayer>> = writable(new Map());
export enum Tool {
ROUTING,
@@ -33,66 +62,14 @@ export enum Tool {
}
export const currentTool = writable<Tool | null>(null);
export function getFileStore(file: GPXFile): Writable<GPXFile> {
return get(files).find(store => get(store) === file) ?? addFile(file);
}
export function getFileIndex(file: GPXFile): number {
return get(files).findIndex(store => get(store) === file);
}
export function applyToFileElement<T extends AnyGPXTreeElement>(store: Writable<GPXFile>, element: T, callback: (element: T) => void, updateSelected: boolean) {
store.update($file => {
callback(element);
return $file;
});
if (updateSelected) {
selectedFiles.update($selected => $selected);
}
}
export function applyToFile(file: GPXFile, callback: (file: GPXFile) => void, updateSelected: boolean) {
let store = getFileStore(file);
applyToFileStore(store, callback, updateSelected);
}
export function applyToFileStore(store: Writable<GPXFile>, callback: (file: GPXFile) => void, updateSelected: boolean) {
store.update($file => {
callback($file)
return $file;
});
if (updateSelected) {
selectedFiles.update($selected => $selected);
}
}
export function applyToSelectedFiles(callback: (file: GPXFile) => void, updateSelected: boolean) {
get(fileOrder).forEach(file => {
if (get(selectedFiles).has(file)) {
applyToFile(file, callback, false);
}
});
if (updateSelected) {
selectedFiles.update($selected => $selected);
}
}
export function addFile(file: GPXFile): Writable<GPXFile> {
let fileStore = writable(file);
files.update($files => {
$files.push(fileStore);
return $files;
});
return fileStore;
}
export function createFile(): Writable<GPXFile> {
export function createFile() {
let file = new GPXFile();
file.metadata.name = get(_)("menu.new_filename");
let fileStore = addFile(file);
tick().then(() => get(selectFiles).select(file));
filestore.add(file);
tick().then(() => get(selectFiles).select(file._data.id));
currentTool.set(Tool.ROUTING);
return fileStore;
}
export function triggerFileInput() {
@@ -112,36 +89,43 @@ export function triggerFileInput() {
export async function loadFiles(list: FileList) {
let bounds = new mapboxgl.LngLatBounds();
let mapBounds = new mapboxgl.LngLatBounds([180, 90, -180, -90]);
if (get(files).length > 0) {
if (get(filestore).length > 0) {
mapBounds = get(map)?.getBounds() ?? mapBounds;
bounds.extend(mapBounds);
}
let files = [];
for (let i = 0; i < list.length; i++) {
let file = await loadFile(list[i]);
if (file) {
if (i == 0) {
get(selectFiles).select(get(file));
}
files.push(file);
let fileBounds = get(file).getStatistics().bounds;
let fileBounds = file.getStatistics().bounds;
bounds.extend(fileBounds.southWest);
bounds.extend(fileBounds.northEast);
bounds.extend([fileBounds.southWest.lon, fileBounds.northEast.lat]);
bounds.extend([fileBounds.northEast.lon, fileBounds.southWest.lat]);
if (!mapBounds.contains(bounds.getSouthWest()) || !mapBounds.contains(bounds.getNorthEast()) || !mapBounds.contains(bounds.getSouthEast()) || !mapBounds.contains(bounds.getNorthWest())) {
get(map)?.fitBounds(bounds, {
padding: 80,
linear: true,
easing: () => 1
});
}
}
}
filestore.addMultiple(files);
if (!mapBounds.contains(bounds.getSouthWest()) || !mapBounds.contains(bounds.getNorthEast()) || !mapBounds.contains(bounds.getSouthEast()) || !mapBounds.contains(bounds.getNorthWest())) {
get(map)?.fitBounds(bounds, {
padding: 80,
linear: true,
easing: () => 1
});
}
await tick();
if (files.length > 0) {
get(selectFiles).select(files[0]._data.id);
}
}
export async function loadFile(file: File) {
let result = await new Promise<Writable<GPXFile> | null>((resolve) => {
export async function loadFile(file: File): Promise<GPXFile | null> {
let result = await new Promise<GPXFile | null>((resolve) => {
const reader = new FileReader();
reader.onload = () => {
let data = reader.result?.toString() ?? null;
@@ -150,7 +134,7 @@ export async function loadFile(file: File) {
if (gpx.metadata.name === undefined) {
gpx.metadata['name'] = file.name.split('.').slice(0, -1).join('.');
}
resolve(addFile(gpx));
resolve(gpx);
} else {
resolve(null);
}
@@ -160,49 +144,18 @@ export async function loadFile(file: File) {
return result;
}
export function duplicateSelectedFiles() {
applyToSelectedFiles(file => {
let clone = file.clone();
addFile(clone);
}, false);
}
export function removeSelectedFiles() {
files.update($files => {
let index = 0;
while (index < $files.length) {
if (get(selectedFiles).has(get($files[index]))) {
$files.splice(index, 1);
} else {
index++;
}
export async function exportSelectedFiles() {
for (let file of get(filestore)) {
if (get(selectedFiles).has(file._data.id)) {
exportFile(file);
await new Promise(resolve => setTimeout(resolve, 200));
}
return $files;
});
selectedFiles.update($selected => {
$selected.clear();
return $selected;
});
}
export function removeAllFiles() {
files.update($files => {
$files.splice(0, $files.length);
return $files;
});
selectedFiles.update($selected => {
$selected.clear();
return $selected;
});
}
export function exportSelectedFiles() {
get(selectedFiles).forEach(file => exportFile(file));
}
}
export async function exportAllFiles() {
for (let file of get(files)) {
exportFile(get(file));
for (let file of get(filestore)) {
exportFile(file);
await new Promise(resolve => setTimeout(resolve, 200));
}
}
@@ -215,11 +168,4 @@ export function exportFile(file: GPXFile) {
a.download = file.metadata.name + '.gpx';
a.click();
URL.revokeObjectURL(url);
}
export function reverseSelectedFiles() {
selectedFiles.update($selected => {
$selected.forEach(file => applyToFile(file, file => file.reverse(), false));
return $selected;
});
}