Files
gpx.studio/website/src/lib/components/toolbar/tools/scissors/split-controls.ts
T
vcoppeandvcoppe 8fe7d8d64d Migration to new Rust-based engine (#401)
* wasm first steps

* parsing start

* parsing continued

* progress

* progress

* progress

* progress

* progress

* progress

* progress

* progress

* fixes

* reorganize

* change type

* fix

* progress

* refactoring

* progress

* progress

* progress

* keep style info

* progress

* progress

* remove (copy) in name

* progress

* merge methods into 1

* splice

* progress

* progress

* progress

* cleaning

* progress

* progress

* progress

* visibility

* progress

* progress

* progress

* progress

* progress

* fixes

* progress

* fix markers

* fix

* progress

* progress

* progress

* progress

* progress

* progress

* small fix

* use engine info

* fix popups

* small fix

* progress

* progress

* progress

* clean tool

* handle self closing elements

* reduce data exchanges across boundary

* copy on wasm side to avoid any data corruption

* speed fix

* routing

* refactoring

* reverse

* reverse

* crop

* split

* merge

* progress

* time tool

* fix bounds for waypoints

* reduce

* fix reactivity

* handle corrupt time data

* export

* progress

* remove gpx js package

* remove todo

* update readme

* cleaning

* progress

* fix link fields

* remove unused fields

* refactoring and tests

* import and export of routes, ref #192

* per-chunk categories storage

* cross-tab sync

* outdated state

* refactoring

* reorder methods

* refactoring

* fix

* improve flow

* renaming

* progress

* progress

* fix

* progress

* per file history

* keep original flag

* use history variant

* fix

* progress

* file explorer

* progress

* fix

* sticky folders

* improved sticky folders

* fix sortable

* fix sortable

* fix

* fix tab size

* no file delete on desktop

* fix routing on other file

* fix sorting

* remember language

* open links in browser

* commit missing changes

* avoid selecting on resize

* clarify filename

* explorer actions

* fix folder styling

* drop anywhere in folder

* cleaning

* fixes

* remove focus-ring

* full screen

* small fix

* consistent highlight color

* improved preview

* performance improvements

* sparser data transfers

* sparser data transfers

* show popup once data is loaded

* fix routing control size

* fix

* sparse desktop build

* remove custom ign styles

* use new endpoint for openhikingmap

* strip native menu

* reorder context menu items

* route full support

* route - track conversion

* create route file action

* route export, filter out anchors at high zoom level

* clarify name handling

* move hide & center to view

* routes continued

* update docs

* fix power format, closes #378

* lint fixes

* fix display of additional data with gaps, closes #361

* fix linting issues

* fix import modules

* fix multidrag

* change base to resolve

* fix type errors

* fix layer typings

* fix last type error

* each keys

* improve typings

* deploy to cloudflare

---------

Co-authored-by: vcoppe <vcoppe@hexaly.com>
2026-10-31 18:08:22 +01:00

201 lines
7.4 KiB
TypeScript

import { currentTool, Tool } from '$lib/components/toolbar/tools';
import { cuts, routeSegmentIds, splitAs } from '$lib/components/toolbar/tools/scissors/scissors';
import { Scissors } from 'lucide-static';
import { get } from 'svelte/store';
import { mapCursor, MapCursorState } from '$lib/state/map-cursor';
import type { GeoJSONSource, Map, MapLayerMouseEvent } from 'maplibre-gl';
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
import type { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
import { loadSVGIcon } from '$lib/utils';
import { coversSegments } from '$lib/engine/selection-helpers';
import {
engine,
type Selection,
type SelectionStatistics,
type StatisticsRequest,
} from '$lib/engine';
/**
* The anchors inside the segments of the selection, where a click splits the file, the route, the
* track or the segment: a command of the engine, which finds them by the index of their trackpoint
* in the selection. Only the segments that can be split as `splitAs` says have them.
*/
export class SplitControls {
map: Map;
layerEventManager: MapLayerEventManager;
unsubscribes: (() => void)[] = [];
/** What the tool needs from the engine, while it shows the anchors. */
request: StatisticsRequest = engine.requestStatistics();
selection: Selection = { type: 'empty' };
statistics: SelectionStatistics | undefined = undefined;
layerOnMouseEnterBinded: () => void = this.layerOnMouseEnter.bind(this);
layerOnMouseLeaveBinded: () => void = this.layerOnMouseLeave.bind(this);
layerOnClickBinded: (e: MapLayerMouseEvent) => void = this.layerOnClick.bind(this);
constructor(map: Map, layerEventManager: MapLayerEventManager) {
this.map = map;
this.layerEventManager = layerEventManager;
loadSVGIcon(
this.map,
'split-control',
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">
<circle cx="20" cy="20" r="20" fill="white" />
<g transform="translate(8 8)">
${Scissors.replace('stroke="currentColor"', 'stroke="black"')}
</g>
</svg>`
);
this.unsubscribes.push(
engine.statistics.subscribe((statistics) => {
this.statistics = statistics;
this.addIfNeeded();
})
);
this.unsubscribes.push(currentTool.subscribe(this.addIfNeeded.bind(this)));
this.unsubscribes.push(splitAs.subscribe(this.addIfNeeded.bind(this)));
this.unsubscribes.push(
engine.selection.subscribe((selection) => {
this.selection = selection;
this.addIfNeeded();
})
);
}
addIfNeeded() {
// the tool works on files, routes, tracks and segments, not on waypoints
const scissors = get(currentTool) === Tool.SCISSORS && coversSegments(this.selection);
this.request.set(scissors ? ['anchors'] : []);
if (!scissors) {
this.remove();
return;
}
this.updateControls();
}
/** The anchors that are inside a segment, which is not where it starts or ends. */
inner(): GeoJSON.Feature[] {
const statistics = this.statistics;
const anchors = statistics?.anchors;
if (!statistics || !anchors) {
return [];
}
const starts = anchors.segmentStarts;
const routeSegments = routeSegmentIds(this.selection);
const type = get(splitAs);
const features: GeoJSON.Feature[] = [];
let segment = 0;
for (let i = 0; i < anchors.indices.length; i++) {
const index = anchors.indices[i];
// the anchors are sorted: the segment can only be the same or a following one
while (segment + 1 < starts.length && starts[segment + 1] <= index) {
segment++;
}
const end = segment + 1 < starts.length ? starts[segment + 1] : statistics.length;
const inRoute = routeSegments.has(anchors.segmentIds[segment]);
if (index > starts[segment] && index < end - 1 && cuts(type, inRoute)) {
features.push({
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [statistics.lng[index], statistics.lat[index]],
},
properties: { index, minZoom: anchors.zooms[i] },
});
}
}
return features;
}
updateControls() {
const data: GeoJSON.FeatureCollection = {
type: 'FeatureCollection',
features: this.inner(),
};
try {
const source = this.map.getSource('split-controls') as GeoJSONSource | undefined;
if (source) {
source.setData(data);
} else {
this.map.addSource('split-controls', {
type: 'geojson',
data: data,
});
}
if (!this.map.getLayer('split-controls')) {
this.map.addLayer(
{
id: 'split-controls',
type: 'symbol',
source: 'split-controls',
layout: {
'icon-image': 'split-control',
'icon-size': 0.25,
'icon-padding': 0,
},
filter: ['<=', ['get', 'minZoom'], ['zoom']],
},
ANCHOR_LAYER_KEY.interactions
);
this.layerEventManager.on(
'mouseenter',
'split-controls',
this.layerOnMouseEnterBinded
);
this.layerEventManager.on(
'mouseleave',
'split-controls',
this.layerOnMouseLeaveBinded
);
this.layerEventManager.on('click', 'split-controls', this.layerOnClickBinded);
}
} catch {
// No reliable way to check if the map is ready to add sources and layers
}
}
remove() {
this.layerEventManager.off('mouseenter', 'split-controls', this.layerOnMouseEnterBinded);
this.layerEventManager.off('mouseleave', 'split-controls', this.layerOnMouseLeaveBinded);
this.layerEventManager.off('click', 'split-controls', this.layerOnClickBinded);
try {
if (this.map.getLayer('split-controls')) {
this.map.removeLayer('split-controls');
}
if (this.map.getSource('split-controls')) {
this.map.removeSource('split-controls');
}
} catch {
// No reliable way to check if the map is ready to remove sources and layers
}
}
layerOnMouseEnter() {
mapCursor.notify(MapCursorState.SPLIT_CONTROL, true);
}
layerOnMouseLeave() {
mapCursor.notify(MapCursorState.SPLIT_CONTROL, false);
}
layerOnClick(e: MapLayerMouseEvent) {
const revision = this.statistics?.anchors?.revision;
if (revision !== undefined) {
engine.split(revision, e.features![0].properties!.index, get(splitAs));
}
}
destroy() {
this.remove();
this.request.release();
this.unsubscribes.forEach((unsubscribe) => unsubscribe());
}
}