mirror of
https://github.com/gpxstudio/gpx.studio.git
synced 2026-10-06 22:04:06 +00:00
fix popups
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
use crate::{
|
||||
Clean, Crop, Delete, DeleteAll, Duplicate, Elevation, Extract, Load, LoadFiles, Merge,
|
||||
Metadata, Move, MoveWaypoint, New, NewTrack, NewTrackSegment, NewWaypoint, Paste, Reverse,
|
||||
SpliceTrackpoints, Split, Style, Time,
|
||||
Clean, Crop, Delete, DeleteAll, DeleteWaypoint, Duplicate, EditWaypoint, Elevation, Extract,
|
||||
Load, LoadFiles, Merge, Metadata, Move, MoveWaypoint, New, NewTrack, NewTrackSegment,
|
||||
NewWaypoint, Paste, Reverse, SpliceTrackpoints, Split, Style, Time,
|
||||
};
|
||||
|
||||
/// A user action that edits the files. Each variant wraps the command's own struct, whose
|
||||
@@ -20,6 +20,7 @@ pub enum Command<'a> {
|
||||
Paste(Paste),
|
||||
Move(Move),
|
||||
DeleteAll(DeleteAll),
|
||||
DeleteWaypoint(DeleteWaypoint),
|
||||
Metadata(Metadata<'a>),
|
||||
Style(Style<'a>),
|
||||
NewTrack(NewTrack),
|
||||
@@ -27,6 +28,7 @@ pub enum Command<'a> {
|
||||
Reverse(Reverse),
|
||||
SpliceTrackpoints(SpliceTrackpoints<'a>),
|
||||
NewWaypoint(NewWaypoint<'a>),
|
||||
EditWaypoint(EditWaypoint<'a>),
|
||||
MoveWaypoint(MoveWaypoint),
|
||||
Crop(Crop),
|
||||
Split(Split),
|
||||
@@ -48,6 +50,7 @@ impl Apply for Command<'_> {
|
||||
Command::Paste(c) => c.apply(state),
|
||||
Command::Move(c) => c.apply(state),
|
||||
Command::DeleteAll(c) => c.apply(state),
|
||||
Command::DeleteWaypoint(c) => c.apply(state),
|
||||
Command::Metadata(c) => c.apply(state),
|
||||
Command::Style(c) => c.apply(state),
|
||||
Command::NewTrack(c) => c.apply(state),
|
||||
@@ -55,6 +58,7 @@ impl Apply for Command<'_> {
|
||||
Command::Reverse(c) => c.apply(state),
|
||||
Command::SpliceTrackpoints(c) => c.apply(state),
|
||||
Command::NewWaypoint(c) => c.apply(state),
|
||||
Command::EditWaypoint(c) => c.apply(state),
|
||||
Command::MoveWaypoint(c) => c.apply(state),
|
||||
Command::Crop(c) => c.apply(state),
|
||||
Command::Split(c) => c.apply(state),
|
||||
|
||||
@@ -76,7 +76,7 @@ impl Apply for Delete {
|
||||
}
|
||||
}
|
||||
|
||||
fn delete_waypoints(
|
||||
pub(crate) fn delete_waypoints(
|
||||
files: &mut StackEntry,
|
||||
file_id: FileId,
|
||||
filter: impl Fn(&Waypoint) -> bool,
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
use crate::{Apply, CommandError, FileId, Selection, State, WaypointId, delete_waypoints};
|
||||
|
||||
/// Deletes a waypoint of a file, whatever is selected (what the delete button of its popup does).
|
||||
/// If it was the only selected element, its file gets selected.
|
||||
#[derive(Debug)]
|
||||
pub struct DeleteWaypoint {
|
||||
pub file_id: FileId,
|
||||
pub waypoint_id: WaypointId,
|
||||
}
|
||||
|
||||
impl Apply for DeleteWaypoint {
|
||||
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||
delete_waypoints(state.files, self.file_id, |wpt| wpt.id == self.waypoint_id)?;
|
||||
if let Selection::Waypoint { file_id, wpt_ids } = &*state.selection
|
||||
&& *file_id == self.file_id
|
||||
&& wpt_ids.iter().all(|id| *id == self.waypoint_id)
|
||||
{
|
||||
*state.selection = Selection::File {
|
||||
file_ids: [self.file_id].into(),
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{
|
||||
File, Selection, Waypoint, WaypointChunk, engine::command::fixture::Fixture, waypoint_ids,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_deletes_one_waypoint_without_touching_the_selection() {
|
||||
let mut fx = Fixture::default();
|
||||
let mut file = File::default();
|
||||
file.wpt.push(Rc::new(WaypointChunk {
|
||||
wpt: (0..3)
|
||||
.map(|i| Waypoint {
|
||||
name: Some(format!("w{i}")),
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}));
|
||||
let id = file.id;
|
||||
let ids: Vec<_> = waypoint_ids(&file).collect();
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
fx.order.0.push(id);
|
||||
fx.selection = Selection::File {
|
||||
file_ids: [id].into(),
|
||||
};
|
||||
|
||||
DeleteWaypoint {
|
||||
file_id: id,
|
||||
waypoint_id: ids[1],
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
|
||||
let names: Vec<_> = fx.files[&id]
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|chunk| &chunk.wpt)
|
||||
.map(|wpt| wpt.name.clone().unwrap())
|
||||
.collect();
|
||||
assert_eq!(names, ["w0", "w2"]);
|
||||
assert_eq!(
|
||||
fx.selection,
|
||||
Selection::File {
|
||||
file_ids: [id].into()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deleting_the_selected_waypoint_selects_its_file() {
|
||||
let mut fx = Fixture::default();
|
||||
let mut file = File::default();
|
||||
file.wpt.push(Rc::new(WaypointChunk {
|
||||
wpt: vec![Waypoint::default(), Waypoint::default()],
|
||||
..Default::default()
|
||||
}));
|
||||
let id = file.id;
|
||||
let ids: Vec<_> = waypoint_ids(&file).collect();
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
fx.selection = Selection::Waypoint {
|
||||
file_id: id,
|
||||
wpt_ids: [ids[0]].into(),
|
||||
};
|
||||
DeleteWaypoint {
|
||||
file_id: id,
|
||||
waypoint_id: ids[0],
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fx.selection,
|
||||
Selection::File {
|
||||
file_ids: [id].into()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_waypoint_is_nothing_to_do() {
|
||||
let mut fx = Fixture::default();
|
||||
let file = File::default();
|
||||
let id = file.id;
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
let result = DeleteWaypoint {
|
||||
file_id: id,
|
||||
waypoint_id: WaypointId::default(),
|
||||
}
|
||||
.apply(&mut fx.state());
|
||||
assert!(matches!(result, Err(CommandError::NothingToDo)));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
mod delete;
|
||||
mod delete_all;
|
||||
mod delete_waypoint;
|
||||
mod duplicate;
|
||||
mod load;
|
||||
mod move_elements;
|
||||
@@ -9,6 +10,7 @@ mod transfer;
|
||||
|
||||
pub use delete::*;
|
||||
pub use delete_all::*;
|
||||
pub use delete_waypoint::*;
|
||||
pub use duplicate::*;
|
||||
pub use load::*;
|
||||
pub use move_elements::*;
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
use crate::{
|
||||
Apply, CommandError, Edit, Editor, State, Waypoint, set_waypoint_fields, update_selected,
|
||||
};
|
||||
|
||||
/// Changes the selected waypoints (what the form of the waypoint tool does): their name,
|
||||
/// description, icon, link, position and elevation. The strings that are empty remove the field.
|
||||
#[derive(Debug)]
|
||||
pub struct EditWaypoint<'a> {
|
||||
pub lng: f64,
|
||||
pub lat: f64,
|
||||
pub ele: f64,
|
||||
pub name: &'a str,
|
||||
pub desc: &'a str,
|
||||
pub icon: &'a str,
|
||||
pub link: &'a str,
|
||||
}
|
||||
|
||||
impl Apply for EditWaypoint<'_> {
|
||||
fn apply(mut self, state: &mut State) -> Result<(), CommandError> {
|
||||
update_selected(state, &mut self);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Editor for EditWaypoint<'_> {
|
||||
fn waypoint(&mut self, waypoint: &mut Waypoint) -> Edit {
|
||||
set_waypoint_fields(
|
||||
waypoint,
|
||||
(self.lng, self.lat, self.ele),
|
||||
self.name,
|
||||
self.desc,
|
||||
self.icon,
|
||||
self.link,
|
||||
);
|
||||
Edit::Changed
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{collections::HashSet, rc::Rc};
|
||||
|
||||
use crate::{
|
||||
File, Link, Selection, WaypointChunk, engine::command::fixture::Fixture, waypoint_ids,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_edit_the_selected_waypoint() {
|
||||
let mut fx = Fixture::default();
|
||||
let mut file = File::default();
|
||||
file.wpt.push(Rc::new(WaypointChunk {
|
||||
wpt: vec![
|
||||
Waypoint {
|
||||
name: Some("old".into()),
|
||||
desc: Some("old description".into()),
|
||||
cmt: Some("old comment".into()),
|
||||
sym: Some("Flag".into()),
|
||||
link: Some(Link {
|
||||
href: "https://old".into(),
|
||||
text: None,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
Waypoint {
|
||||
name: Some("other".into()),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
}));
|
||||
let id = file.id;
|
||||
let ids: Vec<_> = waypoint_ids(&file).collect();
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
fx.selection = Selection::Waypoint {
|
||||
file_id: id,
|
||||
wpt_ids: HashSet::from([ids[0]]),
|
||||
};
|
||||
|
||||
EditWaypoint {
|
||||
lng: 4.5,
|
||||
lat: 50.5,
|
||||
ele: 12.0,
|
||||
name: "new",
|
||||
desc: "new description",
|
||||
icon: "Summit",
|
||||
link: "",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
|
||||
let wpts: Vec<_> = fx.files[&id]
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|c| c.wpt.iter())
|
||||
.collect();
|
||||
let edited = wpts[0];
|
||||
assert_eq!(edited.id, ids[0]);
|
||||
assert_eq!(edited.name.as_deref(), Some("new"));
|
||||
assert_eq!(edited.desc.as_deref(), Some("new description"));
|
||||
assert_eq!(edited.cmt.as_deref(), Some("new description"));
|
||||
assert_eq!(edited.sym.as_deref(), Some("Summit"));
|
||||
// an empty link removes it
|
||||
assert!(edited.link.is_none());
|
||||
assert_eq!(
|
||||
(edited.coordinates.lng, edited.coordinates.lat, edited.ele),
|
||||
(4.5, 50.5, 12.0)
|
||||
);
|
||||
// the other waypoint is as it was
|
||||
assert_eq!(wpts[1].name.as_deref(), Some("other"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
mod clean;
|
||||
mod crop;
|
||||
mod edit_waypoint;
|
||||
mod elevation;
|
||||
mod extract;
|
||||
mod merge;
|
||||
@@ -12,6 +13,7 @@ mod time;
|
||||
|
||||
pub use clean::*;
|
||||
pub use crop::*;
|
||||
pub use edit_waypoint::*;
|
||||
pub use elevation::*;
|
||||
pub use extract::*;
|
||||
pub use merge::*;
|
||||
|
||||
@@ -1,15 +1,130 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{Apply, CommandError, FileId, LngLat, State, WaypointId, edit_waypoint_chunks};
|
||||
|
||||
/// Moves a waypoint of a file, whatever is selected (what a drag does): only its position and
|
||||
/// elevation change.
|
||||
#[derive(Debug)]
|
||||
pub struct MoveWaypoint {
|
||||
pub file_id: FileId,
|
||||
pub waypoint_id: WaypointId,
|
||||
pub lng: f64,
|
||||
pub lat: f64,
|
||||
pub ele: f64,
|
||||
}
|
||||
|
||||
impl Apply for MoveWaypoint {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("move waypoint"))
|
||||
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||
let file = state
|
||||
.files
|
||||
.get(&self.file_id)
|
||||
.ok_or(CommandError::NothingToDo)?;
|
||||
let mut file = (**file).clone();
|
||||
let changed = edit_waypoint_chunks(
|
||||
&mut file,
|
||||
|wpt| wpt.id == self.waypoint_id,
|
||||
|wpts| {
|
||||
for wpt in wpts.iter_mut().filter(|wpt| wpt.id == self.waypoint_id) {
|
||||
wpt.coordinates = LngLat {
|
||||
lng: self.lng,
|
||||
lat: self.lat,
|
||||
};
|
||||
wpt.ele = self.ele;
|
||||
}
|
||||
true
|
||||
},
|
||||
);
|
||||
if !changed {
|
||||
return Err(CommandError::NothingToDo);
|
||||
}
|
||||
state.files.insert(self.file_id, Rc::new(file));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{
|
||||
File, Selection, Waypoint, WaypointChunk, engine::command::fixture::Fixture, waypoint_ids,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn fixture() -> (Fixture, crate::FileId, Vec<crate::WaypointId>) {
|
||||
let mut fx = Fixture::default();
|
||||
let mut file = File::default();
|
||||
file.wpt.push(Rc::new(WaypointChunk {
|
||||
wpt: (0..3)
|
||||
.map(|i| Waypoint {
|
||||
name: Some(format!("w{i}")),
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}));
|
||||
let id = file.id;
|
||||
let ids = waypoint_ids(&file).collect();
|
||||
fx.files.insert(id, Rc::new(file));
|
||||
fx.order.0.push(id);
|
||||
(fx, id, ids)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_only_the_given_waypoint_moves_whatever_is_selected() {
|
||||
let (mut fx, id, ids) = fixture();
|
||||
let rev = fx.files[&id].wpt_rev_id;
|
||||
|
||||
MoveWaypoint {
|
||||
file_id: id,
|
||||
waypoint_id: ids[1],
|
||||
lng: 4.0,
|
||||
lat: 50.0,
|
||||
ele: 42.0,
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
|
||||
let wpts: Vec<_> = fx.files[&id]
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|c| c.wpt.iter())
|
||||
.collect();
|
||||
assert_eq!(wpts.len(), 3);
|
||||
assert_eq!(
|
||||
(
|
||||
wpts[1].coordinates.lng,
|
||||
wpts[1].coordinates.lat,
|
||||
wpts[1].ele
|
||||
),
|
||||
(4.0, 50.0, 42.0)
|
||||
);
|
||||
// the other fields and the other waypoints are as they were
|
||||
assert_eq!(wpts[1].name.as_deref(), Some("w1"));
|
||||
assert_eq!(wpts[1].id, ids[1]);
|
||||
assert_eq!((wpts[0].coordinates.lng, wpts[0].ele), (0.0, 0.0));
|
||||
assert_eq!((wpts[2].coordinates.lat, wpts[2].ele), (0.0, 0.0));
|
||||
// the coordinates changed, which is noticed by what is derived from them
|
||||
assert_ne!(fx.files[&id].wpt_rev_id, rev);
|
||||
assert_eq!(fx.selection, Selection::Empty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_unknown_waypoint_or_file_is_nothing_to_do() {
|
||||
let (mut fx, id, ids) = fixture();
|
||||
let before = fx.files[&id].clone();
|
||||
for (file_id, waypoint_id) in [(id, WaypointId::default()), (FileId::default(), ids[0])] {
|
||||
let result = MoveWaypoint {
|
||||
file_id,
|
||||
waypoint_id,
|
||||
lng: 1.0,
|
||||
lat: 1.0,
|
||||
ele: 1.0,
|
||||
}
|
||||
.apply(&mut fx.state());
|
||||
assert!(matches!(result, Err(CommandError::NothingToDo)));
|
||||
}
|
||||
assert!(Rc::ptr_eq(&fx.files[&id], &before));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
use crate::{Apply, CommandError, State};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{
|
||||
Apply, CommandError, File, FileId, Link, LngLat, Selection, State, Waypoint,
|
||||
insert_waypoints_at,
|
||||
};
|
||||
|
||||
/// Adds a waypoint at the end of the waypoints of each selected file (or of the file of the
|
||||
/// selected elements). The strings are empty when the waypoint does not have the field.
|
||||
#[derive(Debug)]
|
||||
pub struct NewWaypoint<'a> {
|
||||
pub lng: f64,
|
||||
@@ -11,9 +18,222 @@ pub struct NewWaypoint<'a> {
|
||||
pub link: &'a str,
|
||||
}
|
||||
|
||||
fn non_empty(text: &str) -> Option<String> {
|
||||
(!text.is_empty()).then(|| text.to_owned())
|
||||
}
|
||||
|
||||
/// Sets the fields of a waypoint: the strings that are empty remove the field.
|
||||
pub fn set_waypoint_fields(
|
||||
waypoint: &mut Waypoint,
|
||||
position: (f64, f64, f64),
|
||||
name: &str,
|
||||
desc: &str,
|
||||
icon: &str,
|
||||
link: &str,
|
||||
) {
|
||||
let (lng, lat, ele) = position;
|
||||
waypoint.coordinates = LngLat { lng, lat };
|
||||
waypoint.ele = ele;
|
||||
waypoint.name = non_empty(name);
|
||||
waypoint.desc = non_empty(desc);
|
||||
// the description is also the comment, as it is what the other applications show
|
||||
waypoint.cmt = non_empty(desc);
|
||||
waypoint.sym = non_empty(icon);
|
||||
waypoint.link = non_empty(link).map(|href| Link { href, text: None });
|
||||
}
|
||||
|
||||
impl Apply for NewWaypoint<'_> {
|
||||
fn apply(self, _state: &mut State) -> Result<(), CommandError> {
|
||||
// TODO
|
||||
Err(CommandError::NotImplemented("new waypoint"))
|
||||
fn apply(self, state: &mut State) -> Result<(), CommandError> {
|
||||
let file_ids: Vec<FileId> = match &*state.selection {
|
||||
Selection::Empty => vec![],
|
||||
Selection::File { file_ids } => state
|
||||
.order
|
||||
.0
|
||||
.iter()
|
||||
.filter(|id| file_ids.contains(id))
|
||||
.copied()
|
||||
.collect(),
|
||||
Selection::Track { file_id, .. }
|
||||
| Selection::TrackSegment { file_id, .. }
|
||||
| Selection::Waypoints { file_id }
|
||||
| Selection::Waypoint { file_id, .. } => vec![*file_id],
|
||||
};
|
||||
let file_ids: Vec<FileId> = file_ids
|
||||
.into_iter()
|
||||
.filter(|id| state.files.contains_key(id))
|
||||
.collect();
|
||||
if file_ids.is_empty() {
|
||||
return Err(CommandError::NothingToDo);
|
||||
}
|
||||
|
||||
for id in file_ids {
|
||||
let mut waypoint = Waypoint::default();
|
||||
set_waypoint_fields(
|
||||
&mut waypoint,
|
||||
(self.lng, self.lat, self.ele),
|
||||
self.name,
|
||||
self.desc,
|
||||
self.icon,
|
||||
self.link,
|
||||
);
|
||||
let file: &mut File = Rc::make_mut(state.files.get_mut(&id).unwrap());
|
||||
insert_waypoints_at(file, usize::MAX, vec![waypoint]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::{New, TrackId, TrackSegmentId, engine::command::fixture::Fixture, waypoint_ids};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn new_waypoint(name: &str) -> NewWaypoint<'_> {
|
||||
NewWaypoint {
|
||||
lng: 4.5,
|
||||
lat: 50.25,
|
||||
ele: 123.0,
|
||||
name,
|
||||
desc: "a description",
|
||||
icon: "Summit",
|
||||
link: "https://example.com",
|
||||
}
|
||||
}
|
||||
|
||||
fn waypoints(fx: &Fixture, id: FileId) -> Vec<Waypoint> {
|
||||
fx.files[&id]
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|chunk| chunk.wpt.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_waypoint_in_the_selected_file() {
|
||||
let mut fx = Fixture::default();
|
||||
New { name: "a" }.apply(&mut fx.state()).unwrap();
|
||||
New { name: "b" }.apply(&mut fx.state()).unwrap();
|
||||
let (a, b) = (fx.order.0[0], fx.order.0[1]);
|
||||
let rev = fx.files[&b].wpt_rev_id;
|
||||
|
||||
// b is selected
|
||||
new_waypoint("peak").apply(&mut fx.state()).unwrap();
|
||||
assert!(waypoints(&fx, a).is_empty());
|
||||
let created = waypoints(&fx, b);
|
||||
assert_eq!(created.len(), 1);
|
||||
let wpt = &created[0];
|
||||
assert_eq!(
|
||||
(wpt.coordinates.lng, wpt.coordinates.lat, wpt.ele),
|
||||
(4.5, 50.25, 123.0)
|
||||
);
|
||||
assert_eq!(wpt.name.as_deref(), Some("peak"));
|
||||
assert_eq!(wpt.desc.as_deref(), Some("a description"));
|
||||
assert_eq!(wpt.cmt.as_deref(), Some("a description"));
|
||||
assert_eq!(wpt.sym.as_deref(), Some("Summit"));
|
||||
assert_eq!(
|
||||
wpt.link.as_ref().map(|l| l.href.as_str()),
|
||||
Some("https://example.com")
|
||||
);
|
||||
assert_ne!(fx.files[&b].wpt_rev_id, rev);
|
||||
|
||||
// added after the others
|
||||
let mut second = new_waypoint("second");
|
||||
second.lng = 5.0;
|
||||
second.apply(&mut fx.state()).unwrap();
|
||||
let names: Vec<_> = waypoints(&fx, b)
|
||||
.iter()
|
||||
.map(|w| w.name.clone().unwrap())
|
||||
.collect();
|
||||
assert_eq!(names, ["peak", "second"]);
|
||||
// and not selected
|
||||
assert_eq!(fx.selected_files(), [b].into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_fields_are_not_set() {
|
||||
let mut fx = Fixture::default();
|
||||
New { name: "a" }.apply(&mut fx.state()).unwrap();
|
||||
let a = fx.order.0[0];
|
||||
NewWaypoint {
|
||||
lng: 1.0,
|
||||
lat: 2.0,
|
||||
ele: 0.0,
|
||||
name: "",
|
||||
desc: "",
|
||||
icon: "",
|
||||
link: "",
|
||||
}
|
||||
.apply(&mut fx.state())
|
||||
.unwrap();
|
||||
let wpt = &waypoints(&fx, a)[0];
|
||||
assert!(wpt.name.is_none() && wpt.desc.is_none() && wpt.cmt.is_none());
|
||||
assert!(wpt.sym.is_none() && wpt.link.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_each_selected_file_gets_its_own_waypoint() {
|
||||
let mut fx = Fixture::default();
|
||||
for name in ["a", "b", "c"] {
|
||||
New { name }.apply(&mut fx.state()).unwrap();
|
||||
}
|
||||
let ids = fx.order.0.clone();
|
||||
fx.selection = Selection::File {
|
||||
file_ids: HashSet::from([ids[0], ids[2]]),
|
||||
};
|
||||
new_waypoint("w").apply(&mut fx.state()).unwrap();
|
||||
assert_eq!(waypoints(&fx, ids[0]).len(), 1);
|
||||
assert!(waypoints(&fx, ids[1]).is_empty());
|
||||
assert_eq!(waypoints(&fx, ids[2]).len(), 1);
|
||||
// not the same waypoint
|
||||
assert_ne!(waypoints(&fx, ids[0])[0].id, waypoints(&fx, ids[2])[0].id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_the_file_of_the_selected_elements_is_used() {
|
||||
for selection in [
|
||||
|id| Selection::Track {
|
||||
file_id: id,
|
||||
trk_ids: [TrackId::default()].into(),
|
||||
},
|
||||
|id| Selection::TrackSegment {
|
||||
file_id: id,
|
||||
trk_id: TrackId::default(),
|
||||
trkseg_ids: [TrackSegmentId::default()].into(),
|
||||
},
|
||||
|id| Selection::Waypoints { file_id: id },
|
||||
|id| Selection::Waypoint {
|
||||
file_id: id,
|
||||
wpt_ids: HashSet::new(),
|
||||
},
|
||||
] {
|
||||
let mut fx = Fixture::default();
|
||||
New { name: "a" }.apply(&mut fx.state()).unwrap();
|
||||
let a = fx.order.0[0];
|
||||
fx.selection = selection(a);
|
||||
new_waypoint("w").apply(&mut fx.state()).unwrap();
|
||||
assert_eq!(waypoint_ids(&fx.files[&a]).count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_nothing_selected_or_unknown_file() {
|
||||
let mut fx = Fixture::default();
|
||||
New { name: "a" }.apply(&mut fx.state()).unwrap();
|
||||
fx.selection = Selection::Empty;
|
||||
assert_eq!(
|
||||
new_waypoint("w").apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
fx.selection = Selection::Waypoints {
|
||||
file_id: FileId::default(),
|
||||
};
|
||||
assert_eq!(
|
||||
new_waypoint("w").apply(&mut fx.state()),
|
||||
Err(CommandError::NothingToDo)
|
||||
);
|
||||
assert_eq!(fx.files.len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::{
|
||||
Action, Apply, Clipboard, Command, CoordinatesCache, Diff, FileId, FileOrder, FileStructure,
|
||||
FileStructureCache, GlobalStatistics, SelectMode, Selection, Stack, State, StatisticsBuffer,
|
||||
StatisticsCache, TrackSegmentId,
|
||||
StatisticsCache, TrackSegmentId, Trackpoint, Waypoint, WaypointId,
|
||||
};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
@@ -60,6 +60,35 @@ impl Engine {
|
||||
self.clipboard_changed
|
||||
}
|
||||
|
||||
/// A waypoint of a file, with all its data. `None` if it does not exist.
|
||||
pub fn waypoint(&self, file_id: &FileId, id: &WaypointId) -> Option<&Waypoint> {
|
||||
self.stack
|
||||
.current()?
|
||||
.get(file_id)?
|
||||
.wpt
|
||||
.iter()
|
||||
.flat_map(|chunk| &chunk.wpt)
|
||||
.find(|wpt| wpt.id == *id)
|
||||
}
|
||||
|
||||
/// A trackpoint of a segment of a file. `None` if it does not exist.
|
||||
pub fn trackpoint(
|
||||
&self,
|
||||
file_id: &FileId,
|
||||
segment_id: &TrackSegmentId,
|
||||
index: usize,
|
||||
) -> Option<&Trackpoint> {
|
||||
let segment = self
|
||||
.stack
|
||||
.current()?
|
||||
.get(file_id)?
|
||||
.trk
|
||||
.iter()
|
||||
.flat_map(|trk| &trk.trkseg)
|
||||
.find(|seg| seg.id == *segment_id)?;
|
||||
(index < segment.len()).then(|| &segment[index])
|
||||
}
|
||||
|
||||
/// Whether there is something to undo.
|
||||
pub fn can_undo(&self) -> bool {
|
||||
self.stack.can_undo()
|
||||
@@ -1110,4 +1139,120 @@ mod tests {
|
||||
assert!(engine.execute(Action::Redo));
|
||||
assert_eq!(engine.order().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_edit_and_move_a_waypoint() {
|
||||
use crate::{EditWaypoint, MoveWaypoint, NewWaypoint};
|
||||
|
||||
let mut engine = Engine::default();
|
||||
new(&mut engine, "file");
|
||||
let file = engine.order()[0];
|
||||
assert!(edit(
|
||||
&mut engine,
|
||||
Command::NewWaypoint(NewWaypoint {
|
||||
lng: 4.0,
|
||||
lat: 50.0,
|
||||
ele: 10.0,
|
||||
name: "created",
|
||||
desc: "",
|
||||
icon: "Flag",
|
||||
link: "",
|
||||
})
|
||||
));
|
||||
let id = engine.file_structure(&file).unwrap().waypoints[0].id;
|
||||
let waypoint = engine.waypoint(&file, &id).unwrap();
|
||||
assert_eq!(waypoint.name.as_deref(), Some("created"));
|
||||
assert_eq!(waypoint.sym.as_deref(), Some("Flag"));
|
||||
assert_eq!(waypoint.ele, 10.0);
|
||||
// unknown waypoint or file
|
||||
assert!(engine.waypoint(&file, &Default::default()).is_none());
|
||||
assert!(engine.waypoint(&Default::default(), &id).is_none());
|
||||
|
||||
// no selection needed
|
||||
assert!(edit(
|
||||
&mut engine,
|
||||
Command::MoveWaypoint(MoveWaypoint {
|
||||
file_id: file,
|
||||
waypoint_id: id,
|
||||
lng: 5.0,
|
||||
lat: 51.0,
|
||||
ele: 20.0,
|
||||
})
|
||||
));
|
||||
let moved = engine.waypoint(&file, &id).unwrap();
|
||||
assert_eq!(
|
||||
(moved.coordinates.lng, moved.coordinates.lat, moved.ele),
|
||||
(5.0, 51.0, 20.0)
|
||||
);
|
||||
assert_eq!(moved.name.as_deref(), Some("created"));
|
||||
// the coordinates buffer follows
|
||||
assert_eq!(engine.waypoint_coordinates(&file), &[5.0, 51.0]);
|
||||
|
||||
// editing applies to the selected waypoints
|
||||
select_elements(
|
||||
&mut engine,
|
||||
Selection::Waypoint {
|
||||
file_id: file,
|
||||
wpt_ids: [id].into(),
|
||||
},
|
||||
SelectMode::Replace,
|
||||
);
|
||||
assert!(edit(
|
||||
&mut engine,
|
||||
Command::EditWaypoint(EditWaypoint {
|
||||
lng: 6.0,
|
||||
lat: 52.0,
|
||||
ele: 30.0,
|
||||
name: "edited",
|
||||
desc: "text",
|
||||
icon: "",
|
||||
link: "https://example.com",
|
||||
})
|
||||
));
|
||||
let edited = engine.waypoint(&file, &id).unwrap();
|
||||
assert_eq!(edited.name.as_deref(), Some("edited"));
|
||||
assert_eq!(edited.cmt.as_deref(), Some("text"));
|
||||
assert!(edited.sym.is_none());
|
||||
assert_eq!(engine.waypoint_coordinates(&file), &[6.0, 52.0]);
|
||||
|
||||
// each of them can be undone
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert_eq!(
|
||||
engine.waypoint(&file, &id).unwrap().name.as_deref(),
|
||||
Some("created")
|
||||
);
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert_eq!(engine.waypoint_coordinates(&file), &[4.0, 50.0]);
|
||||
|
||||
// deleting does not need a selection either
|
||||
assert!(edit(
|
||||
&mut engine,
|
||||
Command::DeleteWaypoint(crate::DeleteWaypoint {
|
||||
file_id: file,
|
||||
waypoint_id: id,
|
||||
})
|
||||
));
|
||||
assert!(engine.waypoint(&file, &id).is_none());
|
||||
assert!(engine.waypoint_coordinates(&file).is_empty());
|
||||
assert!(engine.execute(Action::Undo));
|
||||
assert!(engine.waypoint(&file, &id).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_trackpoint() {
|
||||
let mut engine = Engine::default();
|
||||
load(&mut engine, "data/simple.gpx");
|
||||
let file = engine.order()[0];
|
||||
let structure = engine.file_structure(&file).unwrap();
|
||||
let seg = &structure.tracks[0].segments[0];
|
||||
let (seg_id, len) = (seg.id, seg.len);
|
||||
let coordinates = engine.segment_coordinates(&seg_id).to_vec();
|
||||
let last = engine.trackpoint(&file, &seg_id, len - 1).unwrap();
|
||||
assert_eq!(
|
||||
[last.coordinates.lng, last.coordinates.lat],
|
||||
coordinates[(len - 1) * 2..]
|
||||
);
|
||||
assert!(engine.trackpoint(&file, &seg_id, len).is_none());
|
||||
assert!(engine.trackpoint(&Default::default(), &seg_id, 0).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
+145
-2
@@ -284,12 +284,59 @@ pub fn new_waypoint(
|
||||
}))
|
||||
}
|
||||
|
||||
/// Moves a waypoint of a file, whatever is selected.
|
||||
#[wasm_bindgen]
|
||||
pub fn move_waypoint(lng: f64, lat: f64, ele: f64) -> bool {
|
||||
edit(Command::MoveWaypoint(engine::MoveWaypoint {
|
||||
pub fn move_waypoint(file_id: &str, waypoint_id: &str, lng: f64, lat: f64, ele: f64) -> bool {
|
||||
match (parse_file_id(file_id), parse_waypoint_id(waypoint_id)) {
|
||||
(Some(file_id), Some(waypoint_id)) => edit(Command::MoveWaypoint(engine::MoveWaypoint {
|
||||
file_id,
|
||||
waypoint_id,
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
})),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes a waypoint of a file, whatever is selected.
|
||||
#[wasm_bindgen]
|
||||
pub fn delete_waypoint(file_id: &str, waypoint_id: &str) -> bool {
|
||||
match (parse_file_id(file_id), parse_waypoint_id(waypoint_id)) {
|
||||
(Some(file_id), Some(waypoint_id)) => {
|
||||
edit(Command::DeleteWaypoint(engine::DeleteWaypoint {
|
||||
file_id,
|
||||
waypoint_id,
|
||||
}))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_waypoint_id(id: &str) -> Option<engine::WaypointId> {
|
||||
uuid::Uuid::parse_str(id).ok().map(engine::WaypointId)
|
||||
}
|
||||
|
||||
/// Changes the selected waypoints: their name, description, icon, link, position and elevation.
|
||||
/// The strings that are empty remove the field.
|
||||
#[wasm_bindgen]
|
||||
pub fn update_waypoint(
|
||||
lng: f64,
|
||||
lat: f64,
|
||||
ele: f64,
|
||||
name: &str,
|
||||
desc: &str,
|
||||
icon: &str,
|
||||
link: &str,
|
||||
) -> bool {
|
||||
edit(Command::EditWaypoint(engine::EditWaypoint {
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
name,
|
||||
desc,
|
||||
icon,
|
||||
link,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -629,6 +676,28 @@ export type MoveTarget =
|
||||
| { type: 'tracks'; fileId: string; index: number }
|
||||
| { type: 'segments'; fileId: string; trackId: string; index: number }
|
||||
| { type: 'waypoints'; fileId: string; index: number };
|
||||
/** All the data of a waypoint. The fields it does not have are absent. */
|
||||
export interface WaypointDetails {
|
||||
id: string;
|
||||
lng: number;
|
||||
lat: number;
|
||||
ele: number;
|
||||
/** ms since epoch */
|
||||
time?: number;
|
||||
name?: string;
|
||||
desc?: string;
|
||||
cmt?: string;
|
||||
link?: { href: string; text?: string };
|
||||
sym?: string;
|
||||
}
|
||||
/** The position, elevation and time of a trackpoint. */
|
||||
export interface TrackpointDetails {
|
||||
lng: number;
|
||||
lat: number;
|
||||
ele: number;
|
||||
/** ms since epoch */
|
||||
time?: number;
|
||||
}
|
||||
/** What was copied or cut, to be pasted: the kind of the elements and their ids. */
|
||||
export interface Clipboard {
|
||||
type: 'files' | 'tracks' | 'segments' | 'waypoints';
|
||||
@@ -710,6 +779,10 @@ export interface WaypointNode {
|
||||
extern "C" {
|
||||
#[wasm_bindgen(typescript_type = "Selection")]
|
||||
pub type Selection;
|
||||
#[wasm_bindgen(typescript_type = "WaypointDetails | undefined")]
|
||||
pub type WaypointDetails;
|
||||
#[wasm_bindgen(typescript_type = "TrackpointDetails | undefined")]
|
||||
pub type TrackpointDetails;
|
||||
#[wasm_bindgen(typescript_type = "MoveTarget")]
|
||||
pub type MoveTarget;
|
||||
#[wasm_bindgen(typescript_type = "Clipboard | undefined")]
|
||||
@@ -941,6 +1014,76 @@ pub fn selection() -> Selection {
|
||||
.unchecked_into()
|
||||
}
|
||||
|
||||
/// All the data of a waypoint of a file, `undefined` if it does not exist.
|
||||
#[wasm_bindgen]
|
||||
pub fn waypoint(file_id: &str, waypoint_id: &str) -> WaypointDetails {
|
||||
uuid::Uuid::parse_str(file_id)
|
||||
.ok()
|
||||
.zip(uuid::Uuid::parse_str(waypoint_id).ok())
|
||||
.and_then(|(file_id, id)| {
|
||||
with_engine(|e| {
|
||||
e.waypoint(&FileId(file_id), &engine::WaypointId(id))
|
||||
.map(|wpt| {
|
||||
let object = Object::new();
|
||||
set(&object, "id", wpt.id.0.to_string());
|
||||
set(&object, "lng", wpt.coordinates.lng);
|
||||
set(&object, "lat", wpt.coordinates.lat);
|
||||
set(&object, "ele", wpt.ele);
|
||||
if let Some(time) = wpt.time {
|
||||
set(&object, "time", time as f64);
|
||||
}
|
||||
for (key, value) in [
|
||||
("name", &wpt.name),
|
||||
("desc", &wpt.desc),
|
||||
("cmt", &wpt.cmt),
|
||||
("sym", &wpt.sym),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
set(&object, key, value.as_str());
|
||||
}
|
||||
}
|
||||
if let Some(link) = &wpt.link {
|
||||
let link_object = Object::new();
|
||||
set(&link_object, "href", link.href.as_str());
|
||||
if let Some(text) = &link.text {
|
||||
set(&link_object, "text", text.as_str());
|
||||
}
|
||||
set(&object, "link", link_object);
|
||||
}
|
||||
JsValue::from(object)
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.unwrap_or(JsValue::UNDEFINED)
|
||||
.unchecked_into()
|
||||
}
|
||||
|
||||
/// A trackpoint of a segment of a file, `undefined` if it does not exist.
|
||||
#[wasm_bindgen]
|
||||
pub fn trackpoint(file_id: &str, segment_id: &str, index: usize) -> TrackpointDetails {
|
||||
parse_file_id(file_id)
|
||||
.zip(uuid::Uuid::parse_str(segment_id).ok())
|
||||
.and_then(|(file_id, segment_id)| {
|
||||
with_engine(|e| {
|
||||
e.trackpoint(&file_id, &engine::TrackSegmentId(segment_id), index)
|
||||
.map(|pt| {
|
||||
let object = Object::new();
|
||||
set(&object, "lng", pt.coordinates.lng);
|
||||
set(&object, "lat", pt.coordinates.lat);
|
||||
set(&object, "ele", pt.ele);
|
||||
if let Some(time) = pt.time {
|
||||
set(&object, "time", time as f64);
|
||||
}
|
||||
JsValue::from(object)
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.unwrap_or(JsValue::UNDEFINED)
|
||||
.unchecked_into()
|
||||
}
|
||||
|
||||
/// What was copied or cut and is waiting to be pasted, `undefined` if nothing: the kind of the
|
||||
/// elements and their ids (UUID strings).
|
||||
#[wasm_bindgen]
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { closestPointIndex } from './closest-point';
|
||||
|
||||
describe('closestPointIndex', () => {
|
||||
const line = [0, 0, 1, 0, 2, 0, 2, 1];
|
||||
|
||||
it('has no point on an empty polyline', () => {
|
||||
assert.equal(closestPointIndex([], { lng: 0, lat: 0 }), undefined);
|
||||
});
|
||||
|
||||
it('is the only point of a polyline of one point', () => {
|
||||
assert.equal(closestPointIndex([3, 4], { lng: 0, lat: 0 }), 0);
|
||||
});
|
||||
|
||||
it('is the nearest end of the nearest segment', () => {
|
||||
assert.equal(closestPointIndex(line, { lng: 0.2, lat: 0.1 }), 0);
|
||||
assert.equal(closestPointIndex(line, { lng: 0.8, lat: 0.1 }), 1);
|
||||
assert.equal(closestPointIndex(line, { lng: 1.6, lat: -0.1 }), 2);
|
||||
assert.equal(closestPointIndex(line, { lng: 2.1, lat: 0.9 }), 3);
|
||||
});
|
||||
|
||||
it('uses the distance to the segment, not to its ends', () => {
|
||||
// far from every point but right next to the long segment
|
||||
const coordinates = [0, 0, 10, 0, 10, 5];
|
||||
assert.equal(closestPointIndex(coordinates, { lng: 7, lat: 0.01 }), 1);
|
||||
assert.equal(closestPointIndex(coordinates, { lng: 3, lat: 0.01 }), 0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
const metersPerDegree = 111320;
|
||||
|
||||
/**
|
||||
* Index of the point of a polyline (flat `[lng, lat, ...]` coordinates) that is the closest to
|
||||
* `point`, among the two ends of the segment of the polyline that passes the closest to it.
|
||||
* `undefined` for an empty polyline. Planar approximation, like the one used to simplify tracks.
|
||||
*/
|
||||
export function closestPointIndex(
|
||||
coordinates: ArrayLike<number>,
|
||||
point: { lng: number; lat: number }
|
||||
): number | undefined {
|
||||
const count = Math.floor(coordinates.length / 2);
|
||||
if (count === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const kx = Math.cos((point.lat * Math.PI) / 180) * metersPerDegree;
|
||||
const ky = metersPerDegree;
|
||||
const px = point.lng * kx;
|
||||
const py = point.lat * ky;
|
||||
const x = (i: number) => coordinates[2 * i] * kx - px;
|
||||
const y = (i: number) => coordinates[2 * i + 1] * ky - py;
|
||||
|
||||
let best = 0;
|
||||
let bestDistance = Number.MAX_VALUE;
|
||||
for (let i = 0; i < count - 1; i++) {
|
||||
const [ax, ay, bx, by] = [x(i), y(i), x(i + 1), y(i + 1)];
|
||||
const [dx, dy] = [bx - ax, by - ay];
|
||||
const length = dx * dx + dy * dy;
|
||||
// the point is at the origin: the closest position on the segment, as a ratio
|
||||
const t = length === 0 ? 0 : Math.max(0, Math.min(1, -(ax * dx + ay * dy) / length));
|
||||
const distance = Math.hypot(ax + t * dx, ay + t * dy);
|
||||
if (distance < bestDistance) {
|
||||
bestDistance = distance;
|
||||
best = t < 0.5 ? i : i + 1;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -38,12 +38,8 @@
|
||||
selectionSize,
|
||||
type FileTreeNode,
|
||||
} from '$lib/selection-helpers';
|
||||
// TODO centering on the selection and the waypoint popup still work on the previous
|
||||
// implementation
|
||||
import { boundsManager } from '$lib/logic/bounds';
|
||||
// import { gpxLayers } from '$lib/components/map/gpx-layer/gpx-layers';
|
||||
// import { fileStateCollection } from '$lib/logic/file-state';
|
||||
// import { waypointPopup } from '$lib/components/map/gpx-layer/gpx-layer-popup';
|
||||
import { waypointPopup } from '$lib/components/map/gpx-layer/gpx-layer-popup';
|
||||
|
||||
let {
|
||||
fileState,
|
||||
@@ -165,26 +161,21 @@
|
||||
}
|
||||
}}
|
||||
onmouseenter={() => {
|
||||
// TODO waypoint popup: it needs the waypoint of the previous implementation
|
||||
// if (node.type === 'waypoint') {
|
||||
// let layer = gpxLayers.getLayer(node.fileId);
|
||||
// let file = fileStateCollection.getFile(node.fileId);
|
||||
// if (layer && file) {
|
||||
// let waypoint = file.wpt[waypointIndex];
|
||||
// if (waypoint && !waypoint._data.hidden) {
|
||||
// waypointPopup?.setItem({ item: waypoint, fileId: node.fileId });
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
if (node.type === 'waypoint' && !isHidden(fileState, node.waypointId)) {
|
||||
const waypoint = engine.waypoint(node.fileId, node.waypointId);
|
||||
if (waypoint) {
|
||||
waypointPopup?.setItem({
|
||||
item: waypoint,
|
||||
kind: 'waypoint',
|
||||
fileId: node.fileId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}}
|
||||
onmouseleave={() => {
|
||||
// TODO waypoint popup
|
||||
// if (node.type === 'waypoint') {
|
||||
// let layer = gpxLayers.getLayer(node.fileId);
|
||||
// if (layer) {
|
||||
// waypointPopup?.setItem(null);
|
||||
// }
|
||||
// }
|
||||
if (node.type === 'waypoint') {
|
||||
waypointPopup?.setItem(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{#if level === ListLevel.SEGMENT}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { map } from '$lib/components/map/map';
|
||||
import { trackpointPopup } from '$lib/components/map/gpx-layer/gpx-layer-popup';
|
||||
import { TrackPoint } from 'gpx';
|
||||
|
||||
map.onLoad((map_) => {
|
||||
map_.on('contextmenu', (e) => {
|
||||
@@ -16,12 +15,8 @@
|
||||
return;
|
||||
}
|
||||
trackpointPopup?.setItem({
|
||||
item: new TrackPoint({
|
||||
attributes: {
|
||||
lat: e.lngLat.lat,
|
||||
lon: e.lngLat.lng,
|
||||
},
|
||||
}),
|
||||
kind: 'trackpoint',
|
||||
item: { lng: e.lngLat.lng, lat: e.lngLat.lat },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<script lang="ts">
|
||||
import { TrackPoint, Waypoint } from 'gpx';
|
||||
import WaypointPopup from '$lib/components/map/gpx-layer/WaypointPopup.svelte';
|
||||
import TrackpointPopup from '$lib/components/map/gpx-layer/TrackpointPopup.svelte';
|
||||
import OverpassPopup from '$lib/components/map/layer-control/OverpassPopup.svelte';
|
||||
@@ -23,9 +22,9 @@
|
||||
|
||||
<div bind:this={container}>
|
||||
{#if $item}
|
||||
{#if $item.item instanceof Waypoint}
|
||||
{#if $item.kind === 'waypoint'}
|
||||
<WaypointPopup waypoint={$item} />
|
||||
{:else if $item.item instanceof TrackPoint}
|
||||
{:else if $item.kind === 'trackpoint'}
|
||||
<TrackpointPopup trackpoint={$item} />
|
||||
{:else}
|
||||
<OverpassPopup poi={$item} />
|
||||
|
||||
@@ -2,14 +2,13 @@
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { ClipboardCopy } from '@lucide/svelte';
|
||||
import { i18n } from '$lib/i18n.svelte';
|
||||
import type { Coordinates } from 'gpx';
|
||||
|
||||
let {
|
||||
coordinates,
|
||||
onCopy = () => {},
|
||||
class: className = '',
|
||||
}: {
|
||||
coordinates: Coordinates;
|
||||
coordinates: { lng: number; lat: number };
|
||||
onCopy?: () => void;
|
||||
class?: string;
|
||||
} = $props();
|
||||
@@ -20,7 +19,7 @@
|
||||
variant="outline"
|
||||
onclick={() => {
|
||||
navigator.clipboard.writeText(
|
||||
`${coordinates.lat.toFixed(6)}, ${coordinates.lon.toFixed(6)}`
|
||||
`${coordinates.lat.toFixed(6)}, ${coordinates.lng.toFixed(6)}`
|
||||
);
|
||||
onCopy();
|
||||
}}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<script lang="ts">
|
||||
import type { TrackPoint } from 'gpx';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import CopyCoordinates from '$lib/components/map/gpx-layer/CopyCoordinates.svelte';
|
||||
import * as Card from '$lib/components/ui/card';
|
||||
@@ -7,18 +6,17 @@
|
||||
import { Compass, Earth, Mountain, Timer } from '@lucide/svelte';
|
||||
import { i18n } from '$lib/i18n.svelte';
|
||||
import type { PopupItem } from '$lib/components/map/map-popup';
|
||||
import type { TrackpointDetails } from '$lib/engine';
|
||||
import { map } from '$lib/components/map/map';
|
||||
|
||||
let { trackpoint }: { trackpoint: PopupItem<TrackPoint> } = $props();
|
||||
let { trackpoint }: { trackpoint: PopupItem<Pick<TrackpointDetails, 'lng' | 'lat'> & Partial<TrackpointDetails>> } = $props();
|
||||
</script>
|
||||
|
||||
<Card.Root class="border-none shadow-md text-base p-2">
|
||||
<Card.Content class="flex flex-col p-0 text-xs gap-1">
|
||||
<div class="flex flex-row items-center gap-1">
|
||||
<Compass size="14" />
|
||||
{trackpoint.item.getLatitude().toFixed(6)}° {trackpoint.item
|
||||
.getLongitude()
|
||||
.toFixed(6)}°
|
||||
{trackpoint.item.lat.toFixed(6)}° {trackpoint.item.lng.toFixed(6)}°
|
||||
</div>
|
||||
{#if trackpoint.item.ele !== undefined}
|
||||
<div class="flex flex-row items-center gap-1">
|
||||
@@ -26,14 +24,14 @@
|
||||
<WithUnits value={trackpoint.item.ele} type="elevation" />
|
||||
</div>
|
||||
{/if}
|
||||
{#if trackpoint.item.time}
|
||||
{#if trackpoint.item.time !== undefined}
|
||||
<div class="flex flex-row items-center gap-1">
|
||||
<Timer size="14" />
|
||||
{i18n.df.format(trackpoint.item.time)}
|
||||
{i18n.df.format(new Date(trackpoint.item.time))}
|
||||
</div>
|
||||
{/if}
|
||||
<CopyCoordinates
|
||||
coordinates={trackpoint.item.attributes}
|
||||
coordinates={trackpoint.item}
|
||||
onCopy={() => trackpoint.hide?.()}
|
||||
class="mt-0.5"
|
||||
/>
|
||||
@@ -41,7 +39,7 @@
|
||||
<Button
|
||||
variant="outline"
|
||||
class="justify-start"
|
||||
href={`https://www.openstreetmap.org/edit?#map=${(($map?.getZoom() ?? 17) + 1).toFixed(0)}/${trackpoint.item.getLatitude().toFixed(5)}/${trackpoint.item.getLongitude().toFixed(5)}`}
|
||||
href={`https://www.openstreetmap.org/edit?#map=${(($map?.getZoom() ?? 17) + 1).toFixed(0)}/${trackpoint.item.lat.toFixed(5)}/${trackpoint.item.lng.toFixed(5)}`}
|
||||
target="_blank"
|
||||
>
|
||||
<Earth size="14" />
|
||||
|
||||
@@ -9,21 +9,23 @@
|
||||
import { getSymbolKey, symbols } from '$lib/assets/symbols';
|
||||
import { i18n } from '$lib/i18n.svelte';
|
||||
import sanitizeHtml from 'sanitize-html';
|
||||
import type { Waypoint } from 'gpx';
|
||||
import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
|
||||
import { fileActions } from '$lib/logic/file-actions';
|
||||
import type { PopupItem } from '$lib/components/map/map-popup';
|
||||
import { selection } from '$lib/logic/selection';
|
||||
import { ListFileItem } from '$lib/components/file-list/file-list';
|
||||
import { engine, type WaypointDetails } from '$lib/engine';
|
||||
import { hasSelectionWithin } from '$lib/selection-helpers';
|
||||
|
||||
let {
|
||||
waypoint,
|
||||
}: {
|
||||
waypoint: PopupItem<Waypoint>;
|
||||
waypoint: PopupItem<WaypointDetails>;
|
||||
} = $props();
|
||||
|
||||
const { selection } = engine;
|
||||
|
||||
let selected = $derived(
|
||||
waypoint.fileId ? $selection.hasAnyChildren(new ListFileItem(waypoint.fileId)) : false
|
||||
waypoint.fileId
|
||||
? hasSelectionWithin($selection, { type: 'file', fileId: waypoint.fileId })
|
||||
: false
|
||||
);
|
||||
let symbolKey = $derived(waypoint ? getSymbolKey(waypoint.item.sym) : undefined);
|
||||
|
||||
@@ -44,9 +46,9 @@
|
||||
<Card.Root class="border-none shadow-md text-base p-2 max-w-[50dvw] gap-0">
|
||||
<Card.Header class="p-0 gap-0">
|
||||
<Card.Title class="text-md">
|
||||
{#if waypoint.item.link && waypoint.item.link.attributes && waypoint.item.link.attributes.href}
|
||||
<a href={waypoint.item.link.attributes.href} target="_blank">
|
||||
{waypoint.item.name ?? waypoint.item.link.attributes.href}
|
||||
{#if waypoint.item.link?.href}
|
||||
<a href={waypoint.item.link.href} target="_blank">
|
||||
{waypoint.item.name ?? waypoint.item.link.href}
|
||||
<ExternalLink size="12" class="inline-block mb-1.5" />
|
||||
</a>
|
||||
{:else}
|
||||
@@ -68,13 +70,9 @@
|
||||
</span>
|
||||
<Dot size="16" />
|
||||
{/if}
|
||||
{waypoint.item.getLatitude().toFixed(6)}° {waypoint.item
|
||||
.getLongitude()
|
||||
.toFixed(6)}°
|
||||
{#if waypoint.item.ele !== undefined}
|
||||
{waypoint.item.lat.toFixed(6)}° {waypoint.item.lng.toFixed(6)}°
|
||||
<Dot size="16" />
|
||||
<WithUnits value={waypoint.item.ele} type="elevation" />
|
||||
{/if}
|
||||
</div>
|
||||
<ScrollArea class="flex flex-col max-h-[30dvh]">
|
||||
{#if waypoint.item.desc}
|
||||
@@ -85,13 +83,13 @@
|
||||
{/if}
|
||||
</ScrollArea>
|
||||
<div class="mt-2 flex flex-col gap-1">
|
||||
<CopyCoordinates coordinates={waypoint.item.attributes} />
|
||||
<CopyCoordinates coordinates={waypoint.item} />
|
||||
{#if $currentTool === Tool.WAYPOINT && selected}
|
||||
<Button
|
||||
variant="outline"
|
||||
onclick={() => {
|
||||
if (waypoint.fileId) {
|
||||
fileActions.deleteWaypoint(waypoint.fileId, waypoint.item._data.index);
|
||||
engine.deleteWaypoint(waypoint.fileId, waypoint.item.id);
|
||||
waypoint.hide?.();
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -8,7 +8,8 @@ import maplibregl, {
|
||||
} from 'maplibre-gl';
|
||||
import { map } from '$lib/components/map/map';
|
||||
import { waypointPopup, trackpointPopup } from './gpx-layer-popup';
|
||||
import { getClosestLinePoint, getElevation, loadSVGIcon } from '$lib/utils';
|
||||
import { closestPointIndex } from '$lib/closest-point';
|
||||
import { getElevation, loadSVGIcon } from '$lib/utils';
|
||||
import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint';
|
||||
import { MapPin, Square } from 'lucide-static';
|
||||
import { getSymbolKey, symbols } from '$lib/assets/symbols';
|
||||
@@ -18,7 +19,6 @@ import { isCovered, hasSelectionWithin, type FileTreeNode } from '$lib/selection
|
||||
import { isSegmentHidden, isWaypointHidden } from '$lib/file-visibility';
|
||||
import { settings } from '$lib/logic/settings';
|
||||
import { currentTool, Tool } from '$lib/components/toolbar/tools';
|
||||
import { fileActionManager } from '$lib/logic/file-action-manager';
|
||||
import { fileActions } from '$lib/logic/file-actions';
|
||||
import { splitAs } from '$lib/components/toolbar/tools/scissors/scissors';
|
||||
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
|
||||
@@ -398,18 +398,18 @@ export class GPXLayer {
|
||||
|
||||
layerOnMouseMove(e: any) {
|
||||
if (e.originalEvent.shiftKey) {
|
||||
let trackIndex = e.features[0].properties.trackIndex;
|
||||
let segmentIndex = e.features[0].properties.segmentIndex;
|
||||
|
||||
// TODO needs the trackpoints of the previous implementation (see oldFile)
|
||||
// const file = null;
|
||||
// if (file) {
|
||||
// const closest = getClosestLinePoint(
|
||||
// file.trk[trackIndex].trkseg[segmentIndex].trkpt,
|
||||
// { lat: e.lngLat.lat, lon: e.lngLat.lng }
|
||||
// );
|
||||
// trackpointPopup?.setItem({ item: closest, fileId: this.fileId });
|
||||
// }
|
||||
const { segmentId } = e.features[0].properties;
|
||||
const lngLat = { lng: e.lngLat.lng, lat: e.lngLat.lat };
|
||||
const index = closestPointIndex(engine.segmentCoordinates(segmentId), lngLat);
|
||||
const trackpoint =
|
||||
index === undefined ? undefined : engine.trackpoint(this.fileId, segmentId, index);
|
||||
if (trackpoint) {
|
||||
trackpointPopup?.setItem({
|
||||
item: trackpoint,
|
||||
kind: 'trackpoint',
|
||||
fileId: this.fileId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -471,15 +471,18 @@ export class GPXLayer {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO the popup needs the waypoint of the previous implementation (see oldFile)
|
||||
// let waypoint = this.oldFile?.wpt[e.features![0].properties!.waypointIndex];
|
||||
// if (waypoint) {
|
||||
// waypointPopup?.setItem({ item: waypoint, fileId: this.fileId });
|
||||
// }
|
||||
this.showWaypointPopup(e.features![0].properties!.waypointId);
|
||||
|
||||
mapCursor.notify(MapCursorState.WAYPOINT_HOVER, true);
|
||||
}
|
||||
|
||||
showWaypointPopup(waypointId: string) {
|
||||
const waypoint = engine.waypoint(this.fileId, waypointId);
|
||||
if (waypoint) {
|
||||
waypointPopup?.setItem({ item: waypoint, kind: 'waypoint', fileId: this.fileId });
|
||||
}
|
||||
}
|
||||
|
||||
waypointLayerOnMouseLeave() {
|
||||
mapCursor.notify(MapCursorState.WAYPOINT_HOVER, false);
|
||||
}
|
||||
@@ -487,19 +490,14 @@ export class GPXLayer {
|
||||
waypointLayerOnClick(e: MapLayerMouseEvent) {
|
||||
e.preventDefault();
|
||||
|
||||
const { waypointIndex, waypointId } = e.features![0].properties!;
|
||||
// TODO the popup and the waypoint tool need the waypoint of the previous implementation
|
||||
const { waypointId } = e.features![0].properties!;
|
||||
if (get(currentTool) === Tool.WAYPOINT) {
|
||||
if (this.selected) {
|
||||
if (e.originalEvent.shiftKey) {
|
||||
// TODO
|
||||
// fileActions.deleteWaypoint(this.fileId, waypointIndex);
|
||||
engine.deleteWaypoint(this.fileId, waypointId);
|
||||
} else {
|
||||
engine.selectWaypoints(this.fileId, [waypointId]);
|
||||
// TODO
|
||||
// if (waypoint) {
|
||||
// selectedWaypoint.set([waypoint, this.fileId]);
|
||||
// }
|
||||
selectedWaypoint.set({ fileId: this.fileId, id: waypointId });
|
||||
}
|
||||
} else {
|
||||
if (get(treeFileView)) {
|
||||
@@ -507,10 +505,7 @@ export class GPXLayer {
|
||||
} else {
|
||||
engine.select([this.fileId]);
|
||||
}
|
||||
// TODO
|
||||
// if (waypoint) {
|
||||
// selectedWaypoint.set([waypoint, this.fileId]);
|
||||
// }
|
||||
selectedWaypoint.set({ fileId: this.fileId, id: waypointId });
|
||||
}
|
||||
} else {
|
||||
if (get(treeFileView)) {
|
||||
@@ -524,10 +519,7 @@ export class GPXLayer {
|
||||
if (!this.selected) {
|
||||
engine.select([this.fileId]);
|
||||
}
|
||||
// TODO
|
||||
// if (waypoint) {
|
||||
// waypointPopup?.setItem({ item: waypoint, fileId: this.fileId });
|
||||
// }
|
||||
this.showWaypointPopup(waypointId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -622,23 +614,27 @@ export class GPXLayer {
|
||||
return;
|
||||
}
|
||||
|
||||
// the dragged waypoint, as it is in the features of the source
|
||||
const waypointId =
|
||||
this.currentWaypointData?.features[this.draggedWaypointIndex].properties?.waypointId;
|
||||
getElevation([
|
||||
{
|
||||
lat: e.lngLat.lat,
|
||||
lon: e.lngLat.lng,
|
||||
},
|
||||
]).then((ele) => {
|
||||
]).then(async (ele) => {
|
||||
if (this.draggedWaypointIndex === null) {
|
||||
return;
|
||||
}
|
||||
fileActionManager.applyToFile(this.fileId, (file) => {
|
||||
let wpt = file.wpt[this.draggedWaypointIndex!];
|
||||
wpt.setCoordinates({
|
||||
lat: e.lngLat.lat,
|
||||
lon: e.lngLat.lng,
|
||||
});
|
||||
wpt.ele = ele[0];
|
||||
});
|
||||
if (waypointId) {
|
||||
await engine.moveWaypoint(
|
||||
this.fileId,
|
||||
waypointId,
|
||||
e.lngLat.lng,
|
||||
e.lngLat.lat,
|
||||
ele[0]
|
||||
);
|
||||
}
|
||||
this.draggedWaypointIndex = null;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
import { PencilLine, MapPin } from '@lucide/svelte';
|
||||
import { i18n } from '$lib/i18n.svelte';
|
||||
import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';
|
||||
import type { WaypointType } from 'gpx';
|
||||
import type { PopupItem } from '$lib/components/map/map-popup';
|
||||
import { fileActions } from '$lib/logic/file-actions';
|
||||
import { selection } from '$lib/logic/selection';
|
||||
import { engine } from '$lib/engine';
|
||||
import { selectionSize } from '$lib/selection-helpers';
|
||||
import { getElevation } from '$lib/utils';
|
||||
|
||||
let {
|
||||
poi,
|
||||
@@ -27,28 +27,22 @@
|
||||
return '';
|
||||
});
|
||||
|
||||
function addToFile() {
|
||||
const { selection } = engine;
|
||||
|
||||
async function addToFile() {
|
||||
const desc = Object.entries(tags)
|
||||
.map(([key, value]) => `${key}: ${value}`)
|
||||
.join('\n');
|
||||
let wpt: WaypointType = {
|
||||
attributes: {
|
||||
const [ele] = await getElevation([{ lat: poi.item.lat, lon: poi.item.lng }]);
|
||||
await engine.newWaypoint({
|
||||
lng: poi.item.lng,
|
||||
lat: poi.item.lat,
|
||||
lon: poi.item.lon,
|
||||
},
|
||||
name: name,
|
||||
desc: desc,
|
||||
cmt: desc,
|
||||
sym: poi.item.sym,
|
||||
};
|
||||
if (tags.website) {
|
||||
wpt.link = {
|
||||
attributes: {
|
||||
href: tags.website,
|
||||
},
|
||||
};
|
||||
}
|
||||
fileActions.addOrUpdateWaypoint(wpt);
|
||||
ele,
|
||||
name,
|
||||
desc,
|
||||
icon: poi.item.sym ?? '',
|
||||
link: tags.website ?? '',
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -58,7 +52,7 @@
|
||||
<div class="flex flex-col">
|
||||
<p>{name}</p>
|
||||
<div class="text-muted-foreground text-xs font-normal">
|
||||
{poi.item.lat.toFixed(6)}° {poi.item.lon.toFixed(6)}°
|
||||
{poi.item.lat.toFixed(6)}° {poi.item.lng.toFixed(6)}°
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -111,7 +105,7 @@
|
||||
size="sm"
|
||||
class="mt-1 justify-start"
|
||||
variant="outline"
|
||||
disabled={$selection.size === 0}
|
||||
disabled={selectionSize($selection) === 0}
|
||||
onclick={addToFile}
|
||||
>
|
||||
<MapPin size="14" />
|
||||
|
||||
@@ -143,6 +143,7 @@ export class OverpassLayer {
|
||||
|
||||
onHover(e: any) {
|
||||
this.popup.setItem({
|
||||
kind: 'overpass',
|
||||
item: {
|
||||
...e.features[0].properties,
|
||||
sym: overpassQueryData[e.features[0].properties.query].symbol ?? '',
|
||||
@@ -235,7 +236,7 @@ export class OverpassLayer {
|
||||
properties: {
|
||||
id: element.id,
|
||||
lat: element.center ? element.center.lat : element.lat,
|
||||
lon: element.center ? element.center.lon : element.lon,
|
||||
lng: element.center ? element.center.lon : element.lon,
|
||||
query: query,
|
||||
icon: `overpass-${query}`,
|
||||
tags: element.tags,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { TrackPoint, Waypoint } from 'gpx';
|
||||
import maplibregl from 'maplibre-gl';
|
||||
import { mount, tick, unmount } from 'svelte';
|
||||
import { get, writable, type Writable } from 'svelte/store';
|
||||
import MapPopupComponent from '$lib/components/map/MapPopup.svelte';
|
||||
|
||||
export type PopupItem<T = Waypoint | TrackPoint | any> = {
|
||||
export type PopupItem<T = any> = {
|
||||
/** Has a position (`lng` and `lat`). */
|
||||
item: T;
|
||||
/** What the item is: a `WaypointDetails`, a `TrackpointDetails` or an Overpass element. */
|
||||
kind: 'waypoint' | 'trackpoint' | 'overpass';
|
||||
fileId?: string;
|
||||
hide?: () => void;
|
||||
};
|
||||
@@ -77,8 +79,6 @@ export class MapPopup {
|
||||
if (item === null) {
|
||||
return new maplibregl.LngLat(0, 0);
|
||||
}
|
||||
return item.item instanceof Waypoint || item.item instanceof TrackPoint
|
||||
? item.item.getCoordinates()
|
||||
: new maplibregl.LngLat(item.item.lon, item.item.lat);
|
||||
return new maplibregl.LngLat(item.item.lng, item.item.lat);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,15 +5,15 @@
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import { i18n } from '$lib/i18n.svelte';
|
||||
import { ListWaypointItem } from '$lib/components/file-list/file-list';
|
||||
import Help from '$lib/components/Help.svelte';
|
||||
import { onDestroy, onMount, untrack } from 'svelte';
|
||||
import { getURLForLanguage } from '$lib/utils';
|
||||
import { MapPin, CircleX, Save } from '@lucide/svelte';
|
||||
import { getSymbolKey, symbols } from '$lib/assets/symbols';
|
||||
import { selection } from '$lib/logic/selection';
|
||||
import { engine } from '$lib/engine';
|
||||
import { selectionSize } from '$lib/selection-helpers';
|
||||
import { getElevation } from '$lib/utils';
|
||||
import { selectedWaypoint } from './waypoint';
|
||||
import { fileActions } from '$lib/logic/file-actions';
|
||||
import { map } from '$lib/components/map/map';
|
||||
import { mapCursor, MapCursorState } from '$lib/logic/map-cursor';
|
||||
import maplibregl from 'maplibre-gl';
|
||||
@@ -31,7 +31,9 @@
|
||||
let latitude = $state(0);
|
||||
let symbolKey = $derived(getSymbolKey(sym));
|
||||
|
||||
let canCreate = $derived($selection.size > 0);
|
||||
const { selection } = engine;
|
||||
|
||||
let canCreate = $derived(selectionSize($selection) > 0);
|
||||
|
||||
let sortedSymbols = $derived(
|
||||
Object.entries(symbols).sort((a, b) => {
|
||||
@@ -58,24 +60,24 @@
|
||||
|
||||
$effect(() => {
|
||||
if ($selectedWaypoint) {
|
||||
const wpt = $selectedWaypoint[0];
|
||||
const wpt = $selectedWaypoint.waypoint;
|
||||
untrack(() => {
|
||||
name = wpt.name ?? '';
|
||||
description = wpt.desc ?? '';
|
||||
if (wpt.cmt !== undefined && wpt.cmt !== wpt.desc) {
|
||||
description += '\n\n' + wpt.cmt;
|
||||
}
|
||||
link = wpt.link?.attributes?.href ?? '';
|
||||
link = wpt.link?.href ?? '';
|
||||
sym = wpt.sym ?? '';
|
||||
longitude = parseFloat(wpt.getLongitude().toFixed(6));
|
||||
latitude = parseFloat(wpt.getLatitude().toFixed(6));
|
||||
longitude = parseFloat(wpt.lng.toFixed(6));
|
||||
latitude = parseFloat(wpt.lat.toFixed(6));
|
||||
});
|
||||
} else {
|
||||
untrack(reset);
|
||||
}
|
||||
});
|
||||
|
||||
function createOrUpdateWaypoint() {
|
||||
async function createOrUpdateWaypoint() {
|
||||
if (typeof latitude === 'string') {
|
||||
latitude = parseFloat(latitude);
|
||||
}
|
||||
@@ -85,22 +87,25 @@
|
||||
latitude = parseFloat(latitude.toFixed(6));
|
||||
longitude = parseFloat(longitude.toFixed(6));
|
||||
|
||||
fileActions.addOrUpdateWaypoint(
|
||||
{
|
||||
attributes: {
|
||||
const target = $selectedWaypoint;
|
||||
const [ele] = await getElevation([{ lat: latitude, lon: longitude }]);
|
||||
const waypoint = {
|
||||
lng: longitude,
|
||||
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: sym.length > 0 ? sym : undefined,
|
||||
},
|
||||
selectedWaypoint.wpt && selectedWaypoint.fileId
|
||||
? new ListWaypointItem(selectedWaypoint.fileId, selectedWaypoint.wpt._data.index)
|
||||
: undefined
|
||||
);
|
||||
ele,
|
||||
name,
|
||||
desc: description,
|
||||
icon: sym,
|
||||
link,
|
||||
};
|
||||
if (target) {
|
||||
// the engine changes the selected waypoint
|
||||
await engine.selectWaypoints(target.fileId, [target.id]);
|
||||
await engine.updateWaypoint(waypoint);
|
||||
} else {
|
||||
// it goes in the selected files
|
||||
await engine.newWaypoint(waypoint);
|
||||
}
|
||||
|
||||
reset();
|
||||
}
|
||||
|
||||
@@ -1,74 +1,107 @@
|
||||
import { ListWaypointItem } from '$lib/components/file-list/file-list';
|
||||
import { fileStateCollection } from '$lib/logic/file-state';
|
||||
import { selection } from '$lib/logic/selection';
|
||||
import { get, writable } from 'svelte/store';
|
||||
import { engine, type WaypointDetails } from '$lib/engine';
|
||||
import { settings } from '$lib/logic/settings';
|
||||
import type { Waypoint } from 'gpx';
|
||||
import { get, writable, type Writable } from 'svelte/store';
|
||||
|
||||
export type SelectedWaypoint = {
|
||||
fileId: string;
|
||||
id: string;
|
||||
/** The data of the waypoint, kept up to date with the file. */
|
||||
waypoint: WaypointDetails;
|
||||
};
|
||||
|
||||
/**
|
||||
* The waypoint that the waypoint tool is about: the selected one when the file tree is shown and
|
||||
* a single waypoint is selected, or the one that was set explicitly (clicking a waypoint of the
|
||||
* map) until the selection changes to something else than its file or itself (that is what
|
||||
* clicking it selects, depending on the view, and the selection may arrive after it is set).
|
||||
*/
|
||||
export class WaypointSelection {
|
||||
private _selection: Writable<[Waypoint, string] | undefined>;
|
||||
private _selection = writable<SelectedWaypoint | undefined>(undefined);
|
||||
private _fileUnsubscribe: (() => void) | undefined;
|
||||
private _explicit: { fileId: string; id: string } | undefined;
|
||||
|
||||
constructor() {
|
||||
this._selection = writable(undefined);
|
||||
settings.treeFileView.subscribe(() => {
|
||||
this.update();
|
||||
});
|
||||
selection.subscribe(() => {
|
||||
this.update();
|
||||
});
|
||||
settings.treeFileView.subscribe(() => this.updateFromSelection());
|
||||
engine.selection.subscribe(() => this.updateFromSelection());
|
||||
}
|
||||
|
||||
subscribe(
|
||||
run: (value: [Waypoint, string] | undefined) => void,
|
||||
invalidate?: (value?: [Waypoint, string] | undefined) => void
|
||||
run: (value: SelectedWaypoint | undefined) => void,
|
||||
invalidate?: (value?: SelectedWaypoint | undefined) => void
|
||||
) {
|
||||
return this._selection.subscribe(run, invalidate);
|
||||
}
|
||||
|
||||
set(value: [Waypoint, string] | undefined) {
|
||||
this._selection.set(value);
|
||||
/** Sets the waypoint, whatever the selection is. */
|
||||
set(target: { fileId: string; id: string } | undefined) {
|
||||
this._explicit = target;
|
||||
this.track(target);
|
||||
}
|
||||
|
||||
update() {
|
||||
if (this._fileUnsubscribe) {
|
||||
this._fileUnsubscribe();
|
||||
this._fileUnsubscribe = undefined;
|
||||
updateFromSelection() {
|
||||
const selection = get(engine.selection);
|
||||
const explicit = this._explicit;
|
||||
if (
|
||||
explicit &&
|
||||
((selection.type === 'file' &&
|
||||
selection.fileIds.length === 1 &&
|
||||
selection.fileIds[0] === explicit.fileId) ||
|
||||
(selection.type === 'waypoint' &&
|
||||
selection.fileId === explicit.fileId &&
|
||||
selection.waypointIds.length === 1 &&
|
||||
selection.waypointIds[0] === explicit.id))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this._selection.update(() => {
|
||||
if (get(settings.treeFileView) && get(selection).size === 1) {
|
||||
let item = get(selection).getSelected()[0];
|
||||
if (item instanceof ListWaypointItem) {
|
||||
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()];
|
||||
this._explicit = undefined;
|
||||
if (
|
||||
get(settings.treeFileView) &&
|
||||
selection.type === 'waypoint' &&
|
||||
selection.waypointIds.length === 1
|
||||
) {
|
||||
this.track({ fileId: selection.fileId, id: selection.waypointIds[0] });
|
||||
} else {
|
||||
this.track(undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
|
||||
reset() {
|
||||
this._selection.set(undefined);
|
||||
this._explicit = undefined;
|
||||
this.track(undefined);
|
||||
}
|
||||
|
||||
get wpt(): Waypoint | undefined {
|
||||
const selection = get(this._selection);
|
||||
return selection ? selection[0] : undefined;
|
||||
get waypoint(): WaypointDetails | undefined {
|
||||
return get(this._selection)?.waypoint;
|
||||
}
|
||||
|
||||
get fileId(): string | undefined {
|
||||
const selection = get(this._selection);
|
||||
return selection ? selection[1] : undefined;
|
||||
return get(this._selection)?.fileId;
|
||||
}
|
||||
|
||||
get id(): string | undefined {
|
||||
return get(this._selection)?.id;
|
||||
}
|
||||
|
||||
private track(target: { fileId: string; id: string } | undefined) {
|
||||
this._fileUnsubscribe?.();
|
||||
this._fileUnsubscribe = undefined;
|
||||
|
||||
if (!target) {
|
||||
this._selection.set(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
// read again each time the file changes
|
||||
const read = () => {
|
||||
const waypoint = engine.waypoint(target.fileId, target.id);
|
||||
this._selection.set(waypoint ? { ...target, waypoint } : undefined);
|
||||
};
|
||||
const file = get(engine.files).get(target.fileId);
|
||||
if (file) {
|
||||
this._fileUnsubscribe = file.subscribe(read);
|
||||
} else {
|
||||
read();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,20 @@ import { FileColorAllocator, normalizeColor } from '$lib/file-colors';
|
||||
import { setHidden, type Visibility } from '$lib/file-visibility';
|
||||
import { selectedElementIds, type FileTreeNode } from '$lib/selection-helpers';
|
||||
import type { Feature, FeatureCollection, LineString, Point } from 'geojson';
|
||||
import type { Clipboard, GlobalStatistics, FileStructure, MoveTarget, Selection } from 'gpx-rs';
|
||||
import type {
|
||||
Clipboard,
|
||||
GlobalStatistics,
|
||||
FileStructure,
|
||||
MoveTarget,
|
||||
Selection,
|
||||
WaypointDetails,
|
||||
TrackpointDetails,
|
||||
} from 'gpx-rs';
|
||||
|
||||
export type {
|
||||
Clipboard,
|
||||
WaypointDetails,
|
||||
TrackpointDetails,
|
||||
MoveTarget,
|
||||
GlobalStatistics,
|
||||
FileStructure,
|
||||
@@ -59,6 +69,17 @@ export type WaypointProperties = {
|
||||
sym?: string;
|
||||
};
|
||||
|
||||
/** The data of a waypoint to create or to change. Empty strings are fields it does not have. */
|
||||
export type NewWaypoint = {
|
||||
lng: number;
|
||||
lat: number;
|
||||
ele: number;
|
||||
name: string;
|
||||
desc: string;
|
||||
icon: string;
|
||||
link: string;
|
||||
};
|
||||
|
||||
/** Everything the UI knows about one file. */
|
||||
export type FileState = {
|
||||
structure: FileStructure;
|
||||
@@ -403,6 +424,61 @@ class Engine {
|
||||
return this.run((w) => w.move_elements(what, to));
|
||||
}
|
||||
|
||||
// Waypoints
|
||||
|
||||
/** All the data of a waypoint, `undefined` if it does not exist (or before the engine is loaded). */
|
||||
waypoint(fileId: string, waypointId: string): WaypointDetails | undefined {
|
||||
return this.wasm?.waypoint(fileId, waypointId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a waypoint to each selected file (or to the file of the selected elements). Empty
|
||||
* strings are fields that the waypoint does not have.
|
||||
*/
|
||||
newWaypoint(waypoint: NewWaypoint) {
|
||||
return this.run((w) =>
|
||||
w.new_waypoint(
|
||||
waypoint.lng,
|
||||
waypoint.lat,
|
||||
waypoint.ele,
|
||||
waypoint.name,
|
||||
waypoint.desc,
|
||||
waypoint.icon,
|
||||
waypoint.link
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Changes the selected waypoints. Empty strings remove the field. */
|
||||
updateWaypoint(waypoint: NewWaypoint) {
|
||||
return this.run((w) =>
|
||||
w.update_waypoint(
|
||||
waypoint.lng,
|
||||
waypoint.lat,
|
||||
waypoint.ele,
|
||||
waypoint.name,
|
||||
waypoint.desc,
|
||||
waypoint.icon,
|
||||
waypoint.link
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Moves a waypoint, selected or not: only its position and elevation change. */
|
||||
moveWaypoint(fileId: string, waypointId: string, lng: number, lat: number, ele: number) {
|
||||
return this.run((w) => w.move_waypoint(fileId, waypointId, lng, lat, ele));
|
||||
}
|
||||
|
||||
/** Deletes a waypoint, selected or not. */
|
||||
deleteWaypoint(fileId: string, waypointId: string) {
|
||||
return this.run((w) => w.delete_waypoint(fileId, waypointId));
|
||||
}
|
||||
|
||||
/** A trackpoint of a segment, `undefined` if it does not exist. */
|
||||
trackpoint(fileId: string, segmentId: string, index: number): TrackpointDetails | undefined {
|
||||
return this.wasm?.trackpoint(fileId, segmentId, index);
|
||||
}
|
||||
|
||||
// Edits of the selection
|
||||
|
||||
newTrack() {
|
||||
|
||||
Reference in New Issue
Block a user