prettier config + format all, closes #175

This commit is contained in:
vcoppe
2025-02-02 11:17:22 +01:00
parent 01cfd448f0
commit 0b457f9a1e
157 changed files with 17194 additions and 29365 deletions

View File

@@ -1,188 +1,188 @@
<script lang="ts" context="module">
enum CleanType {
INSIDE = 'inside',
OUTSIDE = 'outside'
}
enum CleanType {
INSIDE = 'inside',
OUTSIDE = 'outside',
}
</script>
<script lang="ts">
import { Label } from '$lib/components/ui/label/index.js';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as RadioGroup from '$lib/components/ui/radio-group';
import { Button } from '$lib/components/ui/button';
import Help from '$lib/components/Help.svelte';
import { _, locale } from 'svelte-i18n';
import { onDestroy, onMount } from 'svelte';
import { getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { Trash2 } from 'lucide-svelte';
import { map } from '$lib/stores';
import { selection } from '$lib/components/file-list/Selection';
import { dbUtils } from '$lib/db';
import { Label } from '$lib/components/ui/label/index.js';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as RadioGroup from '$lib/components/ui/radio-group';
import { Button } from '$lib/components/ui/button';
import Help from '$lib/components/Help.svelte';
import { _, locale } from 'svelte-i18n';
import { onDestroy, onMount } from 'svelte';
import { getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { Trash2 } from 'lucide-svelte';
import { map } from '$lib/stores';
import { selection } from '$lib/components/file-list/Selection';
import { dbUtils } from '$lib/db';
let cleanType = CleanType.INSIDE;
let deleteTrackpoints = true;
let deleteWaypoints = true;
let rectangleCoordinates: mapboxgl.LngLat[] = [];
let cleanType = CleanType.INSIDE;
let deleteTrackpoints = true;
let deleteWaypoints = true;
let rectangleCoordinates: mapboxgl.LngLat[] = [];
function updateRectangle() {
if ($map) {
if (rectangleCoordinates.length != 2) {
if ($map.getLayer('rectangle')) {
$map.removeLayer('rectangle');
}
} else {
let data = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [
[
[rectangleCoordinates[0].lng, rectangleCoordinates[0].lat],
[rectangleCoordinates[1].lng, rectangleCoordinates[0].lat],
[rectangleCoordinates[1].lng, rectangleCoordinates[1].lat],
[rectangleCoordinates[0].lng, rectangleCoordinates[1].lat],
[rectangleCoordinates[0].lng, rectangleCoordinates[0].lat]
]
]
}
};
let source = $map.getSource('rectangle');
if (source) {
source.setData(data);
} else {
$map.addSource('rectangle', {
type: 'geojson',
data: data
});
}
if (!$map.getLayer('rectangle')) {
$map.addLayer({
id: 'rectangle',
type: 'fill',
source: 'rectangle',
paint: {
'fill-color': 'SteelBlue',
'fill-opacity': 0.5
}
});
}
}
}
}
function updateRectangle() {
if ($map) {
if (rectangleCoordinates.length != 2) {
if ($map.getLayer('rectangle')) {
$map.removeLayer('rectangle');
}
} else {
let data = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [
[
[rectangleCoordinates[0].lng, rectangleCoordinates[0].lat],
[rectangleCoordinates[1].lng, rectangleCoordinates[0].lat],
[rectangleCoordinates[1].lng, rectangleCoordinates[1].lat],
[rectangleCoordinates[0].lng, rectangleCoordinates[1].lat],
[rectangleCoordinates[0].lng, rectangleCoordinates[0].lat],
],
],
},
};
let source = $map.getSource('rectangle');
if (source) {
source.setData(data);
} else {
$map.addSource('rectangle', {
type: 'geojson',
data: data,
});
}
if (!$map.getLayer('rectangle')) {
$map.addLayer({
id: 'rectangle',
type: 'fill',
source: 'rectangle',
paint: {
'fill-color': 'SteelBlue',
'fill-opacity': 0.5,
},
});
}
}
}
}
$: if (rectangleCoordinates) {
updateRectangle();
}
$: if (rectangleCoordinates) {
updateRectangle();
}
let mousedown = false;
function onMouseDown(e: any) {
mousedown = true;
rectangleCoordinates = [e.lngLat, e.lngLat];
}
let mousedown = false;
function onMouseDown(e: any) {
mousedown = true;
rectangleCoordinates = [e.lngLat, e.lngLat];
}
function onMouseMove(e: any) {
if (mousedown) {
rectangleCoordinates[1] = e.lngLat;
}
}
function onMouseMove(e: any) {
if (mousedown) {
rectangleCoordinates[1] = e.lngLat;
}
}
function onMouseUp(e: any) {
mousedown = false;
}
function onMouseUp(e: any) {
mousedown = false;
}
onMount(() => {
setCrosshairCursor();
});
onMount(() => {
setCrosshairCursor();
});
$: if ($map) {
$map.on('mousedown', onMouseDown);
$map.on('mousemove', onMouseMove);
$map.on('mouseup', onMouseUp);
$map.on('touchstart', onMouseDown);
$map.on('touchmove', onMouseMove);
$map.on('touchend', onMouseUp);
$map.dragPan.disable();
}
$: if ($map) {
$map.on('mousedown', onMouseDown);
$map.on('mousemove', onMouseMove);
$map.on('mouseup', onMouseUp);
$map.on('touchstart', onMouseDown);
$map.on('touchmove', onMouseMove);
$map.on('touchend', onMouseUp);
$map.dragPan.disable();
}
onDestroy(() => {
resetCursor();
if ($map) {
$map.off('mousedown', onMouseDown);
$map.off('mousemove', onMouseMove);
$map.off('mouseup', onMouseUp);
$map.off('touchstart', onMouseDown);
$map.off('touchmove', onMouseMove);
$map.off('touchend', onMouseUp);
$map.dragPan.enable();
onDestroy(() => {
resetCursor();
if ($map) {
$map.off('mousedown', onMouseDown);
$map.off('mousemove', onMouseMove);
$map.off('mouseup', onMouseUp);
$map.off('touchstart', onMouseDown);
$map.off('touchmove', onMouseMove);
$map.off('touchend', onMouseUp);
$map.dragPan.enable();
if ($map.getLayer('rectangle')) {
$map.removeLayer('rectangle');
}
if ($map.getSource('rectangle')) {
$map.removeSource('rectangle');
}
}
});
if ($map.getLayer('rectangle')) {
$map.removeLayer('rectangle');
}
if ($map.getSource('rectangle')) {
$map.removeSource('rectangle');
}
}
});
$: validSelection = $selection.size > 0;
$: validSelection = $selection.size > 0;
</script>
<div class="flex flex-col gap-3 w-full max-w-80 items-center {$$props.class ?? ''}">
<fieldset class="flex flex-col gap-3">
<div class="flex flex-row items-center gap-[6.4px] h-3">
<Checkbox id="delete-trkpt" bind:checked={deleteTrackpoints} class="scale-90" />
<Label for="delete-trkpt">
{$_('toolbar.clean.delete_trackpoints')}
</Label>
</div>
<div class="flex flex-row items-center gap-[6.4px] h-3">
<Checkbox id="delete-wpt" bind:checked={deleteWaypoints} class="scale-90" />
<Label for="delete-wpt">
{$_('toolbar.clean.delete_waypoints')}
</Label>
</div>
<RadioGroup.Root bind:value={cleanType}>
<Label class="flex flex-row items-center gap-2">
<RadioGroup.Item value={CleanType.INSIDE} />
{$_('toolbar.clean.delete_inside')}
</Label>
<Label class="flex flex-row items-center gap-2">
<RadioGroup.Item value={CleanType.OUTSIDE} />
{$_('toolbar.clean.delete_outside')}
</Label>
</RadioGroup.Root>
</fieldset>
<Button
variant="outline"
class="w-full"
disabled={!validSelection || rectangleCoordinates.length != 2}
on:click={() => {
dbUtils.cleanSelection(
[
{
lat: Math.min(rectangleCoordinates[0].lat, rectangleCoordinates[1].lat),
lon: Math.min(rectangleCoordinates[0].lng, rectangleCoordinates[1].lng)
},
{
lat: Math.max(rectangleCoordinates[0].lat, rectangleCoordinates[1].lat),
lon: Math.max(rectangleCoordinates[0].lng, rectangleCoordinates[1].lng)
}
],
cleanType === CleanType.INSIDE,
deleteTrackpoints,
deleteWaypoints
);
rectangleCoordinates = [];
}}
>
<Trash2 size="16" class="mr-1" />
{$_('toolbar.clean.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/clean')}>
{#if validSelection}
{$_('toolbar.clean.help')}
{:else}
{$_('toolbar.clean.help_no_selection')}
{/if}
</Help>
<fieldset class="flex flex-col gap-3">
<div class="flex flex-row items-center gap-[6.4px] h-3">
<Checkbox id="delete-trkpt" bind:checked={deleteTrackpoints} class="scale-90" />
<Label for="delete-trkpt">
{$_('toolbar.clean.delete_trackpoints')}
</Label>
</div>
<div class="flex flex-row items-center gap-[6.4px] h-3">
<Checkbox id="delete-wpt" bind:checked={deleteWaypoints} class="scale-90" />
<Label for="delete-wpt">
{$_('toolbar.clean.delete_waypoints')}
</Label>
</div>
<RadioGroup.Root bind:value={cleanType}>
<Label class="flex flex-row items-center gap-2">
<RadioGroup.Item value={CleanType.INSIDE} />
{$_('toolbar.clean.delete_inside')}
</Label>
<Label class="flex flex-row items-center gap-2">
<RadioGroup.Item value={CleanType.OUTSIDE} />
{$_('toolbar.clean.delete_outside')}
</Label>
</RadioGroup.Root>
</fieldset>
<Button
variant="outline"
class="w-full"
disabled={!validSelection || rectangleCoordinates.length != 2}
on:click={() => {
dbUtils.cleanSelection(
[
{
lat: Math.min(rectangleCoordinates[0].lat, rectangleCoordinates[1].lat),
lon: Math.min(rectangleCoordinates[0].lng, rectangleCoordinates[1].lng),
},
{
lat: Math.max(rectangleCoordinates[0].lat, rectangleCoordinates[1].lat),
lon: Math.max(rectangleCoordinates[0].lng, rectangleCoordinates[1].lng),
},
],
cleanType === CleanType.INSIDE,
deleteTrackpoints,
deleteWaypoints
);
rectangleCoordinates = [];
}}
>
<Trash2 size="16" class="mr-1" />
{$_('toolbar.clean.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/clean')}>
{#if validSelection}
{$_('toolbar.clean.help')}
{:else}
{$_('toolbar.clean.help_no_selection')}
{/if}
</Help>
</div>

View File

@@ -1,35 +1,35 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { selection } from '$lib/components/file-list/Selection';
import Help from '$lib/components/Help.svelte';
import { MountainSnow } from 'lucide-svelte';
import { dbUtils } from '$lib/db';
import { map } from '$lib/stores';
import { _, locale } from 'svelte-i18n';
import { getURLForLanguage } from '$lib/utils';
import { Button } from '$lib/components/ui/button';
import { selection } from '$lib/components/file-list/Selection';
import Help from '$lib/components/Help.svelte';
import { MountainSnow } from 'lucide-svelte';
import { dbUtils } from '$lib/db';
import { map } from '$lib/stores';
import { _, locale } from 'svelte-i18n';
import { getURLForLanguage } from '$lib/utils';
$: validSelection = $selection.size > 0;
$: validSelection = $selection.size > 0;
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<Button
variant="outline"
class="whitespace-normal h-fit"
disabled={!validSelection}
on:click={async () => {
if ($map) {
dbUtils.addElevationToSelection($map);
}
}}
>
<MountainSnow size="16" class="mr-1 shrink-0" />
{$_('toolbar.elevation.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/elevation')}>
{#if validSelection}
{$_('toolbar.elevation.help')}
{:else}
{$_('toolbar.elevation.help_no_selection')}
{/if}
</Help>
<Button
variant="outline"
class="whitespace-normal h-fit"
disabled={!validSelection}
on:click={async () => {
if ($map) {
dbUtils.addElevationToSelection($map);
}
}}
>
<MountainSnow size="16" class="mr-1 shrink-0" />
{$_('toolbar.elevation.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/elevation')}>
{#if validSelection}
{$_('toolbar.elevation.help')}
{:else}
{$_('toolbar.elevation.help_no_selection')}
{/if}
</Help>
</div>

View File

@@ -1,53 +1,53 @@
<script lang="ts">
import { Button } from '$lib/components/ui/button';
import { Ungroup } from 'lucide-svelte';
import { selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
ListTrackItem,
ListTrackSegmentItem,
ListWaypointItem,
ListWaypointsItem
} from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { dbUtils, getFile } from '$lib/db';
import { _, locale } from 'svelte-i18n';
import { getURLForLanguage } from '$lib/utils';
import { Button } from '$lib/components/ui/button';
import { Ungroup } from 'lucide-svelte';
import { selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
ListTrackItem,
ListTrackSegmentItem,
ListWaypointItem,
ListWaypointsItem,
} from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { dbUtils, getFile } from '$lib/db';
import { _, locale } from 'svelte-i18n';
import { getURLForLanguage } from '$lib/utils';
$: validSelection =
$selection.size > 0 &&
$selection.getSelected().every((item) => {
if (
item instanceof ListWaypointsItem ||
item instanceof ListWaypointItem ||
item instanceof ListTrackSegmentItem
) {
return false;
}
let file = getFile(item.getFileId());
if (file) {
if (item instanceof ListFileItem) {
return file.getSegments().length > 1;
} else if (item instanceof ListTrackItem) {
if (item.getTrackIndex() < file.trk.length) {
return file.trk[item.getTrackIndex()].getSegments().length > 1;
}
}
}
return false;
});
$: validSelection =
$selection.size > 0 &&
$selection.getSelected().every((item) => {
if (
item instanceof ListWaypointsItem ||
item instanceof ListWaypointItem ||
item instanceof ListTrackSegmentItem
) {
return false;
}
let file = getFile(item.getFileId());
if (file) {
if (item instanceof ListFileItem) {
return file.getSegments().length > 1;
} else if (item instanceof ListTrackItem) {
if (item.getTrackIndex() < file.trk.length) {
return file.trk[item.getTrackIndex()].getSegments().length > 1;
}
}
}
return false;
});
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<Button variant="outline" disabled={!validSelection} on:click={dbUtils.extractSelection}>
<Ungroup size="16" class="mr-1" />
{$_('toolbar.extract.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/extract')}>
{#if validSelection}
{$_('toolbar.extract.help')}
{:else}
{$_('toolbar.extract.help_invalid_selection')}
{/if}
</Help>
<Button variant="outline" disabled={!validSelection} on:click={dbUtils.extractSelection}>
<Ungroup size="16" class="mr-1" />
{$_('toolbar.extract.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/extract')}>
{#if validSelection}
{$_('toolbar.extract.help')}
{:else}
{$_('toolbar.extract.help_invalid_selection')}
{/if}
</Help>
</div>

View File

@@ -1,117 +1,117 @@
<script lang="ts" context="module">
enum MergeType {
TRACES = 'traces',
CONTENTS = 'contents'
}
enum MergeType {
TRACES = 'traces',
CONTENTS = 'contents',
}
</script>
<script lang="ts">
import { ListFileItem, ListTrackItem } from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { selection } from '$lib/components/file-list/Selection';
import { Button } from '$lib/components/ui/button';
import { Label } from '$lib/components/ui/label/index.js';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as RadioGroup from '$lib/components/ui/radio-group';
import { _, locale } from 'svelte-i18n';
import { dbUtils, getFile } from '$lib/db';
import { Group } from 'lucide-svelte';
import { getURLForLanguage } from '$lib/utils';
import Shortcut from '$lib/components/Shortcut.svelte';
import { gpxStatistics } from '$lib/stores';
import { ListFileItem, ListTrackItem } from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { selection } from '$lib/components/file-list/Selection';
import { Button } from '$lib/components/ui/button';
import { Label } from '$lib/components/ui/label/index.js';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as RadioGroup from '$lib/components/ui/radio-group';
import { _, locale } from 'svelte-i18n';
import { dbUtils, getFile } from '$lib/db';
import { Group } from 'lucide-svelte';
import { getURLForLanguage } from '$lib/utils';
import Shortcut from '$lib/components/Shortcut.svelte';
import { gpxStatistics } from '$lib/stores';
let canMergeTraces = false;
let canMergeContents = false;
let removeGaps = false;
let canMergeTraces = false;
let canMergeContents = false;
let removeGaps = false;
$: if ($selection.size > 1) {
canMergeTraces = true;
} else if ($selection.size === 1) {
let selected = $selection.getSelected()[0];
if (selected instanceof ListFileItem) {
let file = getFile(selected.getFileId());
if (file) {
canMergeTraces = file.getSegments().length > 1;
} else {
canMergeTraces = false;
}
} else if (selected instanceof ListTrackItem) {
let trackIndex = selected.getTrackIndex();
let file = getFile(selected.getFileId());
if (file && trackIndex < file.trk.length) {
canMergeTraces = file.trk[trackIndex].getSegments().length > 1;
} else {
canMergeTraces = false;
}
} else {
canMergeContents = false;
}
}
$: if ($selection.size > 1) {
canMergeTraces = true;
} else if ($selection.size === 1) {
let selected = $selection.getSelected()[0];
if (selected instanceof ListFileItem) {
let file = getFile(selected.getFileId());
if (file) {
canMergeTraces = file.getSegments().length > 1;
} else {
canMergeTraces = false;
}
} else if (selected instanceof ListTrackItem) {
let trackIndex = selected.getTrackIndex();
let file = getFile(selected.getFileId());
if (file && trackIndex < file.trk.length) {
canMergeTraces = file.trk[trackIndex].getSegments().length > 1;
} else {
canMergeTraces = false;
}
} else {
canMergeContents = false;
}
}
$: canMergeContents =
$selection.size > 1 &&
$selection
.getSelected()
.some((item) => item instanceof ListFileItem || item instanceof ListTrackItem);
$: canMergeContents =
$selection.size > 1 &&
$selection
.getSelected()
.some((item) => item instanceof ListFileItem || item instanceof ListTrackItem);
let mergeType = MergeType.TRACES;
let mergeType = MergeType.TRACES;
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<RadioGroup.Root bind:value={mergeType}>
<Label class="flex flex-row items-center gap-1.5 leading-5">
<RadioGroup.Item value={MergeType.TRACES} />
{$_('toolbar.merge.merge_traces')}
</Label>
<Label class="flex flex-row items-center gap-1.5 leading-5">
<RadioGroup.Item value={MergeType.CONTENTS} />
{$_('toolbar.merge.merge_contents')}
</Label>
</RadioGroup.Root>
{#if mergeType === MergeType.TRACES && $gpxStatistics.global.time.total > 0}
<div class="flex flex-row items-center gap-1.5">
<Checkbox id="remove-gaps" bind:checked={removeGaps} />
<Label for="remove-gaps">{$_('toolbar.merge.remove_gaps')}</Label>
</div>
{/if}
<Button
variant="outline"
class="whitespace-normal h-fit"
disabled={(mergeType === MergeType.TRACES && !canMergeTraces) ||
(mergeType === MergeType.CONTENTS && !canMergeContents)}
on:click={() => {
dbUtils.mergeSelection(
mergeType === MergeType.TRACES,
mergeType === MergeType.TRACES && $gpxStatistics.global.time.total > 0 && removeGaps
);
}}
>
<Group size="16" class="mr-1 shrink-0" />
{$_('toolbar.merge.merge_selection')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/merge')}>
{#if mergeType === MergeType.TRACES && canMergeTraces}
{$_('toolbar.merge.help_merge_traces')}
{:else if mergeType === MergeType.TRACES && !canMergeTraces}
{$_('toolbar.merge.help_cannot_merge_traces')}
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[0]}
<Shortcut
ctrl={true}
click={true}
class="inline-flex text-muted-foreground text-xs border rounded p-0.5 gap-0"
/>
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[1]}
{:else if mergeType === MergeType.CONTENTS && canMergeContents}
{$_('toolbar.merge.help_merge_contents')}
{:else if mergeType === MergeType.CONTENTS && !canMergeContents}
{$_('toolbar.merge.help_cannot_merge_contents')}
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[0]}
<Shortcut
ctrl={true}
click={true}
class="inline-flex text-muted-foreground text-xs border rounded p-0.5 gap-0"
/>
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[1]}
{/if}
</Help>
<RadioGroup.Root bind:value={mergeType}>
<Label class="flex flex-row items-center gap-1.5 leading-5">
<RadioGroup.Item value={MergeType.TRACES} />
{$_('toolbar.merge.merge_traces')}
</Label>
<Label class="flex flex-row items-center gap-1.5 leading-5">
<RadioGroup.Item value={MergeType.CONTENTS} />
{$_('toolbar.merge.merge_contents')}
</Label>
</RadioGroup.Root>
{#if mergeType === MergeType.TRACES && $gpxStatistics.global.time.total > 0}
<div class="flex flex-row items-center gap-1.5">
<Checkbox id="remove-gaps" bind:checked={removeGaps} />
<Label for="remove-gaps">{$_('toolbar.merge.remove_gaps')}</Label>
</div>
{/if}
<Button
variant="outline"
class="whitespace-normal h-fit"
disabled={(mergeType === MergeType.TRACES && !canMergeTraces) ||
(mergeType === MergeType.CONTENTS && !canMergeContents)}
on:click={() => {
dbUtils.mergeSelection(
mergeType === MergeType.TRACES,
mergeType === MergeType.TRACES && $gpxStatistics.global.time.total > 0 && removeGaps
);
}}
>
<Group size="16" class="mr-1 shrink-0" />
{$_('toolbar.merge.merge_selection')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/merge')}>
{#if mergeType === MergeType.TRACES && canMergeTraces}
{$_('toolbar.merge.help_merge_traces')}
{:else if mergeType === MergeType.TRACES && !canMergeTraces}
{$_('toolbar.merge.help_cannot_merge_traces')}
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[0]}
<Shortcut
ctrl={true}
click={true}
class="inline-flex text-muted-foreground text-xs border rounded p-0.5 gap-0"
/>
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[1]}
{:else if mergeType === MergeType.CONTENTS && canMergeContents}
{$_('toolbar.merge.help_merge_contents')}
{:else if mergeType === MergeType.CONTENTS && !canMergeContents}
{$_('toolbar.merge.help_cannot_merge_contents')}
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[0]}
<Shortcut
ctrl={true}
click={true}
class="inline-flex text-muted-foreground text-xs border rounded p-0.5 gap-0"
/>
{$_('toolbar.merge.selection_tip').split('{KEYBOARD_SHORTCUT}')[1]}
{/if}
</Help>
</div>

View File

@@ -1,178 +1,187 @@
<script lang="ts">
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import { Slider } from '$lib/components/ui/slider';
import { selection } from '$lib/components/file-list/Selection';
import { ListItem, ListRootItem, ListTrackSegmentItem } from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { Filter } from 'lucide-svelte';
import { _, locale } from 'svelte-i18n';
import WithUnits from '$lib/components/WithUnits.svelte';
import { dbUtils, fileObservers } from '$lib/db';
import { map } from '$lib/stores';
import { onDestroy } from 'svelte';
import { ramerDouglasPeucker, TrackPoint, type SimplifiedTrackPoint } from 'gpx';
import { derived } from 'svelte/store';
import { getURLForLanguage } from '$lib/utils';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import { Slider } from '$lib/components/ui/slider';
import { selection } from '$lib/components/file-list/Selection';
import {
ListItem,
ListRootItem,
ListTrackSegmentItem,
} from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { Filter } from 'lucide-svelte';
import { _, locale } from 'svelte-i18n';
import WithUnits from '$lib/components/WithUnits.svelte';
import { dbUtils, fileObservers } from '$lib/db';
import { map } from '$lib/stores';
import { onDestroy } from 'svelte';
import { ramerDouglasPeucker, TrackPoint, type SimplifiedTrackPoint } from 'gpx';
import { derived } from 'svelte/store';
import { getURLForLanguage } from '$lib/utils';
let sliderValue = [50];
let maxPoints = 0;
let currentPoints = 0;
const minTolerance = 0.1;
const maxTolerance = 10000;
let sliderValue = [50];
let maxPoints = 0;
let currentPoints = 0;
const minTolerance = 0.1;
const maxTolerance = 10000;
$: validSelection = $selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']);
$: validSelection = $selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']);
$: tolerance =
minTolerance * 2 ** (sliderValue[0] / (100 / Math.log2(maxTolerance / minTolerance)));
$: tolerance =
minTolerance * 2 ** (sliderValue[0] / (100 / Math.log2(maxTolerance / minTolerance)));
let simplified = new Map<string, [ListItem, number, SimplifiedTrackPoint[]]>();
let unsubscribes = new Map<string, () => void>();
let simplified = new Map<string, [ListItem, number, SimplifiedTrackPoint[]]>();
let unsubscribes = new Map<string, () => void>();
function update() {
maxPoints = 0;
currentPoints = 0;
function update() {
maxPoints = 0;
currentPoints = 0;
let data: GeoJSON.FeatureCollection = {
type: 'FeatureCollection',
features: []
};
let data: GeoJSON.FeatureCollection = {
type: 'FeatureCollection',
features: [],
};
simplified.forEach(([item, maxPts, points], itemFullId) => {
maxPoints += maxPts;
simplified.forEach(([item, maxPts, points], itemFullId) => {
maxPoints += maxPts;
let current = points.filter(
(point) => point.distance === undefined || point.distance >= tolerance
);
currentPoints += current.length;
let current = points.filter(
(point) => point.distance === undefined || point.distance >= tolerance
);
currentPoints += current.length;
data.features.push({
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: current.map((point) => [
point.point.getLongitude(),
point.point.getLatitude()
])
},
properties: {}
});
});
data.features.push({
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: current.map((point) => [
point.point.getLongitude(),
point.point.getLatitude(),
]),
},
properties: {},
});
});
if ($map) {
let source = $map.getSource('simplified');
if (source) {
source.setData(data);
} else {
$map.addSource('simplified', {
type: 'geojson',
data: data
});
}
if (!$map.getLayer('simplified')) {
$map.addLayer({
id: 'simplified',
type: 'line',
source: 'simplified',
paint: {
'line-color': 'white',
'line-width': 3
}
});
} else {
$map.moveLayer('simplified');
}
}
}
if ($map) {
let source = $map.getSource('simplified');
if (source) {
source.setData(data);
} else {
$map.addSource('simplified', {
type: 'geojson',
data: data,
});
}
if (!$map.getLayer('simplified')) {
$map.addLayer({
id: 'simplified',
type: 'line',
source: 'simplified',
paint: {
'line-color': 'white',
'line-width': 3,
},
});
} else {
$map.moveLayer('simplified');
}
}
}
$: if ($fileObservers) {
unsubscribes.forEach((unsubscribe, fileId) => {
if (!$fileObservers.has(fileId)) {
unsubscribe();
unsubscribes.delete(fileId);
}
});
$fileObservers.forEach((fileStore, fileId) => {
if (!unsubscribes.has(fileId)) {
let unsubscribe = derived([fileStore, selection], ([fs, sel]) => [fs, sel]).subscribe(
([fs, sel]) => {
if (fs) {
fs.file.forEachSegment((segment, trackIndex, segmentIndex) => {
let segmentItem = new ListTrackSegmentItem(fileId, trackIndex, segmentIndex);
if (sel.hasAnyParent(segmentItem)) {
let statistics = fs.statistics.getStatisticsFor(segmentItem);
simplified.set(segmentItem.getFullId(), [
segmentItem,
statistics.local.points.length,
ramerDouglasPeucker(statistics.local.points, minTolerance)
]);
update();
} else if (simplified.has(segmentItem.getFullId())) {
simplified.delete(segmentItem.getFullId());
update();
}
});
}
}
);
unsubscribes.set(fileId, unsubscribe);
}
});
}
$: if ($fileObservers) {
unsubscribes.forEach((unsubscribe, fileId) => {
if (!$fileObservers.has(fileId)) {
unsubscribe();
unsubscribes.delete(fileId);
}
});
$fileObservers.forEach((fileStore, fileId) => {
if (!unsubscribes.has(fileId)) {
let unsubscribe = derived([fileStore, selection], ([fs, sel]) => [
fs,
sel,
]).subscribe(([fs, sel]) => {
if (fs) {
fs.file.forEachSegment((segment, trackIndex, segmentIndex) => {
let segmentItem = new ListTrackSegmentItem(
fileId,
trackIndex,
segmentIndex
);
if (sel.hasAnyParent(segmentItem)) {
let statistics = fs.statistics.getStatisticsFor(segmentItem);
simplified.set(segmentItem.getFullId(), [
segmentItem,
statistics.local.points.length,
ramerDouglasPeucker(statistics.local.points, minTolerance),
]);
update();
} else if (simplified.has(segmentItem.getFullId())) {
simplified.delete(segmentItem.getFullId());
update();
}
});
}
});
unsubscribes.set(fileId, unsubscribe);
}
});
}
$: if (tolerance) {
update();
}
$: if (tolerance) {
update();
}
onDestroy(() => {
if ($map) {
if ($map.getLayer('simplified')) {
$map.removeLayer('simplified');
}
if ($map.getSource('simplified')) {
$map.removeSource('simplified');
}
}
unsubscribes.forEach((unsubscribe) => unsubscribe());
simplified.clear();
});
onDestroy(() => {
if ($map) {
if ($map.getLayer('simplified')) {
$map.removeLayer('simplified');
}
if ($map.getSource('simplified')) {
$map.removeSource('simplified');
}
}
unsubscribes.forEach((unsubscribe) => unsubscribe());
simplified.clear();
});
function reduce() {
let itemsAndPoints = new Map<ListItem, TrackPoint[]>();
simplified.forEach(([item, maxPts, points], itemFullId) => {
itemsAndPoints.set(
item,
points
.filter((point) => point.distance === undefined || point.distance >= tolerance)
.map((point) => point.point)
);
});
dbUtils.reduce(itemsAndPoints);
}
function reduce() {
let itemsAndPoints = new Map<ListItem, TrackPoint[]>();
simplified.forEach(([item, maxPts, points], itemFullId) => {
itemsAndPoints.set(
item,
points
.filter((point) => point.distance === undefined || point.distance >= tolerance)
.map((point) => point.point)
);
});
dbUtils.reduce(itemsAndPoints);
}
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<div class="p-2">
<Slider bind:value={sliderValue} min={0} max={100} step={1} />
</div>
<Label class="flex flex-row justify-between">
<span>{$_('toolbar.reduce.tolerance')}</span>
<WithUnits value={tolerance / 1000} type="distance" decimals={4} class="font-normal" />
</Label>
<Label class="flex flex-row justify-between">
<span>{$_('toolbar.reduce.number_of_points')}</span>
<span class="font-normal">{currentPoints}/{maxPoints}</span>
</Label>
<Button variant="outline" disabled={!validSelection} on:click={reduce}>
<Filter size="16" class="mr-1" />
{$_('toolbar.reduce.button')}
</Button>
<div class="p-2">
<Slider bind:value={sliderValue} min={0} max={100} step={1} />
</div>
<Label class="flex flex-row justify-between">
<span>{$_('toolbar.reduce.tolerance')}</span>
<WithUnits value={tolerance / 1000} type="distance" decimals={4} class="font-normal" />
</Label>
<Label class="flex flex-row justify-between">
<span>{$_('toolbar.reduce.number_of_points')}</span>
<span class="font-normal">{currentPoints}/{maxPoints}</span>
</Label>
<Button variant="outline" disabled={!validSelection} on:click={reduce}>
<Filter size="16" class="mr-1" />
{$_('toolbar.reduce.button')}
</Button>
<Help link={getURLForLanguage($locale, '/help/toolbar/minify')}>
{#if validSelection}
{$_('toolbar.reduce.help')}
{:else}
{$_('toolbar.reduce.help_no_selection')}
{/if}
</Help>
<Help link={getURLForLanguage($locale, '/help/toolbar/minify')}>
{#if validSelection}
{$_('toolbar.reduce.help')}
{:else}
{$_('toolbar.reduce.help_no_selection')}
{/if}
</Help>
</div>

View File

@@ -1,393 +1,404 @@
<script lang="ts">
import DatePicker from '$lib/components/ui/date-picker/DatePicker.svelte';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import { Checkbox } from '$lib/components/ui/checkbox';
import TimePicker from '$lib/components/ui/time-picker/TimePicker.svelte';
import { dbUtils, settings } from '$lib/db';
import { gpxStatistics } from '$lib/stores';
import {
distancePerHourToSecondsPerDistance,
getConvertedVelocity,
milesToKilometers,
nauticalMilesToKilometers
} from '$lib/units';
import { CalendarDate, type DateValue } from '@internationalized/date';
import { CalendarClock, CirclePlay, CircleStop, CircleX, Timer, Zap } from 'lucide-svelte';
import { tick } from 'svelte';
import { _, locale } from 'svelte-i18n';
import { get } from 'svelte/store';
import { selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
ListRootItem,
ListTrackItem,
ListTrackSegmentItem
} from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { getURLForLanguage } from '$lib/utils';
import DatePicker from '$lib/components/ui/date-picker/DatePicker.svelte';
import { Input } from '$lib/components/ui/input';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import { Checkbox } from '$lib/components/ui/checkbox';
import TimePicker from '$lib/components/ui/time-picker/TimePicker.svelte';
import { dbUtils, settings } from '$lib/db';
import { gpxStatistics } from '$lib/stores';
import {
distancePerHourToSecondsPerDistance,
getConvertedVelocity,
milesToKilometers,
nauticalMilesToKilometers,
} from '$lib/units';
import { CalendarDate, type DateValue } from '@internationalized/date';
import { CalendarClock, CirclePlay, CircleStop, CircleX, Timer, Zap } from 'lucide-svelte';
import { tick } from 'svelte';
import { _, locale } from 'svelte-i18n';
import { get } from 'svelte/store';
import { selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
ListRootItem,
ListTrackItem,
ListTrackSegmentItem,
} from '$lib/components/file-list/FileList';
import Help from '$lib/components/Help.svelte';
import { getURLForLanguage } from '$lib/utils';
let startDate: DateValue | undefined = undefined;
let startTime: string | undefined = undefined;
let endDate: DateValue | undefined = undefined;
let endTime: string | undefined = undefined;
let movingTime: number | undefined = undefined;
let speed: number | undefined = undefined;
let artificial = false;
let startDate: DateValue | undefined = undefined;
let startTime: string | undefined = undefined;
let endDate: DateValue | undefined = undefined;
let endTime: string | undefined = undefined;
let movingTime: number | undefined = undefined;
let speed: number | undefined = undefined;
let artificial = false;
function toCalendarDate(date: Date): CalendarDate {
return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate());
}
function toCalendarDate(date: Date): CalendarDate {
return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate());
}
function toTimeString(date: Date): string {
return date.toTimeString().split(' ')[0];
}
function toTimeString(date: Date): string {
return date.toTimeString().split(' ')[0];
}
const { velocityUnits, distanceUnits } = settings;
const { velocityUnits, distanceUnits } = settings;
function setSpeed(value: number) {
let speedValue = getConvertedVelocity(value);
if ($velocityUnits === 'speed') {
speedValue = parseFloat(speedValue.toFixed(2));
}
speed = speedValue;
}
function setSpeed(value: number) {
let speedValue = getConvertedVelocity(value);
if ($velocityUnits === 'speed') {
speedValue = parseFloat(speedValue.toFixed(2));
}
speed = speedValue;
}
function setGPXData() {
if ($gpxStatistics.global.time.start) {
startDate = toCalendarDate($gpxStatistics.global.time.start);
startTime = toTimeString($gpxStatistics.global.time.start);
} else {
startDate = undefined;
startTime = undefined;
}
if ($gpxStatistics.global.time.end) {
endDate = toCalendarDate($gpxStatistics.global.time.end);
endTime = toTimeString($gpxStatistics.global.time.end);
} else {
endDate = undefined;
endTime = undefined;
}
if ($gpxStatistics.global.time.moving) {
movingTime = $gpxStatistics.global.time.moving;
} else {
movingTime = undefined;
}
if ($gpxStatistics.global.speed.moving) {
setSpeed($gpxStatistics.global.speed.moving);
} else {
speed = undefined;
}
}
function setGPXData() {
if ($gpxStatistics.global.time.start) {
startDate = toCalendarDate($gpxStatistics.global.time.start);
startTime = toTimeString($gpxStatistics.global.time.start);
} else {
startDate = undefined;
startTime = undefined;
}
if ($gpxStatistics.global.time.end) {
endDate = toCalendarDate($gpxStatistics.global.time.end);
endTime = toTimeString($gpxStatistics.global.time.end);
} else {
endDate = undefined;
endTime = undefined;
}
if ($gpxStatistics.global.time.moving) {
movingTime = $gpxStatistics.global.time.moving;
} else {
movingTime = undefined;
}
if ($gpxStatistics.global.speed.moving) {
setSpeed($gpxStatistics.global.speed.moving);
} else {
speed = undefined;
}
}
$: if ($gpxStatistics && $velocityUnits && $distanceUnits) {
setGPXData();
}
$: if ($gpxStatistics && $velocityUnits && $distanceUnits) {
setGPXData();
}
function getDate(date: DateValue, time: string): Date {
if (date === undefined) {
return new Date();
}
let [hours, minutes, seconds] = time.split(':').map((x) => parseInt(x));
if (seconds === undefined) {
seconds = 0;
}
return new Date(date.year, date.month - 1, date.day, hours, minutes, seconds);
}
function getDate(date: DateValue, time: string): Date {
if (date === undefined) {
return new Date();
}
let [hours, minutes, seconds] = time.split(':').map((x) => parseInt(x));
if (seconds === undefined) {
seconds = 0;
}
return new Date(date.year, date.month - 1, date.day, hours, minutes, seconds);
}
function updateEnd() {
if (startDate && movingTime !== undefined) {
if (startTime === undefined) {
startTime = '00:00:00';
}
let start = getDate(startDate, startTime);
let ratio =
$gpxStatistics.global.time.moving > 0
? $gpxStatistics.global.time.total / $gpxStatistics.global.time.moving
: 1;
let end = new Date(start.getTime() + ratio * movingTime * 1000);
endDate = toCalendarDate(end);
endTime = toTimeString(end);
}
}
function updateEnd() {
if (startDate && movingTime !== undefined) {
if (startTime === undefined) {
startTime = '00:00:00';
}
let start = getDate(startDate, startTime);
let ratio =
$gpxStatistics.global.time.moving > 0
? $gpxStatistics.global.time.total / $gpxStatistics.global.time.moving
: 1;
let end = new Date(start.getTime() + ratio * movingTime * 1000);
endDate = toCalendarDate(end);
endTime = toTimeString(end);
}
}
function updateStart() {
if (endDate && movingTime !== undefined) {
if (endTime === undefined) {
endTime = '00:00:00';
}
let end = getDate(endDate, endTime);
let ratio =
$gpxStatistics.global.time.moving > 0
? $gpxStatistics.global.time.total / $gpxStatistics.global.time.moving
: 1;
let start = new Date(end.getTime() - ratio * movingTime * 1000);
startDate = toCalendarDate(start);
startTime = toTimeString(start);
}
}
function updateStart() {
if (endDate && movingTime !== undefined) {
if (endTime === undefined) {
endTime = '00:00:00';
}
let end = getDate(endDate, endTime);
let ratio =
$gpxStatistics.global.time.moving > 0
? $gpxStatistics.global.time.total / $gpxStatistics.global.time.moving
: 1;
let start = new Date(end.getTime() - ratio * movingTime * 1000);
startDate = toCalendarDate(start);
startTime = toTimeString(start);
}
}
function getSpeed() {
if (speed === undefined) {
return undefined;
}
function getSpeed() {
if (speed === undefined) {
return undefined;
}
let speedValue = speed;
if ($velocityUnits === 'pace') {
speedValue = distancePerHourToSecondsPerDistance(speed);
}
if ($distanceUnits === 'imperial') {
speedValue = milesToKilometers(speedValue);
} else if ($distanceUnits === 'nautical') {
speedValue = nauticalMilesToKilometers(speedValue);
}
return speedValue;
}
let speedValue = speed;
if ($velocityUnits === 'pace') {
speedValue = distancePerHourToSecondsPerDistance(speed);
}
if ($distanceUnits === 'imperial') {
speedValue = milesToKilometers(speedValue);
} else if ($distanceUnits === 'nautical') {
speedValue = nauticalMilesToKilometers(speedValue);
}
return speedValue;
}
function updateDataFromSpeed() {
let speedValue = getSpeed();
if (speedValue === undefined) {
return;
}
function updateDataFromSpeed() {
let speedValue = getSpeed();
if (speedValue === undefined) {
return;
}
let distance =
$gpxStatistics.global.distance.moving > 0
? $gpxStatistics.global.distance.moving
: $gpxStatistics.global.distance.total;
movingTime = (distance / speedValue) * 3600;
let distance =
$gpxStatistics.global.distance.moving > 0
? $gpxStatistics.global.distance.moving
: $gpxStatistics.global.distance.total;
movingTime = (distance / speedValue) * 3600;
updateEnd();
}
updateEnd();
}
function updateDataFromTotalTime() {
if (movingTime === undefined) {
return;
}
let distance =
$gpxStatistics.global.distance.moving > 0
? $gpxStatistics.global.distance.moving
: $gpxStatistics.global.distance.total;
setSpeed(distance / (movingTime / 3600));
updateEnd();
}
function updateDataFromTotalTime() {
if (movingTime === undefined) {
return;
}
let distance =
$gpxStatistics.global.distance.moving > 0
? $gpxStatistics.global.distance.moving
: $gpxStatistics.global.distance.total;
setSpeed(distance / (movingTime / 3600));
updateEnd();
}
$: canUpdate =
$selection.size === 1 && $selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']);
$: canUpdate =
$selection.size === 1 && $selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']);
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<fieldset class="flex flex-col gap-2">
<div class="flex flex-row gap-2 justify-center">
<div class="flex flex-col gap-2 grow">
<Label for="speed" class="flex flex-row">
<Zap size="16" class="mr-1" />
{#if $velocityUnits === 'speed'}
{$_('quantities.speed')}
{:else}
{$_('quantities.pace')}
{/if}
</Label>
<div class="flex flex-row gap-1 items-center">
{#if $velocityUnits === 'speed'}
<Input
id="speed"
type="number"
step={0.01}
min={0.01}
disabled={!canUpdate}
bind:value={speed}
on:change={updateDataFromSpeed}
/>
<span class="text-sm shrink-0">
{#if $distanceUnits === 'imperial'}
{$_('units.miles_per_hour')}
{:else if $distanceUnits === 'metric'}
{$_('units.kilometers_per_hour')}
{:else if $distanceUnits === 'nautical'}
{$_('units.knots')}
{/if}
</span>
{:else}
<TimePicker
bind:value={speed}
showHours={false}
disabled={!canUpdate}
onChange={updateDataFromSpeed}
/>
<span class="text-sm shrink-0">
{#if $distanceUnits === 'imperial'}
{$_('units.minutes_per_mile')}
{:else if $distanceUnits === 'metric'}
{$_('units.minutes_per_kilometer')}
{:else if $distanceUnits === 'nautical'}
{$_('units.minutes_per_nautical_mile')}
{/if}
</span>
{/if}
</div>
</div>
<div class="flex flex-col gap-2 grow">
<Label for="duration" class="flex flex-row">
<Timer size="16" class="mr-1" />
{$_('toolbar.time.total_time')}
</Label>
<TimePicker
bind:value={movingTime}
disabled={!canUpdate}
onChange={updateDataFromTotalTime}
/>
</div>
</div>
<Label class="flex flex-row">
<CirclePlay size="16" class="mr-1" />
{$_('toolbar.time.start')}
</Label>
<div class="flex flex-row gap-2">
<DatePicker
bind:value={startDate}
disabled={!canUpdate}
locale={get(locale) ?? 'en'}
placeholder={$_('toolbar.time.pick_date')}
class="w-fit grow"
onValueChange={async () => {
await tick();
updateEnd();
}}
/>
<input
type="time"
step={1}
disabled={!canUpdate}
bind:value={startTime}
class="w-fit"
on:change={updateEnd}
/>
</div>
<Label class="flex flex-row">
<CircleStop size="16" class="mr-1" />
{$_('toolbar.time.end')}
</Label>
<div class="flex flex-row gap-2">
<DatePicker
bind:value={endDate}
disabled={!canUpdate}
locale={get(locale) ?? 'en'}
placeholder={$_('toolbar.time.pick_date')}
class="w-fit grow"
onValueChange={async () => {
await tick();
updateStart();
}}
/>
<input
type="time"
step={1}
disabled={!canUpdate}
bind:value={endTime}
class="w-fit"
on:change={updateStart}
/>
</div>
{#if $gpxStatistics.global.time.moving === 0 || $gpxStatistics.global.time.moving === undefined}
<div class="mt-0.5 flex flex-row gap-1 items-center">
<Checkbox id="artificial-time" bind:checked={artificial} disabled={!canUpdate} />
<Label for="artificial-time">
{$_('toolbar.time.artificial')}
</Label>
</div>
{/if}
</fieldset>
<div class="flex flex-row gap-2 items-center">
<Button
variant="outline"
disabled={!canUpdate}
class="grow whitespace-normal h-fit"
on:click={() => {
let effectiveSpeed = getSpeed();
if (startDate === undefined || startTime === undefined || effectiveSpeed === undefined) {
return;
}
<fieldset class="flex flex-col gap-2">
<div class="flex flex-row gap-2 justify-center">
<div class="flex flex-col gap-2 grow">
<Label for="speed" class="flex flex-row">
<Zap size="16" class="mr-1" />
{#if $velocityUnits === 'speed'}
{$_('quantities.speed')}
{:else}
{$_('quantities.pace')}
{/if}
</Label>
<div class="flex flex-row gap-1 items-center">
{#if $velocityUnits === 'speed'}
<Input
id="speed"
type="number"
step={0.01}
min={0.01}
disabled={!canUpdate}
bind:value={speed}
on:change={updateDataFromSpeed}
/>
<span class="text-sm shrink-0">
{#if $distanceUnits === 'imperial'}
{$_('units.miles_per_hour')}
{:else if $distanceUnits === 'metric'}
{$_('units.kilometers_per_hour')}
{:else if $distanceUnits === 'nautical'}
{$_('units.knots')}
{/if}
</span>
{:else}
<TimePicker
bind:value={speed}
showHours={false}
disabled={!canUpdate}
onChange={updateDataFromSpeed}
/>
<span class="text-sm shrink-0">
{#if $distanceUnits === 'imperial'}
{$_('units.minutes_per_mile')}
{:else if $distanceUnits === 'metric'}
{$_('units.minutes_per_kilometer')}
{:else if $distanceUnits === 'nautical'}
{$_('units.minutes_per_nautical_mile')}
{/if}
</span>
{/if}
</div>
</div>
<div class="flex flex-col gap-2 grow">
<Label for="duration" class="flex flex-row">
<Timer size="16" class="mr-1" />
{$_('toolbar.time.total_time')}
</Label>
<TimePicker
bind:value={movingTime}
disabled={!canUpdate}
onChange={updateDataFromTotalTime}
/>
</div>
</div>
<Label class="flex flex-row">
<CirclePlay size="16" class="mr-1" />
{$_('toolbar.time.start')}
</Label>
<div class="flex flex-row gap-2">
<DatePicker
bind:value={startDate}
disabled={!canUpdate}
locale={get(locale) ?? 'en'}
placeholder={$_('toolbar.time.pick_date')}
class="w-fit grow"
onValueChange={async () => {
await tick();
updateEnd();
}}
/>
<input
type="time"
step={1}
disabled={!canUpdate}
bind:value={startTime}
class="w-fit"
on:change={updateEnd}
/>
</div>
<Label class="flex flex-row">
<CircleStop size="16" class="mr-1" />
{$_('toolbar.time.end')}
</Label>
<div class="flex flex-row gap-2">
<DatePicker
bind:value={endDate}
disabled={!canUpdate}
locale={get(locale) ?? 'en'}
placeholder={$_('toolbar.time.pick_date')}
class="w-fit grow"
onValueChange={async () => {
await tick();
updateStart();
}}
/>
<input
type="time"
step={1}
disabled={!canUpdate}
bind:value={endTime}
class="w-fit"
on:change={updateStart}
/>
</div>
{#if $gpxStatistics.global.time.moving === 0 || $gpxStatistics.global.time.moving === undefined}
<div class="mt-0.5 flex flex-row gap-1 items-center">
<Checkbox id="artificial-time" bind:checked={artificial} disabled={!canUpdate} />
<Label for="artificial-time">
{$_('toolbar.time.artificial')}
</Label>
</div>
{/if}
</fieldset>
<div class="flex flex-row gap-2 items-center">
<Button
variant="outline"
disabled={!canUpdate}
class="grow whitespace-normal h-fit"
on:click={() => {
let effectiveSpeed = getSpeed();
if (
startDate === undefined ||
startTime === undefined ||
effectiveSpeed === undefined
) {
return;
}
if (Math.abs(effectiveSpeed - $gpxStatistics.global.speed.moving) < 0.01) {
effectiveSpeed = $gpxStatistics.global.speed.moving;
}
if (Math.abs(effectiveSpeed - $gpxStatistics.global.speed.moving) < 0.01) {
effectiveSpeed = $gpxStatistics.global.speed.moving;
}
let ratio = 1;
if (
$gpxStatistics.global.speed.moving > 0 &&
$gpxStatistics.global.speed.moving !== effectiveSpeed
) {
ratio = $gpxStatistics.global.speed.moving / effectiveSpeed;
}
let ratio = 1;
if (
$gpxStatistics.global.speed.moving > 0 &&
$gpxStatistics.global.speed.moving !== effectiveSpeed
) {
ratio = $gpxStatistics.global.speed.moving / effectiveSpeed;
}
let item = $selection.getSelected()[0];
let fileId = item.getFileId();
dbUtils.applyToFile(fileId, (file) => {
if (item instanceof ListFileItem) {
if (artificial) {
file.createArtificialTimestamps(getDate(startDate, startTime), movingTime);
} else {
file.changeTimestamps(getDate(startDate, startTime), effectiveSpeed, ratio);
}
} else if (item instanceof ListTrackItem) {
if (artificial) {
file.createArtificialTimestamps(
getDate(startDate, startTime),
movingTime,
item.getTrackIndex()
);
} else {
file.changeTimestamps(
getDate(startDate, startTime),
effectiveSpeed,
ratio,
item.getTrackIndex()
);
}
} else if (item instanceof ListTrackSegmentItem) {
if (artificial) {
file.createArtificialTimestamps(
getDate(startDate, startTime),
movingTime,
item.getTrackIndex(),
item.getSegmentIndex()
);
} else {
file.changeTimestamps(
getDate(startDate, startTime),
effectiveSpeed,
ratio,
item.getTrackIndex(),
item.getSegmentIndex()
);
}
}
});
}}
>
<CalendarClock size="16" class="mr-1 shrink-0" />
{$_('toolbar.time.update')}
</Button>
<Button variant="outline" on:click={setGPXData}>
<CircleX size="16" />
</Button>
</div>
<Help link={getURLForLanguage($locale, '/help/toolbar/time')}>
{#if canUpdate}
{$_('toolbar.time.help')}
{:else}
{$_('toolbar.time.help_invalid_selection')}
{/if}
</Help>
let item = $selection.getSelected()[0];
let fileId = item.getFileId();
dbUtils.applyToFile(fileId, (file) => {
if (item instanceof ListFileItem) {
if (artificial) {
file.createArtificialTimestamps(
getDate(startDate, startTime),
movingTime
);
} else {
file.changeTimestamps(
getDate(startDate, startTime),
effectiveSpeed,
ratio
);
}
} else if (item instanceof ListTrackItem) {
if (artificial) {
file.createArtificialTimestamps(
getDate(startDate, startTime),
movingTime,
item.getTrackIndex()
);
} else {
file.changeTimestamps(
getDate(startDate, startTime),
effectiveSpeed,
ratio,
item.getTrackIndex()
);
}
} else if (item instanceof ListTrackSegmentItem) {
if (artificial) {
file.createArtificialTimestamps(
getDate(startDate, startTime),
movingTime,
item.getTrackIndex(),
item.getSegmentIndex()
);
} else {
file.changeTimestamps(
getDate(startDate, startTime),
effectiveSpeed,
ratio,
item.getTrackIndex(),
item.getSegmentIndex()
);
}
}
});
}}
>
<CalendarClock size="16" class="mr-1 shrink-0" />
{$_('toolbar.time.update')}
</Button>
<Button variant="outline" on:click={setGPXData}>
<CircleX size="16" />
</Button>
</div>
<Help link={getURLForLanguage($locale, '/help/toolbar/time')}>
{#if canUpdate}
{$_('toolbar.time.help')}
{:else}
{$_('toolbar.time.help_invalid_selection')}
{/if}
</Help>
</div>
<style lang="postcss">
div :global(input[type='time']) {
/*
div :global(input[type='time']) {
/*
Style copy-pasted from shadcn-svelte Input.
Needed to use native time input to avoid a bug with 2-level bind:value.
*/
@apply flex h-10 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50;
}
@apply flex h-10 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50;
}
</style>

View File

@@ -1,283 +1,292 @@
<script lang="ts" context="module">
import { writable } from 'svelte/store';
import { writable } from 'svelte/store';
export const selectedWaypoint = writable<[Waypoint, string] | undefined>(undefined);
export const selectedWaypoint = writable<[Waypoint, string] | undefined>(undefined);
</script>
<script lang="ts">
import { Input } from '$lib/components/ui/input';
import { Textarea } from '$lib/components/ui/textarea';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import * as Select from '$lib/components/ui/select';
import { selection } from '$lib/components/file-list/Selection';
import { Waypoint } from 'gpx';
import { _, locale } from 'svelte-i18n';
import { ListWaypointItem } from '$lib/components/file-list/FileList';
import { dbUtils, fileObservers, getFile, settings, type GPXFileWithStatistics } from '$lib/db';
import { get } from 'svelte/store';
import Help from '$lib/components/Help.svelte';
import { onDestroy, onMount } from 'svelte';
import { map } from '$lib/stores';
import { getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { MapPin, CircleX, Save } from 'lucide-svelte';
import { getSymbolKey, symbols } from '$lib/assets/symbols';
import { Input } from '$lib/components/ui/input';
import { Textarea } from '$lib/components/ui/textarea';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import * as Select from '$lib/components/ui/select';
import { selection } from '$lib/components/file-list/Selection';
import { Waypoint } from 'gpx';
import { _, locale } from 'svelte-i18n';
import { ListWaypointItem } from '$lib/components/file-list/FileList';
import { dbUtils, fileObservers, getFile, settings, type GPXFileWithStatistics } from '$lib/db';
import { get } from 'svelte/store';
import Help from '$lib/components/Help.svelte';
import { onDestroy, onMount } from 'svelte';
import { map } from '$lib/stores';
import { getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { MapPin, CircleX, Save } from 'lucide-svelte';
import { getSymbolKey, symbols } from '$lib/assets/symbols';
let name: string;
let description: string;
let link: string;
let longitude: number;
let latitude: number;
let name: string;
let description: string;
let link: string;
let longitude: number;
let latitude: number;
let selectedSymbol = {
value: '',
label: ''
};
let selectedSymbol = {
value: '',
label: '',
};
const { treeFileView } = settings;
const { treeFileView } = settings;
$: canCreate = $selection.size > 0;
$: canCreate = $selection.size > 0;
$: if ($treeFileView && $selection) {
selectedWaypoint.update(() => {
if ($selection.size === 1) {
let item = $selection.getSelected()[0];
if (item instanceof ListWaypointItem) {
let file = getFile(item.getFileId());
let waypoint = file?.wpt[item.getWaypointIndex()];
if (waypoint) {
return [waypoint, item.getFileId()];
}
}
}
return undefined;
});
}
$: if ($treeFileView && $selection) {
selectedWaypoint.update(() => {
if ($selection.size === 1) {
let item = $selection.getSelected()[0];
if (item instanceof ListWaypointItem) {
let file = getFile(item.getFileId());
let waypoint = file?.wpt[item.getWaypointIndex()];
if (waypoint) {
return [waypoint, item.getFileId()];
}
}
}
return undefined;
});
}
let unsubscribe: (() => void) | undefined = undefined;
function updateWaypointData(fileStore: GPXFileWithStatistics | undefined) {
if ($selectedWaypoint) {
if (fileStore) {
if ($selectedWaypoint[0]._data.index < fileStore.file.wpt.length) {
$selectedWaypoint[0] = fileStore.file.wpt[$selectedWaypoint[0]._data.index];
name = $selectedWaypoint[0].name ?? '';
description = $selectedWaypoint[0].desc ?? '';
if (
$selectedWaypoint[0].cmt !== undefined &&
$selectedWaypoint[0].cmt !== $selectedWaypoint[0].desc
) {
description += '\n\n' + $selectedWaypoint[0].cmt;
}
link = $selectedWaypoint[0].link?.attributes?.href ?? '';
let symbol = $selectedWaypoint[0].sym ?? '';
let symbolKey = getSymbolKey(symbol);
if (symbolKey) {
selectedSymbol = {
value: symbol,
label: $_(`gpx.symbol.${symbolKey}`)
};
} else {
selectedSymbol = {
value: symbol,
label: ''
};
}
longitude = parseFloat($selectedWaypoint[0].getLongitude().toFixed(6));
latitude = parseFloat($selectedWaypoint[0].getLatitude().toFixed(6));
} else {
selectedWaypoint.set(undefined);
}
} else {
selectedWaypoint.set(undefined);
}
}
}
let unsubscribe: (() => void) | undefined = undefined;
function updateWaypointData(fileStore: GPXFileWithStatistics | undefined) {
if ($selectedWaypoint) {
if (fileStore) {
if ($selectedWaypoint[0]._data.index < fileStore.file.wpt.length) {
$selectedWaypoint[0] = fileStore.file.wpt[$selectedWaypoint[0]._data.index];
name = $selectedWaypoint[0].name ?? '';
description = $selectedWaypoint[0].desc ?? '';
if (
$selectedWaypoint[0].cmt !== undefined &&
$selectedWaypoint[0].cmt !== $selectedWaypoint[0].desc
) {
description += '\n\n' + $selectedWaypoint[0].cmt;
}
link = $selectedWaypoint[0].link?.attributes?.href ?? '';
let symbol = $selectedWaypoint[0].sym ?? '';
let symbolKey = getSymbolKey(symbol);
if (symbolKey) {
selectedSymbol = {
value: symbol,
label: $_(`gpx.symbol.${symbolKey}`),
};
} else {
selectedSymbol = {
value: symbol,
label: '',
};
}
longitude = parseFloat($selectedWaypoint[0].getLongitude().toFixed(6));
latitude = parseFloat($selectedWaypoint[0].getLatitude().toFixed(6));
} else {
selectedWaypoint.set(undefined);
}
} else {
selectedWaypoint.set(undefined);
}
}
}
function resetWaypointData() {
name = '';
description = '';
link = '';
selectedSymbol = {
value: '',
label: ''
};
longitude = 0;
latitude = 0;
}
function resetWaypointData() {
name = '';
description = '';
link = '';
selectedSymbol = {
value: '',
label: '',
};
longitude = 0;
latitude = 0;
}
$: {
if (unsubscribe) {
unsubscribe();
unsubscribe = undefined;
}
if ($selectedWaypoint) {
let fileStore = get(fileObservers).get($selectedWaypoint[1]);
if (fileStore) {
unsubscribe = fileStore.subscribe(updateWaypointData);
}
} else {
resetWaypointData();
}
}
$: {
if (unsubscribe) {
unsubscribe();
unsubscribe = undefined;
}
if ($selectedWaypoint) {
let fileStore = get(fileObservers).get($selectedWaypoint[1]);
if (fileStore) {
unsubscribe = fileStore.subscribe(updateWaypointData);
}
} else {
resetWaypointData();
}
}
function createOrUpdateWaypoint() {
if (typeof latitude === 'string') {
latitude = parseFloat(latitude);
}
if (typeof longitude === 'string') {
longitude = parseFloat(longitude);
}
latitude = parseFloat(latitude.toFixed(6));
longitude = parseFloat(longitude.toFixed(6));
function createOrUpdateWaypoint() {
if (typeof latitude === 'string') {
latitude = parseFloat(latitude);
}
if (typeof longitude === 'string') {
longitude = parseFloat(longitude);
}
latitude = parseFloat(latitude.toFixed(6));
longitude = parseFloat(longitude.toFixed(6));
dbUtils.addOrUpdateWaypoint(
{
attributes: {
lat: latitude,
lon: longitude
},
name: name.length > 0 ? name : undefined,
desc: description.length > 0 ? description : undefined,
cmt: description.length > 0 ? description : undefined,
link: link.length > 0 ? { attributes: { href: link } } : undefined,
sym: selectedSymbol.value.length > 0 ? selectedSymbol.value : undefined
},
$selectedWaypoint
? new ListWaypointItem($selectedWaypoint[1], $selectedWaypoint[0]._data.index)
: undefined
);
dbUtils.addOrUpdateWaypoint(
{
attributes: {
lat: latitude,
lon: longitude,
},
name: name.length > 0 ? name : undefined,
desc: description.length > 0 ? description : undefined,
cmt: description.length > 0 ? description : undefined,
link: link.length > 0 ? { attributes: { href: link } } : undefined,
sym: selectedSymbol.value.length > 0 ? selectedSymbol.value : undefined,
},
$selectedWaypoint
? new ListWaypointItem($selectedWaypoint[1], $selectedWaypoint[0]._data.index)
: undefined
);
selectedWaypoint.set(undefined);
resetWaypointData();
}
selectedWaypoint.set(undefined);
resetWaypointData();
}
function setCoordinates(e: any) {
latitude = e.lngLat.lat.toFixed(6);
longitude = e.lngLat.lng.toFixed(6);
}
function setCoordinates(e: any) {
latitude = e.lngLat.lat.toFixed(6);
longitude = e.lngLat.lng.toFixed(6);
}
$: sortedSymbols = Object.entries(symbols).sort((a, b) => {
return $_(`gpx.symbol.${a[0]}`).localeCompare($_(`gpx.symbol.${b[0]}`), $locale ?? 'en');
});
$: sortedSymbols = Object.entries(symbols).sort((a, b) => {
return $_(`gpx.symbol.${a[0]}`).localeCompare($_(`gpx.symbol.${b[0]}`), $locale ?? 'en');
});
onMount(() => {
let m = get(map);
m?.on('click', setCoordinates);
setCrosshairCursor();
});
onMount(() => {
let m = get(map);
m?.on('click', setCoordinates);
setCrosshairCursor();
});
onDestroy(() => {
let m = get(map);
m?.off('click', setCoordinates);
resetCursor();
onDestroy(() => {
let m = get(map);
m?.off('click', setCoordinates);
resetCursor();
if (unsubscribe) {
unsubscribe();
unsubscribe = undefined;
}
});
if (unsubscribe) {
unsubscribe();
unsubscribe = undefined;
}
});
</script>
<div class="flex flex-col gap-3 w-full max-w-96 {$$props.class ?? ''}">
<fieldset class="flex flex-col gap-2">
<Label for="name">{$_('menu.metadata.name')}</Label>
<Input
bind:value={name}
id="name"
class="font-semibold h-8"
disabled={!canCreate && !$selectedWaypoint}
/>
<Label for="description">{$_('menu.metadata.description')}</Label>
<Textarea
bind:value={description}
id="description"
disabled={!canCreate && !$selectedWaypoint}
/>
<Label for="symbol">{$_('toolbar.waypoint.icon')}</Label>
<Select.Root bind:selected={selectedSymbol}>
<Select.Trigger id="symbol" class="w-full h-8" disabled={!canCreate && !$selectedWaypoint}>
<Select.Value />
</Select.Trigger>
<Select.Content class="max-h-60 overflow-y-scroll">
{#each sortedSymbols as [key, symbol]}
<Select.Item value={symbol.value}>
<span>
{#if symbol.icon}
<svelte:component
this={symbol.icon}
size="14"
class="inline-block align-sub mr-0.5"
/>
{:else}
<span class="w-4 inline-block" />
{/if}
{$_(`gpx.symbol.${key}`)}
</span>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
<Label for="link">{$_('toolbar.waypoint.link')}</Label>
<Input bind:value={link} id="link" class="h-8" disabled={!canCreate && !$selectedWaypoint} />
<div class="flex flex-row gap-2">
<div class="grow">
<Label for="latitude">{$_('toolbar.waypoint.latitude')}</Label>
<Input
bind:value={latitude}
type="number"
id="latitude"
step={1e-6}
min={-90}
max={90}
class="text-xs h-8"
disabled={!canCreate && !$selectedWaypoint}
/>
</div>
<div class="grow">
<Label for="longitude">{$_('toolbar.waypoint.longitude')}</Label>
<Input
bind:value={longitude}
type="number"
id="longitude"
step={1e-6}
min={-180}
max={180}
class="text-xs h-8"
disabled={!canCreate && !$selectedWaypoint}
/>
</div>
</div>
</fieldset>
<div class="flex flex-row gap-2 items-center">
<Button
variant="outline"
disabled={!canCreate && !$selectedWaypoint}
class="grow whitespace-normal h-fit"
on:click={createOrUpdateWaypoint}
>
{#if $selectedWaypoint}
<Save size="16" class="mr-1 shrink-0" />
{$_('menu.metadata.save')}
{:else}
<MapPin size="16" class="mr-1 shrink-0" />
{$_('toolbar.waypoint.create')}
{/if}
</Button>
<Button
variant="outline"
on:click={() => {
selectedWaypoint.set(undefined);
resetWaypointData();
}}
>
<CircleX size="16" />
</Button>
</div>
<Help link={getURLForLanguage($locale, '/help/toolbar/poi')}>
{#if $selectedWaypoint || canCreate}
{$_('toolbar.waypoint.help')}
{:else}
{$_('toolbar.waypoint.help_no_selection')}
{/if}
</Help>
<fieldset class="flex flex-col gap-2">
<Label for="name">{$_('menu.metadata.name')}</Label>
<Input
bind:value={name}
id="name"
class="font-semibold h-8"
disabled={!canCreate && !$selectedWaypoint}
/>
<Label for="description">{$_('menu.metadata.description')}</Label>
<Textarea
bind:value={description}
id="description"
disabled={!canCreate && !$selectedWaypoint}
/>
<Label for="symbol">{$_('toolbar.waypoint.icon')}</Label>
<Select.Root bind:selected={selectedSymbol}>
<Select.Trigger
id="symbol"
class="w-full h-8"
disabled={!canCreate && !$selectedWaypoint}
>
<Select.Value />
</Select.Trigger>
<Select.Content class="max-h-60 overflow-y-scroll">
{#each sortedSymbols as [key, symbol]}
<Select.Item value={symbol.value}>
<span>
{#if symbol.icon}
<svelte:component
this={symbol.icon}
size="14"
class="inline-block align-sub mr-0.5"
/>
{:else}
<span class="w-4 inline-block" />
{/if}
{$_(`gpx.symbol.${key}`)}
</span>
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
<Label for="link">{$_('toolbar.waypoint.link')}</Label>
<Input
bind:value={link}
id="link"
class="h-8"
disabled={!canCreate && !$selectedWaypoint}
/>
<div class="flex flex-row gap-2">
<div class="grow">
<Label for="latitude">{$_('toolbar.waypoint.latitude')}</Label>
<Input
bind:value={latitude}
type="number"
id="latitude"
step={1e-6}
min={-90}
max={90}
class="text-xs h-8"
disabled={!canCreate && !$selectedWaypoint}
/>
</div>
<div class="grow">
<Label for="longitude">{$_('toolbar.waypoint.longitude')}</Label>
<Input
bind:value={longitude}
type="number"
id="longitude"
step={1e-6}
min={-180}
max={180}
class="text-xs h-8"
disabled={!canCreate && !$selectedWaypoint}
/>
</div>
</div>
</fieldset>
<div class="flex flex-row gap-2 items-center">
<Button
variant="outline"
disabled={!canCreate && !$selectedWaypoint}
class="grow whitespace-normal h-fit"
on:click={createOrUpdateWaypoint}
>
{#if $selectedWaypoint}
<Save size="16" class="mr-1 shrink-0" />
{$_('menu.metadata.save')}
{:else}
<MapPin size="16" class="mr-1 shrink-0" />
{$_('toolbar.waypoint.create')}
{/if}
</Button>
<Button
variant="outline"
on:click={() => {
selectedWaypoint.set(undefined);
resetWaypointData();
}}
>
<CircleX size="16" />
</Button>
</div>
<Help link={getURLForLanguage($locale, '/help/toolbar/poi')}>
{#if $selectedWaypoint || canCreate}
{$_('toolbar.waypoint.help')}
{:else}
{$_('toolbar.waypoint.help_no_selection')}
{/if}
</Help>
</div>

View File

@@ -1,249 +1,253 @@
<script lang="ts">
import * as Select from '$lib/components/ui/select';
import { Switch } from '$lib/components/ui/switch';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import Help from '$lib/components/Help.svelte';
import ButtonWithTooltip from '$lib/components/ButtonWithTooltip.svelte';
import Tooltip from '$lib/components/Tooltip.svelte';
import Shortcut from '$lib/components/Shortcut.svelte';
import {
Bike,
Footprints,
Waves,
TrainFront,
Route,
TriangleAlert,
ArrowRightLeft,
Home,
RouteOff,
Repeat,
SquareArrowUpLeft,
SquareArrowOutDownRight
} from 'lucide-svelte';
import * as Select from '$lib/components/ui/select';
import { Switch } from '$lib/components/ui/switch';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import Help from '$lib/components/Help.svelte';
import ButtonWithTooltip from '$lib/components/ButtonWithTooltip.svelte';
import Tooltip from '$lib/components/Tooltip.svelte';
import Shortcut from '$lib/components/Shortcut.svelte';
import {
Bike,
Footprints,
Waves,
TrainFront,
Route,
TriangleAlert,
ArrowRightLeft,
Home,
RouteOff,
Repeat,
SquareArrowUpLeft,
SquareArrowOutDownRight,
} from 'lucide-svelte';
import { map, newGPXFile, routingControls, selectFileWhenLoaded } from '$lib/stores';
import { dbUtils, getFile, getFileIds, settings } from '$lib/db';
import { brouterProfiles, routingProfileSelectItem } from './Routing';
import { map, newGPXFile, routingControls, selectFileWhenLoaded } from '$lib/stores';
import { dbUtils, getFile, getFileIds, settings } from '$lib/db';
import { brouterProfiles, routingProfileSelectItem } from './Routing';
import { _, locale } from 'svelte-i18n';
import { RoutingControls } from './RoutingControls';
import mapboxgl from 'mapbox-gl';
import { fileObservers } from '$lib/db';
import { slide } from 'svelte/transition';
import { getOrderedSelection, selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
ListRootItem,
ListTrackItem,
ListTrackSegmentItem,
type ListItem
} from '$lib/components/file-list/FileList';
import { flyAndScale, getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { onDestroy, onMount } from 'svelte';
import { TrackPoint } from 'gpx';
import { _, locale } from 'svelte-i18n';
import { RoutingControls } from './RoutingControls';
import mapboxgl from 'mapbox-gl';
import { fileObservers } from '$lib/db';
import { slide } from 'svelte/transition';
import { getOrderedSelection, selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
ListRootItem,
ListTrackItem,
ListTrackSegmentItem,
type ListItem,
} from '$lib/components/file-list/FileList';
import { flyAndScale, getURLForLanguage, resetCursor, setCrosshairCursor } from '$lib/utils';
import { onDestroy, onMount } from 'svelte';
import { TrackPoint } from 'gpx';
export let minimized = false;
export let minimizable = true;
export let popup: mapboxgl.Popup | undefined = undefined;
export let popupElement: HTMLElement | undefined = undefined;
let selectedItem: ListItem | null = null;
export let minimized = false;
export let minimizable = true;
export let popup: mapboxgl.Popup | undefined = undefined;
export let popupElement: HTMLElement | undefined = undefined;
let selectedItem: ListItem | null = null;
const { privateRoads, routing } = settings;
const { privateRoads, routing } = settings;
$: if ($map && popup && popupElement) {
// remove controls for deleted files
routingControls.forEach((controls, fileId) => {
if (!$fileObservers.has(fileId)) {
controls.destroy();
routingControls.delete(fileId);
$: if ($map && popup && popupElement) {
// remove controls for deleted files
routingControls.forEach((controls, fileId) => {
if (!$fileObservers.has(fileId)) {
controls.destroy();
routingControls.delete(fileId);
if (selectedItem && selectedItem.getFileId() === fileId) {
selectedItem = null;
}
} else if ($map !== controls.map) {
controls.updateMap($map);
}
});
// add controls for new files
$fileObservers.forEach((file, fileId) => {
if (!routingControls.has(fileId)) {
routingControls.set(fileId, new RoutingControls($map, fileId, file, popup, popupElement));
}
});
}
if (selectedItem && selectedItem.getFileId() === fileId) {
selectedItem = null;
}
} else if ($map !== controls.map) {
controls.updateMap($map);
}
});
// add controls for new files
$fileObservers.forEach((file, fileId) => {
if (!routingControls.has(fileId)) {
routingControls.set(
fileId,
new RoutingControls($map, fileId, file, popup, popupElement)
);
}
});
}
$: validSelection = $selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']);
$: validSelection = $selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']);
function createFileWithPoint(e: any) {
if ($selection.size === 0) {
let file = newGPXFile();
file.replaceTrackPoints(0, 0, 0, 0, [
new TrackPoint({
attributes: {
lat: e.lngLat.lat,
lon: e.lngLat.lng
}
})
]);
file._data.id = getFileIds(1)[0];
dbUtils.add(file);
selectFileWhenLoaded(file._data.id);
}
}
function createFileWithPoint(e: any) {
if ($selection.size === 0) {
let file = newGPXFile();
file.replaceTrackPoints(0, 0, 0, 0, [
new TrackPoint({
attributes: {
lat: e.lngLat.lat,
lon: e.lngLat.lng,
},
}),
]);
file._data.id = getFileIds(1)[0];
dbUtils.add(file);
selectFileWhenLoaded(file._data.id);
}
}
onMount(() => {
setCrosshairCursor();
$map?.on('click', createFileWithPoint);
});
onMount(() => {
setCrosshairCursor();
$map?.on('click', createFileWithPoint);
});
onDestroy(() => {
resetCursor();
$map?.off('click', createFileWithPoint);
onDestroy(() => {
resetCursor();
$map?.off('click', createFileWithPoint);
routingControls.forEach((controls) => controls.destroy());
routingControls.clear();
});
routingControls.forEach((controls) => controls.destroy());
routingControls.clear();
});
</script>
{#if minimizable && minimized}
<div class="-m-1.5 -mb-2">
<Button variant="ghost" class="px-1 h-[26px]" on:click={() => (minimized = false)}>
<SquareArrowOutDownRight size="18" />
</Button>
</div>
<div class="-m-1.5 -mb-2">
<Button variant="ghost" class="px-1 h-[26px]" on:click={() => (minimized = false)}>
<SquareArrowOutDownRight size="18" />
</Button>
</div>
{:else}
<div
class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}"
in:flyAndScale={{ x: -2, y: 0, duration: 50 }}
>
<div class="flex flex-col gap-3">
<Label class="flex flex-row justify-between items-center gap-2">
<span class="flex flex-row items-center gap-1">
{#if $routing}
<Route size="16" />
{:else}
<RouteOff size="16" />
{/if}
{$_('toolbar.routing.use_routing')}
</span>
<Tooltip label={$_('toolbar.routing.use_routing_tooltip')}>
<Switch class="scale-90" bind:checked={$routing} />
<Shortcut slot="extra" key="F5" />
</Tooltip>
</Label>
{#if $routing}
<div class="flex flex-col gap-3" in:slide>
<Label class="flex flex-row justify-between items-center gap-2">
<span class="shrink-0 flex flex-row items-center gap-1">
{#if $routingProfileSelectItem.value.includes('bike') || $routingProfileSelectItem.value.includes('motorcycle')}
<Bike size="16" />
{:else if $routingProfileSelectItem.value.includes('foot')}
<Footprints size="16" />
{:else if $routingProfileSelectItem.value.includes('water')}
<Waves size="16" />
{:else if $routingProfileSelectItem.value.includes('railway')}
<TrainFront size="16" />
{/if}
{$_('toolbar.routing.activity')}
</span>
<Select.Root bind:selected={$routingProfileSelectItem}>
<Select.Trigger class="h-8 grow">
<Select.Value />
</Select.Trigger>
<Select.Content>
{#each Object.keys(brouterProfiles) as profile}
<Select.Item value={profile}
>{$_(`toolbar.routing.activities.${profile}`)}</Select.Item
>
{/each}
</Select.Content>
</Select.Root>
</Label>
<Label class="flex flex-row justify-between items-center gap-2">
<span class="flex flex-row gap-1">
<TriangleAlert size="16" />
{$_('toolbar.routing.allow_private')}
</span>
<Switch class="scale-90" bind:checked={$privateRoads} />
</Label>
</div>
{/if}
</div>
<div class="flex flex-row flex-wrap justify-center gap-1">
<ButtonWithTooltip
label={$_('toolbar.routing.reverse.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={dbUtils.reverseSelection}
>
<ArrowRightLeft size="12" />{$_('toolbar.routing.reverse.button')}
</ButtonWithTooltip>
<ButtonWithTooltip
label={$_('toolbar.routing.route_back_to_start.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={() => {
const selected = getOrderedSelection();
if (selected.length > 0) {
const firstFileId = selected[0].getFileId();
const firstFile = getFile(firstFileId);
if (firstFile) {
let start = (() => {
if (selected[0] instanceof ListFileItem) {
return firstFile.trk[0]?.trkseg[0]?.trkpt[0];
} else if (selected[0] instanceof ListTrackItem) {
return firstFile.trk[selected[0].getTrackIndex()]?.trkseg[0]?.trkpt[0];
} else if (selected[0] instanceof ListTrackSegmentItem) {
return firstFile.trk[selected[0].getTrackIndex()]?.trkseg[
selected[0].getSegmentIndex()
]?.trkpt[0];
}
})();
<div
class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}"
in:flyAndScale={{ x: -2, y: 0, duration: 50 }}
>
<div class="flex flex-col gap-3">
<Label class="flex flex-row justify-between items-center gap-2">
<span class="flex flex-row items-center gap-1">
{#if $routing}
<Route size="16" />
{:else}
<RouteOff size="16" />
{/if}
{$_('toolbar.routing.use_routing')}
</span>
<Tooltip label={$_('toolbar.routing.use_routing_tooltip')}>
<Switch class="scale-90" bind:checked={$routing} />
<Shortcut slot="extra" key="F5" />
</Tooltip>
</Label>
{#if $routing}
<div class="flex flex-col gap-3" in:slide>
<Label class="flex flex-row justify-between items-center gap-2">
<span class="shrink-0 flex flex-row items-center gap-1">
{#if $routingProfileSelectItem.value.includes('bike') || $routingProfileSelectItem.value.includes('motorcycle')}
<Bike size="16" />
{:else if $routingProfileSelectItem.value.includes('foot')}
<Footprints size="16" />
{:else if $routingProfileSelectItem.value.includes('water')}
<Waves size="16" />
{:else if $routingProfileSelectItem.value.includes('railway')}
<TrainFront size="16" />
{/if}
{$_('toolbar.routing.activity')}
</span>
<Select.Root bind:selected={$routingProfileSelectItem}>
<Select.Trigger class="h-8 grow">
<Select.Value />
</Select.Trigger>
<Select.Content>
{#each Object.keys(brouterProfiles) as profile}
<Select.Item value={profile}
>{$_(`toolbar.routing.activities.${profile}`)}</Select.Item
>
{/each}
</Select.Content>
</Select.Root>
</Label>
<Label class="flex flex-row justify-between items-center gap-2">
<span class="flex flex-row gap-1">
<TriangleAlert size="16" />
{$_('toolbar.routing.allow_private')}
</span>
<Switch class="scale-90" bind:checked={$privateRoads} />
</Label>
</div>
{/if}
</div>
<div class="flex flex-row flex-wrap justify-center gap-1">
<ButtonWithTooltip
label={$_('toolbar.routing.reverse.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={dbUtils.reverseSelection}
>
<ArrowRightLeft size="12" />{$_('toolbar.routing.reverse.button')}
</ButtonWithTooltip>
<ButtonWithTooltip
label={$_('toolbar.routing.route_back_to_start.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={() => {
const selected = getOrderedSelection();
if (selected.length > 0) {
const firstFileId = selected[0].getFileId();
const firstFile = getFile(firstFileId);
if (firstFile) {
let start = (() => {
if (selected[0] instanceof ListFileItem) {
return firstFile.trk[0]?.trkseg[0]?.trkpt[0];
} else if (selected[0] instanceof ListTrackItem) {
return firstFile.trk[selected[0].getTrackIndex()]?.trkseg[0]
?.trkpt[0];
} else if (selected[0] instanceof ListTrackSegmentItem) {
return firstFile.trk[selected[0].getTrackIndex()]?.trkseg[
selected[0].getSegmentIndex()
]?.trkpt[0];
}
})();
if (start !== undefined) {
const lastFileId = selected[selected.length - 1].getFileId();
routingControls
.get(lastFileId)
?.appendAnchorWithCoordinates(start.getCoordinates());
}
}
}
}}
>
<Home size="12" />{$_('toolbar.routing.route_back_to_start.button')}
</ButtonWithTooltip>
<ButtonWithTooltip
label={$_('toolbar.routing.round_trip.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={dbUtils.createRoundTripForSelection}
>
<Repeat size="12" />{$_('toolbar.routing.round_trip.button')}
</ButtonWithTooltip>
</div>
<div class="w-full flex flex-row gap-2 items-end justify-between">
<Help link={getURLForLanguage($locale, '/help/toolbar/routing')}>
{#if !validSelection}
{$_('toolbar.routing.help_no_file')}
{:else}
{$_('toolbar.routing.help')}
{/if}
</Help>
<Button
variant="ghost"
class="px-1 h-6"
on:click={() => {
if (minimizable) {
minimized = true;
}
}}
>
<SquareArrowUpLeft size="18" />
</Button>
</div>
</div>
if (start !== undefined) {
const lastFileId = selected[selected.length - 1].getFileId();
routingControls
.get(lastFileId)
?.appendAnchorWithCoordinates(start.getCoordinates());
}
}
}
}}
>
<Home size="12" />{$_('toolbar.routing.route_back_to_start.button')}
</ButtonWithTooltip>
<ButtonWithTooltip
label={$_('toolbar.routing.round_trip.tooltip')}
variant="outline"
class="flex flex-row gap-1 text-xs px-2"
disabled={!validSelection}
on:click={dbUtils.createRoundTripForSelection}
>
<Repeat size="12" />{$_('toolbar.routing.round_trip.button')}
</ButtonWithTooltip>
</div>
<div class="w-full flex flex-row gap-2 items-end justify-between">
<Help link={getURLForLanguage($locale, '/help/toolbar/routing')}>
{#if !validSelection}
{$_('toolbar.routing.help_no_file')}
{:else}
{$_('toolbar.routing.help')}
{/if}
</Help>
<Button
variant="ghost"
class="px-1 h-6"
on:click={() => {
if (minimizable) {
minimized = true;
}
}}
>
<SquareArrowUpLeft size="18" />
</Button>
</div>
</div>
{/if}

View File

@@ -1,9 +1,9 @@
import type { Coordinates } from "gpx";
import { TrackPoint, distance } from "gpx";
import { derived, get, writable } from "svelte/store";
import { settings } from "$lib/db";
import { _, isLoading, locale } from "svelte-i18n";
import { getElevation } from "$lib/utils";
import type { Coordinates } from 'gpx';
import { TrackPoint, distance } from 'gpx';
import { derived, get, writable } from 'svelte/store';
import { settings } from '$lib/db';
import { _, isLoading, locale } from 'svelte-i18n';
import { getElevation } from '$lib/utils';
const { routing, routingProfile, privateRoads } = settings;
@@ -15,22 +15,31 @@ export const brouterProfiles: { [key: string]: string } = {
foot: 'Hiking-Alpine-SAC6',
motorcycle: 'Car-FastEco',
water: 'river',
railway: 'rail'
railway: 'rail',
};
export const routingProfileSelectItem = writable({
value: '',
label: ''
label: '',
});
derived([routingProfile, locale, isLoading], ([profile, l, i]) => [profile, l, i]).subscribe(([profile, l, i]) => {
if (!i && profile !== '' && (profile !== get(routingProfileSelectItem).value || get(_)(`toolbar.routing.activities.${profile}`) !== get(routingProfileSelectItem).label) && l !== null) {
routingProfileSelectItem.update((item) => {
item.value = profile;
item.label = get(_)(`toolbar.routing.activities.${profile}`);
return item;
});
derived([routingProfile, locale, isLoading], ([profile, l, i]) => [profile, l, i]).subscribe(
([profile, l, i]) => {
if (
!i &&
profile !== '' &&
(profile !== get(routingProfileSelectItem).value ||
get(_)(`toolbar.routing.activities.${profile}`) !==
get(routingProfileSelectItem).label) &&
l !== null
) {
routingProfileSelectItem.update((item) => {
item.value = profile;
item.label = get(_)(`toolbar.routing.activities.${profile}`);
return item;
});
}
}
});
);
routingProfileSelectItem.subscribe((item) => {
if (item.value !== '' && item.value !== get(routingProfile)) {
routingProfile.set(item.value);
@@ -45,8 +54,12 @@ export function route(points: Coordinates[]): Promise<TrackPoint[]> {
}
}
async function getRoute(points: Coordinates[], brouterProfile: string, privateRoads: boolean): Promise<TrackPoint[]> {
let url = `https://routing.gpx.studio?lonlats=${points.map(point => `${point.lon.toFixed(8)},${point.lat.toFixed(8)}`).join('|')}&profile=${brouterProfile + (privateRoads ? '-private' : '')}&format=geojson&alternativeidx=0`;
async function getRoute(
points: Coordinates[],
brouterProfile: string,
privateRoads: boolean
): Promise<TrackPoint[]> {
let url = `https://routing.gpx.studio?lonlats=${points.map((point) => `${point.lon.toFixed(8)},${point.lat.toFixed(8)}`).join('|')}&profile=${brouterProfile + (privateRoads ? '-private' : '')}&format=geojson&alternativeidx=0`;
let response = await fetch(url);
@@ -61,25 +74,29 @@ async function getRoute(points: Coordinates[], brouterProfile: string, privateRo
let coordinates = geojson.features[0].geometry.coordinates;
let messages = geojson.features[0].properties.messages;
const lngIdx = messages[0].indexOf("Longitude");
const latIdx = messages[0].indexOf("Latitude");
const tagIdx = messages[0].indexOf("WayTags");
const lngIdx = messages[0].indexOf('Longitude');
const latIdx = messages[0].indexOf('Latitude');
const tagIdx = messages[0].indexOf('WayTags');
let messageIdx = 1;
let tags = messageIdx < messages.length ? getTags(messages[messageIdx][tagIdx]) : {};
for (let i = 0; i < coordinates.length; i++) {
let coord = coordinates[i];
route.push(new TrackPoint({
attributes: {
lat: coord[1],
lon: coord[0]
},
ele: coord[2] ?? (i > 0 ? route[i - 1].ele : 0)
}));
route.push(
new TrackPoint({
attributes: {
lat: coord[1],
lon: coord[0],
},
ele: coord[2] ?? (i > 0 ? route[i - 1].ele : 0),
})
);
if (messageIdx < messages.length &&
if (
messageIdx < messages.length &&
coordinates[i][0] == Number(messages[messageIdx][lngIdx]) / 1000000 &&
coordinates[i][1] == Number(messages[messageIdx][latIdx]) / 1000000) {
coordinates[i][1] == Number(messages[messageIdx][latIdx]) / 1000000
) {
messageIdx++;
if (messageIdx == messages.length) tags = {};
@@ -93,10 +110,10 @@ async function getRoute(points: Coordinates[], brouterProfile: string, privateRo
}
function getTags(message: string): { [key: string]: string } {
const fields = message.split(" ");
const fields = message.split(' ');
let tags: { [key: string]: string } = {};
for (let i = 0; i < fields.length; i++) {
let [key, value] = fields[i].split("=");
let [key, value] = fields[i].split('=');
key = key.replace(/:/g, '_');
tags[key] = value;
}
@@ -107,26 +124,31 @@ function getIntermediatePoints(points: Coordinates[]): Promise<TrackPoint[]> {
let route: TrackPoint[] = [];
let step = 0.05;
for (let i = 0; i < points.length - 1; i++) { // Add intermediate points between each pair of points
for (let i = 0; i < points.length - 1; i++) {
// Add intermediate points between each pair of points
let dist = distance(points[i], points[i + 1]) / 1000;
for (let d = 0; d < dist; d += step) {
let lat = points[i].lat + d / dist * (points[i + 1].lat - points[i].lat);
let lon = points[i].lon + d / dist * (points[i + 1].lon - points[i].lon);
route.push(new TrackPoint({
attributes: {
lat: lat,
lon: lon
}
}));
let lat = points[i].lat + (d / dist) * (points[i + 1].lat - points[i].lat);
let lon = points[i].lon + (d / dist) * (points[i + 1].lon - points[i].lon);
route.push(
new TrackPoint({
attributes: {
lat: lat,
lon: lon,
},
})
);
}
}
route.push(new TrackPoint({
attributes: {
lat: points[points.length - 1].lat,
lon: points[points.length - 1].lon
}
}));
route.push(
new TrackPoint({
attributes: {
lat: points[points.length - 1].lat,
lon: points[points.length - 1].lon,
},
})
);
return getElevation(route).then((elevations) => {
route.forEach((point, i) => {
@@ -134,4 +156,4 @@ function getIntermediatePoints(points: Coordinates[]): Promise<TrackPoint[]> {
});
return route;
});
}
}

View File

@@ -1,37 +1,37 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import Shortcut from '$lib/components/Shortcut.svelte';
import { canChangeStart } from './RoutingControls';
import { CirclePlay, Trash2 } from 'lucide-svelte';
import * as Card from '$lib/components/ui/card';
import { Button } from '$lib/components/ui/button';
import Shortcut from '$lib/components/Shortcut.svelte';
import { canChangeStart } from './RoutingControls';
import { CirclePlay, Trash2 } from 'lucide-svelte';
import { _ } from 'svelte-i18n';
import { _ } from 'svelte-i18n';
export let element: HTMLElement;
export let element: HTMLElement;
</script>
<div bind:this={element} class="hidden">
<Card.Root class="border-none shadow-md text-base">
<Card.Content class="flex flex-col p-1">
{#if $canChangeStart}
<Button
class="w-full px-2 py-1 h-6 justify-start"
variant="ghost"
on:click={() => element.dispatchEvent(new CustomEvent('change-start'))}
>
<CirclePlay size="16" class="mr-1" />
{$_('toolbar.routing.start_loop_here')}
</Button>
{/if}
<Button
class="w-full px-2 py-1 h-6 justify-start"
variant="ghost"
on:click={() => element.dispatchEvent(new CustomEvent('delete'))}
>
<Trash2 size="16" class="mr-1" />
{$_('menu.delete')}
<Shortcut shift={true} click={true} />
</Button>
</Card.Content>
</Card.Root>
<Card.Root class="border-none shadow-md text-base">
<Card.Content class="flex flex-col p-1">
{#if $canChangeStart}
<Button
class="w-full px-2 py-1 h-6 justify-start"
variant="ghost"
on:click={() => element.dispatchEvent(new CustomEvent('change-start'))}
>
<CirclePlay size="16" class="mr-1" />
{$_('toolbar.routing.start_loop_here')}
</Button>
{/if}
<Button
class="w-full px-2 py-1 h-6 justify-start"
variant="ghost"
on:click={() => element.dispatchEvent(new CustomEvent('delete'))}
>
<Trash2 size="16" class="mr-1" />
{$_('menu.delete')}
<Shortcut shift={true} click={true} />
</Button>
</Card.Content>
</Card.Root>
</div>

View File

@@ -1,14 +1,18 @@
import { distance, type Coordinates, TrackPoint, TrackSegment, Track, projectedPoint } from "gpx";
import { get, writable, type Readable } from "svelte/store";
import mapboxgl from "mapbox-gl";
import { route } from "./Routing";
import { toast } from "svelte-sonner";
import { _ } from "svelte-i18n";
import { dbUtils, settings, type GPXFileWithStatistics } from "$lib/db";
import { getOrderedSelection, selection } from "$lib/components/file-list/Selection";
import { ListFileItem, ListTrackItem, ListTrackSegmentItem } from "$lib/components/file-list/FileList";
import { currentTool, streetViewEnabled, Tool } from "$lib/stores";
import { getClosestLinePoint, resetCursor, setGrabbingCursor } from "$lib/utils";
import { distance, type Coordinates, TrackPoint, TrackSegment, Track, projectedPoint } from 'gpx';
import { get, writable, type Readable } from 'svelte/store';
import mapboxgl from 'mapbox-gl';
import { route } from './Routing';
import { toast } from 'svelte-sonner';
import { _ } from 'svelte-i18n';
import { dbUtils, settings, type GPXFileWithStatistics } from '$lib/db';
import { getOrderedSelection, selection } from '$lib/components/file-list/Selection';
import {
ListFileItem,
ListTrackItem,
ListTrackSegmentItem,
} from '$lib/components/file-list/FileList';
import { currentTool, streetViewEnabled, Tool } from '$lib/stores';
import { getClosestLinePoint, resetCursor, setGrabbingCursor } from '$lib/utils';
const { streetViewSource } = settings;
export const canChangeStart = writable(false);
@@ -28,15 +32,22 @@ export class RoutingControls {
popupElement: HTMLElement;
temporaryAnchor: AnchorWithMarker;
lastDragEvent = 0;
fileUnsubscribe: () => void = () => { };
fileUnsubscribe: () => void = () => {};
unsubscribes: Function[] = [];
toggleAnchorsForZoomLevelAndBoundsBinded: () => void = this.toggleAnchorsForZoomLevelAndBounds.bind(this);
toggleAnchorsForZoomLevelAndBoundsBinded: () => void =
this.toggleAnchorsForZoomLevelAndBounds.bind(this);
showTemporaryAnchorBinded: (e: any) => void = this.showTemporaryAnchor.bind(this);
updateTemporaryAnchorBinded: (e: any) => void = this.updateTemporaryAnchor.bind(this);
appendAnchorBinded: (e: mapboxgl.MapMouseEvent) => void = this.appendAnchor.bind(this);
constructor(map: mapboxgl.Map, fileId: string, file: Readable<GPXFileWithStatistics | undefined>, popup: mapboxgl.Popup, popupElement: HTMLElement) {
constructor(
map: mapboxgl.Map,
fileId: string,
file: Readable<GPXFileWithStatistics | undefined>,
popup: mapboxgl.Popup,
popupElement: HTMLElement
) {
this.map = map;
this.fileId = fileId;
this.file = file;
@@ -46,8 +57,8 @@ export class RoutingControls {
let point = new TrackPoint({
attributes: {
lat: 0,
lon: 0
}
lon: 0,
},
});
this.temporaryAnchor = this.createAnchor(point, new TrackSegment(), 0, 0);
this.temporaryAnchor.marker.getElement().classList.remove('z-10'); // Show below the other markers
@@ -65,7 +76,9 @@ export class RoutingControls {
return;
}
let selected = get(selection).hasAnyChildren(new ListFileItem(this.fileId), true, ['waypoints']);
let selected = get(selection).hasAnyChildren(new ListFileItem(this.fileId), true, [
'waypoints',
]);
if (selected) {
if (this.active) {
this.updateControls();
@@ -88,7 +101,8 @@ export class RoutingControls {
this.fileUnsubscribe = this.file.subscribe(this.updateControls.bind(this));
}
updateControls() { // Update the markers when the file changes
updateControls() {
// Update the markers when the file changes
let file = get(this.file)?.file;
if (!file) {
return;
@@ -96,8 +110,13 @@ export class RoutingControls {
let anchorIndex = 0;
file.forEachSegment((segment, trackIndex, segmentIndex) => {
if (get(selection).hasAnyParent(new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex))) {
for (let point of segment.trkpt) { // Update the existing anchors (could be improved by matching the existing anchors with the new ones?)
if (
get(selection).hasAnyParent(
new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex)
)
) {
for (let point of segment.trkpt) {
// Update the existing anchors (could be improved by matching the existing anchors with the new ones?)
if (point._data.anchor) {
if (anchorIndex < this.anchors.length) {
this.anchors[anchorIndex].point = point;
@@ -106,7 +125,9 @@ export class RoutingControls {
this.anchors[anchorIndex].segmentIndex = segmentIndex;
this.anchors[anchorIndex].marker.setLngLat(point.getCoordinates());
} else {
this.anchors.push(this.createAnchor(point, segment, trackIndex, segmentIndex));
this.anchors.push(
this.createAnchor(point, segment, trackIndex, segmentIndex)
);
}
anchorIndex++;
}
@@ -114,7 +135,8 @@ export class RoutingControls {
}
});
while (anchorIndex < this.anchors.length) { // Remove the extra anchors
while (anchorIndex < this.anchors.length) {
// Remove the extra anchors
this.anchors.pop()?.marker.remove();
}
@@ -141,14 +163,19 @@ export class RoutingControls {
this.map = map;
}
createAnchor(point: TrackPoint, segment: TrackSegment, trackIndex: number, segmentIndex: number): AnchorWithMarker {
createAnchor(
point: TrackPoint,
segment: TrackSegment,
trackIndex: number,
segmentIndex: number
): AnchorWithMarker {
let element = document.createElement('div');
element.className = `h-5 w-5 xs:h-4 xs:w-4 md:h-3 md:w-3 rounded-full bg-white border-2 border-black cursor-pointer`;
let marker = new mapboxgl.Marker({
draggable: true,
className: 'z-10',
element
element,
}).setLngLat(point.getCoordinates());
let anchor = {
@@ -157,7 +184,7 @@ export class RoutingControls {
trackIndex,
segmentIndex,
marker,
inZoom: false
inZoom: false,
};
marker.on('dragstart', (e) => {
@@ -185,7 +212,8 @@ export class RoutingControls {
e.preventDefault();
e.stopPropagation();
if (Date.now() - this.lastDragEvent < 100) { // Prevent click event during drag
if (Date.now() - this.lastDragEvent < 100) {
// Prevent click event during drag
return;
}
@@ -204,7 +232,12 @@ export class RoutingControls {
return false;
}
let segment = anchor.segment;
if (distance(segment.trkpt[0].getCoordinates(), segment.trkpt[segment.trkpt.length - 1].getCoordinates()) > 1000) {
if (
distance(
segment.trkpt[0].getCoordinates(),
segment.trkpt[segment.trkpt.length - 1].getCoordinates()
) > 1000
) {
return false;
}
return true;
@@ -224,7 +257,8 @@ export class RoutingControls {
};
}
toggleAnchorsForZoomLevelAndBounds() { // Show markers only if they are in the current zoom level and bounds
toggleAnchorsForZoomLevelAndBounds() {
// Show markers only if they are in the current zoom level and bounds
this.shownAnchors.splice(0, this.shownAnchors.length);
let center = this.map.getCenter();
@@ -245,7 +279,8 @@ export class RoutingControls {
}
showTemporaryAnchor(e: any) {
if (this.temporaryAnchor.marker.getElement().classList.contains('cursor-grabbing')) { // Do not not change the source point if it is already being dragged
if (this.temporaryAnchor.marker.getElement().classList.contains('cursor-grabbing')) {
// Do not not change the source point if it is already being dragged
return;
}
@@ -253,7 +288,15 @@ export class RoutingControls {
return;
}
if (!get(selection).hasAnyParent(new ListTrackSegmentItem(this.fileId, e.features[0].properties.trackIndex, e.features[0].properties.segmentIndex))) {
if (
!get(selection).hasAnyParent(
new ListTrackSegmentItem(
this.fileId,
e.features[0].properties.trackIndex,
e.features[0].properties.segmentIndex
)
)
) {
return;
}
@@ -263,7 +306,7 @@ export class RoutingControls {
this.temporaryAnchor.point.setCoordinates({
lat: e.lngLat.lat,
lon: e.lngLat.lng
lon: e.lngLat.lng,
});
this.temporaryAnchor.marker.setLngLat(e.lngLat).addTo(this.map);
@@ -271,12 +314,17 @@ export class RoutingControls {
}
updateTemporaryAnchor(e: any) {
if (this.temporaryAnchor.marker.getElement().classList.contains('cursor-grabbing')) { // Do not hide if it is being dragged, and stop listening for mousemove
if (this.temporaryAnchor.marker.getElement().classList.contains('cursor-grabbing')) {
// Do not hide if it is being dragged, and stop listening for mousemove
this.map.off('mousemove', this.updateTemporaryAnchorBinded);
return;
}
if (e.point.dist(this.map.project(this.temporaryAnchor.point.getCoordinates())) > 20 || this.temporaryAnchorCloseToOtherAnchor(e)) { // Hide if too far from the layer
if (
e.point.dist(this.map.project(this.temporaryAnchor.point.getCoordinates())) > 20 ||
this.temporaryAnchorCloseToOtherAnchor(e)
) {
// Hide if too far from the layer
this.temporaryAnchor.marker.remove();
this.map.off('mousemove', this.updateTemporaryAnchorBinded);
return;
@@ -294,14 +342,16 @@ export class RoutingControls {
return false;
}
async moveAnchor(anchorWithMarker: AnchorWithMarker) { // Move the anchor and update the route from and to the neighbouring anchors
async moveAnchor(anchorWithMarker: AnchorWithMarker) {
// Move the anchor and update the route from and to the neighbouring anchors
let coordinates = {
lat: anchorWithMarker.marker.getLngLat().lat,
lon: anchorWithMarker.marker.getLngLat().lng
lon: anchorWithMarker.marker.getLngLat().lng,
};
let anchor = anchorWithMarker as Anchor;
if (anchorWithMarker === this.temporaryAnchor) { // Temporary anchor, need to find the closest point of the segment and create an anchor for it
if (anchorWithMarker === this.temporaryAnchor) {
// Temporary anchor, need to find the closest point of the segment and create an anchor for it
this.temporaryAnchor.marker.remove();
anchor = this.getPermanentAnchor();
}
@@ -326,7 +376,8 @@ export class RoutingControls {
let success = await this.routeBetweenAnchors(anchors, targetCoordinates);
if (!success) { // Route failed, revert the anchor to the previous position
if (!success) {
// Route failed, revert the anchor to the previous position
anchorWithMarker.marker.setLngLat(anchorWithMarker.point.getCoordinates());
}
}
@@ -338,16 +389,24 @@ export class RoutingControls {
let minDetails: any = { distance: Number.MAX_VALUE };
let minAnchor = this.temporaryAnchor as Anchor;
file?.forEachSegment((segment, trackIndex, segmentIndex) => {
if (get(selection).hasAnyParent(new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex))) {
if (
get(selection).hasAnyParent(
new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex)
)
) {
let details: any = {};
let closest = getClosestLinePoint(segment.trkpt, this.temporaryAnchor.point, details);
let closest = getClosestLinePoint(
segment.trkpt,
this.temporaryAnchor.point,
details
);
if (details.distance < minDetails.distance) {
minDetails = details;
minAnchor = {
point: closest,
segment,
trackIndex,
segmentIndex
segmentIndex,
};
}
}
@@ -374,41 +433,67 @@ export class RoutingControls {
point: this.temporaryAnchor.point,
trackIndex: -1,
segmentIndex: -1,
trkptIndex: -1
trkptIndex: -1,
};
file?.forEachSegment((segment, trackIndex, segmentIndex) => {
if (get(selection).hasAnyParent(new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex))) {
if (
get(selection).hasAnyParent(
new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex)
)
) {
let details: any = {};
getClosestLinePoint(segment.trkpt, this.temporaryAnchor.point, details);
if (details.distance < minDetails.distance) {
minDetails = details;
let before = details.before ? details.index : details.index - 1;
let projectedPt = projectedPoint(segment.trkpt[before], segment.trkpt[before + 1], this.temporaryAnchor.point);
let ratio = distance(segment.trkpt[before], projectedPt) / distance(segment.trkpt[before], segment.trkpt[before + 1]);
let projectedPt = projectedPoint(
segment.trkpt[before],
segment.trkpt[before + 1],
this.temporaryAnchor.point
);
let ratio =
distance(segment.trkpt[before], projectedPt) /
distance(segment.trkpt[before], segment.trkpt[before + 1]);
let point = segment.trkpt[before].clone();
point.setCoordinates(projectedPt);
point.ele = (1 - ratio) * (segment.trkpt[before].ele ?? 0) + ratio * (segment.trkpt[before + 1].ele ?? 0);
point.time = (segment.trkpt[before].time && segment.trkpt[before + 1].time) ? new Date((1 - ratio) * segment.trkpt[before].time.getTime() + ratio * segment.trkpt[before + 1].time.getTime()) : undefined;
point.ele =
(1 - ratio) * (segment.trkpt[before].ele ?? 0) +
ratio * (segment.trkpt[before + 1].ele ?? 0);
point.time =
segment.trkpt[before].time && segment.trkpt[before + 1].time
? new Date(
(1 - ratio) * segment.trkpt[before].time.getTime() +
ratio * segment.trkpt[before + 1].time.getTime()
)
: undefined;
point._data = {
anchor: true,
zoom: 0
zoom: 0,
};
minInfo = {
point,
trackIndex,
segmentIndex,
trkptIndex: before + 1
trkptIndex: before + 1,
};
}
}
});
if (minInfo.trackIndex !== -1) {
dbUtils.applyToFile(this.fileId, (file) => file.replaceTrackPoints(minInfo.trackIndex, minInfo.segmentIndex, minInfo.trkptIndex, minInfo.trkptIndex - 1, [minInfo.point]));
dbUtils.applyToFile(this.fileId, (file) =>
file.replaceTrackPoints(
minInfo.trackIndex,
minInfo.segmentIndex,
minInfo.trkptIndex,
minInfo.trkptIndex - 1,
[minInfo.point]
)
);
}
}
@@ -416,22 +501,46 @@ export class RoutingControls {
return () => this.deleteAnchor(anchor);
}
async deleteAnchor(anchor: Anchor) { // Remove the anchor and route between the neighbouring anchors if they exist
async deleteAnchor(anchor: Anchor) {
// Remove the anchor and route between the neighbouring anchors if they exist
this.popup.remove();
let [previousAnchor, nextAnchor] = this.getNeighbouringAnchors(anchor);
if (previousAnchor === null && nextAnchor === null) { // Only one point, remove it
dbUtils.applyToFile(this.fileId, (file) => file.replaceTrackPoints(anchor.trackIndex, anchor.segmentIndex, 0, 0, []));
} else if (previousAnchor === null) { // First point, remove trackpoints until nextAnchor
dbUtils.applyToFile(this.fileId, (file) => file.replaceTrackPoints(anchor.trackIndex, anchor.segmentIndex, 0, nextAnchor.point._data.index - 1, []));
} else if (nextAnchor === null) { // Last point, remove trackpoints from previousAnchor
if (previousAnchor === null && nextAnchor === null) {
// Only one point, remove it
dbUtils.applyToFile(this.fileId, (file) =>
file.replaceTrackPoints(anchor.trackIndex, anchor.segmentIndex, 0, 0, [])
);
} else if (previousAnchor === null) {
// First point, remove trackpoints until nextAnchor
dbUtils.applyToFile(this.fileId, (file) =>
file.replaceTrackPoints(
anchor.trackIndex,
anchor.segmentIndex,
0,
nextAnchor.point._data.index - 1,
[]
)
);
} else if (nextAnchor === null) {
// Last point, remove trackpoints from previousAnchor
dbUtils.applyToFile(this.fileId, (file) => {
let segment = file.getSegment(anchor.trackIndex, anchor.segmentIndex);
file.replaceTrackPoints(anchor.trackIndex, anchor.segmentIndex, previousAnchor.point._data.index + 1, segment.trkpt.length - 1, []);
file.replaceTrackPoints(
anchor.trackIndex,
anchor.segmentIndex,
previousAnchor.point._data.index + 1,
segment.trkpt.length - 1,
[]
);
});
} else { // Route between previousAnchor and nextAnchor
this.routeBetweenAnchors([previousAnchor, nextAnchor], [previousAnchor.point.getCoordinates(), nextAnchor.point.getCoordinates()]);
} else {
// Route between previousAnchor and nextAnchor
this.routeBetweenAnchors(
[previousAnchor, nextAnchor],
[previousAnchor.point.getCoordinates(), nextAnchor.point.getCoordinates()]
);
}
}
@@ -447,27 +556,43 @@ export class RoutingControls {
return;
}
let speed = fileWithStats.statistics.getStatisticsFor(new ListTrackSegmentItem(this.fileId, anchor.trackIndex, anchor.segmentIndex)).global.speed.moving;
let speed = fileWithStats.statistics.getStatisticsFor(
new ListTrackSegmentItem(this.fileId, anchor.trackIndex, anchor.segmentIndex)
).global.speed.moving;
let segment = anchor.segment;
dbUtils.applyToFile(this.fileId, (file) => {
file.replaceTrackPoints(anchor.trackIndex, anchor.segmentIndex, segment.trkpt.length, segment.trkpt.length - 1, segment.trkpt.slice(0, anchor.point._data.index), speed > 0 ? speed : undefined);
file.crop(anchor.point._data.index, anchor.point._data.index + segment.trkpt.length - 1, [anchor.trackIndex], [anchor.segmentIndex]);
file.replaceTrackPoints(
anchor.trackIndex,
anchor.segmentIndex,
segment.trkpt.length,
segment.trkpt.length - 1,
segment.trkpt.slice(0, anchor.point._data.index),
speed > 0 ? speed : undefined
);
file.crop(
anchor.point._data.index,
anchor.point._data.index + segment.trkpt.length - 1,
[anchor.trackIndex],
[anchor.segmentIndex]
);
});
}
async appendAnchor(e: mapboxgl.MapMouseEvent) { // Add a new anchor to the end of the last segment
async appendAnchor(e: mapboxgl.MapMouseEvent) {
// Add a new anchor to the end of the last segment
if (get(streetViewEnabled) && get(streetViewSource) === 'google') {
return;
}
this.appendAnchorWithCoordinates({
lat: e.lngLat.lat,
lon: e.lngLat.lng
lon: e.lngLat.lng,
});
}
async appendAnchorWithCoordinates(coordinates: Coordinates) { // Add a new anchor to the end of the last segment
async appendAnchorWithCoordinates(coordinates: Coordinates) {
// Add a new anchor to the end of the last segment
let selected = getOrderedSelection();
if (selected.length === 0 || selected[selected.length - 1].getFileId() !== this.fileId) {
return;
@@ -477,7 +602,7 @@ export class RoutingControls {
let lastAnchor = this.anchors[this.anchors.length - 1];
let newPoint = new TrackPoint({
attributes: coordinates
attributes: coordinates,
});
newPoint._data.anchor = true;
newPoint._data.zoom = 0;
@@ -488,7 +613,10 @@ export class RoutingControls {
if (item instanceof ListTrackItem || item instanceof ListTrackSegmentItem) {
trackIndex = item.getTrackIndex();
}
let segmentIndex = (file.trk.length > 0 && file.trk[trackIndex].trkseg.length > 0) ? file.trk[trackIndex].trkseg.length - 1 : 0;
let segmentIndex =
file.trk.length > 0 && file.trk[trackIndex].trkseg.length > 0
? file.trk[trackIndex].trkseg.length - 1
: 0;
if (item instanceof ListTrackSegmentItem) {
segmentIndex = item.getSegmentIndex();
}
@@ -512,10 +640,13 @@ export class RoutingControls {
point: newPoint,
segment: lastAnchor.segment,
trackIndex: lastAnchor.trackIndex,
segmentIndex: lastAnchor.segmentIndex
segmentIndex: lastAnchor.segmentIndex,
};
await this.routeBetweenAnchors([lastAnchor, newAnchor], [lastAnchor.point.getCoordinates(), newAnchor.point.getCoordinates()]);
await this.routeBetweenAnchors(
[lastAnchor, newAnchor],
[lastAnchor.point.getCoordinates(), newAnchor.point.getCoordinates()]
);
}
getNeighbouringAnchors(anchor: Anchor): [Anchor | null, Anchor | null] {
@@ -525,11 +656,17 @@ export class RoutingControls {
for (let i = 0; i < this.anchors.length; i++) {
if (this.anchors[i].segment === anchor.segment && this.anchors[i].inZoom) {
if (this.anchors[i].point._data.index < anchor.point._data.index) {
if (!previousAnchor || this.anchors[i].point._data.index > previousAnchor.point._data.index) {
if (
!previousAnchor ||
this.anchors[i].point._data.index > previousAnchor.point._data.index
) {
previousAnchor = this.anchors[i];
}
} else if (this.anchors[i].point._data.index > anchor.point._data.index) {
if (!nextAnchor || this.anchors[i].point._data.index < nextAnchor.point._data.index) {
if (
!nextAnchor ||
this.anchors[i].point._data.index < nextAnchor.point._data.index
) {
nextAnchor = this.anchors[i];
}
}
@@ -539,7 +676,10 @@ export class RoutingControls {
return [previousAnchor, nextAnchor];
}
async routeBetweenAnchors(anchors: Anchor[], targetCoordinates: Coordinates[]): Promise<boolean> {
async routeBetweenAnchors(
anchors: Anchor[],
targetCoordinates: Coordinates[]
): Promise<boolean> {
let segment = anchors[0].segment;
let fileWithStats = get(this.file);
@@ -547,10 +687,15 @@ export class RoutingControls {
return false;
}
if (anchors.length === 1) { // Only one anchor, update the point in the segment
dbUtils.applyToFile(this.fileId, (file) => file.replaceTrackPoints(anchors[0].trackIndex, anchors[0].segmentIndex, 0, 0, [new TrackPoint({
attributes: targetCoordinates[0],
})]));
if (anchors.length === 1) {
// Only one anchor, update the point in the segment
dbUtils.applyToFile(this.fileId, (file) =>
file.replaceTrackPoints(anchors[0].trackIndex, anchors[0].segmentIndex, 0, 0, [
new TrackPoint({
attributes: targetCoordinates[0],
}),
])
);
return true;
}
@@ -559,23 +704,28 @@ export class RoutingControls {
response = await route(targetCoordinates);
} catch (e: any) {
if (e.message.includes('from-position not mapped in existing datafile')) {
toast.error(get(_)("toolbar.routing.error.from"));
toast.error(get(_)('toolbar.routing.error.from'));
} else if (e.message.includes('via1-position not mapped in existing datafile')) {
toast.error(get(_)("toolbar.routing.error.via"));
toast.error(get(_)('toolbar.routing.error.via'));
} else if (e.message.includes('to-position not mapped in existing datafile')) {
toast.error(get(_)("toolbar.routing.error.to"));
toast.error(get(_)('toolbar.routing.error.to'));
} else if (e.message.includes('Time-out')) {
toast.error(get(_)("toolbar.routing.error.timeout"));
toast.error(get(_)('toolbar.routing.error.timeout'));
} else {
toast.error(e.message);
}
return false;
}
if (anchors[0].point._data.index === 0) { // First anchor is the first point of the segment
if (anchors[0].point._data.index === 0) {
// First anchor is the first point of the segment
anchors[0].point = response[0]; // replace the first anchor
anchors[0].point._data.index = 0;
} else if (anchors[0].point._data.index === segment.trkpt.length - 1 && distance(anchors[0].point.getCoordinates(), response[0].getCoordinates()) < 1) { // First anchor is the last point of the segment, and the new point is close enough
} else if (
anchors[0].point._data.index === segment.trkpt.length - 1 &&
distance(anchors[0].point.getCoordinates(), response[0].getCoordinates()) < 1
) {
// First anchor is the last point of the segment, and the new point is close enough
anchors[0].point = response[0]; // replace the first anchor
anchors[0].point._data.index = segment.trkpt.length - 1;
} else {
@@ -583,7 +733,8 @@ export class RoutingControls {
response.splice(0, 0, anchors[0].point); // Insert it in the response to keep it
}
if (anchors[anchors.length - 1].point._data.index === segment.trkpt.length - 1) { // Last anchor is the last point of the segment
if (anchors[anchors.length - 1].point._data.index === segment.trkpt.length - 1) {
// Last anchor is the last point of the segment
anchors[anchors.length - 1].point = response[response.length - 1]; // replace the last anchor
anchors[anchors.length - 1].point._data.index = segment.trkpt.length - 1;
} else {
@@ -594,7 +745,7 @@ export class RoutingControls {
for (let i = 1; i < anchors.length - 1; i++) {
// Find the closest point to the intermediate anchor
// and transfer the marker to that point
anchors[i].point = getClosestLinePoint(response.slice(1, - 1), targetCoordinates[i]);
anchors[i].point = getClosestLinePoint(response.slice(1, -1), targetCoordinates[i]);
}
anchors.forEach((anchor) => {
@@ -602,36 +753,64 @@ export class RoutingControls {
anchor.point._data.zoom = 0; // Make these anchors permanent
});
let stats = fileWithStats.statistics.getStatisticsFor(new ListTrackSegmentItem(this.fileId, anchors[0].trackIndex, anchors[0].segmentIndex));
let stats = fileWithStats.statistics.getStatisticsFor(
new ListTrackSegmentItem(this.fileId, anchors[0].trackIndex, anchors[0].segmentIndex)
);
let speed: number | undefined = undefined;
let startTime = anchors[0].point.time;
if (stats.global.speed.moving > 0) {
let replacingDistance = 0;
for (let i = 1; i < response.length; i++) {
replacingDistance += distance(response[i - 1].getCoordinates(), response[i].getCoordinates()) / 1000;
replacingDistance +=
distance(response[i - 1].getCoordinates(), response[i].getCoordinates()) / 1000;
}
let replacedDistance = stats.local.distance.moving[anchors[anchors.length - 1].point._data.index] - stats.local.distance.moving[anchors[0].point._data.index];
let replacedDistance =
stats.local.distance.moving[anchors[anchors.length - 1].point._data.index] -
stats.local.distance.moving[anchors[0].point._data.index];
let newDistance = stats.global.distance.moving + replacingDistance - replacedDistance;
let newTime = newDistance / stats.global.speed.moving * 3600;
let newTime = (newDistance / stats.global.speed.moving) * 3600;
let remainingTime = stats.global.time.moving - (stats.local.time.moving[anchors[anchors.length - 1].point._data.index] - stats.local.time.moving[anchors[0].point._data.index]);
let remainingTime =
stats.global.time.moving -
(stats.local.time.moving[anchors[anchors.length - 1].point._data.index] -
stats.local.time.moving[anchors[0].point._data.index]);
let replacingTime = newTime - remainingTime;
if (replacingTime <= 0) { // Fallback to simple time difference
replacingTime = stats.local.time.total[anchors[anchors.length - 1].point._data.index] - stats.local.time.total[anchors[0].point._data.index];
if (replacingTime <= 0) {
// Fallback to simple time difference
replacingTime =
stats.local.time.total[anchors[anchors.length - 1].point._data.index] -
stats.local.time.total[anchors[0].point._data.index];
}
speed = replacingDistance / replacingTime * 3600;
speed = (replacingDistance / replacingTime) * 3600;
if (startTime === undefined) { // Replacing the first point
if (startTime === undefined) {
// Replacing the first point
let endIndex = anchors[anchors.length - 1].point._data.index;
startTime = new Date((segment.trkpt[endIndex].time?.getTime() ?? 0) - (replacingTime + stats.local.time.total[endIndex] - stats.local.time.moving[endIndex]) * 1000);
startTime = new Date(
(segment.trkpt[endIndex].time?.getTime() ?? 0) -
(replacingTime +
stats.local.time.total[endIndex] -
stats.local.time.moving[endIndex]) *
1000
);
}
}
dbUtils.applyToFile(this.fileId, (file) => file.replaceTrackPoints(anchors[0].trackIndex, anchors[0].segmentIndex, anchors[0].point._data.index, anchors[anchors.length - 1].point._data.index, response, speed, startTime));
dbUtils.applyToFile(this.fileId, (file) =>
file.replaceTrackPoints(
anchors[0].trackIndex,
anchors[0].segmentIndex,
anchors[0].point._data.index,
anchors[anchors.length - 1].point._data.index,
response,
speed,
startTime
)
);
return true;
}

View File

@@ -1,4 +1,4 @@
import { ramerDouglasPeucker, type GPXFile, type TrackSegment } from "gpx";
import { ramerDouglasPeucker, type GPXFile, type TrackSegment } from 'gpx';
const earthRadius = 6371008.8;
@@ -17,7 +17,8 @@ export function updateAnchorPoints(file: GPXFile) {
let segments = file.getSegments();
for (let segment of segments) {
if (!segment._data.anchors) { // New segment, compute anchor points for it
if (!segment._data.anchors) {
// New segment, compute anchor points for it
computeAnchorPoints(segment);
continue;
}
@@ -42,4 +43,3 @@ function computeAnchorPoints(segment: TrackSegment) {
});
segment._data.anchors = true;
}

View File

@@ -1,146 +1,151 @@
<script lang="ts" context="module">
export enum SplitType {
FILES = 'files',
TRACKS = 'tracks',
SEGMENTS = 'segments'
}
export enum SplitType {
FILES = 'files',
TRACKS = 'tracks',
SEGMENTS = 'segments',
}
</script>
<script lang="ts">
import Help from '$lib/components/Help.svelte';
import { ListRootItem } from '$lib/components/file-list/FileList';
import { selection } from '$lib/components/file-list/Selection';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import { Slider } from '$lib/components/ui/slider';
import * as Select from '$lib/components/ui/select';
import { Separator } from '$lib/components/ui/separator';
import { gpxStatistics, map, slicedGPXStatistics, splitAs } from '$lib/stores';
import { get } from 'svelte/store';
import { _, locale } from 'svelte-i18n';
import { onDestroy, tick } from 'svelte';
import { Crop } from 'lucide-svelte';
import { dbUtils } from '$lib/db';
import { SplitControls } from './SplitControls';
import { getURLForLanguage } from '$lib/utils';
import Help from '$lib/components/Help.svelte';
import { ListRootItem } from '$lib/components/file-list/FileList';
import { selection } from '$lib/components/file-list/Selection';
import { Label } from '$lib/components/ui/label/index.js';
import { Button } from '$lib/components/ui/button';
import { Slider } from '$lib/components/ui/slider';
import * as Select from '$lib/components/ui/select';
import { Separator } from '$lib/components/ui/separator';
import { gpxStatistics, map, slicedGPXStatistics, splitAs } from '$lib/stores';
import { get } from 'svelte/store';
import { _, locale } from 'svelte-i18n';
import { onDestroy, tick } from 'svelte';
import { Crop } from 'lucide-svelte';
import { dbUtils } from '$lib/db';
import { SplitControls } from './SplitControls';
import { getURLForLanguage } from '$lib/utils';
let splitControls: SplitControls | undefined = undefined;
let canCrop = false;
let splitControls: SplitControls | undefined = undefined;
let canCrop = false;
$: if ($map) {
if (splitControls) {
splitControls.destroy();
}
splitControls = new SplitControls($map);
}
$: if ($map) {
if (splitControls) {
splitControls.destroy();
}
splitControls = new SplitControls($map);
}
$: validSelection =
$selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']) &&
$gpxStatistics.local.points.length > 0;
$: validSelection =
$selection.hasAnyChildren(new ListRootItem(), true, ['waypoints']) &&
$gpxStatistics.local.points.length > 0;
let maxSliderValue = 1;
let sliderValues = [0, 1];
let maxSliderValue = 1;
let sliderValues = [0, 1];
function updateCanCrop() {
canCrop = sliderValues[0] != 0 || sliderValues[1] != maxSliderValue;
}
function updateCanCrop() {
canCrop = sliderValues[0] != 0 || sliderValues[1] != maxSliderValue;
}
function updateSlicedGPXStatistics() {
if (validSelection && canCrop) {
$slicedGPXStatistics = [
get(gpxStatistics).slice(sliderValues[0], sliderValues[1]),
sliderValues[0],
sliderValues[1]
];
} else {
$slicedGPXStatistics = undefined;
}
}
function updateSlicedGPXStatistics() {
if (validSelection && canCrop) {
$slicedGPXStatistics = [
get(gpxStatistics).slice(sliderValues[0], sliderValues[1]),
sliderValues[0],
sliderValues[1],
];
} else {
$slicedGPXStatistics = undefined;
}
}
function updateSliderValues() {
if ($slicedGPXStatistics !== undefined) {
sliderValues = [$slicedGPXStatistics[1], $slicedGPXStatistics[2]];
}
}
function updateSliderValues() {
if ($slicedGPXStatistics !== undefined) {
sliderValues = [$slicedGPXStatistics[1], $slicedGPXStatistics[2]];
}
}
async function updateSliderLimits() {
if (validSelection && $gpxStatistics.local.points.length > 0) {
maxSliderValue = $gpxStatistics.local.points.length - 1;
} else {
maxSliderValue = 1;
}
await tick();
sliderValues = [0, maxSliderValue];
}
async function updateSliderLimits() {
if (validSelection && $gpxStatistics.local.points.length > 0) {
maxSliderValue = $gpxStatistics.local.points.length - 1;
} else {
maxSliderValue = 1;
}
await tick();
sliderValues = [0, maxSliderValue];
}
$: if ($gpxStatistics.local.points.length - 1 != maxSliderValue) {
updateSliderLimits();
}
$: if ($gpxStatistics.local.points.length - 1 != maxSliderValue) {
updateSliderLimits();
}
$: if (sliderValues) {
updateCanCrop();
updateSlicedGPXStatistics();
}
$: if (sliderValues) {
updateCanCrop();
updateSlicedGPXStatistics();
}
$: if (
$slicedGPXStatistics !== undefined &&
($slicedGPXStatistics[1] !== sliderValues[0] || $slicedGPXStatistics[2] !== sliderValues[1])
) {
updateSliderValues();
updateCanCrop();
}
$: if (
$slicedGPXStatistics !== undefined &&
($slicedGPXStatistics[1] !== sliderValues[0] || $slicedGPXStatistics[2] !== sliderValues[1])
) {
updateSliderValues();
updateCanCrop();
}
const splitTypes = [
{ value: SplitType.FILES, label: $_('gpx.files') },
{ value: SplitType.TRACKS, label: $_('gpx.tracks') },
{ value: SplitType.SEGMENTS, label: $_('gpx.segments') }
];
const splitTypes = [
{ value: SplitType.FILES, label: $_('gpx.files') },
{ value: SplitType.TRACKS, label: $_('gpx.tracks') },
{ value: SplitType.SEGMENTS, label: $_('gpx.segments') },
];
let splitType = splitTypes.find((type) => type.value === $splitAs) ?? splitTypes[0];
let splitType = splitTypes.find((type) => type.value === $splitAs) ?? splitTypes[0];
$: splitAs.set(splitType.value);
$: splitAs.set(splitType.value);
onDestroy(() => {
$slicedGPXStatistics = undefined;
if (splitControls) {
splitControls.destroy();
splitControls = undefined;
}
});
onDestroy(() => {
$slicedGPXStatistics = undefined;
if (splitControls) {
splitControls.destroy();
splitControls = undefined;
}
});
</script>
<div class="flex flex-col gap-3 w-full max-w-80 {$$props.class ?? ''}">
<div class="p-2">
<Slider bind:value={sliderValues} max={maxSliderValue} step={1} disabled={!validSelection} />
</div>
<Button
variant="outline"
disabled={!validSelection || !canCrop}
on:click={() => dbUtils.cropSelection(sliderValues[0], sliderValues[1])}
>
<Crop size="16" class="mr-1" />{$_('toolbar.scissors.crop')}
</Button>
<Separator />
<Label class="flex flex-row flex-wrap gap-3 items-center">
<span class="shrink-0">
{$_('toolbar.scissors.split_as')}
</span>
<Select.Root bind:selected={splitType}>
<Select.Trigger class="h-8 w-fit grow">
<Select.Value />
</Select.Trigger>
<Select.Content>
{#each splitTypes as { value, label }}
<Select.Item {value}>{label}</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</Label>
<Help link={getURLForLanguage($locale, '/help/toolbar/scissors')}>
{#if validSelection}
{$_('toolbar.scissors.help')}
{:else}
{$_('toolbar.scissors.help_invalid_selection')}
{/if}
</Help>
<div class="p-2">
<Slider
bind:value={sliderValues}
max={maxSliderValue}
step={1}
disabled={!validSelection}
/>
</div>
<Button
variant="outline"
disabled={!validSelection || !canCrop}
on:click={() => dbUtils.cropSelection(sliderValues[0], sliderValues[1])}
>
<Crop size="16" class="mr-1" />{$_('toolbar.scissors.crop')}
</Button>
<Separator />
<Label class="flex flex-row flex-wrap gap-3 items-center">
<span class="shrink-0">
{$_('toolbar.scissors.split_as')}
</span>
<Select.Root bind:selected={splitType}>
<Select.Trigger class="h-8 w-fit grow">
<Select.Value />
</Select.Trigger>
<Select.Content>
{#each splitTypes as { value, label }}
<Select.Item {value}>{label}</Select.Item>
{/each}
</Select.Content>
</Select.Root>
</Label>
<Help link={getURLForLanguage($locale, '/help/toolbar/scissors')}>
{#if validSelection}
{$_('toolbar.scissors.help')}
{:else}
{$_('toolbar.scissors.help_invalid_selection')}
{/if}
</Help>
</div>

View File

@@ -1,12 +1,15 @@
import { TrackPoint, TrackSegment } from "gpx";
import { get } from "svelte/store";
import mapboxgl from "mapbox-gl";
import { dbUtils, getFile } from "$lib/db";
import { applyToOrderedSelectedItemsFromFile, selection } from "$lib/components/file-list/Selection";
import { ListTrackSegmentItem } from "$lib/components/file-list/FileList";
import { currentTool, gpxStatistics, Tool } from "$lib/stores";
import { _ } from "svelte-i18n";
import { Scissors } from "lucide-static";
import { TrackPoint, TrackSegment } from 'gpx';
import { get } from 'svelte/store';
import mapboxgl from 'mapbox-gl';
import { dbUtils, getFile } from '$lib/db';
import {
applyToOrderedSelectedItemsFromFile,
selection,
} from '$lib/components/file-list/Selection';
import { ListTrackSegmentItem } from '$lib/components/file-list/FileList';
import { currentTool, gpxStatistics, Tool } from '$lib/stores';
import { _ } from 'svelte-i18n';
import { Scissors } from 'lucide-static';
export class SplitControls {
active: boolean = false;
@@ -15,7 +18,8 @@ export class SplitControls {
shownControls: ControlWithMarker[] = [];
unsubscribes: Function[] = [];
toggleControlsForZoomLevelAndBoundsBinded: () => void = this.toggleControlsForZoomLevelAndBounds.bind(this);
toggleControlsForZoomLevelAndBoundsBinded: () => void =
this.toggleControlsForZoomLevelAndBounds.bind(this);
constructor(map: mapboxgl.Map) {
this.map = map;
@@ -48,15 +52,21 @@ export class SplitControls {
this.map.on('move', this.toggleControlsForZoomLevelAndBoundsBinded);
}
updateControls() { // Update the markers when the files change
updateControls() {
// Update the markers when the files change
let controlIndex = 0;
applyToOrderedSelectedItemsFromFile((fileId, level, items) => {
let file = getFile(fileId);
if (file) {
file.forEachSegment((segment, trackIndex, segmentIndex) => {
if (get(selection).hasAnyParent(new ListTrackSegmentItem(fileId, trackIndex, segmentIndex))) {
for (let point of segment.trkpt.slice(1, -1)) { // Update the existing controls (could be improved by matching the existing controls with the new ones?)
if (
get(selection).hasAnyParent(
new ListTrackSegmentItem(fileId, trackIndex, segmentIndex)
)
) {
for (let point of segment.trkpt.slice(1, -1)) {
// Update the existing controls (could be improved by matching the existing controls with the new ones?)
if (point._data.anchor) {
if (controlIndex < this.controls.length) {
this.controls[controlIndex].fileId = fileId;
@@ -64,20 +74,30 @@ export class SplitControls {
this.controls[controlIndex].segment = segment;
this.controls[controlIndex].trackIndex = trackIndex;
this.controls[controlIndex].segmentIndex = segmentIndex;
this.controls[controlIndex].marker.setLngLat(point.getCoordinates());
this.controls[controlIndex].marker.setLngLat(
point.getCoordinates()
);
} else {
this.controls.push(this.createControl(point, segment, fileId, trackIndex, segmentIndex));
this.controls.push(
this.createControl(
point,
segment,
fileId,
trackIndex,
segmentIndex
)
);
}
controlIndex++;
}
}
}
});
}
}, false);
while (controlIndex < this.controls.length) { // Remove the extra controls
while (controlIndex < this.controls.length) {
// Remove the extra controls
this.controls.pop()?.marker.remove();
}
@@ -94,7 +114,8 @@ export class SplitControls {
this.map.off('move', this.toggleControlsForZoomLevelAndBoundsBinded);
}
toggleControlsForZoomLevelAndBounds() { // Show markers only if they are in the current zoom level and bounds
toggleControlsForZoomLevelAndBounds() {
// Show markers only if they are in the current zoom level and bounds
this.shownControls.splice(0, this.shownControls.length);
let southWest = this.map.unproject([0, this.map.getCanvas().height]);
@@ -113,15 +134,23 @@ export class SplitControls {
});
}
createControl(point: TrackPoint, segment: TrackSegment, fileId: string, trackIndex: number, segmentIndex: number): ControlWithMarker {
createControl(
point: TrackPoint,
segment: TrackSegment,
fileId: string,
trackIndex: number,
segmentIndex: number
): ControlWithMarker {
let element = document.createElement('div');
element.className = `h-6 w-6 p-0.5 rounded-full bg-white border-2 border-black cursor-pointer`;
element.innerHTML = Scissors.replace('width="24"', "").replace('height="24"', "").replace('stroke="currentColor"', 'stroke="black"');
element.innerHTML = Scissors.replace('width="24"', '')
.replace('height="24"', '')
.replace('stroke="currentColor"', 'stroke="black"');
let marker = new mapboxgl.Marker({
draggable: true,
className: 'z-10',
element
element,
}).setLngLat(point.getCoordinates());
let control = {
@@ -131,12 +160,18 @@ export class SplitControls {
trackIndex,
segmentIndex,
marker,
inZoom: false
inZoom: false,
};
marker.getElement().addEventListener('click', (e) => {
e.stopPropagation();
dbUtils.split(control.fileId, control.trackIndex, control.segmentIndex, control.point.getCoordinates(), control.point._data.index);
dbUtils.split(
control.fileId,
control.trackIndex,
control.segmentIndex,
control.point.getCoordinates(),
control.point._data.index
);
});
return control;