This commit is contained in:
vcoppe
2026-10-04 10:15:51 +02:00
parent 68c8933c35
commit 763a7406ce
2 changed files with 141 additions and 238 deletions
@@ -1,4 +1,5 @@
import { get, type Readable } from 'svelte/store'; import { get, type Readable } from 'svelte/store';
import type { GPXFile } from 'gpx';
import maplibregl, { import maplibregl, {
type GeoJSONSource, type GeoJSONSource,
type FilterSpecification, type FilterSpecification,
@@ -7,20 +8,14 @@ import maplibregl, {
} from 'maplibre-gl'; } from 'maplibre-gl';
import { map } from '$lib/components/map/map'; import { map } from '$lib/components/map/map';
import { waypointPopup, trackpointPopup } from './gpx-layer-popup'; import { waypointPopup, trackpointPopup } from './gpx-layer-popup';
import {
ListTrackSegmentItem,
ListWaypointItem,
ListWaypointsItem,
ListTrackItem,
ListFileItem,
ListRootItem,
} from '$lib/components/file-list/file-list';
import { getClosestLinePoint, getElevation, loadSVGIcon } from '$lib/utils'; import { getClosestLinePoint, getElevation, loadSVGIcon } from '$lib/utils';
import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint'; import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint';
import { MapPin, Square } from 'lucide-static'; import { MapPin, Square } from 'lucide-static';
import { getSymbolKey, symbols } from '$lib/assets/symbols'; import { getSymbolKey, symbols } from '$lib/assets/symbols';
import type { GPXFileWithStatistics } from '$lib/logic/statistics-tree'; import { fileStateCollection } from '$lib/logic/file-state';
import { selection } from '$lib/logic/selection'; import { engine, type FileState, type Selection } from '$lib/engine';
import { isCovered, hasSelectionWithin, type FileTreeNode } from '$lib/selection-helpers';
import { isSegmentHidden, isWaypointHidden } from '$lib/file-visibility';
import { settings } from '$lib/logic/settings'; import { settings } from '$lib/logic/settings';
import { currentTool, Tool } from '$lib/components/toolbar/tools'; import { currentTool, Tool } from '$lib/components/toolbar/tools';
import { fileActionManager } from '$lib/logic/file-action-manager'; import { fileActionManager } from '$lib/logic/file-action-manager';
@@ -28,58 +23,6 @@ import { fileActions } from '$lib/logic/file-actions';
import { splitAs } from '$lib/components/toolbar/tools/scissors/scissors'; import { splitAs } from '$lib/components/toolbar/tools/scissors/scissors';
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor'; import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style'; import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import { gpxColors } from '$lib/components/map/gpx-layer/gpx-layers';
const colors = [
'#ff0000',
'#0000ff',
'#46e646',
'#00ccff',
'#ff9900',
'#ff00ff',
'#ffff32',
'#288228',
'#9933ff',
'#50f0be',
'#8c645a',
];
const colorCount: { [key: string]: number } = {};
for (let color of colors) {
colorCount[color] = 0;
}
// Get the color with the least amount of uses
function getColor(fileId: string) {
let color = colors.reduce((a, b) => (colorCount[a] <= colorCount[b] ? a : b));
colorCount[color]++;
gpxColors.update((colors) => {
colors.set(fileId, color);
return colors;
});
return color;
}
function replaceColor(fileId: string, oldColor: string, newColor: string) {
if (colorCount.hasOwnProperty(oldColor)) {
colorCount[oldColor]--;
}
colorCount[newColor]++;
gpxColors.update((colors) => {
colors.set(fileId, newColor);
return colors;
});
}
function removeColor(fileId: string, color: string) {
if (colorCount.hasOwnProperty(color)) {
colorCount[color]--;
}
gpxColors.update((colors) => {
colors.delete(fileId);
return colors;
});
}
export function getSvgForSymbol(symbol?: string | undefined, layerColor?: string | undefined) { export function getSvgForSymbol(symbol?: string | undefined, layerColor?: string | undefined) {
let symbolSvg = symbol ? symbols[symbol]?.iconSvg : undefined; let symbolSvg = symbol ? symbols[symbol]?.iconSvg : undefined;
@@ -115,8 +58,9 @@ const { directionMarkers, treeFileView, defaultOpacity, defaultWidth } = setting
export class GPXLayer { export class GPXLayer {
fileId: string; fileId: string;
file: Readable<GPXFileWithStatistics | undefined>; file: Readable<FileState>;
layerColor: string; layerColor: string = '';
selectionState: Selection = { type: 'empty' };
selected: boolean = false; selected: boolean = false;
currentWaypointData: GeoJSON.FeatureCollection | null = null; currentWaypointData: GeoJSON.FeatureCollection | null = null;
draggedWaypointIndex: number | null = null; draggedWaypointIndex: number | null = null;
@@ -144,10 +88,9 @@ export class GPXLayer {
waypointLayerOnMouseUpBinded: (e: MapLayerMouseEvent | MapLayerTouchEvent) => void = waypointLayerOnMouseUpBinded: (e: MapLayerMouseEvent | MapLayerTouchEvent) => void =
this.waypointLayerOnMouseUp.bind(this); this.waypointLayerOnMouseUp.bind(this);
constructor(fileId: string, file: Readable<GPXFileWithStatistics | undefined>) { constructor(fileId: string, file: Readable<FileState>) {
this.fileId = fileId; this.fileId = fileId;
this.file = file; this.file = file;
this.layerColor = getColor(fileId);
this.unsubscribe.push( this.unsubscribe.push(
map.subscribe(($map) => { map.subscribe(($map) => {
if ($map) { if ($map) {
@@ -158,8 +101,9 @@ export class GPXLayer {
); );
this.unsubscribe.push(file.subscribe(this.updateBinded)); this.unsubscribe.push(file.subscribe(this.updateBinded));
this.unsubscribe.push( this.unsubscribe.push(
selection.subscribe(($selection) => { engine.selection.subscribe(($selection) => {
let newSelected = $selection.hasAnyChildren(new ListFileItem(this.fileId)); this.selectionState = $selection;
let newSelected = hasSelectionWithin($selection, this.fileNode());
if (this.selected || newSelected) { if (this.selected || newSelected) {
this.selected = newSelected; this.selected = newSelected;
this.update(); this.update();
@@ -172,21 +116,29 @@ export class GPXLayer {
this.unsubscribe.push(directionMarkers.subscribe(this.updateBinded)); this.unsubscribe.push(directionMarkers.subscribe(this.updateBinded));
} }
fileNode(): FileTreeNode {
return { type: 'file', fileId: this.fileId };
}
segmentNode(properties: GeoJSON.GeoJsonProperties): FileTreeNode {
return {
type: 'segment',
fileId: this.fileId,
trackId: properties!.trackId,
segmentId: properties!.segmentId,
};
}
update() { update() {
const _map = get(map); const _map = get(map);
const layerEventManager = map.layerEventManager; const layerEventManager = map.layerEventManager;
let file = get(this.file)?.file; const state = get(this.file);
if (!_map || !layerEventManager || !file) { if (!_map || !layerEventManager) {
return; return;
} }
if ( if (this.layerColor !== state.color) {
file._data.style && this.layerColor = state.color;
file._data.style.color &&
this.layerColor !== `#${file._data.style.color}`
) {
replaceColor(this.fileId, this.layerColor, `#${file._data.style.color}`);
this.layerColor = `#${file._data.style.color}`;
} }
this.loadIcons(); this.loadIcons();
@@ -228,16 +180,16 @@ export class GPXLayer {
layerEventManager.on('mousemove', this.fileId, this.layerOnMouseMoveBinded); layerEventManager.on('mousemove', this.fileId, this.layerOnMouseMoveBinded);
} }
let visibleTrackSegmentIds: string[] = []; const visibleSegmentIds = state.segments.features
file.forEachSegment((segment, trackIndex, segmentIndex) => { .filter(
if (!segment._data.hidden) { ({ properties }) =>
visibleTrackSegmentIds.push(`${trackIndex}-${segmentIndex}`); !isSegmentHidden(state, properties.trackId, properties.segmentId)
} )
}); .map(({ properties }) => properties.segmentId);
const segmentFilter: FilterSpecification = [ const segmentFilter: FilterSpecification = [
'in', 'in',
['get', 'trackSegmentId'], ['get', 'segmentId'],
['literal', visibleTrackSegmentIds], ['literal', visibleSegmentIds],
]; ];
_map.setFilter(this.fileId, segmentFilter, { validate: false }); _map.setFilter(this.fileId, segmentFilter, { validate: false });
@@ -334,12 +286,9 @@ export class GPXLayer {
); );
} }
let visibleWaypoints: number[] = []; const visibleWaypoints = state.waypoints.features
file.wpt.forEach((waypoint, waypointIndex) => { .filter(({ properties }) => !isWaypointHidden(state, properties.waypointId))
if (!waypoint._data.hidden) { .map(({ properties }) => properties.index);
visibleWaypoints.push(waypointIndex);
}
});
_map.setFilter( _map.setFilter(
this.fileId + '-waypoints', this.fileId + '-waypoints',
@@ -413,8 +362,6 @@ export class GPXLayer {
} }
this.unsubscribe.forEach((unsubscribe) => unsubscribe()); this.unsubscribe.forEach((unsubscribe) => unsubscribe());
removeColor(this.fileId, this.layerColor);
} }
moveToFront() { moveToFront() {
@@ -434,14 +381,9 @@ export class GPXLayer {
} }
layerOnMouseEnter(e: any) { layerOnMouseEnter(e: any) {
let trackIndex = e.features[0].properties.trackIndex;
let segmentIndex = e.features[0].properties.segmentIndex;
if ( if (
get(currentTool) === Tool.SCISSORS && get(currentTool) === Tool.SCISSORS &&
get(selection).hasAnyParent( isCovered(this.selectionState, this.segmentNode(e.features[0].properties))
new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex)
)
) { ) {
mapCursor.notify(MapCursorState.SCISSORS, true); mapCursor.notify(MapCursorState.SCISSORS, true);
} else { } else {
@@ -459,66 +401,62 @@ export class GPXLayer {
let trackIndex = e.features[0].properties.trackIndex; let trackIndex = e.features[0].properties.trackIndex;
let segmentIndex = e.features[0].properties.segmentIndex; let segmentIndex = e.features[0].properties.segmentIndex;
const file = get(this.file)?.file; // TODO needs the trackpoints of the previous implementation (see oldFile)
if (file) { // const file = null;
const closest = getClosestLinePoint( // if (file) {
file.trk[trackIndex].trkseg[segmentIndex].trkpt, // const closest = getClosestLinePoint(
{ lat: e.lngLat.lat, lon: e.lngLat.lng } // file.trk[trackIndex].trkseg[segmentIndex].trkpt,
); // { lat: e.lngLat.lat, lon: e.lngLat.lng }
trackpointPopup?.setItem({ item: closest, fileId: this.fileId }); // );
} // trackpointPopup?.setItem({ item: closest, fileId: this.fileId });
// }
} }
} }
layerOnClick(e: MapLayerMouseEvent) { layerOnClick(e: MapLayerMouseEvent) {
const properties = e.features![0].properties!;
const { trackId, segmentId, trackIndex, segmentIndex } = properties;
const selectionType = this.selectionState.type;
if ( if (
get(currentTool) === Tool.ROUTING && get(currentTool) === Tool.ROUTING &&
get(selection).hasAnyChildren(new ListRootItem(), true, ['waypoints']) selectionType !== 'empty' &&
selectionType !== 'waypoints' &&
selectionType !== 'waypoint'
) { ) {
return; return;
} }
let trackIndex = e.features![0].properties!.trackIndex;
let segmentIndex = e.features![0].properties!.segmentIndex;
if ( if (
get(currentTool) === Tool.SCISSORS && get(currentTool) === Tool.SCISSORS &&
get(selection).hasAnyParent( isCovered(this.selectionState, this.segmentNode(properties))
new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex)
)
) { ) {
if (get(map)?.queryRenderedFeatures(e.point, { layers: ['split-controls'] }).length) { if (get(map)?.queryRenderedFeatures(e.point, { layers: ['split-controls'] }).length) {
// Clicked on split control, ignoring // Clicked on split control, ignoring
return; return;
} }
fileActions.split(get(splitAs), this.fileId, trackIndex, segmentIndex, { // TODO the engine can split (Command::Split) but needs the index of the trackpoint
lat: e.lngLat.lat, // fileActions.split(get(splitAs), this.fileId, trackIndex, segmentIndex, {
lon: e.lngLat.lng, // lat: e.lngLat.lat,
}); // lon: e.lngLat.lng,
// });
return; return;
} }
let file = get(this.file)?.file; const add = e.originalEvent.ctrlKey || e.originalEvent.metaKey;
if (!file) { const { tracks } = get(this.file).structure;
return; const segmentCount = tracks.reduce((count, track) => count + track.segments.length, 0);
} if (get(treeFileView) && segmentCount > 1) {
let item = undefined;
if (get(treeFileView) && file.getSegments().length > 1) {
// Select inner item // Select inner item
item = const track = tracks.find((track) => track.id === trackId);
file.children[trackIndex].children.length > 1 if (track && track.segments.length > 1) {
? new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex) engine.selectSegments(this.fileId, trackId, [segmentId], add);
: new ListTrackItem(this.fileId, trackIndex); } else {
engine.selectTracks(this.fileId, [trackId], add);
}
} else { } else {
item = new ListFileItem(this.fileId); engine.select([this.fileId], add);
}
if (e.originalEvent.ctrlKey || e.originalEvent.metaKey) {
selection.addSelectItem(item);
} else {
selection.selectItem(item);
} }
} }
@@ -532,14 +470,12 @@ export class GPXLayer {
if (this.draggedWaypointIndex !== null) { if (this.draggedWaypointIndex !== null) {
return; return;
} }
let file = get(this.file)?.file;
if (!file) {
return;
}
let waypointIndex = e.features![0].properties!.waypointIndex; // TODO the popup needs the waypoint of the previous implementation (see oldFile)
let waypoint = file.wpt[waypointIndex]; // let waypoint = this.oldFile?.wpt[e.features![0].properties!.waypointIndex];
waypointPopup?.setItem({ item: waypoint, fileId: this.fileId }); // if (waypoint) {
// waypointPopup?.setItem({ item: waypoint, fileId: this.fileId });
// }
mapCursor.notify(MapCursorState.WAYPOINT_HOVER, true); mapCursor.notify(MapCursorState.WAYPOINT_HOVER, true);
} }
@@ -551,41 +487,43 @@ export class GPXLayer {
waypointLayerOnClick(e: MapLayerMouseEvent) { waypointLayerOnClick(e: MapLayerMouseEvent) {
e.preventDefault(); e.preventDefault();
let waypointIndex = e.features![0].properties!.waypointIndex; const { waypointIndex, waypointId } = e.features![0].properties!;
let file = get(this.file)?.file; // TODO the popup and the waypoint tool need the waypoint of the previous implementation
if (!file) {
return;
}
let waypoint = file.wpt[waypointIndex];
if (get(currentTool) === Tool.WAYPOINT) { if (get(currentTool) === Tool.WAYPOINT) {
if (this.selected) { if (this.selected) {
if (e.originalEvent.shiftKey) { if (e.originalEvent.shiftKey) {
fileActions.deleteWaypoint(this.fileId, waypointIndex); // TODO
// fileActions.deleteWaypoint(this.fileId, waypointIndex);
} else { } else {
selection.selectItem(new ListWaypointItem(this.fileId, waypointIndex)); engine.selectWaypoints(this.fileId, [waypointId]);
selectedWaypoint.set([waypoint, this.fileId]); // TODO
// if (waypoint) {
// selectedWaypoint.set([waypoint, this.fileId]);
// }
} }
} else { } else {
if (get(treeFileView)) { if (get(treeFileView)) {
selection.selectItem(new ListWaypointItem(this.fileId, waypointIndex)); engine.selectWaypoints(this.fileId, [waypointId]);
} else { } else {
selection.selectItem(new ListFileItem(this.fileId)); engine.select([this.fileId]);
} }
selectedWaypoint.set([waypoint, this.fileId]); // TODO
// if (waypoint) {
// selectedWaypoint.set([waypoint, this.fileId]);
// }
} }
} else { } else {
if (get(treeFileView)) { if (get(treeFileView)) {
if ((e.originalEvent.ctrlKey || e.originalEvent.metaKey) && this.selected) { const add = e.originalEvent.ctrlKey || e.originalEvent.metaKey;
selection.addSelectItem(new ListWaypointItem(this.fileId, waypointIndex)); engine.selectWaypoints(this.fileId, [waypointId], add && this.selected);
} else {
selection.selectItem(new ListWaypointItem(this.fileId, waypointIndex));
}
} else { } else {
if (!this.selected) { if (!this.selected) {
selection.selectItem(new ListFileItem(this.fileId)); engine.select([this.fileId]);
} }
waypointPopup?.setItem({ item: waypoint, fileId: this.fileId }); // TODO
// if (waypoint) {
// waypointPopup?.setItem({ item: waypoint, fileId: this.fileId });
// }
} }
} }
} }
@@ -702,93 +640,58 @@ export class GPXLayer {
} }
getGeoJSON(): GeoJSON.FeatureCollection { getGeoJSON(): GeoJSON.FeatureCollection {
let file = get(this.file)?.file; const state = get(this.file);
if (!file) { const waypointsSelected = hasSelectionWithin(this.selectionState, {
return { type: 'waypoints',
type: 'FeatureCollection', fileId: this.fileId,
features: [], });
};
}
let data = file.toGeoJSON(); return {
type: 'FeatureCollection',
let trackIndex = 0, features: state.segments.features.map((feature) => {
segmentIndex = 0; const properties = {
for (let feature of data.features) { ...feature.properties,
if (!feature.properties) { opacity: feature.properties.opacity ?? get(defaultOpacity),
feature.properties = {}; width: feature.properties.width ?? get(defaultWidth),
} };
if (!feature.properties.color) { if (
feature.properties.color = this.layerColor; isCovered(this.selectionState, this.segmentNode(properties)) ||
} waypointsSelected
if (!feature.properties.opacity) { ) {
feature.properties.opacity = get(defaultOpacity); properties.width = properties.width + 2;
} properties.opacity = Math.min(1, properties.opacity + 0.1);
if (!feature.properties.width) { }
feature.properties.width = get(defaultWidth); return { ...feature, properties };
} }),
if ( };
get(selection).hasAnyParent(
new ListTrackSegmentItem(this.fileId, trackIndex, segmentIndex)
) ||
get(selection).hasAnyChildren(new ListWaypointsItem(this.fileId), true)
) {
feature.properties.width = feature.properties.width + 2;
feature.properties.opacity = Math.min(1, feature.properties.opacity + 0.1);
}
feature.properties.trackIndex = trackIndex;
feature.properties.segmentIndex = segmentIndex;
feature.properties.trackSegmentId = `${trackIndex}-${segmentIndex}`;
segmentIndex++;
if (segmentIndex >= file.trk[trackIndex].trkseg.length) {
segmentIndex = 0;
trackIndex++;
}
}
return data;
} }
getWaypointsGeoJSON(): GeoJSON.FeatureCollection { getWaypointsGeoJSON(): GeoJSON.FeatureCollection {
let file = get(this.file)?.file; return {
let data: GeoJSON.FeatureCollection = {
type: 'FeatureCollection', type: 'FeatureCollection',
features: [], features: get(this.file).waypoints.features.map((feature) => ({
};
if (!file) {
return data;
}
file.wpt.forEach((waypoint, index) => {
data.features.push({
type: 'Feature', type: 'Feature',
geometry: { // copied: the coordinates are changed while a waypoint is dragged
type: 'Point', geometry: { type: 'Point', coordinates: [...feature.geometry.coordinates] },
coordinates: [waypoint.getLongitude(), waypoint.getLatitude()],
},
properties: { properties: {
fileId: this.fileId, fileId: this.fileId,
waypointIndex: index, waypointId: feature.properties.waypointId,
icon: `waypoint-${getSymbolKey(waypoint.sym) ?? 'default'}-${this.layerColor}`, waypointIndex: feature.properties.index,
icon: `waypoint-${getSymbolKey(feature.properties.sym) ?? 'default'}-${this.layerColor}`,
}, },
}); })),
}); };
return data;
} }
loadIcons() { loadIcons() {
const _map = get(map); const _map = get(map);
let file = get(this.file)?.file; if (!_map) {
if (!_map || !file) {
return; return;
} }
let symbols = new Set<string | undefined>(); let symbols = new Set<string | undefined>();
file.wpt.forEach((waypoint) => { get(this.file).waypoints.features.forEach((feature) => {
symbols.add(getSymbolKey(waypoint.sym)); symbols.add(getSymbolKey(feature.properties.sym));
}); });
symbols.forEach((symbol) => { symbols.forEach((symbol) => {
@@ -1,10 +1,10 @@
import { GPXFileStateCollectionObserver } from '$lib/logic/file-state'; import { FileStateCollectionObserver } from '$lib/engine';
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import { GPXLayer } from './gpx-layer'; import { GPXLayer } from './gpx-layer';
export class GPXLayerCollection { export class GPXLayerCollection {
private _layers: Map<string, GPXLayer>; private _layers: Map<string, GPXLayer>;
private _fileStateCollectionObserver: GPXFileStateCollectionObserver | null = null; private _fileStateCollectionObserver: FileStateCollectionObserver | null = null;
constructor() { constructor() {
this._layers = new Map<string, GPXLayer>(); this._layers = new Map<string, GPXLayer>();
@@ -14,10 +14,10 @@ export class GPXLayerCollection {
if (this._fileStateCollectionObserver) { if (this._fileStateCollectionObserver) {
return; return;
} }
this._fileStateCollectionObserver = new GPXFileStateCollectionObserver( this._fileStateCollectionObserver = new FileStateCollectionObserver(
(newFiles) => { (newFiles) => {
newFiles.forEach((fileState, fileId) => { newFiles.forEach((fileStore, fileId) => {
const layer = new GPXLayer(fileId, fileState); const layer = new GPXLayer(fileId, fileStore);
this._layers.set(fileId, layer); this._layers.set(fileId, layer);
}); });
}, },