start of routing reactivity

This commit is contained in:
vcoppe
2024-04-24 20:13:42 +02:00
parent 88c6681a78
commit 482dff54f4
8 changed files with 125 additions and 101 deletions

View File

@@ -230,7 +230,7 @@
}); });
$: if (chart && $settings) { $: if (chart && $settings) {
let gpxFiles = new GPXFiles(Array.from($selectedFiles)); let gpxFiles = new GPXFiles(Array.from($selectedFiles).map((file) => get(file)));
gpxFiles.files.sort(function (a, b) { gpxFiles.files.sort(function (a, b) {
return get(fileOrder).indexOf(a) - get(fileOrder).indexOf(b); return get(fileOrder).indexOf(a) - get(fileOrder).indexOf(b);
}); });

View File

@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import { fileOrder, fileCollection, selectedFiles, selectFiles } from '$lib/stores'; import { fileOrder, files, selectedFiles, selectFiles } from '$lib/stores';
import { ScrollArea } from '$lib/components/ui/scroll-area/index'; import { ScrollArea } from '$lib/components/ui/scroll-area/index';
import Sortable from 'sortablejs/Sortable'; import Sortable from 'sortablejs/Sortable';
@@ -7,13 +7,13 @@
import type { GPXFile } from 'gpx'; import type { GPXFile } from 'gpx';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { get } from 'svelte/store'; import { get, type Writable } from 'svelte/store';
let tabs: HTMLDivElement; let tabs: HTMLDivElement;
let buttons: HTMLButtonElement[] = []; let buttons: HTMLButtonElement[] = [];
let sortable: Sortable; let sortable: Sortable;
function selectFile(file: GPXFile) { function selectFile(file: Writable<GPXFile>) {
selectedFiles.update((selectedFiles) => { selectedFiles.update((selectedFiles) => {
selectedFiles.clear(); selectedFiles.clear();
selectedFiles.add(file); selectedFiles.add(file);
@@ -21,7 +21,7 @@
}); });
} }
function addSelectFile(file: GPXFile) { function addSelectFile(file: Writable<GPXFile>) {
selectedFiles.update((selectedFiles) => { selectedFiles.update((selectedFiles) => {
selectedFiles.add(file); selectedFiles.add(file);
return selectedFiles; return selectedFiles;
@@ -30,14 +30,14 @@
function selectAllFiles() { function selectAllFiles() {
selectedFiles.update((selectedFiles) => { selectedFiles.update((selectedFiles) => {
get(fileCollection).files.forEach((file) => { get(files).forEach((file) => {
selectedFiles.add(file); selectedFiles.add(file);
}); });
return selectedFiles; return selectedFiles;
}); });
} }
function deselectFile(file: GPXFile) { function deselectFile(file: Writable<GPXFile>) {
selectedFiles.update((selectedFiles) => { selectedFiles.update((selectedFiles) => {
selectedFiles.delete(file); selectedFiles.delete(file);
return selectedFiles; return selectedFiles;
@@ -53,12 +53,12 @@
avoidImplicitDeselect: true, avoidImplicitDeselect: true,
onSelect: (e) => { onSelect: (e) => {
const index = parseInt(e.item.getAttribute('data-id')); const index = parseInt(e.item.getAttribute('data-id'));
addSelectFile($fileCollection.files[index]); addSelectFile($files[index]);
if (!e.originalEvent.shiftKey && $selectedFiles.size > 1) { if (!e.originalEvent.shiftKey && $selectedFiles.size > 1) {
$selectedFiles.forEach((file) => { $selectedFiles.forEach((file) => {
if (file !== $fileCollection.files[index]) { if (file !== $files[index]) {
deselectFile(file); deselectFile(file);
const index = $fileCollection.files.indexOf(file); const index = $files.indexOf(file);
Sortable.utils.deselect(buttons[index]); Sortable.utils.deselect(buttons[index]);
} }
}); });
@@ -66,41 +66,39 @@
}, },
onDeselect: (e) => { onDeselect: (e) => {
const index = parseInt(e.item.getAttribute('data-id')); const index = parseInt(e.item.getAttribute('data-id'));
deselectFile($fileCollection.files[index]); deselectFile($files[index]);
}, },
onSort: () => { onSort: () => {
$fileOrder = sortable $fileOrder = sortable.toArray().map((index: string) => $files[parseInt(index)]);
.toArray()
.map((index: string) => $fileCollection.files[parseInt(index)]);
} }
}); });
}); });
selectFiles.update(() => { selectFiles.update(() => {
return { return {
select: (file: GPXFile) => { select: (file: Writable<GPXFile>) => {
buttons.forEach((button) => { buttons.forEach((button) => {
if (button) { if (button) {
Sortable.utils.deselect(button); Sortable.utils.deselect(button);
} }
}); });
const index = $fileCollection.files.indexOf(file); const index = $files.indexOf(file);
Sortable.utils.select(buttons[index]); Sortable.utils.select(buttons[index]);
selectFile(file); selectFile(file);
}, },
addSelect: (file: GPXFile) => { addSelect: (file: Writable<GPXFile>) => {
const index = $fileCollection.files.indexOf(file); const index = $files.indexOf(file);
Sortable.utils.select(buttons[index]); Sortable.utils.select(buttons[index]);
addSelectFile(file); addSelectFile(file);
}, },
selectAllFiles: () => { selectAllFiles: () => {
$fileCollection.files.forEach((file, index) => { $files.forEach((file, index) => {
Sortable.utils.select(buttons[index]); Sortable.utils.select(buttons[index]);
}); });
selectAllFiles(); selectAllFiles();
}, },
removeSelect: (file: GPXFile) => { removeSelect: (file: Writable<GPXFile>) => {
const index = $fileCollection.files.indexOf(file); const index = $files.indexOf(file);
Sortable.utils.deselect(buttons[index]); Sortable.utils.deselect(buttons[index]);
deselectFile(file); deselectFile(file);
} }
@@ -111,13 +109,13 @@
<div class="h-10 -translate-y-10 w-full"> <div class="h-10 -translate-y-10 w-full">
<ScrollArea orientation="horizontal" class="w-full h-full" scrollbarXClasses="h-2"> <ScrollArea orientation="horizontal" class="w-full h-full" scrollbarXClasses="h-2">
<div bind:this={tabs} class="flex flex-row gap-1"> <div bind:this={tabs} class="flex flex-row gap-1">
{#each $fileCollection.files as file, index} {#each $files as file, index}
<button <button
bind:this={buttons[index]} bind:this={buttons[index]}
data-id={index} data-id={index}
class="my-1 px-1.5 py-1 rounded bg-secondary hover:bg-gray-200 shadow-none first:ml-1 last:mr-1" class="my-1 px-1.5 py-1 rounded bg-secondary hover:bg-gray-200 shadow-none first:ml-1 last:mr-1"
> >
{file.metadata.name} {get(file).metadata.name}
</button> </button>
{/each} {/each}
</div> </div>

View File

@@ -5,7 +5,9 @@
import { GPXStatistics } from 'gpx'; import { GPXStatistics } from 'gpx';
import { fileCollection, selectedFiles, settings } from '$lib/stores'; import { selectedFiles, settings } from '$lib/stores';
import { get } from 'svelte/store';
import { MoveDownRight, MoveUpRight, Ruler, Timer, Zap } from 'lucide-svelte'; import { MoveDownRight, MoveUpRight, Ruler, Timer, Zap } from 'lucide-svelte';
import { _ } from 'svelte-i18n'; import { _ } from 'svelte-i18n';
@@ -14,10 +16,8 @@
$: { $: {
gpxData = new GPXStatistics(); gpxData = new GPXStatistics();
$fileCollection.files.forEach((file) => { $selectedFiles.forEach((file) => {
if ($selectedFiles.has(file)) { gpxData.mergeWith(get(file).statistics);
gpxData.mergeWith(file.statistics);
}
}); });
} }
</script> </script>

View File

@@ -41,17 +41,20 @@
<script lang="ts"> <script lang="ts">
import { onDestroy, onMount } from 'svelte'; import { onDestroy, onMount } from 'svelte';
import { GPXFile } from 'gpx'; import { GPXFile } from 'gpx';
import { map, selectedFiles, selectFiles, fileCollection } from '$lib/stores'; import { map, selectedFiles, selectFiles, files } from '$lib/stores';
import { get } from 'svelte/store'; import { get, type Writable } from 'svelte/store';
export let file: GPXFile; export let file: Writable<GPXFile>;
let layerId = getLayerId(); let layerId = getLayerId();
let layerColor = getColor(); let layerColor = getColor();
Object.defineProperty(file, 'layerId', { file.update((f) => {
value: layerId, Object.defineProperty(f, 'layerId', {
writable: false value: layerId,
writable: false
});
return f;
}); });
function selectOnClick(e: any) { function selectOnClick(e: any) {
@@ -74,22 +77,25 @@
} }
} }
function extendGeoJSON(data: any) {
for (let feature of data.features) {
if (!feature.properties.color) {
feature.properties.color = layerColor;
}
if (!feature.properties.weight) {
feature.properties.weight = defaultWeight;
}
if (!feature.properties.opacity) {
feature.properties.opacity = defaultOpacity;
}
}
return data;
}
function addGPXLayer() { function addGPXLayer() {
if ($map) { if ($map) {
if (!$map.getSource(layerId)) { if (!$map.getSource(layerId)) {
let data = file.toGeoJSON(); let data = extendGeoJSON($file.toGeoJSON());
for (let feature of data.features) {
if (!feature.properties.color) {
feature.properties.color = layerColor;
}
if (!feature.properties.weight) {
feature.properties.weight = defaultWeight;
}
if (!feature.properties.opacity) {
feature.properties.opacity = defaultOpacity;
}
}
$map.addSource(layerId, { $map.addSource(layerId, {
type: 'geojson', type: 'geojson',
@@ -132,24 +138,27 @@
onMount(() => { onMount(() => {
addGPXLayer(); addGPXLayer();
if ($map) { if ($map) {
if ($fileCollection.files.length == 1) { if ($files.length == 1) {
$map.fitBounds([file.statistics.bounds.southWest, file.statistics.bounds.northEast], { $map.fitBounds(
padding: 60, [get(file).statistics.bounds.southWest, get(file).statistics.bounds.northEast],
linear: true, {
easing: () => 1 padding: 60,
}); linear: true,
easing: () => 1
}
);
} else { } else {
let mapBounds = $map.getBounds(); let mapBounds = $map.getBounds();
if ( if (
mapBounds.contains(file.statistics.bounds.southWest) && mapBounds.contains(get(file).statistics.bounds.southWest) &&
mapBounds.contains(file.statistics.bounds.northEast) && mapBounds.contains(get(file).statistics.bounds.northEast) &&
mapBounds.contains([ mapBounds.contains([
file.statistics.bounds.southWest.lon, get(file).statistics.bounds.southWest.lon,
file.statistics.bounds.northEast.lat get(file).statistics.bounds.northEast.lat
]) && ]) &&
mapBounds.contains([ mapBounds.contains([
file.statistics.bounds.northEast.lon, get(file).statistics.bounds.northEast.lon,
file.statistics.bounds.southWest.lat get(file).statistics.bounds.southWest.lat
]) ])
) { ) {
return; return;
@@ -159,10 +168,10 @@
$map $map
.getBounds() .getBounds()
.extend([ .extend([
file.statistics.bounds.southWest.lon, get(file).statistics.bounds.southWest.lon,
file.statistics.bounds.southWest.lat, get(file).statistics.bounds.southWest.lat,
file.statistics.bounds.northEast.lon, get(file).statistics.bounds.northEast.lon,
file.statistics.bounds.northEast.lat get(file).statistics.bounds.northEast.lat
]), ]),
{ {
padding: 60 padding: 60
@@ -172,6 +181,13 @@
} }
}); });
$: if ($map) {
let source = $map.getSource(layerId);
if (source) {
source.setData(extendGeoJSON($file.toGeoJSON()));
}
}
onDestroy(() => { onDestroy(() => {
if ($map) { if ($map) {
$map.off('click', layerId, selectOnClick); $map.off('click', layerId, selectOnClick);

View File

@@ -1,9 +1,9 @@
<script lang="ts"> <script lang="ts">
import GPXMapLayer from './GPXMapLayer.svelte'; import GPXMapLayer from './GPXMapLayer.svelte';
import { fileCollection } from '$lib/stores'; import { files } from '$lib/stores';
</script> </script>
{#each $fileCollection.files as file} {#each $files as file}
<GPXMapLayer {file} /> <GPXMapLayer {file} />
{/each} {/each}

View File

@@ -15,7 +15,7 @@
} from 'lucide-svelte'; } from 'lucide-svelte';
import { import {
fileCollection, files,
selectedFiles, selectedFiles,
duplicateSelectedFiles, duplicateSelectedFiles,
exportAllFiles, exportAllFiles,
@@ -69,7 +69,7 @@
{$_('menu.export')} {$_('menu.export')}
<Menubar.Shortcut>⌘S</Menubar.Shortcut> <Menubar.Shortcut>⌘S</Menubar.Shortcut>
</Menubar.Item> </Menubar.Item>
<Menubar.Item on:click={exportAllFiles} disabled={$fileCollection.files.length == 0}> <Menubar.Item on:click={exportAllFiles} disabled={$files.length == 0}>
<Download size="16" class="mr-1" /> <Download size="16" class="mr-1" />
{$_('menu.export_all')} {$_('menu.export_all')}
<Menubar.Shortcut>⇧⌘S</Menubar.Shortcut> <Menubar.Shortcut>⇧⌘S</Menubar.Shortcut>
@@ -98,7 +98,7 @@
<Menubar.Item <Menubar.Item
class="text-destructive data-[highlighted]:text-destructive" class="text-destructive data-[highlighted]:text-destructive"
on:click={removeAllFiles} on:click={removeAllFiles}
disabled={$fileCollection.files.length == 0} disabled={$files.length == 0}
> >
<Trash2 size="16" class="mr-1" /> <Trash2 size="16" class="mr-1" />
{$_('menu.delete_all')}<Menubar.Shortcut>⇧⌘⌫</Menubar.Shortcut></Menubar.Item {$_('menu.delete_all')}<Menubar.Shortcut>⇧⌘⌫</Menubar.Shortcut></Menubar.Item

View File

@@ -7,7 +7,8 @@
import * as Alert from '$lib/components/ui/alert'; import * as Alert from '$lib/components/ui/alert';
import { CircleHelp } from 'lucide-svelte'; import { CircleHelp } from 'lucide-svelte';
import { map, selectedFiles, fileCollection } from '$lib/stores'; import { map, selectedFiles } from '$lib/stores';
import { get, type Writable } from 'svelte/store';
import { AnchorPointHierarchy, getMarker, route } from './routing'; import { AnchorPointHierarchy, getMarker, route } from './routing';
import { onDestroy } from 'svelte'; import { onDestroy } from 'svelte';
import mapboxgl from 'mapbox-gl'; import mapboxgl from 'mapbox-gl';
@@ -35,7 +36,7 @@
let anchorPointHierarchy: AnchorPointHierarchy | null = null; let anchorPointHierarchy: AnchorPointHierarchy | null = null;
let markers: mapboxgl.Marker[] = []; let markers: mapboxgl.Marker[] = [];
let file: GPXFile | null = null; let file: Writable<GPXFile> | null = null;
let kdbush: KDBush | null = null; let kdbush: KDBush | null = null;
function toggleMarkersForZoomLevelAndBounds() { function toggleMarkersForZoomLevelAndBounds() {
@@ -65,6 +66,10 @@
routing routing
); );
console.log(response); console.log(response);
file.update((file) => {
file.append(response);
return file;
});
} }
} }
@@ -106,7 +111,7 @@
$map.off('move', toggleMarkersForZoomLevelAndBounds); $map.off('move', toggleMarkersForZoomLevelAndBounds);
$map.off('click', extendFile); $map.off('click', extendFile);
if (file) { if (file) {
$map.off('mouseover', file.layerId, showInsertableMarker); $map.off('mouseover', get(file).layerId, showInsertableMarker);
} }
if (insertableMarker) { if (insertableMarker) {
insertableMarker.remove(); insertableMarker.remove();
@@ -119,9 +124,10 @@
clean(); clean();
file = $selectedFiles.values().next().value; file = $selectedFiles.values().next().value;
// record time // record time
let start = performance.now(); let start = performance.now();
anchorPointHierarchy = AnchorPointHierarchy.create(file); anchorPointHierarchy = AnchorPointHierarchy.create(get(file));
// record time // record time
let end = performance.now(); let end = performance.now();
console.log('Time to create anchor points: ' + (end - start) + 'ms'); console.log('Time to create anchor points: ' + (end - start) + 'ms');
@@ -132,9 +138,9 @@
$map.on('zoom', toggleMarkersForZoomLevelAndBounds); $map.on('zoom', toggleMarkersForZoomLevelAndBounds);
$map.on('move', toggleMarkersForZoomLevelAndBounds); $map.on('move', toggleMarkersForZoomLevelAndBounds);
$map.on('click', extendFile); $map.on('click', extendFile);
$map.on('mouseover', file.layerId, showInsertableMarker); $map.on('mouseover', get(file).layerId, showInsertableMarker);
let points = file.getTrackPoints(); let points = get(file).getTrackPoints();
start = performance.now(); start = performance.now();
kdbush = new KDBush(points.length); kdbush = new KDBush(points.length);

View File

@@ -1,24 +1,26 @@
import { writable, get } from 'svelte/store'; import { writable, get, type Writable } from 'svelte/store';
import mapboxgl from 'mapbox-gl'; import mapboxgl from 'mapbox-gl';
import { GPXFile, GPXFiles, buildGPX, parseGPX } from 'gpx'; import { GPXFile, buildGPX, parseGPX } from 'gpx';
export const map = writable<mapboxgl.Map | null>(null); export const map = writable<mapboxgl.Map | null>(null);
export const fileCollection = writable<GPXFiles>(new GPXFiles([])); export const files = writable<Writable<GPXFile>[]>([]);
export const fileOrder = writable<GPXFile[]>([]); export const fileOrder = writable<Writable<GPXFile>[]>([]);
export const selectedFiles = writable<Set<GPXFile>>(new Set()); export const selectedFiles = writable<Set<Writable<GPXFile>>>(new Set());
export const selectFiles = writable<{ [key: string]: (file?: GPXFile) => void }>({}); export const selectFiles = writable<{ [key: string]: (file?: Writable<GPXFile>) => void }>({});
export const settings = writable<{ [key: string]: any }>({ export const settings = writable<{ [key: string]: any }>({
distanceUnits: 'metric', distanceUnits: 'metric',
velocityUnits: 'speed', velocityUnits: 'speed',
temperatureUnits: 'celsius', temperatureUnits: 'celsius',
}); });
export function addFile(file: GPXFile) { export function addFile(file: GPXFile): Writable<GPXFile> {
fileCollection.update($files => { let fileStore = writable(file);
$files.files.push(file); files.update($files => {
$files.push(fileStore);
return $files; return $files;
}); });
return fileStore;
} }
export function triggerFileInput() { export function triggerFileInput() {
@@ -45,7 +47,7 @@ export async function loadFiles(list: FileList) {
} }
export async function loadFile(file: File) { export async function loadFile(file: File) {
let result = await new Promise<GPXFile | null>((resolve) => { let result = await new Promise<Writable<GPXFile> | null>((resolve) => {
const reader = new FileReader(); const reader = new FileReader();
reader.onload = () => { reader.onload = () => {
let data = reader.result?.toString() ?? null; let data = reader.result?.toString() ?? null;
@@ -54,8 +56,7 @@ export async function loadFile(file: File) {
if (gpx.metadata.name === undefined) { if (gpx.metadata.name === undefined) {
gpx.metadata['name'] = file.name.split('.').slice(0, -1).join('.'); gpx.metadata['name'] = file.name.split('.').slice(0, -1).join('.');
} }
addFile(gpx); resolve(addFile(gpx));
resolve(gpx);
} else { } else {
resolve(null); resolve(null);
} }
@@ -67,7 +68,7 @@ export async function loadFile(file: File) {
export function duplicateSelectedFiles() { export function duplicateSelectedFiles() {
let selected: GPXFile[] = []; let selected: GPXFile[] = [];
get(selectedFiles).forEach(file => selected.push(file)); get(selectedFiles).forEach(file => selected.push(get(file)));
selected.forEach(file => duplicateFile(file)); selected.forEach(file => duplicateFile(file));
} }
@@ -77,16 +78,16 @@ export function duplicateFile(file: GPXFile) {
} }
export function removeSelectedFiles() { export function removeSelectedFiles() {
fileCollection.update($collection => { files.update($files => {
let index = 0; let index = 0;
while (index < $collection.files.length) { while (index < $files.length) {
if (get(selectedFiles).has($collection.files[index])) { if (get(selectedFiles).has($files[index])) {
$collection.files.splice(index, 1); $files.splice(index, 1);
} else { } else {
index++; index++;
} }
} }
return $collection; return $files;
}); });
selectedFiles.update($selected => { selectedFiles.update($selected => {
$selected.clear(); $selected.clear();
@@ -95,9 +96,9 @@ export function removeSelectedFiles() {
} }
export function removeAllFiles() { export function removeAllFiles() {
fileCollection.update($collection => { files.update($files => {
$collection.files.splice(0, $collection.files.length); $files.splice(0, $files.length);
return $collection; return $files;
}); });
selectedFiles.update($selected => { selectedFiles.update($selected => {
$selected.clear(); $selected.clear();
@@ -106,12 +107,12 @@ export function removeAllFiles() {
} }
export function exportSelectedFiles() { export function exportSelectedFiles() {
get(selectedFiles).forEach(file => exportFile(file)); get(selectedFiles).forEach(file => exportFile(get(file)));
} }
export async function exportAllFiles() { export async function exportAllFiles() {
for (let file of get(fileCollection).files) { for (let file of get(files)) {
exportFile(file); exportFile(get(file));
await new Promise(resolve => setTimeout(resolve, 200)); await new Promise(resolve => setTimeout(resolve, 200));
} }
} }
@@ -127,10 +128,13 @@ export function exportFile(file: GPXFile) {
} }
export function reverseSelectedFiles() { export function reverseSelectedFiles() {
fileCollection.update($files => { files.update($files => {
$files.files.forEach(file => { $files.forEach(file => {
if (get(selectedFiles).has(file)) { if (get(selectedFiles).has(file)) {
file.reverse(); file.update($file => {
$file.reverse();
return $file;
});
} }
}); });
return $files; return $files;