Files
gpx.studio/website/src/lib/components/toolbar/tools/waypoint/waypoint.ts

76 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-10-05 19:34:05 +02:00
import { ListWaypointItem } from '$lib/components/file-list/file-list';
2025-10-17 23:54:45 +02:00
import { fileStateCollection } from '$lib/logic/file-state';
import { selection } from '$lib/logic/selection';
import { settings } from '$lib/logic/settings';
2025-10-05 19:34:05 +02:00
import type { Waypoint } from 'gpx';
2025-10-17 23:54:45 +02:00
import { get, writable, type Writable } from 'svelte/store';
2025-10-05 19:34:05 +02:00
export class WaypointSelection {
2025-10-17 23:54:45 +02:00
private _selection: Writable<[Waypoint, string] | undefined>;
2025-10-18 16:10:08 +02:00
private _fileUnsubscribe: (() => void) | undefined;
2025-10-05 19:34:05 +02:00
constructor() {
2025-10-17 23:54:45 +02:00
this._selection = writable(undefined);
settings.treeFileView.subscribe(() => {
this.update();
});
selection.subscribe(() => {
this.update();
});
}
2025-10-18 16:10:08 +02:00
subscribe(
run: (value: [Waypoint, string] | undefined) => void,
invalidate?: (value?: [Waypoint, string] | undefined) => void
) {
return this._selection.subscribe(run, invalidate);
}
set(value: [Waypoint, string] | undefined) {
this._selection.set(value);
}
2025-10-17 23:54:45 +02:00
update() {
2025-10-18 16:10:08 +02:00
if (this._fileUnsubscribe) {
this._fileUnsubscribe();
this._fileUnsubscribe = undefined;
}
2025-10-17 23:54:45 +02:00
this._selection.update(() => {
if (get(settings.treeFileView) && get(selection).size === 1) {
let item = get(selection).getSelected()[0];
2025-10-05 19:34:05 +02:00
if (item instanceof ListWaypointItem) {
2025-10-18 16:10:08 +02:00
let fileState = fileStateCollection.getFileState(item.getFileId());
if (fileState) {
let first = true;
this._fileUnsubscribe = fileState.subscribe(() => {
if (first) first = false;
else this.update();
});
let waypoint = fileState.file?.wpt[item.getWaypointIndex()];
if (waypoint) {
return [waypoint, item.getFileId()];
}
2025-10-05 19:34:05 +02:00
}
}
}
return undefined;
});
}
reset() {
2025-10-17 23:54:45 +02:00
this._selection.set(undefined);
2025-10-05 19:34:05 +02:00
}
get wpt(): Waypoint | undefined {
2025-10-17 23:54:45 +02:00
const selection = get(this._selection);
return selection ? selection[0] : undefined;
2025-10-05 19:34:05 +02:00
}
get fileId(): string | undefined {
2025-10-17 23:54:45 +02:00
const selection = get(this._selection);
return selection ? selection[1] : undefined;
2025-10-05 19:34:05 +02:00
}
}
export const selectedWaypoint = new WaypointSelection();