mirror of
https://github.com/gpxstudio/gpx.studio.git
synced 2026-12-06 10:34:13 +00:00
Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d4804203f | ||
|
|
657cf8786c | ||
|
|
5f46b08eda | ||
|
|
2cf9a9f982 | ||
|
|
1bd8ac46fe | ||
|
|
304eaa7892 | ||
|
|
2e0edc716b | ||
|
|
776be33ff9 | ||
|
|
2fa721586b | ||
|
|
25e10dbd82 | ||
|
|
2681900a0a | ||
|
|
af46423859 | ||
|
|
8aede444fc | ||
|
|
58b2861160 | ||
|
|
9da64274ac | ||
|
|
761cfcae42 | ||
|
|
b719fe908f | ||
|
|
b6a7df3cf2 | ||
|
|
8ef3eca819 | ||
|
|
0e2a5a39df | ||
|
|
59c9427778 | ||
|
|
57c34b388b | ||
|
|
4050420b3c | ||
|
|
7474f892ce | ||
|
|
002fd259aa | ||
|
|
21e27a4416 | ||
|
|
b80fa7d942 | ||
|
|
2608870505 | ||
|
|
9e289c33be | ||
|
|
419489bcfe | ||
|
|
7a7749a9d3 | ||
|
|
9a23762af4 |
No files matched your search
@@ -52,6 +52,18 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
Each part has its own tests:
|
||||
|
||||
```bash
|
||||
cargo test # the engine (gpx-rs), from the root of the repository
|
||||
(cd wasm && wasm-pack test --node) # the WebAssembly bindings
|
||||
npm test --prefix website # the website, once the WebAssembly engine is built
|
||||
```
|
||||
|
||||
See [`tauri`](tauri/README.md) for the tests of the desktop app.
|
||||
|
||||
## Credits
|
||||
|
||||
This project has been made possible thanks to the following open source projects:
|
||||
@@ -59,6 +71,7 @@ This project has been made possible thanks to the following open source projects
|
||||
- Development:
|
||||
- [Svelte](https://github.com/sveltejs/svelte) and [SvelteKit](https://github.com/sveltejs/kit) — seamless development experience
|
||||
- [MDsveX](https://github.com/pngwn/MDsveX) — allowing a Markdown-based documentation
|
||||
- [Tauri](https://github.com/tauri-apps/tauri) – making a desktop app possible
|
||||
- Design:
|
||||
- [shadcn-svelte](https://github.com/huntabyte/shadcn-svelte) — beautiful components
|
||||
- [@lucide/svelte](https://github.com/lucide-icons/lucide/tree/main/packages/svelte) — beautiful icons
|
||||
@@ -74,6 +87,16 @@ This project has been made possible thanks to the following open source projects
|
||||
- Search:
|
||||
- [DocSearch](https://github.com/algolia/docsearch) — search engine for the documentation
|
||||
|
||||
## Integration
|
||||
|
||||
There are several ways to integrate **gpx.studio** into your website or tools:
|
||||
|
||||
- **Embedding**: show your GPX files on an interactive map in your website. See the [documentation](https://gpx.studio/help/integration) to configure the map and generate the HTML code.
|
||||
- **Map object**: `window._map` gives access to the [MapLibre GL JS](https://maplibre.org/maplibre-gl-js/docs/) map instance.
|
||||
- **Extension API**: `window.gpxstudio` lets browser extensions add map overlays that appear in the layer menu like built-in ones. See [`extension-api.ts`](website/src/lib/components/map/layer-control/extension-api.ts) for the reference.
|
||||
|
||||
To be notified about changes that may affect your integration, subscribe to [this discussion](https://github.com/gpxstudio/gpx.studio/discussions/410).
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
||||
@@ -560,26 +560,6 @@ impl WaypointDetails {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct TrackpointDetails {
|
||||
lng: f64,
|
||||
lat: f64,
|
||||
ele: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
time: Option<f64>,
|
||||
}
|
||||
|
||||
impl TrackpointDetails {
|
||||
pub fn new(pt: &engine::Trackpoint) -> Self {
|
||||
Self {
|
||||
lng: pt.coordinates.lng,
|
||||
lat: pt.coordinates.lat,
|
||||
ele: pt.ele,
|
||||
time: pt.time.map(|t| t as f64),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint.
|
||||
/// Absent fields are unknown.
|
||||
#[derive(Serialize)]
|
||||
|
||||
@@ -63,18 +63,6 @@ pub fn waypoint<H: History>(
|
||||
.map(WaypointDetails::new)
|
||||
}
|
||||
|
||||
/// A trackpoint of a segment of a file, `None` if it does not exist.
|
||||
pub fn trackpoint<H: History>(
|
||||
engine: &Engine<H>,
|
||||
file_id: Uuid,
|
||||
segment_id: Uuid,
|
||||
index: usize,
|
||||
) -> Option<TrackpointDetails> {
|
||||
engine
|
||||
.trackpoint(&FileId(file_id), &engine::TrackSegmentId(segment_id), index)
|
||||
.map(TrackpointDetails::new)
|
||||
}
|
||||
|
||||
/// A file as GPX (UTF-8 bytes), `None` if it does not exist. The options say which data of the
|
||||
/// trackpoints to keep.
|
||||
pub fn export_file<H: History>(
|
||||
|
||||
+197
-8
@@ -3,11 +3,11 @@ use crate::{
|
||||
TrackpointCategories, TrackpointChunk, Waypoint, WaypointChunk, distance,
|
||||
};
|
||||
use chrono::DateTime;
|
||||
use quick_xml::Error;
|
||||
use quick_xml::escape::resolve_predefined_entity;
|
||||
use quick_xml::events::Event;
|
||||
use quick_xml::events::attributes::{Attribute, Attributes};
|
||||
use quick_xml::reader::Reader;
|
||||
use quick_xml::{Error, XmlVersion};
|
||||
|
||||
enum GPXElement {
|
||||
Metadata,
|
||||
@@ -37,6 +37,8 @@ enum GPXElement {
|
||||
Symbol,
|
||||
Type,
|
||||
Color,
|
||||
/// The color of a track or a route in the Garmin extensions (`gpxx:DisplayColor`).
|
||||
DisplayColor,
|
||||
Opacity,
|
||||
Width,
|
||||
}
|
||||
@@ -58,6 +60,50 @@ fn is_route_point_extension(name: &str) -> bool {
|
||||
name == "rpt" || name.ends_with(":rpt")
|
||||
}
|
||||
|
||||
/// The color of a track (`RRGGBB`, the format of the style schema) and its opacity, from a color
|
||||
/// that may start with `#` and may have an alpha channel first (`AARRGGBB`), as some applications
|
||||
/// write it. A color in any other format is kept as it is, without opacity.
|
||||
fn parse_color(value: &str) -> (String, Option<f64>) {
|
||||
let value = value.trim();
|
||||
let hex = value.strip_prefix('#').unwrap_or(value);
|
||||
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return (value.to_owned(), None);
|
||||
}
|
||||
match hex.len() {
|
||||
6 => (hex.to_owned(), None),
|
||||
8 => {
|
||||
let alpha = u8::from_str_radix(&hex[..2], 16).unwrap_or(u8::MAX);
|
||||
let opacity = (f64::from(alpha) / 255.0 * 100.0).round() / 100.0;
|
||||
(hex[2..].to_owned(), Some(opacity))
|
||||
}
|
||||
_ => (value.to_owned(), None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The hexadecimal color of a value of `DisplayColor_t` in the Garmin extensions. None for
|
||||
/// `Transparent` and for what is not part of the schema.
|
||||
fn garmin_display_color(name: &str) -> Option<&'static str> {
|
||||
match name.trim() {
|
||||
"Black" => Some("000000"),
|
||||
"DarkRed" => Some("800000"),
|
||||
"DarkGreen" => Some("008000"),
|
||||
"DarkYellow" => Some("808000"),
|
||||
"DarkBlue" => Some("000080"),
|
||||
"DarkMagenta" => Some("800080"),
|
||||
"DarkCyan" => Some("008080"),
|
||||
"LightGray" => Some("c0c0c0"),
|
||||
"DarkGray" => Some("808080"),
|
||||
"Red" => Some("ff0000"),
|
||||
"Green" => Some("00ff00"),
|
||||
"Yellow" => Some("ffff00"),
|
||||
"Blue" => Some("0000ff"),
|
||||
"Magenta" => Some("ff00ff"),
|
||||
"Cyan" => Some("00ffff"),
|
||||
"White" => Some("ffffff"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the element holds a value, which is its text.
|
||||
fn holds_text(element: Option<&GPXElement>) -> bool {
|
||||
matches!(
|
||||
@@ -81,6 +127,7 @@ fn holds_text(element: Option<&GPXElement>) -> bool {
|
||||
| GPXElement::Symbol
|
||||
| GPXElement::Type
|
||||
| GPXElement::Color
|
||||
| GPXElement::DisplayColor
|
||||
| GPXElement::Opacity
|
||||
| GPXElement::Width
|
||||
)
|
||||
@@ -166,16 +213,21 @@ fn apply_text(
|
||||
}
|
||||
Some(GPXElement::Time) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
|
||||
trkpt.time = DateTime::parse_from_rfc3339(e)
|
||||
.ok()
|
||||
.map(|time| time.timestamp_millis());
|
||||
let time = DateTime::parse_from_rfc3339(e)
|
||||
.ok()
|
||||
.map(|time| time.timestamp_millis());
|
||||
match stack.last_mut() {
|
||||
Some(GPXElement::Trackpoint(trkpt)) => trkpt.time = time,
|
||||
Some(GPXElement::Waypoint(wpt)) => wpt.time = time,
|
||||
Some(GPXElement::Metadata) => gpx.info.time = time,
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Temperature) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Trackpoint(trkpt)) = stack.last_mut() {
|
||||
trkpt.atemp = e.parse().ok();
|
||||
// Garmin Connect writes whole degrees as "21.0"
|
||||
trkpt.atemp = e.parse::<f64>().ok().map(|t| t.round() as i16);
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Heartrate) => {
|
||||
@@ -241,7 +293,21 @@ fn apply_text(
|
||||
Some(GPXElement::Color) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Track(trk)) = stack.last_mut() {
|
||||
trk.info.color = Some(e.to_owned());
|
||||
let (color, opacity) = parse_color(e);
|
||||
trk.info.color = Some(color);
|
||||
// The opacity of the style schema has priority, wherever it is in the extensions
|
||||
if trk.info.opacity.is_none() {
|
||||
trk.info.opacity = opacity;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The color of the style schema has priority, wherever it is in the extensions
|
||||
Some(GPXElement::DisplayColor) => {
|
||||
stack.pop();
|
||||
if let Some(GPXElement::Track(trk)) = stack.last_mut()
|
||||
&& trk.info.color.is_none()
|
||||
{
|
||||
trk.info.color = garmin_display_color(e).map(str::to_owned);
|
||||
}
|
||||
}
|
||||
Some(GPXElement::Opacity) => {
|
||||
@@ -263,7 +329,7 @@ fn apply_text(
|
||||
/// The text of an attribute, without its escaping (`&` is `&`), which is written back when the
|
||||
/// file is. As it is in the file if it cannot be read.
|
||||
fn attribute_text(attr: &Attribute<'_>) -> String {
|
||||
attr.unescape_value()
|
||||
attr.normalized_value(XmlVersion::Implicit1_0)
|
||||
.map_or_else(|_| attr.value.to_string(), |text| text.into_owned())
|
||||
}
|
||||
|
||||
@@ -455,6 +521,7 @@ pub fn parse(data: &[u8], categories: &mut TrackpointCategories) -> Result<File,
|
||||
"sym" => stack.push(GPXElement::Symbol),
|
||||
"type" => stack.push(GPXElement::Type),
|
||||
e if e.ends_with("color") => stack.push(GPXElement::Color),
|
||||
e if e.ends_with("DisplayColor") => stack.push(GPXElement::DisplayColor),
|
||||
e if e.ends_with("opacity") => stack.push(GPXElement::Opacity),
|
||||
e if e.ends_with("width") => stack.push(GPXElement::Width),
|
||||
_ => (),
|
||||
@@ -1080,6 +1147,20 @@ mod tests {
|
||||
assert!(wpt.type_.as_ref().is_some_and(|t| t == "Bike Trail"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_waypoint_time() {
|
||||
let data = r#"<gpx><wpt lat="1" lon="2"><time>2024-05-01T06:10:00Z</time></wpt></gpx>"#;
|
||||
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
|
||||
assert_eq!(gpx.wpt[0].time, Some(1714543800000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_metadata_time() {
|
||||
let data = r#"<gpx><metadata><time>2024-05-01T06:10:00Z</time></metadata></gpx>"#;
|
||||
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
|
||||
assert_eq!(gpx.info.time, Some(1714543800000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trackpoint_time() {
|
||||
let gpx = parse_data("with_time");
|
||||
@@ -1263,6 +1344,14 @@ mod tests {
|
||||
assert!(trkpt.atemp.is_some_and(|t| t == 21));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_trackpoint_decimal_atemp() {
|
||||
let data = r#"<gpx><trk><trkseg><trkpt lat="1" lon="2"><extensions><gpxtpx:TrackPointExtension>
|
||||
<gpxtpx:atemp>21.0</gpxtpx:atemp></gpxtpx:TrackPointExtension></extensions></trkpt></trkseg></trk></gpx>"#;
|
||||
let gpx = parse(data.as_bytes(), &mut Default::default()).unwrap();
|
||||
assert_eq!(gpx.trk[0].trkseg[0][0].atemp, Some(21));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_track_style() {
|
||||
let gpx = parse_data("with_style");
|
||||
@@ -1274,4 +1363,104 @@ mod tests {
|
||||
assert!(trk.info.opacity.is_some_and(|o| o == 0.5));
|
||||
assert!(trk.info.width.is_some_and(|w| w == 6.0));
|
||||
}
|
||||
|
||||
fn parse_text(text: &str) -> File {
|
||||
parse(text.as_bytes(), &mut Default::default()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_garmin_display_color_of_tracks_and_routes() {
|
||||
let gpx = parse_text(
|
||||
r#"<gpx xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"
|
||||
xmlns:gpxtrx="http://www.garmin.com/xmlschemas/GpxExtensions/v3">
|
||||
<trk><extensions><gpxx:TrackExtension>
|
||||
<gpxx:DisplayColor>Blue</gpxx:DisplayColor>
|
||||
</gpxx:TrackExtension></extensions></trk>
|
||||
<trk><extensions><gpxtrx:TrackExtension>
|
||||
<gpxtrx:DisplayColor>DarkRed</gpxtrx:DisplayColor>
|
||||
</gpxtrx:TrackExtension></extensions></trk>
|
||||
<rte><extensions><gpxx:RouteExtension>
|
||||
<gpxx:DisplayColor>Green</gpxx:DisplayColor>
|
||||
</gpxx:RouteExtension></extensions></rte>
|
||||
</gpx>"#,
|
||||
);
|
||||
|
||||
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("0000ff"));
|
||||
assert_eq!(gpx.trk[1].info.color.as_deref(), Some("800000"));
|
||||
assert_eq!(gpx.rte[0].info.color.as_deref(), Some("00ff00"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_garmin_display_color_without_a_color_leaves_the_track_uncolored() {
|
||||
let gpx = parse_text(
|
||||
r#"<gpx>
|
||||
<trk><extensions><gpxx:TrackExtension>
|
||||
<gpxx:DisplayColor>Transparent</gpxx:DisplayColor>
|
||||
</gpxx:TrackExtension></extensions></trk>
|
||||
<trk><extensions><gpxx:TrackExtension>
|
||||
<gpxx:DisplayColor>Mauve</gpxx:DisplayColor>
|
||||
</gpxx:TrackExtension></extensions></trk>
|
||||
</gpx>"#,
|
||||
);
|
||||
|
||||
assert_eq!(gpx.trk[0].info.color, None);
|
||||
assert_eq!(gpx.trk[1].info.color, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_style_color_has_priority_over_garmin_display_color() {
|
||||
let gpx = parse_text(
|
||||
r#"<gpx>
|
||||
<trk><extensions>
|
||||
<gpxx:TrackExtension><gpxx:DisplayColor>Red</gpxx:DisplayColor></gpxx:TrackExtension>
|
||||
<gpx_style:line><gpx_style:color>2d3ee9</gpx_style:color></gpx_style:line>
|
||||
</extensions></trk>
|
||||
<trk><extensions>
|
||||
<gpx_style:line><gpx_style:color>2d3ee9</gpx_style:color></gpx_style:line>
|
||||
<gpxx:TrackExtension><gpxx:DisplayColor>Red</gpxx:DisplayColor></gpxx:TrackExtension>
|
||||
</extensions></trk>
|
||||
</gpx>"#,
|
||||
);
|
||||
|
||||
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("2d3ee9"));
|
||||
assert_eq!(gpx.trk[1].info.color.as_deref(), Some("2d3ee9"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_color_with_hash_and_alpha() {
|
||||
assert_eq!(parse_color("2d3ee9"), ("2d3ee9".into(), None));
|
||||
assert_eq!(parse_color("#0000FF"), ("0000FF".into(), None));
|
||||
assert_eq!(parse_color("#800000FF"), ("0000FF".into(), Some(0.5)));
|
||||
assert_eq!(parse_color("FF0000FF"), ("0000FF".into(), Some(1.0)));
|
||||
assert_eq!(parse_color("#00ff0000"), ("ff0000".into(), Some(0.0)));
|
||||
assert_eq!(parse_color("red"), ("red".into(), None));
|
||||
assert_eq!(parse_color("#abc"), ("#abc".into(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_track_color_with_alpha() {
|
||||
let gpx = parse_text(
|
||||
r#"<gpx>
|
||||
<trk><extensions><xsi:gpx>
|
||||
<physicalColor>#400000FF</physicalColor>
|
||||
<width>4</width>
|
||||
<color>#800000FF</color>
|
||||
</xsi:gpx></extensions></trk>
|
||||
<trk><extensions><gpx_style:line>
|
||||
<gpx_style:opacity>0.3</gpx_style:opacity>
|
||||
<gpx_style:color>#800000FF</gpx_style:color>
|
||||
</gpx_style:line></extensions></trk>
|
||||
<trk><extensions><gpx_style:line>
|
||||
<gpx_style:color>#800000FF</gpx_style:color>
|
||||
<gpx_style:opacity>0.3</gpx_style:opacity>
|
||||
</gpx_style:line></extensions></trk>
|
||||
</gpx>"#,
|
||||
);
|
||||
|
||||
assert_eq!(gpx.trk[0].info.color.as_deref(), Some("0000FF"));
|
||||
assert_eq!(gpx.trk[0].info.opacity, Some(0.5));
|
||||
assert_eq!(gpx.trk[0].info.width, Some(4.0));
|
||||
assert_eq!(gpx.trk[1].info.opacity, Some(0.3));
|
||||
assert_eq!(gpx.trk[2].info.opacity, Some(0.3));
|
||||
}
|
||||
}
|
||||
@@ -24,14 +24,6 @@ pub struct Statistics {
|
||||
}
|
||||
|
||||
impl Statistics {
|
||||
pub fn total_speed(&self) -> Option<f64> {
|
||||
self.global.total_speed()
|
||||
}
|
||||
|
||||
pub fn moving_speed(&self) -> Option<f64> {
|
||||
self.global.moving_speed()
|
||||
}
|
||||
|
||||
pub fn compute(trkseg: &TrackSegment) -> Self {
|
||||
let mut stats = Self::default();
|
||||
if trkseg.is_empty() {
|
||||
|
||||
@@ -36,6 +36,7 @@ impl StatisticsCache {
|
||||
}
|
||||
|
||||
/// Statistics of the segments of the selection.
|
||||
#[cfg(test)]
|
||||
pub fn get<'a>(
|
||||
&'a self,
|
||||
state: Option<&'a Files>,
|
||||
|
||||
@@ -11,7 +11,7 @@ pub use outcome::*;
|
||||
pub use state::*;
|
||||
|
||||
use crate::{
|
||||
ExportOptions, FileId, GlobalStatistics, Restored, Snapshot, TrackSegmentId, Trackpoint,
|
||||
ExportOptions, FileId, GlobalStatistics, Restored, Snapshot, TrackSegmentId,
|
||||
TrackpointCategories, Waypoint, WaypointId, reduction_distances, write,
|
||||
};
|
||||
|
||||
@@ -82,22 +82,6 @@ impl<H: History> Engine<H> {
|
||||
.find(|wpt| wpt.id == *id)
|
||||
}
|
||||
|
||||
/// A trackpoint of a segment (of a route or a track) 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
|
||||
.history
|
||||
.current()?
|
||||
.get(file_id)?
|
||||
.segments()
|
||||
.find(|seg| seg.id == *segment_id)?;
|
||||
(index < segment.len()).then(|| &segment[index])
|
||||
}
|
||||
|
||||
/// For each trackpoint of the selection (numbered as in the statistics), the tolerance up to
|
||||
/// which `Reduce` keeps it, see [`reduction_distances`].
|
||||
pub fn reduction_distances(&self) -> Vec<f64> {
|
||||
|
||||
@@ -1169,24 +1169,6 @@ fn test_categories_are_shared_and_kept_by_the_history() {
|
||||
assert_eq!(expand(&engine.statistics().surface, 5), [1, 1, 0, 2, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_trackpoint() {
|
||||
let mut engine = TestEngine::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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_export_writes_the_file_as_it_is() {
|
||||
let mut engine = TestEngine::default();
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{
|
||||
Batch, ChunkKey, ChunkKind, CommitError, FileId, Revision, Storage, StorageError, StoredData,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use crate::ChunkKind;
|
||||
use crate::{Batch, ChunkKey, CommitError, FileId, Revision, Storage, StorageError, StoredData};
|
||||
|
||||
/// A storage that lives as long as the session. It is what an engine without a host storage uses,
|
||||
/// and what the tests use.
|
||||
@@ -22,6 +22,7 @@ struct State {
|
||||
}
|
||||
|
||||
/// How much there is in a storage.
|
||||
#[cfg(test)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StorageCounts {
|
||||
pub files: usize,
|
||||
@@ -29,6 +30,7 @@ pub struct StorageCounts {
|
||||
pub waypoint_chunks: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl MemoryStorage {
|
||||
/// How many files and chunks are stored.
|
||||
pub fn counts(&self) -> StorageCounts {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# tauri
|
||||
|
||||
The desktop app of gpx.studio, built with [Tauri 2](https://v2.tauri.app/).
|
||||
Its UI is the website ([`../website`](../website)), and it runs the engine of [`../gpx-rs`](../gpx-rs) natively instead of in WebAssembly.
|
||||
|
||||
## Development
|
||||
|
||||
You will need the same tools as for the website: [Node.js](https://nodejs.org/), [Rust](https://rustup.rs/) and [wasm-pack](https://rustwasm.github.io/wasm-pack/).
|
||||
To run the app in development mode, you will also need to install the [system dependencies of Tauri](https://v2.tauri.app/start/prerequisites/) for your platform and the Tauri CLI:
|
||||
|
||||
```bash
|
||||
cargo install tauri-cli --version "^2"
|
||||
```
|
||||
|
||||
### Setting up the frontend
|
||||
|
||||
The desktop app does not use the WebAssembly engine, but the website depends on its package.
|
||||
From the root of the repository, build it once and install the website’s dependencies:
|
||||
|
||||
```bash
|
||||
cd wasm && wasm-pack build --target bundler && cd ..
|
||||
npm install --prefix website
|
||||
```
|
||||
|
||||
For the MapTiler layers, add your key to `website/.env`, as explained in the [main README](../README.md#running-the-website).
|
||||
|
||||
### Running the app
|
||||
|
||||
```bash
|
||||
cd tauri
|
||||
cargo tauri dev
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
cargo test -p gpx-studio-desktop
|
||||
```
|
||||
@@ -57,16 +57,6 @@ pub fn waypoint(
|
||||
state.read(move |e| api::waypoint(e, file_id, waypoint_id))
|
||||
}
|
||||
|
||||
#[tauri::command(async)]
|
||||
pub fn trackpoint(
|
||||
state: State<AppState>,
|
||||
file_id: Uuid,
|
||||
segment_id: Uuid,
|
||||
index: usize,
|
||||
) -> Option<api::TrackpointDetails> {
|
||||
state.read(move |e| api::trackpoint(e, file_id, segment_id, index))
|
||||
}
|
||||
|
||||
/// A file as GPX (UTF-8 bytes), the first byte telling whether the file exists.
|
||||
#[tauri::command(async)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
|
||||
@@ -173,7 +173,6 @@ pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri
|
||||
queries::can_redo,
|
||||
queries::can_paste,
|
||||
queries::waypoint,
|
||||
queries::trackpoint,
|
||||
queries::export_file,
|
||||
queries::exportable_data,
|
||||
queries::reduction_distances,
|
||||
|
||||
@@ -101,18 +101,6 @@ pub fn waypoint(file_id: &str, waypoint_id: &str) -> WaypointDetails {
|
||||
optional_js(details).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 {
|
||||
let details =
|
||||
parse_uuid(file_id)
|
||||
.zip(parse_uuid(segment_id))
|
||||
.and_then(|(file_id, segment_id)| {
|
||||
with_engine(|e| api::trackpoint(e, file_id, segment_id, index)).flatten()
|
||||
});
|
||||
optional_js(details).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]
|
||||
|
||||
@@ -59,14 +59,6 @@ export interface WaypointDetails {
|
||||
links?: { 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;
|
||||
}
|
||||
/**
|
||||
* A trackpoint of the selection: what the statistics buffers do not hold for each trackpoint.
|
||||
* Absent fields are unknown.
|
||||
@@ -189,8 +181,6 @@ extern "C" {
|
||||
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 = "SelectionPoint | undefined")]
|
||||
pub type SelectionPoint;
|
||||
#[wasm_bindgen(typescript_type = "MoveTarget")]
|
||||
|
||||
Generated
+39
-53
@@ -18,7 +18,7 @@
|
||||
"gpx-wasm": "file:../wasm/pkg",
|
||||
"jszip": "^3.10.1",
|
||||
"mapillary-js": "^4.1.2",
|
||||
"maplibre-gl": "^6.15.0",
|
||||
"maplibre-gl": "^6.18.0",
|
||||
"sanitize-html": "^2.17.0",
|
||||
"sortablejs": "^1.15.7"
|
||||
},
|
||||
@@ -26,6 +26,7 @@
|
||||
"@fontsource-variable/inter": "^5.2.8",
|
||||
"@internationalized/date": "^3.12.0",
|
||||
"@lucide/svelte": "^1.7.0",
|
||||
"@mapbox/vector-tile": "^3.0.0",
|
||||
"@sveltejs/adapter-static": "^3.0.8",
|
||||
"@sveltejs/enhanced-img": "^0.6.0",
|
||||
"@sveltejs/kit": "^2.21.2",
|
||||
@@ -56,6 +57,7 @@
|
||||
"mdsvex": "^0.12.6",
|
||||
"mode-watcher": "^1.1.0",
|
||||
"paneforge": "^1.0.0-next.5",
|
||||
"pbf": "^5.2.1",
|
||||
"postcss": "^8.4.47",
|
||||
"prettier": "^3.5.3",
|
||||
"prettier-plugin-svelte": "^3.4.0",
|
||||
@@ -1749,18 +1751,6 @@
|
||||
"pbf": "^5.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@mapbox/vector-tile/node_modules/pbf": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
|
||||
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"resolve-protobuf-schema": "^2.1.0"
|
||||
},
|
||||
"bin": {
|
||||
"pbf": "bin/pbf"
|
||||
}
|
||||
},
|
||||
"node_modules/@maplibre/geojson-vt": {
|
||||
"version": "6.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.3.0.tgz",
|
||||
@@ -1788,9 +1778,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@maplibre/maplibre-gl-style-spec": {
|
||||
"version": "26.4.4",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.4.tgz",
|
||||
"integrity": "sha512-hG4RZR4PBd/+6A3ODdZ3AnQRF106ZQk1y3bhwDg8bH/A4Oz2tnRUJVVWs9BZa6gXZ1d3UKe89C+Mm+olGBELvA==",
|
||||
"version": "26.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.7.0.tgz",
|
||||
"integrity": "sha512-9d7hK1zk1WRx/AFvq7NtmlTlaOGPXS2r+FZXsrMv8453Xy14bnXBpVCPJDBupCfQs/p8FL0/kb0ygbEWTufN0g==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@mapbox/jsonlint-lines-primitives": "^2.0.3",
|
||||
@@ -1816,26 +1806,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@maplibre/vt-pbf": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz",
|
||||
"integrity": "sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==",
|
||||
"version": "4.3.3",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.3.tgz",
|
||||
"integrity": "sha512-dEe5XUd64RQbxNxy2OzIkJnwNDWjVmSXjCd0A7zLirm7QJ/WWbmtDFIkfsiM4yt1cplqzG6oSivRYeWx1SM1yg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mapbox/point-geometry": "^1.1.0",
|
||||
"@types/geojson": "^7946.0.16",
|
||||
"pbf": "^5.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@maplibre/vt-pbf/node_modules/pbf": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
|
||||
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"resolve-protobuf-schema": "^2.1.0"
|
||||
},
|
||||
"bin": {
|
||||
"pbf": "bin/pbf"
|
||||
"pbf": "^5.1.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@polka/url": {
|
||||
@@ -4057,6 +4035,8 @@
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -4673,10 +4653,23 @@
|
||||
"version": "2.1.0",
|
||||
"license": "(MIT AND Zlib)"
|
||||
},
|
||||
"node_modules/mapillary-js/node_modules/pbf": {
|
||||
"version": "3.3.0",
|
||||
"resolved": "https://registry.npmjs.org/pbf/-/pbf-3.3.0.tgz",
|
||||
"integrity": "sha512-XDF38WCH3z5OV/OVa8GKUNtLAyneuzbCisx7QUCF8Q6Nutx0WnJrQe5O+kOtBlLfRNUws98Y58Lblp+NJG5T4Q==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"ieee754": "^1.1.12",
|
||||
"resolve-protobuf-schema": "^2.1.0"
|
||||
},
|
||||
"bin": {
|
||||
"pbf": "bin/pbf"
|
||||
}
|
||||
},
|
||||
"node_modules/maplibre-gl": {
|
||||
"version": "6.15.0",
|
||||
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.15.0.tgz",
|
||||
"integrity": "sha512-kxFetbvUHDOVaAP1CYb226Mdk2QhzIPddqM0xJTFD35wu78Mpd6NM7+H68ALjc6Oa0kAOX5EAdMKyvD2u3qfcg==",
|
||||
"version": "6.18.0",
|
||||
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.18.0.tgz",
|
||||
"integrity": "sha512-8ucT+RhJtEZGFvWGPioVQwvOPMAIuUehEgxl2dELw9aJmX4SpUi+OCHHAD33B9EuohNC7kC/gccJacUgTMQfQQ==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@mapbox/point-geometry": "^1.1.0",
|
||||
@@ -4684,9 +4677,9 @@
|
||||
"@mapbox/unitbezier": "^1.0.0",
|
||||
"@mapbox/vector-tile": "^3.0.0",
|
||||
"@maplibre/geojson-vt": "^6.3.0",
|
||||
"@maplibre/maplibre-gl-style-spec": "^26.4.4",
|
||||
"@maplibre/maplibre-gl-style-spec": "^26.6.0",
|
||||
"@maplibre/mlt": "^1.3.0",
|
||||
"@maplibre/vt-pbf": "^4.3.2",
|
||||
"@maplibre/vt-pbf": "^4.3.3",
|
||||
"@types/geojson": "^7946.0.16",
|
||||
"bidi-js": "^1.1.0",
|
||||
"earcut": "^3.2.4",
|
||||
@@ -4712,18 +4705,6 @@
|
||||
"integrity": "sha512-FHc6yNpnTORB0tM5kmZ03iD2mDuNakDE2lvf4Hw1XkfxtEHIGVi01B/GqUSwx+NcC1WGjidAfpTXzeALtPtfpg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/maplibre-gl/node_modules/pbf": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
|
||||
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"resolve-protobuf-schema": "^2.1.0"
|
||||
},
|
||||
"bin": {
|
||||
"pbf": "bin/pbf"
|
||||
}
|
||||
},
|
||||
"node_modules/martinez-polygon-clipping": {
|
||||
"version": "0.7.4",
|
||||
"license": "MIT",
|
||||
@@ -5085,11 +5066,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/pbf": {
|
||||
"version": "3.3.0",
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.2.1.tgz",
|
||||
"integrity": "sha512-5s6y6g3akGMF98eemb+3QZAWTCUHyox40TJOwcY4M1w40RvoXrfbRUVmY02RlRiEPyE6KVaM0xxfF4+4vjSJTQ==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"ieee754": "^1.1.12",
|
||||
"resolve-protobuf-schema": "^2.1.0"
|
||||
"protocol-buffers-schema": "^3.6.1"
|
||||
},
|
||||
"bin": {
|
||||
"pbf": "bin/pbf"
|
||||
@@ -5313,7 +5295,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/protocol-buffers-schema": {
|
||||
"version": "3.6.0",
|
||||
"version": "3.6.1",
|
||||
"resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.1.tgz",
|
||||
"integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/punycode": {
|
||||
@@ -5395,6 +5379,8 @@
|
||||
},
|
||||
"node_modules/resolve-protobuf-schema": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",
|
||||
"integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"protocol-buffers-schema": "^3.3.1"
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"@fontsource-variable/inter": "^5.2.8",
|
||||
"@internationalized/date": "^3.12.0",
|
||||
"@lucide/svelte": "^1.7.0",
|
||||
"@mapbox/vector-tile": "^3.0.0",
|
||||
"@sveltejs/adapter-static": "^3.0.8",
|
||||
"@sveltejs/enhanced-img": "^0.6.0",
|
||||
"@sveltejs/kit": "^2.21.2",
|
||||
@@ -51,6 +52,7 @@
|
||||
"mdsvex": "^0.12.6",
|
||||
"mode-watcher": "^1.1.0",
|
||||
"paneforge": "^1.0.0-next.5",
|
||||
"pbf": "^5.2.1",
|
||||
"postcss": "^8.4.47",
|
||||
"prettier": "^3.5.3",
|
||||
"prettier-plugin-svelte": "^3.4.0",
|
||||
@@ -82,7 +84,7 @@
|
||||
"gpx-wasm": "file:../wasm/pkg",
|
||||
"jszip": "^3.10.1",
|
||||
"mapillary-js": "^4.1.2",
|
||||
"maplibre-gl": "^6.15.0",
|
||||
"maplibre-gl": "^6.18.0",
|
||||
"sanitize-html": "^2.17.0",
|
||||
"sortablejs": "^1.15.7"
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
statistics,
|
||||
slicedStatistics,
|
||||
hoveredPoint,
|
||||
hoveredTrackpoint,
|
||||
additionalDatasets,
|
||||
elevationFill,
|
||||
showControls = true,
|
||||
@@ -38,6 +39,7 @@
|
||||
statistics: Readable<SelectionStatistics>;
|
||||
slicedStatistics: Writable<SlicedStatistics | undefined>;
|
||||
hoveredPoint: Writable<Coordinates | null>;
|
||||
hoveredTrackpoint?: Readable<number | null>;
|
||||
additionalDatasets: Writable<string[]>;
|
||||
elevationFill: Writable<'slope' | 'surface' | 'highway' | undefined>;
|
||||
showControls?: boolean;
|
||||
@@ -55,7 +57,8 @@
|
||||
additionalDatasets,
|
||||
elevationFill,
|
||||
canvas,
|
||||
overlay
|
||||
overlay,
|
||||
hoveredTrackpoint
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -15,10 +15,15 @@ import {
|
||||
getVelocityWithUnits,
|
||||
} from '$lib/units/units';
|
||||
import Chart, {
|
||||
Tooltip,
|
||||
type ActiveDataPoint,
|
||||
type ChartEvent,
|
||||
type ChartOptions,
|
||||
type ChartType,
|
||||
type Point,
|
||||
type ScriptableLineSegmentContext,
|
||||
type TooltipItem,
|
||||
type TooltipPositionerFunction,
|
||||
} from 'chart.js/auto';
|
||||
import { get, type Readable, type Writable } from 'svelte/store';
|
||||
import type { Coordinates } from '$lib/geo/coordinates';
|
||||
@@ -40,6 +45,25 @@ const { distanceUnits, velocityUnits, temperatureUnits } = settings;
|
||||
Chart.defaults.font.family =
|
||||
'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"'; // Tailwind CSS font
|
||||
|
||||
declare module 'chart.js' {
|
||||
interface TooltipPositionerMap {
|
||||
trackpoint: TooltipPositionerFunction<ChartType>;
|
||||
}
|
||||
}
|
||||
|
||||
/** Marks the positions of the trackpoints shown without an event of the chart. */
|
||||
const trackpointPosition = Symbol('trackpointPosition');
|
||||
|
||||
/**
|
||||
* Like the default for the events of the chart. A trackpoint that is shown without one is given by
|
||||
* its position, as it can be between the points of the chart (see `activateTrackpoint`).
|
||||
*/
|
||||
Tooltip.positioners.trackpoint = function (items, position) {
|
||||
return trackpointPosition in position
|
||||
? position
|
||||
: Tooltip.positioners.average.call(this, items, position);
|
||||
};
|
||||
|
||||
/** `undefined` for a missing measure (NaN), so that Chart.js leaves a gap instead of a value. */
|
||||
function optional(value: number, convert: (value: number) => number = (v) => v) {
|
||||
return Number.isNaN(value) ? undefined : convert(value);
|
||||
@@ -55,6 +79,21 @@ interface ElevationProfilePoint {
|
||||
index: number;
|
||||
}
|
||||
|
||||
/** The index of the point the closest to `x`, in points sorted by `x`. */
|
||||
function nearestPointIndex(points: { x: number }[], x: number): number {
|
||||
let low = 0;
|
||||
let high = points.length - 1;
|
||||
while (low < high) {
|
||||
const middle = (low + high) >> 1;
|
||||
if (points[middle].x < x) {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
return low > 0 && x - points[low - 1].x < points[low].x - x ? low - 1 : low;
|
||||
}
|
||||
|
||||
export class ElevationProfile {
|
||||
private _chart: Chart | null = null;
|
||||
private _canvas: HTMLCanvasElement;
|
||||
@@ -71,10 +110,14 @@ export class ElevationProfile {
|
||||
*/
|
||||
private _hovered: { index: number; loaded: boolean; point?: SelectionPoint } | null = null;
|
||||
private _loadingHovered = false;
|
||||
/** The last move over the chart, held until the data of its trackpoint is read. */
|
||||
private _heldMove: MouseEvent | null = null;
|
||||
private _slicedStatistics: Writable<SlicedStatistics | undefined>;
|
||||
private _hoveredPoint: Writable<Coordinates | null>;
|
||||
/** All the points of each dataset, including the ones that the chart decimated. */
|
||||
private _points: ElevationProfilePoint[][] = [];
|
||||
/** The trackpoint hovered somewhere else, that the tooltip shows instead of its elements. */
|
||||
private _shownTrackpoint: number | null = null;
|
||||
private _hoveredTrackpoint: Readable<number | null> | undefined;
|
||||
private _unsubscribeHoveredTrackpoint: (() => void) | undefined;
|
||||
private _additionalDatasets: Readable<string[]>;
|
||||
private _elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>;
|
||||
/** The statistics that are only read from the engine while the profile shows them. */
|
||||
@@ -87,7 +130,8 @@ export class ElevationProfile {
|
||||
additionalDatasets: Readable<string[]>,
|
||||
elevationFill: Readable<'slope' | 'surface' | 'highway' | undefined>,
|
||||
canvas: HTMLCanvasElement,
|
||||
overlay: HTMLCanvasElement
|
||||
overlay: HTMLCanvasElement,
|
||||
hoveredTrackpoint?: Readable<number | null>
|
||||
) {
|
||||
this._statistics = statistics;
|
||||
this._slicedStatistics = slicedStatistics;
|
||||
@@ -96,6 +140,7 @@ export class ElevationProfile {
|
||||
this._elevationFill = elevationFill;
|
||||
this._canvas = canvas;
|
||||
this._overlay = overlay;
|
||||
this._hoveredTrackpoint = hoveredTrackpoint;
|
||||
this._request = engine.requestStatistics();
|
||||
this.updateRequest();
|
||||
|
||||
@@ -127,6 +172,9 @@ export class ElevationProfile {
|
||||
this.updateRequest();
|
||||
this.updateFill();
|
||||
});
|
||||
this._unsubscribeHoveredTrackpoint = this._hoveredTrackpoint?.subscribe((index) => {
|
||||
this.showTrackpoint(index);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -195,20 +243,16 @@ export class ElevationProfile {
|
||||
},
|
||||
tooltip: {
|
||||
enabled: () => !this._dragging && !this._panning,
|
||||
position: 'trackpoint',
|
||||
callbacks: {
|
||||
title: () => {
|
||||
return '';
|
||||
},
|
||||
label: (context: TooltipItem<'line'>) => {
|
||||
const point = context.raw as ElevationProfilePoint;
|
||||
const point = this.pointOf(context);
|
||||
if (context.datasetIndex === 0) {
|
||||
this._hoveredPoint.set(
|
||||
this._dragging
|
||||
? null
|
||||
: {
|
||||
lat: this._data.lat[point.index],
|
||||
lng: this._data.lng[point.index],
|
||||
}
|
||||
this._dragging ? null : this.coordinatesOf(point.index)
|
||||
);
|
||||
return `${i18n._('quantities.elevation')}: ${getElevationWithUnits(point.y, false)}`;
|
||||
} else if (context.datasetIndex === 1) {
|
||||
@@ -228,7 +272,7 @@ export class ElevationProfile {
|
||||
(context) => context.datasetIndex === 0
|
||||
);
|
||||
if (context.length === 0) return;
|
||||
const point = context[0].raw as ElevationProfilePoint;
|
||||
const point = this.pointOf(context[0]);
|
||||
// the rest of the data is there once it is read (see `hover`)
|
||||
const hovered = this._hovered;
|
||||
const details =
|
||||
@@ -365,29 +409,21 @@ export class ElevationProfile {
|
||||
afterEvent: (chart: Chart, args: { event: ChartEvent }) => {
|
||||
if (args.event.type === 'mouseout') {
|
||||
this._hovered = null;
|
||||
this._heldMove = null;
|
||||
this._hoveredPoint.set(null);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
// The tooltip only shows a trackpoint once all its data is read: a move to
|
||||
// another one is held until then, and replayed (see `loadHovered`).
|
||||
id: 'waitForTrackpoint',
|
||||
// The tooltip follows the pointer at once with what the chart knows of the
|
||||
// trackpoint, and shows the rest of its data once it is read (see
|
||||
// `loadHovered`).
|
||||
id: 'loadTrackpoint',
|
||||
events: ['mousemove'],
|
||||
beforeEvent: (chart: Chart, args: { event: ChartEvent }) => {
|
||||
const index = this.indexAt(args.event);
|
||||
if (index === undefined) {
|
||||
return;
|
||||
if (index !== undefined) {
|
||||
this.hover(index);
|
||||
}
|
||||
const hovered = this._hovered;
|
||||
if (hovered?.index === index && hovered.loaded) {
|
||||
this._heldMove = null;
|
||||
return;
|
||||
}
|
||||
this._heldMove = args.event.native as MouseEvent;
|
||||
this.hover(index);
|
||||
return false;
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -478,6 +514,7 @@ export class ElevationProfile {
|
||||
}
|
||||
const data = get(this._statistics);
|
||||
this._data = data;
|
||||
const shownTrackpoint = this._shownTrackpoint;
|
||||
// the indices of the trackpoints are the ones of other statistics
|
||||
this._hovered = null;
|
||||
const units = {
|
||||
@@ -524,6 +561,7 @@ export class ElevationProfile {
|
||||
}
|
||||
}
|
||||
|
||||
this._points = datasets;
|
||||
this._chart.data.datasets[0] = {
|
||||
label: i18n._('quantities.elevation'),
|
||||
data: datasets[0],
|
||||
@@ -570,6 +608,10 @@ export class ElevationProfile {
|
||||
this.setFill();
|
||||
|
||||
this._chart.update();
|
||||
|
||||
if (shownTrackpoint !== null) {
|
||||
this.showTrackpoint(shownTrackpoint);
|
||||
}
|
||||
}
|
||||
|
||||
updateDataVisibility() {
|
||||
@@ -678,6 +720,74 @@ export class ElevationProfile {
|
||||
}
|
||||
}
|
||||
|
||||
/** The point that a line of the tooltip is about. */
|
||||
private pointOf(context: TooltipItem<'line'>): ElevationProfilePoint {
|
||||
return this._shownTrackpoint === null
|
||||
? (context.raw as ElevationProfilePoint)
|
||||
: this._points[context.datasetIndex][this._shownTrackpoint];
|
||||
}
|
||||
|
||||
private coordinatesOf(index: number): Coordinates {
|
||||
return { lat: this._data.lat[index], lng: this._data.lng[index] };
|
||||
}
|
||||
|
||||
/** Shows a trackpoint in the tooltip like when hovering it, or nothing anymore with `null`. */
|
||||
private showTrackpoint(index: number | null) {
|
||||
const shown = this._shownTrackpoint;
|
||||
this._shownTrackpoint = index;
|
||||
if (index !== null) {
|
||||
this.hover(index);
|
||||
if (this._hovered?.loaded) {
|
||||
this.activateTrackpoint(index);
|
||||
}
|
||||
} else if (shown !== null) {
|
||||
this._hovered = null;
|
||||
this.setActiveElements([], { x: 0, y: 0 });
|
||||
this._hoveredPoint.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the tooltip on a trackpoint, once its data is read. The chart can only activate the
|
||||
* points that it kept after decimating its data, which are different for each dataset and might
|
||||
* not include the trackpoint: it activates the nearest ones, within a pixel of it, and the
|
||||
* tooltip reads the values of the trackpoint (see `pointOf`).
|
||||
*/
|
||||
private activateTrackpoint(index: number) {
|
||||
const point = this._points[0]?.[index];
|
||||
if (!this._chart || !point) {
|
||||
return;
|
||||
}
|
||||
const { x: xScale, y: yScale } = this._chart.scales;
|
||||
const elements: ActiveDataPoint[] = [];
|
||||
// when the chart is zoomed, the trackpoint can be outside of it
|
||||
if (xScale.min <= point.x && point.x <= xScale.max) {
|
||||
for (const { index: datasetIndex } of this._chart.getSortedVisibleDatasetMetas()) {
|
||||
if (this._points[datasetIndex]?.[index]?.y !== undefined) {
|
||||
const data = this._chart.data.datasets[datasetIndex].data as { x: number }[];
|
||||
elements.push({ datasetIndex, index: nearestPointIndex(data, point.x) });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (elements.length === 0) {
|
||||
// no tooltip to tell the map about the point
|
||||
this._hoveredPoint.set(this.coordinatesOf(index));
|
||||
}
|
||||
this.setActiveElements(elements, {
|
||||
x: xScale.getPixelForValue(point.x),
|
||||
y: yScale.getPixelForValue(point.y),
|
||||
[trackpointPosition]: true,
|
||||
} as Point);
|
||||
}
|
||||
|
||||
private setActiveElements(elements: ActiveDataPoint[], position: Point) {
|
||||
if (this._chart) {
|
||||
this._chart.tooltip?.setActiveElements(elements, position);
|
||||
this._chart.setActiveElements(elements);
|
||||
this._chart.render();
|
||||
}
|
||||
}
|
||||
|
||||
/** The trackpoint that the tooltip shows for an event, `undefined` outside of the chart. */
|
||||
private indexAt(event: ChartEvent): number | undefined {
|
||||
const elements = this._chart?.getElementsAtEventForMode(
|
||||
@@ -718,11 +828,10 @@ export class ElevationProfile {
|
||||
}
|
||||
hovered.loaded = true;
|
||||
hovered.point = point;
|
||||
// the move that was held can now show the tooltip
|
||||
const move = this._heldMove;
|
||||
this._heldMove = null;
|
||||
if (move) {
|
||||
this._canvas.dispatchEvent(new MouseEvent(move.type, move));
|
||||
if (this._shownTrackpoint === hovered.index) {
|
||||
this.activateTrackpoint(hovered.index);
|
||||
} else {
|
||||
this.refreshTooltip();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -730,6 +839,18 @@ export class ElevationProfile {
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the tooltip again, on the same trackpoint, for the data that was read since. */
|
||||
private refreshTooltip() {
|
||||
// the plugin of the tooltip, whose type only has its model
|
||||
const tooltip = this._chart?.tooltip as
|
||||
| (Chart['tooltip'] & { update(changed: boolean): void })
|
||||
| undefined;
|
||||
if (tooltip && tooltip.getActiveElements().length > 0) {
|
||||
tooltip.update(true);
|
||||
this._chart!.render();
|
||||
}
|
||||
}
|
||||
|
||||
/** The trackpoint that a segment of the chart starts at. */
|
||||
private static segmentStart(context: ScriptableLineSegmentContext & { p0: { raw: any } }) {
|
||||
return (context.p0.raw as ElevationProfilePoint).index;
|
||||
@@ -758,6 +879,7 @@ export class ElevationProfile {
|
||||
|
||||
destroy() {
|
||||
this._request.release();
|
||||
this._unsubscribeHoveredTrackpoint?.();
|
||||
if (this._chart) {
|
||||
this._chart.destroy();
|
||||
this._chart = null;
|
||||
|
||||
@@ -18,7 +18,11 @@
|
||||
import { untrack } from 'svelte';
|
||||
import { isSelected, toggle } from '$lib/components/map/layer-control/utils';
|
||||
import { engine } from '$lib/engine';
|
||||
import { hoveredPoint, slicedStatistics } from '$lib/state/selection-statistics';
|
||||
import {
|
||||
hoveredPoint,
|
||||
hoveredTrackpoint,
|
||||
slicedStatistics,
|
||||
} from '$lib/state/selection-statistics';
|
||||
|
||||
let {
|
||||
useHash = true,
|
||||
@@ -119,6 +123,7 @@
|
||||
{statistics}
|
||||
{slicedStatistics}
|
||||
{hoveredPoint}
|
||||
{hoveredTrackpoint}
|
||||
{additionalDatasets}
|
||||
{elevationFill}
|
||||
showControls={options.elevation.controls}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { StartEndMarkers } from '$lib/components/map/gpx-layer/start-end-markers';
|
||||
import { createPopups, removePopups } from '$lib/components/map/gpx-layer/gpx-layer-popup';
|
||||
import { map } from '$lib/components/map/map';
|
||||
import { hoveredTrackpoint } from '$lib/state/selection-statistics';
|
||||
|
||||
let distanceMarkers: DistanceMarkers;
|
||||
let startEndMarkers: StartEndMarkers;
|
||||
@@ -14,6 +15,11 @@
|
||||
startEndMarkers = new StartEndMarkers();
|
||||
distanceMarkers = new DistanceMarkers();
|
||||
createPopups(map_);
|
||||
// the layers do not see the pointer when it leaves the map or when it drags something
|
||||
const stopHovering = () => hoveredTrackpoint.set(null);
|
||||
map_.on('mouseout', stopHovering);
|
||||
map_.on('mousedown', stopHovering);
|
||||
map_.on('movestart', stopHovering);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
|
||||
@@ -2,17 +2,15 @@
|
||||
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';
|
||||
import WithUnits from '$lib/components/WithUnits.svelte';
|
||||
import { Compass, Earth, Mountain, Timer } from '@lucide/svelte';
|
||||
import { Compass, Earth } from '@lucide/svelte';
|
||||
import { i18n } from '$lib/i18n/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<Pick<TrackpointDetails, 'lng' | 'lat'> & Partial<TrackpointDetails>>;
|
||||
trackpoint: PopupItem<{ lng: number; lat: number }>;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
@@ -22,33 +20,19 @@
|
||||
<Compass size="14" />
|
||||
{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">
|
||||
<Mountain size="14" />
|
||||
<WithUnits value={trackpoint.item.ele} type="elevation" />
|
||||
</div>
|
||||
{/if}
|
||||
{#if trackpoint.item.time !== undefined}
|
||||
<div class="flex flex-row items-center gap-1">
|
||||
<Timer size="14" />
|
||||
{i18n.df.format(new Date(trackpoint.item.time))}
|
||||
</div>
|
||||
{/if}
|
||||
<CopyCoordinates
|
||||
coordinates={trackpoint.item}
|
||||
onCopy={() => trackpoint.hide?.()}
|
||||
class="mt-0.5"
|
||||
/>
|
||||
{#if trackpoint.fileId === undefined}
|
||||
<Button
|
||||
variant="outline"
|
||||
class="justify-start"
|
||||
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" />
|
||||
{i18n._('menu.edit_osm')}
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
variant="outline"
|
||||
class="justify-start"
|
||||
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" />
|
||||
{i18n._('menu.edit_osm')}
|
||||
</Button>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
Point,
|
||||
} from 'maplibre-gl';
|
||||
import { map } from '$lib/components/map/map';
|
||||
import { waypointPopup, trackpointPopup } from './gpx-layer-popup';
|
||||
import { closestPointIndex } from '$lib/geo/closest-point';
|
||||
import { waypointPopup } from './gpx-layer-popup';
|
||||
import { closestPointIndexIn } from '$lib/geo/closest-point';
|
||||
import { getElevation, loadSVGIcon } from '$lib/utils';
|
||||
import { selectedWaypoint } from '$lib/components/toolbar/tools/waypoint/waypoint';
|
||||
import { MapPin, Square } from 'lucide-static';
|
||||
@@ -21,6 +21,7 @@ import { currentTool, Tool } from '$lib/components/toolbar/tools';
|
||||
import { splitAtPoint } from '$lib/components/toolbar/tools/scissors/scissors';
|
||||
import { mapCursor, MapCursorState } from '$lib/state/map-cursor';
|
||||
import { ANCHOR_LAYER_KEY } from '$lib/components/map/style';
|
||||
import { hoveredTrackpoint } from '$lib/state/selection-statistics';
|
||||
|
||||
export function getSvgForSymbol(symbol?: string | undefined, layerColor?: string | undefined) {
|
||||
const symbolSvg = symbol ? symbols[symbol]?.iconSvg : undefined;
|
||||
@@ -63,6 +64,7 @@ export class GPXLayer {
|
||||
currentWaypointData: GeoJSON.FeatureCollection | null = null;
|
||||
draggedWaypointIndex: number | null = null;
|
||||
draggingStartingPosition: Point = new Point(0, 0);
|
||||
hoversTrackpoint: boolean = false;
|
||||
unsubscribe: (() => void)[] = [];
|
||||
|
||||
updateBinded: () => void = this.update.bind(this);
|
||||
@@ -400,25 +402,55 @@ export class GPXLayer {
|
||||
layerOnMouseLeave() {
|
||||
mapCursor.notify(MapCursorState.SCISSORS, false);
|
||||
mapCursor.notify(MapCursorState.LAYER_HOVER, false);
|
||||
this.stopHoveringTrackpoint();
|
||||
}
|
||||
|
||||
async layerOnMouseMove(e: MapLayerMouseEvent) {
|
||||
if (e.originalEvent.shiftKey) {
|
||||
const { segmentId } = e.features![0].properties;
|
||||
const lngLat = { lng: e.lngLat.lng, lat: e.lngLat.lat };
|
||||
const index = closestPointIndex(await engine.segmentCoordinates(segmentId), lngLat);
|
||||
const trackpoint =
|
||||
index === undefined
|
||||
? undefined
|
||||
: await engine.trackpoint(this.fileId, segmentId, index);
|
||||
if (trackpoint) {
|
||||
trackpointPopup?.setItem({
|
||||
item: trackpoint,
|
||||
kind: 'trackpoint',
|
||||
fileId: this.fileId,
|
||||
});
|
||||
layerOnMouseMove(e: MapLayerMouseEvent) {
|
||||
// these tools act on the track under the pointer, and show it themselves
|
||||
const tool = get(currentTool);
|
||||
const index =
|
||||
tool === Tool.ROUTING || tool === Tool.SCISSORS
|
||||
? undefined
|
||||
: this.selectedTrackpointAt(e);
|
||||
if (index === undefined) {
|
||||
this.stopHoveringTrackpoint();
|
||||
} else {
|
||||
this.hoversTrackpoint = true;
|
||||
hoveredTrackpoint.set(index);
|
||||
}
|
||||
}
|
||||
|
||||
stopHoveringTrackpoint() {
|
||||
if (this.hoversTrackpoint) {
|
||||
this.hoversTrackpoint = false;
|
||||
hoveredTrackpoint.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The trackpoint of the statistics of the selection that is the closest to the pointer, in the
|
||||
* first segment under it that is part of the selection.
|
||||
*/
|
||||
selectedTrackpointAt(e: MapLayerMouseEvent): number | undefined {
|
||||
const statistics = get(engine.statistics);
|
||||
if (!statistics.segments) {
|
||||
return undefined;
|
||||
}
|
||||
const { starts, ids } = statistics.segments;
|
||||
for (const { properties } of e.features!) {
|
||||
const segment = ids.indexOf(properties.segmentId);
|
||||
if (segment >= 0) {
|
||||
const end = segment + 1 < starts.length ? starts[segment + 1] : statistics.length;
|
||||
return closestPointIndexIn(
|
||||
statistics.lng,
|
||||
statistics.lat,
|
||||
starts[segment],
|
||||
end,
|
||||
e.lngLat
|
||||
);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
layerOnClick(e: MapLayerMouseEvent) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FileStateCollectionObserver } from '$lib/engine';
|
||||
import { engine, FileStateCollectionObserver } from '$lib/engine';
|
||||
import { writable } from 'svelte/store';
|
||||
import { GPXLayer } from './gpx-layer';
|
||||
|
||||
@@ -14,6 +14,7 @@ export class GPXLayerCollection {
|
||||
if (this._fileStateCollectionObserver) {
|
||||
return;
|
||||
}
|
||||
engine.requestStatistics().set(['segments']);
|
||||
this._fileStateCollectionObserver = new FileStateCollectionObserver(
|
||||
(newFiles) => {
|
||||
newFiles.forEach((fileStore, fileId) => {
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
} from '$lib/data/layers';
|
||||
import { getLayers, isSelected, toggle } from '$lib/components/map/layer-control/utils';
|
||||
import { i18n } from '$lib/i18n/i18n.svelte';
|
||||
import { map } from '$lib/components/map/map';
|
||||
import CustomLayers from './CustomLayers.svelte';
|
||||
import { settings } from '$lib/state/settings';
|
||||
import { untrack } from 'svelte';
|
||||
@@ -209,19 +208,6 @@
|
||||
disabled={selectedOverlay === undefined}
|
||||
onValueChange={(value) => {
|
||||
if (selectedOverlay) {
|
||||
if (
|
||||
$map &&
|
||||
$currentOverlays &&
|
||||
isSelected($currentOverlays, selectedOverlay)
|
||||
) {
|
||||
try {
|
||||
if ($map.getLayer(selectedOverlay)) {
|
||||
$map.removeLayer(selectedOverlay);
|
||||
}
|
||||
} catch {
|
||||
// No reliable way to check if the map is ready to remove sources and layers
|
||||
}
|
||||
}
|
||||
$opacities[selectedOverlay] = value;
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
let {
|
||||
name,
|
||||
node,
|
||||
parent = '',
|
||||
selected = '',
|
||||
onselect = () => {},
|
||||
multiple = false,
|
||||
@@ -19,6 +20,7 @@
|
||||
}: {
|
||||
name: string;
|
||||
node: LayerTreeType;
|
||||
parent?: string;
|
||||
selected?: string;
|
||||
onselect?: (value: string) => void;
|
||||
multiple: boolean;
|
||||
@@ -26,7 +28,21 @@
|
||||
} = $props();
|
||||
|
||||
const { customLayers } = settings;
|
||||
const { isLayerFromExtension, getLayerName } = extensionAPI;
|
||||
const { isLayerFromExtension, getLayerName, isExtensionGroup } = extensionAPI;
|
||||
|
||||
/** The groups of extensions are right below the overlays, with the name they were given. */
|
||||
function getGroupLabel(id: string) {
|
||||
return parent === 'overlays' && $isExtensionGroup(id)
|
||||
? id
|
||||
: i18n._(`layers.label.${id}`, id);
|
||||
}
|
||||
|
||||
function getLabel(id: string) {
|
||||
if (Object.hasOwn($customLayers, id)) {
|
||||
return $customLayers[id].name;
|
||||
}
|
||||
return $isLayerFromExtension(id) ? $getLayerName(id) : i18n._(`layers.label.${id}`);
|
||||
}
|
||||
|
||||
$effect.pre(() => {
|
||||
if (checked !== undefined) {
|
||||
@@ -57,7 +73,7 @@
|
||||
() => checked[id] === true, (value) => (checked[id] = value)
|
||||
}
|
||||
class="scale-90"
|
||||
aria-label={i18n._(`layers.label.${id}`)}
|
||||
aria-label={getLabel(id)}
|
||||
/>
|
||||
{:else}
|
||||
<input
|
||||
@@ -74,25 +90,20 @@
|
||||
/>
|
||||
{/if}
|
||||
<Label for="{name}-{id}" class="flex flex-row items-center gap-1">
|
||||
{#if Object.hasOwn($customLayers, id)}
|
||||
{$customLayers[id].name}
|
||||
{:else if $isLayerFromExtension(id)}
|
||||
{$getLayerName(id)}
|
||||
{:else}
|
||||
{i18n._(`layers.label.${id}`)}
|
||||
{/if}
|
||||
{getLabel(id)}
|
||||
</Label>
|
||||
</div>
|
||||
{/if}
|
||||
{:else if anySelectedLayer(node[id])}
|
||||
<CollapsibleTreeNode {id}>
|
||||
{#snippet trigger()}
|
||||
<span>{i18n._(`layers.label.${id}`, id)}</span>
|
||||
<span>{getGroupLabel(id)}</span>
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
<div class="ml-2">
|
||||
<Self
|
||||
node={node[id] as LayerTreeType}
|
||||
parent={id}
|
||||
{name}
|
||||
{selected}
|
||||
{onselect}
|
||||
|
||||
@@ -5,29 +5,16 @@ import { get } from 'svelte/store';
|
||||
import { overlays, overlayTree, type LayerTreeType } from '$lib/data/layers';
|
||||
import { engine } from '$lib/engine';
|
||||
import { settings } from '$lib/state/settings';
|
||||
import { ExtensionAPI, type CustomOverlay } from './extension-api';
|
||||
import { isSelected } from './utils';
|
||||
import { map } from '$lib/components/map/map';
|
||||
import type { StyleSpecification } from 'maplibre-gl';
|
||||
import { ExtensionAPI, type ExtensionOverlay } from './extension-api';
|
||||
import { isSelected, prefixStyle } from './utils';
|
||||
|
||||
const original = { set: engine.setSetting, delete: engine.deleteSetting };
|
||||
|
||||
/** The raster source that an overlay added by an extension uses. */
|
||||
function rasterSource(id: string) {
|
||||
const style = overlays[id];
|
||||
assert.ok(typeof style === 'object');
|
||||
const source = style.sources[id];
|
||||
assert.ok(source?.type === 'raster');
|
||||
return source;
|
||||
}
|
||||
const overlayTreeBefore = JSON.stringify(overlayTree);
|
||||
const overlayIdsBefore = Object.keys(overlays).sort();
|
||||
|
||||
const overlay = (id: string, extensionName = 'My extension'): CustomOverlay => ({
|
||||
extensionName,
|
||||
id,
|
||||
name: `Overlay ${id}`,
|
||||
tileUrls: [`https://tiles.example.com/${id}/{z}/{x}/{y}.png`],
|
||||
});
|
||||
|
||||
let api: ExtensionAPI;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -40,114 +27,335 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
// the layers are shared by the whole app: leave them as they were
|
||||
api.filterOverlays([]);
|
||||
for (const extension of ['My extension', 'Other extension']) {
|
||||
delete (overlayTree.overlays as LayerTreeType)[extension];
|
||||
}
|
||||
api.setOverlays('Heatmaps', []);
|
||||
api.setOverlays('Other', []);
|
||||
engine.setSetting = original.set;
|
||||
engine.deleteSetting = original.delete;
|
||||
assert.equal(JSON.stringify(overlayTree), overlayTreeBefore);
|
||||
assert.deepEqual(Object.keys(overlays).sort(), overlayIdsBefore);
|
||||
});
|
||||
|
||||
describe('ExtensionAPI', () => {
|
||||
it('adds an overlay as a layer, in the tree of its extension', () => {
|
||||
api.addOrUpdateOverlay(overlay('one'));
|
||||
const rasterStyle = (url = 'https://tiles.example.com/{z}/{x}/{y}.png'): StyleSpecification => ({
|
||||
version: 8,
|
||||
sources: { tiles: { type: 'raster', tiles: [url], tileSize: 256 } },
|
||||
layers: [{ id: 'tiles', type: 'raster', source: 'tiles' }],
|
||||
});
|
||||
|
||||
const source = rasterSource('extension-one');
|
||||
assert.deepEqual(source.tiles, ['https://tiles.example.com/one/{z}/{x}/{y}.png']);
|
||||
assert.equal(source.tileSize, 256);
|
||||
assert.equal(source.maxzoom, 22);
|
||||
const v2 = (id: string, extra: Partial<ExtensionOverlay> = {}): ExtensionOverlay => ({
|
||||
id,
|
||||
name: `Overlay ${id}`,
|
||||
style: rasterStyle(),
|
||||
...extra,
|
||||
});
|
||||
|
||||
assert.ok((overlayTree.overlays as LayerTreeType)['My extension']);
|
||||
assert.equal(isSelected(overlayTree, 'extension-one'), true);
|
||||
assert.equal(isSelected(get(settings.selectedOverlayTree), 'extension-one'), true);
|
||||
// not shown until the user chooses to
|
||||
assert.equal(isSelected(get(settings.currentOverlays)!, 'extension-one'), false);
|
||||
assert.ok(get(api.isLayerFromExtension)('extension-one'));
|
||||
assert.equal(get(api.getLayerName)('extension-one'), 'Overlay one');
|
||||
assert.equal(get(api.getLayerName)('other'), '');
|
||||
const id = (overlayId: string, extension = 'Heatmaps') =>
|
||||
`extension-${encodeURIComponent(extension)}/${encodeURIComponent(overlayId)}`;
|
||||
|
||||
/** The overlays of an extension in a tree, with their state. */
|
||||
const group = (tree: LayerTreeType | undefined, extension = 'Heatmaps') =>
|
||||
(tree!.overlays as LayerTreeType)[extension] as LayerTreeType | undefined;
|
||||
|
||||
/** What the user does in the layer menu. */
|
||||
function setShown(overlayId: string, shown: boolean) {
|
||||
settings.currentOverlays.update((tree) => {
|
||||
group(tree)![overlayId] = shown;
|
||||
return tree;
|
||||
});
|
||||
}
|
||||
|
||||
it('uses big tiles when the urls say so, and the max zoom it is given', () => {
|
||||
api.addOrUpdateOverlay({
|
||||
...overlay('big'),
|
||||
tileUrls: ['https://tiles.example.com/512/{z}/{x}/{y}.png'],
|
||||
maxZoom: 15,
|
||||
describe('prefixStyle', () => {
|
||||
it('prefixes the sources, the layers, and the source of the layers', () => {
|
||||
const prefixed = prefixStyle('overlay', {
|
||||
version: 8,
|
||||
sources: { dem: { type: 'raster-dem', tiles: ['https://dem/{z}/{x}/{y}.png'] } },
|
||||
layers: [
|
||||
{ id: 'relief', type: 'color-relief', source: 'dem' },
|
||||
{ id: 'background', type: 'background' },
|
||||
],
|
||||
});
|
||||
const source = rasterSource('extension-big');
|
||||
assert.equal(source.tileSize, 512);
|
||||
assert.equal(source.maxzoom, 15);
|
||||
assert.deepEqual(Object.keys(prefixed.sources), ['overlay/dem']);
|
||||
assert.deepEqual(
|
||||
prefixed.layers.map((layer) => layer.id),
|
||||
['overlay/relief', 'overlay/background']
|
||||
);
|
||||
assert.equal((prefixed.layers[0] as { source: string }).source, 'overlay/dem');
|
||||
assert.equal('source' in prefixed.layers[1], false);
|
||||
});
|
||||
|
||||
it('refuses an overlay that is not complete', () => {
|
||||
for (const bad of [
|
||||
{ ...overlay('a'), extensionName: '' },
|
||||
{ ...overlay('a'), id: '' },
|
||||
{ ...overlay('a'), name: '' },
|
||||
{ ...overlay('a'), tileUrls: [] },
|
||||
{ ...overlay('a'), tileUrls: undefined as unknown as string[] },
|
||||
]) {
|
||||
assert.throws(() => api.addOrUpdateOverlay(bad), /must have/);
|
||||
it('refuses a style whose layers cannot work', () => {
|
||||
const style = (layers: unknown) =>
|
||||
({ version: 8, sources: {}, layers }) as StyleSpecification;
|
||||
assert.throws(() => prefixStyle('o', style(undefined)), /list of layers/);
|
||||
assert.throws(
|
||||
() => prefixStyle('o', style([{ id: 'a', type: 'raster', source: 'none' }])),
|
||||
/unknown source/
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
prefixStyle(
|
||||
'o',
|
||||
style([
|
||||
{ id: 'a', type: 'background' },
|
||||
{ id: 'a', type: 'background' },
|
||||
])
|
||||
),
|
||||
/repeated layer id/
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ExtensionAPI', () => {
|
||||
it('adds the overlays of an extension, in the order of the list, hidden by default', () => {
|
||||
api.setOverlays('Heatmaps', [v2('b'), v2('a', { name: 'A' }), v2('c', { visible: true })]);
|
||||
|
||||
const expected = [id('b'), id('a'), id('c')];
|
||||
assert.deepEqual(Object.keys(group(overlayTree)!), expected);
|
||||
assert.deepEqual(Object.keys(group(get(settings.selectedOverlayTree))!), expected);
|
||||
assert.deepEqual(group(get(settings.currentOverlays)), {
|
||||
[id('b')]: false,
|
||||
[id('a')]: false,
|
||||
[id('c')]: true,
|
||||
});
|
||||
assert.ok(get(api.isLayerFromExtension)(id('a')));
|
||||
assert.equal(get(api.getLayerName)(id('a')), 'A');
|
||||
assert.equal(api.version, 2);
|
||||
});
|
||||
|
||||
it('uses the style as is, with prefixed ids', () => {
|
||||
api.setOverlays('Heatmaps', [v2('a')]);
|
||||
const style = overlays[id('a')] as StyleSpecification;
|
||||
assert.deepEqual(Object.keys(style.sources), [`${id('a')}/tiles`]);
|
||||
assert.equal(style.layers[0].id, `${id('a')}/tiles`);
|
||||
assert.equal((style.layers[0] as { source: string }).source, `${id('a')}/tiles`);
|
||||
});
|
||||
|
||||
it('names its overlays after the extension', () => {
|
||||
api.setOverlays('My heatmap', [v2('all')]);
|
||||
assert.ok(isSelected(overlayTree, 'extension-My%20heatmap/all'));
|
||||
api.setOverlays('My heatmap', []);
|
||||
});
|
||||
|
||||
it('keeps two extensions with the same overlay ids, or similar names, apart', () => {
|
||||
api.setOverlays('Heatmaps', [v2('a')]);
|
||||
api.setOverlays('Other', [v2('a')]);
|
||||
assert.deepEqual(Object.keys(group(overlayTree)!), [id('a')]);
|
||||
assert.deepEqual(Object.keys(group(overlayTree, 'Other')!), [id('a', 'Other')]);
|
||||
|
||||
api.setOverlays('Heatmaps/a', [v2('b')]);
|
||||
api.setOverlays('Heatmaps', [v2('a'), v2('a/b')]);
|
||||
assert.notEqual(id('a/b'), id('b', 'Heatmaps/a'));
|
||||
assert.ok(get(api.isLayerFromExtension)(id('a/b')));
|
||||
assert.ok(get(api.isLayerFromExtension)(id('b', 'Heatmaps/a')));
|
||||
|
||||
api.setOverlays('Other', []);
|
||||
assert.deepEqual(Object.keys(group(overlayTree)!).length, 2);
|
||||
api.setOverlays('Heatmaps/a', []);
|
||||
});
|
||||
|
||||
it('knows the groups of the extensions', () => {
|
||||
api.setOverlays('Heatmaps', [v2('a')]);
|
||||
assert.equal(get(api.isExtensionGroup)('Heatmaps'), true);
|
||||
assert.equal(get(api.isExtensionGroup)('france'), false);
|
||||
api.setOverlays('Heatmaps', []);
|
||||
assert.equal(get(api.isExtensionGroup)('Heatmaps'), false);
|
||||
});
|
||||
|
||||
it('removes what is not in the list anymore, with its group when it is empty', () => {
|
||||
api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b')]);
|
||||
api.setOverlays('Heatmaps', [v2('b')]);
|
||||
assert.ok(!(id('a') in overlays));
|
||||
assert.equal(get(api.isLayerFromExtension)(id('a')), false);
|
||||
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
|
||||
assert.deepEqual(Object.keys(group(overlayTree)!), [id('b')]);
|
||||
|
||||
api.setOverlays('Heatmaps', []);
|
||||
assert.equal(group(overlayTree), undefined);
|
||||
assert.equal(group(get(settings.selectedOverlayTree)), undefined);
|
||||
assert.equal(group(get(settings.currentOverlays)), undefined);
|
||||
});
|
||||
|
||||
it('keeps the state of an overlay unless told otherwise, and the opacity and menu choices', () => {
|
||||
api.setOverlays('Heatmaps', [v2('a'), v2('b')]);
|
||||
setShown(id('a'), true);
|
||||
settings.opacities.update((opacities) => ({ ...opacities, [id('a')]: 0.3 }));
|
||||
settings.selectedOverlayTree.update((tree) => {
|
||||
group(tree)![id('b')] = false;
|
||||
return tree;
|
||||
});
|
||||
|
||||
api.setOverlays('Heatmaps', [v2('b'), v2('a')]);
|
||||
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), true);
|
||||
assert.equal(isSelected(get(settings.selectedOverlayTree), id('b')), false);
|
||||
assert.equal(get(settings.opacities)[id('a')], 0.3);
|
||||
assert.deepEqual(Object.keys(group(get(settings.selectedOverlayTree))!), [
|
||||
id('b'),
|
||||
id('a'),
|
||||
]);
|
||||
|
||||
api.setOverlays('Heatmaps', [v2('a', { visible: false }), v2('b', { visible: true })]);
|
||||
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
|
||||
// the user took it out of the menu, where it could not be hidden again
|
||||
assert.equal(isSelected(get(settings.currentOverlays)!, id('b')), false);
|
||||
});
|
||||
|
||||
it('changes nothing when the list is not valid', () => {
|
||||
api.setOverlays('Heatmaps', [v2('a')]);
|
||||
const invalid: unknown[] = [
|
||||
[v2('b'), v2('b')],
|
||||
[v2('b'), { id: 'c', name: 'C' }],
|
||||
[v2('b'), { ...v2('c'), style: { version: 8, sources: {} } }],
|
||||
'not a list',
|
||||
];
|
||||
for (const list of invalid) {
|
||||
assert.throws(() => api.setOverlays('Heatmaps', list as ExtensionOverlay[]));
|
||||
}
|
||||
assert.deepEqual(Object.keys(group(overlayTree)!), [id('a')]);
|
||||
assert.ok(!(id('b') in overlays));
|
||||
});
|
||||
|
||||
it('refuses the names that cannot be the group of an extension', () => {
|
||||
for (const name of ['', 'world', 'countries', '__proto__']) {
|
||||
assert.throws(() => api.setOverlays(name, [v2('a')]));
|
||||
}
|
||||
assert.ok(!('extension-a' in overlays));
|
||||
});
|
||||
|
||||
it('waits for the settings', () => {
|
||||
const current = get(settings.currentOverlays);
|
||||
(settings.currentOverlays as unknown as { _value: { set(v: unknown): void } })._value.set(
|
||||
undefined
|
||||
);
|
||||
assert.throws(() => api.setOverlays('Heatmaps', [v2('a')]), /gpxstudio\.ready/);
|
||||
settings.currentOverlays.set(current!);
|
||||
});
|
||||
|
||||
it('tells the extension about the actions of the user only', () => {
|
||||
const calls: Record<string, boolean>[] = [];
|
||||
const stop = api.onVisibilityChange('Heatmaps', (visible) => calls.push(visible));
|
||||
const others: unknown[] = [];
|
||||
api.onVisibilityChange('Other', (visible) => others.push(visible));
|
||||
api.setOverlays('Other', [v2('x')]);
|
||||
|
||||
api.setOverlays('Heatmaps', [v2('a'), v2('b', { visible: true })]);
|
||||
api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b', { visible: false })]);
|
||||
assert.deepEqual(calls, []);
|
||||
|
||||
setShown(id('b'), true);
|
||||
assert.deepEqual(calls, [{ a: true, b: true }]);
|
||||
// nothing changed
|
||||
setShown(id('b'), true);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.deepEqual(others, []);
|
||||
|
||||
stop();
|
||||
setShown(id('b'), false);
|
||||
assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
it('tells the extension when the overlays are all hidden from the menu', () => {
|
||||
const calls: Record<string, boolean>[] = [];
|
||||
api.onVisibilityChange('Heatmaps', (visible) => calls.push(visible));
|
||||
api.setOverlays('Heatmaps', [v2('a', { visible: true })]);
|
||||
settings.currentOverlays.set({ overlays: {} });
|
||||
assert.deepEqual(calls, [{ a: false }]);
|
||||
});
|
||||
|
||||
it('updates an overlay that is added again, keeping it shown', () => {
|
||||
api.addOrUpdateOverlay(overlay('one'));
|
||||
settings.currentOverlays.update((current) => {
|
||||
(current.overlays as LayerTreeType)['My extension'] = { 'extension-one': true };
|
||||
return current;
|
||||
it('survives a callback that throws, or that sets the overlays', () => {
|
||||
const error = console.error;
|
||||
console.error = () => {};
|
||||
const calls: unknown[] = [];
|
||||
api.onVisibilityChange('Heatmaps', () => {
|
||||
throw new Error('from the extension');
|
||||
});
|
||||
api.onVisibilityChange('Heatmaps', (visible) => {
|
||||
calls.push(visible);
|
||||
api.setOverlays('Heatmaps', [v2('a', { visible: visible.a })]);
|
||||
});
|
||||
api.setOverlays('Heatmaps', [v2('a')]);
|
||||
setShown(id('a'), true);
|
||||
console.error = error;
|
||||
assert.deepEqual(calls, [{ a: true }]);
|
||||
});
|
||||
|
||||
api.addOrUpdateOverlay({
|
||||
...overlay('one'),
|
||||
name: 'Renamed',
|
||||
tileUrls: ['https://other/{z}'],
|
||||
it('forgets the state of the overlays with the next session', () => {
|
||||
const saved = () => ({
|
||||
currentOverlays: JSON.stringify(get(settings.currentOverlays)),
|
||||
previousOverlays: JSON.stringify(get(settings.previousOverlays)),
|
||||
selectedOverlayTree: JSON.stringify(get(settings.selectedOverlayTree)),
|
||||
opacities: JSON.stringify(get(settings.opacities)),
|
||||
});
|
||||
assert.equal(get(api.getLayerName)('extension-one'), 'Renamed');
|
||||
assert.deepEqual(rasterSource('extension-one').tiles, ['https://other/{z}']);
|
||||
assert.equal(isSelected(get(settings.currentOverlays)!, 'extension-one'), true);
|
||||
});
|
||||
// what was saved, not the default trees, which are the ones that are allowed
|
||||
settings.connect(saved());
|
||||
|
||||
it('removes the overlays that are not in the list anymore, everywhere', () => {
|
||||
api.addOrUpdateOverlay(overlay('one'));
|
||||
api.addOrUpdateOverlay(overlay('two', 'Other extension'));
|
||||
api.setOverlays('Heatmaps', [v2('a', { visible: true }), v2('b')]);
|
||||
settings.selectedOverlayTree.update((tree) => {
|
||||
group(tree)![id('b')] = false;
|
||||
return tree;
|
||||
});
|
||||
settings.opacities.update((opacities) => ({ ...opacities, [id('a')]: 0.3 }));
|
||||
const stored = saved();
|
||||
assert.ok(stored.currentOverlays.includes(id('a')));
|
||||
|
||||
api.filterOverlays(['two']);
|
||||
assert.ok(!('extension-one' in overlays));
|
||||
assert.ok('extension-two' in overlays);
|
||||
assert.equal(get(api.isLayerFromExtension)('extension-one'), false);
|
||||
assert.equal(get(api.isLayerFromExtension)('extension-two'), true);
|
||||
settings.connect(stored);
|
||||
for (const tree of [
|
||||
overlayTree,
|
||||
get(settings.currentOverlays),
|
||||
get(settings.previousOverlays),
|
||||
get(settings.selectedOverlayTree),
|
||||
get(settings.currentOverlays)!,
|
||||
]) {
|
||||
assert.equal(isSelected(tree, 'extension-one'), false);
|
||||
assert.ok(!JSON.stringify(tree).includes('extension-'));
|
||||
}
|
||||
assert.equal(isSelected(overlayTree, 'extension-two'), true);
|
||||
assert.equal(get(settings.opacities)[id('a')], 0.3);
|
||||
|
||||
// an extension that is still there starts again, as the source of what it remembers
|
||||
const next = new ExtensionAPI();
|
||||
next.setOverlays('Heatmaps', [v2('a'), v2('b', { visible: true })]);
|
||||
assert.equal(isSelected(get(settings.currentOverlays)!, id('a')), false);
|
||||
assert.equal(isSelected(get(settings.currentOverlays)!, id('b')), true);
|
||||
assert.equal(isSelected(get(settings.selectedOverlayTree), id('b')), true);
|
||||
next.setOverlays('Heatmaps', []);
|
||||
});
|
||||
|
||||
api.filterOverlays([]);
|
||||
assert.ok(!('extension-two' in overlays));
|
||||
it('leaves a style URL for the map to fetch', () => {
|
||||
const fetchBefore = globalThis.fetch;
|
||||
globalThis.fetch = (() => assert.fail('fetched')) as typeof fetch;
|
||||
try {
|
||||
const url = 'https://example.com/style.json';
|
||||
api.setOverlays('Heatmaps', [v2('a', { style: url })]);
|
||||
assert.equal(overlays[id('a')], url);
|
||||
} finally {
|
||||
globalThis.fetch = fetchBefore;
|
||||
}
|
||||
});
|
||||
|
||||
it('removes a style that changes from the map, layers first, but not one that stays', () => {
|
||||
const calls: string[] = [];
|
||||
const prefix = id('a');
|
||||
const fakeMap = {
|
||||
getStyle: () => ({
|
||||
sources: { [`${prefix}/tiles`]: {}, [`${prefix}2/tiles`]: {}, core: {} },
|
||||
layers: [{ id: `${prefix}/tiles` }, { id: `${prefix}2/tiles` }, { id: 'core' }],
|
||||
}),
|
||||
removeLayer: (layer: string) => calls.push(`layer ${layer}`),
|
||||
removeSource: (source: string) => calls.push(`source ${source}`),
|
||||
};
|
||||
const store = (map as unknown as { _mapStore: { set(value: unknown): void } })._mapStore;
|
||||
store.set(fakeMap);
|
||||
try {
|
||||
api.setOverlays('Heatmaps', [v2('a', { visible: true })]);
|
||||
api.setOverlays('Heatmaps', [v2('a', { name: 'Renamed' })]);
|
||||
assert.deepEqual(calls, []);
|
||||
|
||||
api.setOverlays('Heatmaps', [v2('a', { style: rasterStyle('https://other/{z}') })]);
|
||||
assert.deepEqual(calls, [`layer ${prefix}/tiles`, `source ${prefix}/tiles`]);
|
||||
|
||||
it('puts the overlays in the order it is given', () => {
|
||||
api.addOrUpdateOverlay(overlay('one'));
|
||||
api.addOrUpdateOverlay(overlay('two'));
|
||||
api.addOrUpdateOverlay(overlay('three'));
|
||||
calls.length = 0;
|
||||
api.setOverlays('Heatmaps', [v2('a', { style: 'https://example.com/style.json' })]);
|
||||
assert.equal(calls.length, 2);
|
||||
|
||||
api.updateOverlaysOrder(['three', 'one', 'two']);
|
||||
const extension = (get(settings.selectedOverlayTree).overlays as LayerTreeType)[
|
||||
'My extension'
|
||||
];
|
||||
assert.deepEqual(Object.keys(extension as LayerTreeType), [
|
||||
'extension-three',
|
||||
'extension-one',
|
||||
'extension-two',
|
||||
]);
|
||||
// ids it does not know are ignored
|
||||
api.updateOverlaysOrder(['unknown', 'two']);
|
||||
assert.equal(Object.keys(extension as LayerTreeType).at(-1), 'extension-two');
|
||||
calls.length = 0;
|
||||
api.setOverlays('Heatmaps', []);
|
||||
assert.equal(calls.length, 2);
|
||||
} finally {
|
||||
store.set(null);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,35 +1,87 @@
|
||||
import { settings } from '$lib/state/settings';
|
||||
import type { StyleSpecification } from 'maplibre-gl';
|
||||
import { derived, get, writable, type Writable } from 'svelte/store';
|
||||
import { isSelected, remove, removeAll } from './utils';
|
||||
import { isSelected, prefixStyle, removeAll } from './utils';
|
||||
import { layerGroup, overlays, overlayTree, type LayerTreeType } from '$lib/data/layers';
|
||||
import { browser } from '$app/environment';
|
||||
import { map } from '$lib/components/map/map';
|
||||
|
||||
const { currentOverlays, previousOverlays, selectedOverlayTree } = settings;
|
||||
|
||||
export type CustomOverlay = {
|
||||
extensionName: string;
|
||||
/** An overlay given by an extension. */
|
||||
export type ExtensionOverlay = {
|
||||
/** Unique within the extension. Keep it stable: the opacity and menu choices are tied to it. */
|
||||
id: string;
|
||||
name: string;
|
||||
tileUrls: string[];
|
||||
maxZoom?: number;
|
||||
/**
|
||||
* The sources and layers of the overlay, or the URL of a style JSON (which must allow
|
||||
* cross-origin requests). It is used as is, with MapLibre's defaults: a `raster` source has
|
||||
* tiles of 512 pixels unless its `tileSize` says otherwise. Layers can only use the sources of
|
||||
* this style, and the rest of a style (`sprite`, `glyphs`, `terrain`...) is ignored.
|
||||
*/
|
||||
style: StyleSpecification | string;
|
||||
/** Applied if given, otherwise the current state is kept (hidden for a new overlay). */
|
||||
visible?: boolean;
|
||||
};
|
||||
|
||||
/** What the API knows of an overlay. */
|
||||
type RegisteredOverlay = {
|
||||
extensionName: string;
|
||||
name: string;
|
||||
/** The style given by the extension, to tell when it changes. */
|
||||
signature: string;
|
||||
};
|
||||
|
||||
type VisibilityCallback = (visible: Record<string, boolean>) => void;
|
||||
|
||||
/** The groups of the overlay tree that an extension cannot put its overlays in. */
|
||||
const reservedGroups = new Set(['__proto__', ...Object.keys(layerGroup(overlayTree.overlays))]);
|
||||
|
||||
/** The id of an overlay. It is encoded so that two extensions cannot clash. */
|
||||
function getExtensionOverlayId(extensionName: string, id: string): string {
|
||||
return `extension-${encodeURIComponent(extensionName)}/${encodeURIComponent(id)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the overlays of an extension in a tree, in order, dropping its other entries. An extension
|
||||
* that has nothing left has no group anymore.
|
||||
*/
|
||||
function setGroup(tree: LayerTreeType, extensionName: string, entries: Record<string, boolean>) {
|
||||
const groups = layerGroup(tree.overlays);
|
||||
if (Object.keys(entries).length > 0) {
|
||||
groups[extensionName] = { ...entries };
|
||||
} else {
|
||||
delete groups[extensionName];
|
||||
}
|
||||
return tree;
|
||||
}
|
||||
|
||||
export class ExtensionAPI {
|
||||
private _overlays: Writable<Map<string, CustomOverlay>> = writable(new Map());
|
||||
/** The version of the API. */
|
||||
readonly version = 2;
|
||||
/**
|
||||
* Resolved once overlays can be set. `gpxstudio:extension-api-ready` is sent on `window` at that
|
||||
* moment.
|
||||
*/
|
||||
ready!: Promise<void>;
|
||||
|
||||
private _overlays: Writable<Map<string, RegisteredOverlay>> = writable(new Map());
|
||||
/** What each extension knows of the visibility of its overlays, by its own overlay ids. */
|
||||
private _visibility: Map<string, Record<string, boolean>> = new Map();
|
||||
private _visibilityCallbacks: Map<string, Set<VisibilityCallback>> = new Map();
|
||||
private _watchingVisibility = false;
|
||||
|
||||
init() {
|
||||
if (browser && !Object.hasOwn(window, 'gpxstudio')) {
|
||||
this.ready = this.whenLoaded();
|
||||
this.ready.then(() => window.dispatchEvent(new Event('gpxstudio:extension-api-ready')));
|
||||
Object.defineProperty(window, 'gpxstudio', {
|
||||
value: this,
|
||||
});
|
||||
addEventListener('beforeunload', () => {
|
||||
this.destroy();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
ensureLoaded(): Promise<void> {
|
||||
private whenLoaded(): Promise<void> {
|
||||
let unsubscribe: () => void;
|
||||
const promise = new Promise<void>((resolve) => {
|
||||
map.onLoad(() => {
|
||||
@@ -46,134 +98,160 @@ export class ExtensionAPI {
|
||||
return promise;
|
||||
}
|
||||
|
||||
addOrUpdateOverlay(overlay: CustomOverlay) {
|
||||
if (
|
||||
!overlay.extensionName ||
|
||||
!overlay.id ||
|
||||
!overlay.name ||
|
||||
!overlay.tileUrls ||
|
||||
overlay.tileUrls.length === 0
|
||||
) {
|
||||
throw new Error(
|
||||
'Overlay must have an extensionName, id, name, and at least one tile URL.'
|
||||
);
|
||||
/**
|
||||
* Replaces the overlays of an extension: the order of the list is the order in the layer menu,
|
||||
* and the overlays that are not in the list are removed. The opacity and the choices of the
|
||||
* layer menu are kept for the ones that stay. Throws, changing nothing, if the list is invalid;
|
||||
* a style URL is only fetched when the overlay is shown, and a failure is then only logged.
|
||||
*/
|
||||
setOverlays(extensionName: string, newOverlays: ExtensionOverlay[]) {
|
||||
if (typeof extensionName !== 'string' || !extensionName) {
|
||||
throw new Error('An extension must have a name.');
|
||||
}
|
||||
overlay.id = this.getOverlayId(overlay.id);
|
||||
|
||||
this._overlays.update(($overlays) => {
|
||||
$overlays.set(overlay.id, overlay);
|
||||
return $overlays;
|
||||
});
|
||||
|
||||
overlays[overlay.id] = {
|
||||
version: 8,
|
||||
sources: {
|
||||
[overlay.id]: {
|
||||
type: 'raster',
|
||||
tiles: overlay.tileUrls,
|
||||
tileSize: overlay.tileUrls.some((url) => url.includes('512')) ? 512 : 256,
|
||||
maxzoom: overlay.maxZoom ?? 22,
|
||||
},
|
||||
},
|
||||
layers: [
|
||||
{
|
||||
id: overlay.id,
|
||||
type: 'raster',
|
||||
source: overlay.id,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const extensions = layerGroup(overlayTree.overlays);
|
||||
if (!Object.hasOwn(extensions, overlay.extensionName)) {
|
||||
extensions[overlay.extensionName] = {};
|
||||
if (reservedGroups.has(extensionName)) {
|
||||
throw new Error(`The extension name ${extensionName} is reserved.`);
|
||||
}
|
||||
if (!Array.isArray(newOverlays)) {
|
||||
throw new Error('The overlays must be a list.');
|
||||
}
|
||||
|
||||
layerGroup(extensions[overlay.extensionName])[overlay.id] = true;
|
||||
|
||||
selectedOverlayTree.update((selected) => {
|
||||
if (!Object.hasOwn(selected.overlays, overlay.extensionName)) {
|
||||
selected.overlays[overlay.extensionName] = {};
|
||||
}
|
||||
selected.overlays[overlay.extensionName][overlay.id] = true;
|
||||
return selected;
|
||||
});
|
||||
|
||||
const current = get(currentOverlays);
|
||||
let show = false;
|
||||
if (current && isSelected(current, overlay.id)) {
|
||||
show = true;
|
||||
try {
|
||||
get(map)?.removeLayer(overlay.id);
|
||||
} catch {
|
||||
// No reliable way to check if the map is ready to remove sources and layers
|
||||
}
|
||||
if (!current) {
|
||||
throw new Error('Overlays cannot be set yet: wait for `gpxstudio.ready`.');
|
||||
}
|
||||
|
||||
currentOverlays.update((current) => {
|
||||
if (!Object.hasOwn(current.overlays, overlay.extensionName)) {
|
||||
current.overlays[overlay.extensionName] = {};
|
||||
const previous = this.getOverlaysOf(extensionName);
|
||||
const next = new Map<string, RegisteredOverlay>();
|
||||
const styles = new Map<string, StyleSpecification | string>();
|
||||
for (const overlay of newOverlays) {
|
||||
if (!overlay?.id || !overlay.name || !overlay.style) {
|
||||
throw new Error('Overlay must have an id, a name and a style.');
|
||||
}
|
||||
current.overlays[overlay.extensionName][overlay.id] = show;
|
||||
return current;
|
||||
});
|
||||
}
|
||||
const id = getExtensionOverlayId(extensionName, overlay.id);
|
||||
if (next.has(id)) {
|
||||
throw new Error(`Overlay ${overlay.id} is in the list twice.`);
|
||||
}
|
||||
const signature = JSON.stringify(overlay.style);
|
||||
// the ids of the style at a URL are prefixed when the map fetches it
|
||||
styles.set(
|
||||
id,
|
||||
typeof overlay.style === 'string'
|
||||
? overlay.style
|
||||
: prefixStyle(id, JSON.parse(signature))
|
||||
);
|
||||
next.set(id, { extensionName, name: overlay.name, signature });
|
||||
}
|
||||
|
||||
filterOverlays(ids: string[]) {
|
||||
ids = ids.map((id) => this.getOverlayId(id));
|
||||
const idsToRemove = Array.from(get(this._overlays).keys()).filter(
|
||||
(id) => !ids.includes(id)
|
||||
);
|
||||
|
||||
currentOverlays.update((current) => {
|
||||
removeAll(current, idsToRemove);
|
||||
return current;
|
||||
});
|
||||
previousOverlays.update((previous) => {
|
||||
removeAll(previous, idsToRemove);
|
||||
return previous;
|
||||
});
|
||||
selectedOverlayTree.update((selected) => {
|
||||
removeAll(selected, idsToRemove);
|
||||
return selected;
|
||||
});
|
||||
Object.keys(overlays).forEach((id) => {
|
||||
if (idsToRemove.includes(id)) {
|
||||
// Nothing can fail from here. The map does not replace a source that it already has, so
|
||||
// what has changed has to be removed first; it is then added back with the new style.
|
||||
const removedIds: string[] = [];
|
||||
previous.forEach((overlay, id) => {
|
||||
if (next.get(id)?.signature !== overlay.signature) {
|
||||
this.removeFromMap(id);
|
||||
}
|
||||
if (!next.has(id)) {
|
||||
removedIds.push(id);
|
||||
delete overlays[id];
|
||||
}
|
||||
});
|
||||
removeAll(overlayTree, idsToRemove);
|
||||
styles.forEach((style, id) => {
|
||||
overlays[id] = style;
|
||||
});
|
||||
this._overlays.update(($overlays) => {
|
||||
$overlays.forEach((_, id) => {
|
||||
if (idsToRemove.includes(id)) {
|
||||
$overlays.delete(id);
|
||||
removedIds.forEach((id) => $overlays.delete(id));
|
||||
next.forEach((overlay, id) => $overlays.set(id, overlay));
|
||||
return $overlays;
|
||||
});
|
||||
|
||||
const available: Record<string, boolean> = {};
|
||||
const selected: Record<string, boolean> = {};
|
||||
const shown: Record<string, boolean> = {};
|
||||
const visibility: Record<string, boolean> = {};
|
||||
const selectedGroup = layerGroup(get(selectedOverlayTree).overlays)[extensionName];
|
||||
newOverlays.forEach((overlay) => {
|
||||
const id = getExtensionOverlayId(extensionName, overlay.id);
|
||||
available[id] = true;
|
||||
// an overlay that the user took out of the layer menu could not be hidden again
|
||||
selected[id] =
|
||||
typeof selectedGroup !== 'object' ||
|
||||
!Object.hasOwn(selectedGroup, id) ||
|
||||
selectedGroup[id] === true;
|
||||
shown[id] = selected[id] && Boolean(overlay.visible ?? isSelected(current, id));
|
||||
visibility[overlay.id] = shown[id];
|
||||
});
|
||||
|
||||
setGroup(overlayTree, extensionName, available);
|
||||
selectedOverlayTree.update((tree) => setGroup(tree, extensionName, selected));
|
||||
previousOverlays.update((tree) => removeAll(tree, removedIds));
|
||||
// this is not an action of the user: there must be nothing to tell the extension about
|
||||
this._visibility.set(extensionName, visibility);
|
||||
currentOverlays.update((tree) => setGroup(tree, extensionName, shown));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls `callback` with the visibility of all the overlays of the extension, by id, when the
|
||||
* user shows or hides one of them (not when `setOverlays` does). Returns how to stop.
|
||||
*/
|
||||
onVisibilityChange(extensionName: string, callback: VisibilityCallback): () => void {
|
||||
const callbacks = this._visibilityCallbacks.get(extensionName) ?? new Set();
|
||||
this._visibilityCallbacks.set(extensionName, callbacks);
|
||||
callbacks.add(callback);
|
||||
if (!this._watchingVisibility) {
|
||||
this._watchingVisibility = true;
|
||||
currentOverlays.subscribe(() => this.notifyVisibility());
|
||||
}
|
||||
return () => {
|
||||
callbacks.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
private notifyVisibility() {
|
||||
const current = get(currentOverlays);
|
||||
if (!current) return;
|
||||
this._visibilityCallbacks.forEach((callbacks, extensionName) => {
|
||||
const known = this._visibility.get(extensionName);
|
||||
if (!known) return;
|
||||
const visibility = Object.fromEntries(
|
||||
Object.keys(known).map((id) => [
|
||||
id,
|
||||
isSelected(current, getExtensionOverlayId(extensionName, id)),
|
||||
])
|
||||
);
|
||||
if (Object.keys(known).every((id) => known[id] === visibility[id])) return;
|
||||
this._visibility.set(extensionName, visibility);
|
||||
callbacks.forEach((callback) => {
|
||||
try {
|
||||
callback({ ...visibility });
|
||||
} catch (e) {
|
||||
// an extension must not break the updates of the store for the others
|
||||
console.error(e);
|
||||
}
|
||||
});
|
||||
return $overlays;
|
||||
});
|
||||
}
|
||||
|
||||
updateOverlaysOrder(ids: string[]) {
|
||||
ids = ids.map((id) => this.getOverlayId(id));
|
||||
selectedOverlayTree.update((selected) => {
|
||||
const isSelected: Record<string, boolean> = {};
|
||||
ids.forEach((id) => {
|
||||
const overlay = get(this._overlays).get(id);
|
||||
if (
|
||||
overlay &&
|
||||
Object.hasOwn(selected.overlays, overlay.extensionName) &&
|
||||
Object.hasOwn(selected.overlays[overlay.extensionName] as LayerTreeType, id)
|
||||
) {
|
||||
isSelected[id] = selected.overlays[overlay.extensionName][id];
|
||||
delete selected.overlays[overlay.extensionName][id];
|
||||
}
|
||||
});
|
||||
Object.entries(isSelected).forEach(([id, value]) => {
|
||||
const overlay = get(this._overlays).get(id)!;
|
||||
selected.overlays[overlay.extensionName][id] = value;
|
||||
});
|
||||
return selected;
|
||||
});
|
||||
private getOverlaysOf(extensionName: string): Map<string, RegisteredOverlay> {
|
||||
return new Map(
|
||||
Array.from(get(this._overlays)).filter(
|
||||
([, overlay]) => overlay.extensionName === extensionName
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Removes the layers and sources of an overlay: their ids start with the one of the overlay. */
|
||||
private removeFromMap(overlayId: string) {
|
||||
const map_ = get(map);
|
||||
if (!map_) return;
|
||||
try {
|
||||
const style = map_.getStyle();
|
||||
style.layers
|
||||
.filter((layer) => layer.id.startsWith(`${overlayId}/`))
|
||||
.forEach((layer) => map_.removeLayer(layer.id));
|
||||
Object.keys(style.sources)
|
||||
.filter((source) => source.startsWith(`${overlayId}/`))
|
||||
.forEach((source) => map_.removeSource(source));
|
||||
} catch {
|
||||
// No reliable way to check if the map is ready to remove sources and layers
|
||||
}
|
||||
}
|
||||
|
||||
isLayerFromExtension = derived(this._overlays, ($overlays) => {
|
||||
@@ -184,31 +262,11 @@ export class ExtensionAPI {
|
||||
return (id: string) => $overlays.get(id)?.name || '';
|
||||
});
|
||||
|
||||
private getOverlayId(id: string): string {
|
||||
return `extension-${id}`;
|
||||
}
|
||||
|
||||
private destroy() {
|
||||
const ids = Array.from(get(this._overlays).keys());
|
||||
currentOverlays.update((current) => {
|
||||
ids.forEach((id) => {
|
||||
remove(current, id);
|
||||
});
|
||||
return current;
|
||||
});
|
||||
previousOverlays.update((previous) => {
|
||||
ids.forEach((id) => {
|
||||
remove(previous, id);
|
||||
});
|
||||
return previous;
|
||||
});
|
||||
selectedOverlayTree.update((selected) => {
|
||||
ids.forEach((id) => {
|
||||
remove(selected, id);
|
||||
});
|
||||
return selected;
|
||||
});
|
||||
}
|
||||
/** Whether a group of the layer trees is an extension, whose name is shown as it was given. */
|
||||
isExtensionGroup = derived(this._overlays, ($overlays) => {
|
||||
const names = new Set(Array.from($overlays.values(), (overlay) => overlay.extensionName));
|
||||
return (id: string) => names.has(id);
|
||||
});
|
||||
}
|
||||
|
||||
export const extensionAPI = new ExtensionAPI();
|
||||
@@ -1,7 +1,16 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import type { LayerTreeType } from '$lib/data/layers';
|
||||
import { anySelectedLayer, getLayers, isSelected, remove, removeAll, toggle } from './utils';
|
||||
import type { LayerSpecification } from 'maplibre-gl';
|
||||
import {
|
||||
anySelectedLayer,
|
||||
getLayers,
|
||||
getOpacityPaint,
|
||||
isSelected,
|
||||
remove,
|
||||
removeAll,
|
||||
toggle,
|
||||
} from './utils';
|
||||
|
||||
// roads: bike (selected), foot
|
||||
// satellite: esri, ign: fr (selected)
|
||||
@@ -72,3 +81,39 @@ describe('layer trees', () => {
|
||||
assert.deepEqual(removeAll(tree(), []), tree());
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOpacityPaint', () => {
|
||||
const layer = (type: string, paint?: Record<string, unknown>) =>
|
||||
({ id: 'layer', type, source: 'source', paint }) as LayerSpecification;
|
||||
|
||||
it('uses the opacity properties of each type of layer', () => {
|
||||
assert.deepEqual(getOpacityPaint(layer('raster'), 0.5), { 'raster-opacity': 0.5 });
|
||||
assert.deepEqual(getOpacityPaint(layer('color-relief'), 0.5), {
|
||||
'color-relief-opacity': 0.5,
|
||||
});
|
||||
assert.deepEqual(getOpacityPaint(layer('symbol'), 0.5), {
|
||||
'icon-opacity': 0.5,
|
||||
'text-opacity': 0.5,
|
||||
});
|
||||
assert.deepEqual(getOpacityPaint(layer('circle'), 0.5), {
|
||||
'circle-opacity': 0.5,
|
||||
'circle-stroke-opacity': 0.5,
|
||||
});
|
||||
assert.deepEqual(getOpacityPaint(layer('hillshade'), 0.5), {
|
||||
'hillshade-exaggeration': 0.25,
|
||||
});
|
||||
});
|
||||
|
||||
it('scales the opacity that the layer already has', () => {
|
||||
assert.deepEqual(getOpacityPaint(layer('line', { 'line-opacity': 0.5 }), 0.5), {
|
||||
'line-opacity': 0.25,
|
||||
});
|
||||
});
|
||||
|
||||
it('replaces an expression, unless the opacity is left at 1', () => {
|
||||
const expression = ['interpolate', ['linear'], ['zoom'], 5, 0, 10, 1];
|
||||
const paint = { 'fill-opacity': expression };
|
||||
assert.deepEqual(getOpacityPaint(layer('fill', paint), 0.5), { 'fill-opacity': 0.5 });
|
||||
assert.deepEqual(getOpacityPaint(layer('fill', paint), 1), { 'fill-opacity': expression });
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,89 @@
|
||||
import type { LayerTreeType } from '$lib/data/layers';
|
||||
import type { LayerSpecification, StyleSpecification } from 'maplibre-gl';
|
||||
|
||||
/** Parts of a style that apply to a whole map, not to an overlay. */
|
||||
const ignoredStyleProperties = ['sprite', 'glyphs', 'terrain', 'sky', 'light', 'projection'];
|
||||
/** The overlays that were warned about those: a style at a URL is read again and again. */
|
||||
const warnedOverlays = new Set<string>();
|
||||
|
||||
/**
|
||||
* A copy of the style of an overlay whose sources and layers have ids of their own, so that they
|
||||
* cannot clash with the ones of gpx.studio or of another overlay.
|
||||
*/
|
||||
export function prefixStyle(overlayId: string, style: StyleSpecification): StyleSpecification {
|
||||
if (typeof style !== 'object' || style === null || !Array.isArray(style.layers)) {
|
||||
throw new Error(`The style of overlay ${overlayId} must have a list of layers.`);
|
||||
}
|
||||
const ignored = ignoredStyleProperties.filter((property) => Object.hasOwn(style, property));
|
||||
if (ignored.length > 0 && !warnedOverlays.has(overlayId)) {
|
||||
warnedOverlays.add(overlayId);
|
||||
console.warn(`Overlay ${overlayId} ignores these style properties: ${ignored.join(', ')}.`);
|
||||
}
|
||||
|
||||
const prefixed = (id: string) => `${overlayId}/${id}`;
|
||||
const sources = style.sources ?? {};
|
||||
const layerIds = new Set<string>();
|
||||
const layers = style.layers.map((layer) => {
|
||||
if (!layer.id || layerIds.has(layer.id)) {
|
||||
throw new Error(`Overlay ${overlayId} has a missing or repeated layer id.`);
|
||||
}
|
||||
layerIds.add(layer.id);
|
||||
if ('source' in layer) {
|
||||
if (!Object.hasOwn(sources, layer.source)) {
|
||||
throw new Error(
|
||||
`Layer ${layer.id} of overlay ${overlayId} uses unknown source ${layer.source}.`
|
||||
);
|
||||
}
|
||||
return { ...layer, id: prefixed(layer.id), source: prefixed(layer.source) };
|
||||
}
|
||||
return { ...layer, id: prefixed(layer.id) };
|
||||
}) as LayerSpecification[];
|
||||
|
||||
return {
|
||||
...style,
|
||||
sources: Object.fromEntries(
|
||||
Object.entries(sources).map(([id, source]) => [prefixed(id), source])
|
||||
),
|
||||
layers,
|
||||
};
|
||||
}
|
||||
|
||||
/** The paint properties that make a layer transparent, by type of layer. */
|
||||
const opacityProperties: Partial<Record<LayerSpecification['type'], string[]>> = {
|
||||
background: ['background-opacity'],
|
||||
circle: ['circle-opacity', 'circle-stroke-opacity'],
|
||||
'color-relief': ['color-relief-opacity'],
|
||||
fill: ['fill-opacity'],
|
||||
'fill-extrusion': ['fill-extrusion-opacity'],
|
||||
heatmap: ['heatmap-opacity'],
|
||||
line: ['line-opacity'],
|
||||
raster: ['raster-opacity'],
|
||||
symbol: ['icon-opacity', 'text-opacity'],
|
||||
};
|
||||
|
||||
/**
|
||||
* The paint properties that give a layer an opacity. The opacity of an overlay applies on top of
|
||||
* those of its layers, so that they stay different from one another. A value that is computed
|
||||
* (an expression) cannot always be scaled: the opacity replaces it, unless it is left at 1.
|
||||
*/
|
||||
export function getOpacityPaint(
|
||||
layer: LayerSpecification,
|
||||
opacity: number
|
||||
): Record<string, unknown> {
|
||||
if (layer.type === 'hillshade') {
|
||||
return { 'hillshade-exaggeration': opacity / 2 };
|
||||
}
|
||||
const paint = (layer.paint ?? {}) as Record<string, unknown>;
|
||||
return Object.fromEntries(
|
||||
(opacityProperties[layer.type] ?? []).map((property) => {
|
||||
const value = paint[property];
|
||||
if (typeof value === 'number') {
|
||||
return [property, value * opacity];
|
||||
}
|
||||
return [property, value !== undefined && opacity === 1 ? value : opacity];
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function anySelectedLayer(node: LayerTreeType) {
|
||||
return (
|
||||
|
||||
@@ -6,7 +6,7 @@ import MapPopupComponent from '$lib/components/map/MapPopup.svelte';
|
||||
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. */
|
||||
/** What the item is: a `WaypointDetails`, the coordinates of a point or an Overpass element. */
|
||||
kind: 'waypoint' | 'trackpoint' | 'overpass';
|
||||
fileId?: string;
|
||||
hide?: () => void;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { settings } from '$lib/state/settings';
|
||||
import { tick } from 'svelte';
|
||||
import { ANCHOR_LAYER_KEY, StyleManager } from '$lib/components/map/style';
|
||||
import { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
|
||||
import { registerOpenSatelliteProtocol } from '$lib/components/map/open-satellite';
|
||||
|
||||
const { treeFileView, elevationProfile, bottomPanelSize, rightPanelSize, distanceUnits } = settings;
|
||||
|
||||
@@ -41,6 +42,7 @@ export class MapLibreGLMap {
|
||||
geolocate: boolean
|
||||
) {
|
||||
maplibregl.setWorkerUrl(workerUrl);
|
||||
registerOpenSatelliteProtocol(maptilerKey);
|
||||
this._maptilerKey = maptilerKey;
|
||||
this._styleManager = new StyleManager(this._mapStore, this._maptilerKey);
|
||||
// MapLibre gives Safari more workers, but only recognizes it by its user agent: not
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// Which imagery each tile of the open satellite basemap is made of, from saved tiles of the
|
||||
// tileset of the countries.
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, it } from 'node:test';
|
||||
import { planTile, type CountryTiles } from './open-satellite';
|
||||
|
||||
const fixtures = new URL('../../../test/fixtures/satellite-countries/', import.meta.url);
|
||||
|
||||
/** The saved tiles, none where there is no file, and the ones that were asked for. */
|
||||
function savedTiles() {
|
||||
const asked: string[] = [];
|
||||
const tiles: CountryTiles = async (z, x, y) => {
|
||||
asked.push(`${z}/${x}/${y}`);
|
||||
try {
|
||||
return new Uint8Array(readFileSync(new URL(`${z}-${x}-${y}.mvt`, fixtures))).buffer;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
return { asked, tiles };
|
||||
}
|
||||
|
||||
function tile(lon: number, lat: number, z: number): [number, number, number] {
|
||||
const n = 2 ** z;
|
||||
const sin = Math.sin((lat * Math.PI) / 180);
|
||||
return [
|
||||
z,
|
||||
Math.floor(((lon + 180) / 360) * n),
|
||||
Math.floor((0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * n),
|
||||
];
|
||||
}
|
||||
|
||||
async function plan([z, x, y]: [number, number, number], tiles: CountryTiles) {
|
||||
const { parts, fallback } = await planTile(z, x, y, tiles);
|
||||
return { parts: parts.map((p) => `${p.source.id}:${p.relation}`).sort(), fallback };
|
||||
}
|
||||
|
||||
describe('planTile', () => {
|
||||
it('takes every tile up to zoom 12 from the imagery of the whole world', async () => {
|
||||
const { asked, tiles } = savedTiles();
|
||||
assert.deepEqual(await plan(tile(2.35, 48.85, 12), tiles), { parts: [], fallback: true });
|
||||
assert.deepEqual(asked, []);
|
||||
});
|
||||
|
||||
it('takes a tile far from every country from the fallback, without asking for countries', async () => {
|
||||
const { asked, tiles } = savedTiles();
|
||||
// London, and the Atlantic
|
||||
assert.deepEqual(await plan(tile(-0.12, 51.5, 14), tiles), { parts: [], fallback: true });
|
||||
assert.deepEqual(await plan(tile(-30, 40, 13), tiles), { parts: [], fallback: true });
|
||||
assert.deepEqual(asked, []);
|
||||
});
|
||||
|
||||
it('takes a tile inside a country from its agency alone', async () => {
|
||||
const { tiles } = savedTiles();
|
||||
assert.deepEqual(await plan(tile(2.35, 48.85, 15), tiles), {
|
||||
parts: ['FR:full'],
|
||||
fallback: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('puts the countries of a border tile together, over the fallback where none is', async () => {
|
||||
const { tiles } = savedTiles();
|
||||
// Basel: France, Switzerland and Germany, which is not in the patchwork
|
||||
assert.deepEqual(await plan([13, 4268, 2861], tiles), {
|
||||
parts: ['CH:partial', 'FR:partial'],
|
||||
fallback: true,
|
||||
});
|
||||
// only Germany
|
||||
assert.deepEqual(await plan([13, 4269, 2860], tiles), { parts: [], fallback: true });
|
||||
});
|
||||
|
||||
it('needs no fallback where the countries cover the tile between them', async () => {
|
||||
const { tiles } = savedTiles();
|
||||
// Wattrelos: France and Belgium
|
||||
assert.deepEqual(await plan([13, 4166, 2750], tiles), {
|
||||
parts: ['BE:partial', 'FR:partial'],
|
||||
fallback: false,
|
||||
});
|
||||
// Baarle, with its enclaves of Belgium and the Netherlands
|
||||
assert.deepEqual(await plan([13, 4208, 2726], tiles), {
|
||||
parts: ['BE:partial', 'NL:partial'],
|
||||
fallback: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('asks for a tile of the countries once for all the tiles of imagery inside it', async () => {
|
||||
const { asked, tiles } = savedTiles();
|
||||
// around Lausanne, which no other test asks for
|
||||
const [, x, y] = tile(6.63, 46.52, 12);
|
||||
for (let dx = 0; dx < 4; dx++) {
|
||||
for (let dy = 0; dy < 4; dy++) {
|
||||
await planTile(14, x * 4 + dx, y * 4 + dy, tiles);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(asked, [`12/${x}/${y}`]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,422 @@
|
||||
import * as maplibregl from 'maplibre-gl';
|
||||
import { VectorTile } from '@mapbox/vector-tile';
|
||||
import { PbfReader } from 'pbf';
|
||||
|
||||
/**
|
||||
* A satellite basemap made of the open imagery of national mapping agencies, drawn through a
|
||||
* custom protocol: each tile is taken from the agency whose country covers it, the tiles on a
|
||||
* border are put together on a canvas clipped to the border of each country, and only the parts
|
||||
* no open source covers are taken from the commercial fallback.
|
||||
*/
|
||||
|
||||
export const OPEN_SATELLITE_PROTOCOL = 'opensat';
|
||||
|
||||
type TileUrl = (z: number, x: number, y: number) => string;
|
||||
|
||||
type ImagerySource = {
|
||||
/** ISO code of the country, in the tileset of the countries */
|
||||
id: string;
|
||||
url: TileUrl;
|
||||
/** Above it, the tile of this zoom level is scaled up. */
|
||||
maxzoom: number;
|
||||
};
|
||||
|
||||
const xyz =
|
||||
(template: string): TileUrl =>
|
||||
(z, x, y) =>
|
||||
template.replace('{z}', String(z)).replace('{x}', String(x)).replace('{y}', String(y));
|
||||
|
||||
const ignOrthophotos = xyz(
|
||||
'https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&STYLE=normal&FORMAT=image/jpeg&TILEMATRIXSET=PM&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}'
|
||||
);
|
||||
|
||||
/**
|
||||
* Up to zoom 12, IGN's orthophotos cover the whole world with a mosaic of satellite images: all
|
||||
* tiles come from it there, and the national sources and the commercial fallback only above.
|
||||
*/
|
||||
const world: ImagerySource = { id: 'world', url: ignOrthophotos, maxzoom: 12 };
|
||||
|
||||
/** In order of priority, the first one covering a point is used. */
|
||||
const sources: ImagerySource[] = [
|
||||
{
|
||||
id: 'CH',
|
||||
url: xyz(
|
||||
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg'
|
||||
),
|
||||
maxzoom: 20,
|
||||
},
|
||||
{
|
||||
id: 'FR',
|
||||
url: ignOrthophotos,
|
||||
maxzoom: 19,
|
||||
},
|
||||
{
|
||||
id: 'ES',
|
||||
url: xyz(
|
||||
'https://www.ign.es/wmts/pnoa-ma?layer=OI.OrthoimageCoverage&style=default&tilematrixset=GoogleMapsCompatible&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/jpeg&TileMatrix={z}&TileCol={x}&TileRow={y}'
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
{
|
||||
id: 'AT',
|
||||
url: xyz(
|
||||
'https://mapsneu.wien.gv.at/basemap/bmaporthofoto30cm/normal/google3857/{z}/{y}/{x}.jpeg'
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
{
|
||||
id: 'NL',
|
||||
url: xyz(
|
||||
'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg'
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
{
|
||||
id: 'LU',
|
||||
url: xyz(
|
||||
'https://wmts1.geoportail.lu/opendata/wmts/ortho_latest/GLOBAL_WEBMERCATOR_4_V3/{z}/{x}/{y}.jpeg'
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
{
|
||||
id: 'CZ',
|
||||
url: xyz(
|
||||
'https://ags.cuzk.gov.cz/arcgis1/rest/services/ORTOFOTO_WM/MapServer/tile/{z}/{y}/{x}'
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
{
|
||||
id: 'BE',
|
||||
url: xyz(
|
||||
'https://wmts.ngi.be/inspire/ortho/1.0.0/orthoimage_coverage/default/3857/latest/{z}/{y}/{x}.png'
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
{
|
||||
id: 'PL',
|
||||
url: xyz(
|
||||
'https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTOFOTOMAPA&STYLE=default&FORMAT=image/jpeg&TILEMATRIXSET=EPSG:3857&TILEMATRIX=EPSG:3857:{z}&TILEROW={y}&TILECOL={x}'
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
];
|
||||
|
||||
export const openSatelliteAttribution = [
|
||||
'<a href="https://www.swisstopo.admin.ch/" target="_blank">swisstopo</a>',
|
||||
'<a href="https://geoservices.ign.fr/" target="_blank">IGN-F/Géoplateforme</a>',
|
||||
'PNOA © <a href="https://www.ign.es/" target="_blank">IGN España</a>',
|
||||
'<a href="https://basemap.at/" target="_blank">basemap.at</a>',
|
||||
'<a href="https://www.pdok.nl/" target="_blank">PDOK</a>',
|
||||
'<a href="https://geoportail.lu/" target="_blank">geoportail.lu</a>',
|
||||
'<a href="https://cuzk.gov.cz/" target="_blank">ČÚZK</a>',
|
||||
'<a href="https://www.ngi.be/" target="_blank">NGI/IGN</a>',
|
||||
'<a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>',
|
||||
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a>',
|
||||
].join(', ');
|
||||
|
||||
// Countries, from the tileset of their polygons, built from the borders of OpenStreetMap
|
||||
|
||||
const COUNTRIES_URL = xyz('https://tiles.gpx.studio/satellite-countries/{z}/{x}/{y}.mvt');
|
||||
/** The only zoom level of the tileset. */
|
||||
const COUNTRIES_ZOOM = 12;
|
||||
|
||||
const sourceByCountry = new Map(sources.map((source) => [source.id, source]));
|
||||
|
||||
/** The tiles of the countries, from their tileset: null where there is none. */
|
||||
export type CountryTiles = (z: number, x: number, y: number) => Promise<ArrayBuffer | null>;
|
||||
|
||||
async function fetchCountryTile(z: number, x: number, y: number): Promise<ArrayBuffer | null> {
|
||||
try {
|
||||
const response = await fetch(COUNTRIES_URL(z, x, y));
|
||||
if (!response.ok) return null;
|
||||
const bytes = await response.arrayBuffer();
|
||||
return bytes.byteLength > 0 ? bytes : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A tile of the countries is shared by the 4^(z - 12) tiles of imagery inside it. */
|
||||
const countryTiles = new Map<string, Promise<ArrayBuffer | null>>();
|
||||
|
||||
function getCountryTile(x: number, y: number, tiles: CountryTiles) {
|
||||
const key = `${x}/${y}`;
|
||||
let tile = countryTiles.get(key);
|
||||
if (tile) {
|
||||
// the last used, at the end of the map
|
||||
countryTiles.delete(key);
|
||||
} else {
|
||||
tile = tiles(COUNTRIES_ZOOM, x, y);
|
||||
if (countryTiles.size >= 256) countryTiles.delete(countryTiles.keys().next().value!);
|
||||
}
|
||||
countryTiles.set(key, tile);
|
||||
return tile;
|
||||
}
|
||||
|
||||
/** The tiles of zoom `zoom` where there is a country, as y * 2^zoom + x. */
|
||||
let areas: Promise<{ zoom: number; tiles: Set<number> }> | null = null;
|
||||
|
||||
function getAreas() {
|
||||
areas ??= import('$lib/data/satellite-countries.json').then((module) => ({
|
||||
zoom: module.default.zoom,
|
||||
tiles: new Set(module.default.tiles),
|
||||
}));
|
||||
return areas;
|
||||
}
|
||||
|
||||
// Geometry, in pixels of the tile of imagery
|
||||
|
||||
const TILE_SIZE = 256;
|
||||
const TILE_AREA = TILE_SIZE * TILE_SIZE;
|
||||
|
||||
type Ring = [number, number][];
|
||||
|
||||
/** The ring cut to the tile (Sutherland–Hodgman), which keeps its orientation. */
|
||||
function clipRing(ring: Ring): Ring {
|
||||
let points = ring;
|
||||
const edges: [(p: [number, number]) => number, number][] = [
|
||||
[(p) => p[0], 0],
|
||||
[(p) => -p[0], -TILE_SIZE],
|
||||
[(p) => p[1], 0],
|
||||
[(p) => -p[1], -TILE_SIZE],
|
||||
];
|
||||
for (const [value, min] of edges) {
|
||||
if (points.length === 0) break;
|
||||
const clipped: Ring = [];
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const current = points[i];
|
||||
const previous = points[(i + points.length - 1) % points.length];
|
||||
const inCurrent = value(current) >= min;
|
||||
const inPrevious = value(previous) >= min;
|
||||
if (inCurrent !== inPrevious) {
|
||||
const t = (min - value(previous)) / (value(current) - value(previous));
|
||||
clipped.push([
|
||||
previous[0] + t * (current[0] - previous[0]),
|
||||
previous[1] + t * (current[1] - previous[1]),
|
||||
]);
|
||||
}
|
||||
if (inCurrent) clipped.push(current);
|
||||
}
|
||||
points = clipped;
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
/** Positive for an outer ring of a vector tile, negative for a hole. */
|
||||
function signedArea(ring: Ring) {
|
||||
let area = 0;
|
||||
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
|
||||
area += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1];
|
||||
}
|
||||
return area / 2;
|
||||
}
|
||||
|
||||
/** The polygons of the countries with imagery in the tile, cut to it, with their area. */
|
||||
function countriesInTile(
|
||||
bytes: ArrayBuffer,
|
||||
z: number,
|
||||
x: number,
|
||||
y: number
|
||||
): { source: ImagerySource; rings: Ring[]; area: number }[] {
|
||||
const layer = new VectorTile(new PbfReader(bytes)).layers.countries;
|
||||
if (!layer) return [];
|
||||
const d = z - COUNTRIES_ZOOM;
|
||||
const scale = (TILE_SIZE * 2 ** d) / layer.extent;
|
||||
const offsetX = (x - ((x >> d) << d)) * TILE_SIZE;
|
||||
const offsetY = (y - ((y >> d) << d)) * TILE_SIZE;
|
||||
const countries = [];
|
||||
for (let i = 0; i < layer.length; i++) {
|
||||
const feature = layer.feature(i);
|
||||
const source = sourceByCountry.get(String(feature.properties.country));
|
||||
if (!source) continue;
|
||||
const rings = feature
|
||||
.loadGeometry()
|
||||
.map((ring) =>
|
||||
clipRing(ring.map((p) => [p.x * scale - offsetX, p.y * scale - offsetY]))
|
||||
)
|
||||
.filter((ring) => ring.length >= 3);
|
||||
const area = rings.reduce((sum, ring) => sum + signedArea(ring), 0);
|
||||
// less than a pixel: a polygon of the tile of the countries outside this one
|
||||
if (area >= 1) countries.push({ source, rings, area });
|
||||
}
|
||||
return countries;
|
||||
}
|
||||
|
||||
// Imagery
|
||||
|
||||
async function fetchBytes(url: string, signal: AbortSignal): Promise<ArrayBuffer | null> {
|
||||
try {
|
||||
const response = await fetch(url, { signal });
|
||||
if (!response.ok) return null;
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
if (!contentType.startsWith('image/')) return null;
|
||||
const bytes = await response.arrayBuffer();
|
||||
return (await isBlank(bytes)) ? null : bytes;
|
||||
} catch (e) {
|
||||
if (signal.aborted) throw e;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the image is all white or transparent: what some agencies give where they have no
|
||||
* imagery, such as IGN on the French part of Lake Geneva. Such an image is small, the others
|
||||
* are not even decoded.
|
||||
*/
|
||||
async function isBlank(bytes: ArrayBuffer) {
|
||||
if (bytes.byteLength > 4096) return false;
|
||||
try {
|
||||
const image = await createImageBitmap(new Blob([bytes]));
|
||||
const canvas = new OffscreenCanvas(16, 16);
|
||||
const context = canvas.getContext('2d')!;
|
||||
context.drawImage(image, 0, 0, 16, 16);
|
||||
image.close();
|
||||
const pixels = context.getImageData(0, 0, 16, 16).data;
|
||||
for (let i = 0; i < pixels.length; i += 4) {
|
||||
const transparent = pixels[i + 3] < 8;
|
||||
const white = pixels[i] >= 250 && pixels[i + 1] >= 250 && pixels[i + 2] >= 250;
|
||||
if (!transparent && !white) return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The image of the tile, or of the part of its ancestor at the max zoom of the source. */
|
||||
async function fetchImage(
|
||||
url: TileUrl,
|
||||
maxzoom: number,
|
||||
z: number,
|
||||
x: number,
|
||||
y: number,
|
||||
signal: AbortSignal
|
||||
): Promise<{ image: ImageBitmap; sx: number; sy: number; size: number } | null> {
|
||||
const d = Math.max(0, z - maxzoom);
|
||||
const bytes = await fetchBytes(url(z - d, x >> d, y >> d), signal);
|
||||
if (!bytes) return null;
|
||||
try {
|
||||
const image = await createImageBitmap(new Blob([bytes]));
|
||||
const size = image.width / 2 ** d;
|
||||
return {
|
||||
image,
|
||||
sx: (x - ((x >> d) << d)) * size,
|
||||
sy: (y - ((y >> d) << d)) * size,
|
||||
size,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function clipTo(context: OffscreenCanvasRenderingContext2D, rings: Ring[]) {
|
||||
context.beginPath();
|
||||
for (const ring of rings) {
|
||||
ring.forEach(([px, py], i) => (i === 0 ? context.moveTo(px, py) : context.lineTo(px, py)));
|
||||
context.closePath();
|
||||
}
|
||||
context.clip('evenodd');
|
||||
}
|
||||
|
||||
type TilePart = { source: ImagerySource; relation: 'full' | 'partial'; rings: Ring[] };
|
||||
|
||||
/**
|
||||
* The sources of the tile, in drawing order: the one covering the whole tile, or those
|
||||
* covering part of it, and whether the fallback is needed below them.
|
||||
*/
|
||||
export async function planTile(
|
||||
z: number,
|
||||
x: number,
|
||||
y: number,
|
||||
tiles: CountryTiles = fetchCountryTile
|
||||
): Promise<{ parts: TilePart[]; fallback: boolean }> {
|
||||
const none = { parts: [], fallback: true };
|
||||
if (z <= world.maxzoom) return none;
|
||||
const { zoom, tiles: withCountries } = await getAreas();
|
||||
const d = z - zoom;
|
||||
if (!withCountries.has((y >> d) * 2 ** zoom + (x >> d))) return none;
|
||||
|
||||
const bytes = await getCountryTile(x >> (z - COUNTRIES_ZOOM), y >> (z - COUNTRIES_ZOOM), tiles);
|
||||
if (!bytes) return none;
|
||||
const countries = countriesInTile(bytes, z, x, y);
|
||||
// a pixel of margin, for the rounding of the coordinates of the tiles
|
||||
const whole = countries.find((country) => country.area >= TILE_AREA - TILE_SIZE);
|
||||
if (whole) {
|
||||
return { parts: [{ source: whole.source, relation: 'full', rings: [] }], fallback: false };
|
||||
}
|
||||
const covered = countries.reduce((sum, country) => sum + country.area, 0);
|
||||
return {
|
||||
parts: countries.map(({ source, rings }) => ({ source, relation: 'partial', rings })),
|
||||
fallback: covered < TILE_AREA - TILE_SIZE,
|
||||
};
|
||||
}
|
||||
|
||||
export function maptilerSource(maptilerKey: string): ImagerySource {
|
||||
return {
|
||||
id: 'fallback',
|
||||
url: xyz(`https://api.maptiler.com/tiles/satellite-v2/{z}/{x}/{y}.jpg?key=${maptilerKey}`),
|
||||
maxzoom: 18,
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadTile(
|
||||
z: number,
|
||||
x: number,
|
||||
y: number,
|
||||
commercialFallback: ImagerySource,
|
||||
signal: AbortSignal
|
||||
): Promise<ArrayBuffer | ImageBitmap> {
|
||||
const fallback = z <= world.maxzoom ? world : commercialFallback;
|
||||
const plan = await planTile(z, x, y);
|
||||
const { parts } = plan;
|
||||
|
||||
// a single tile as it is, without drawing it again
|
||||
const single =
|
||||
parts.length === 0
|
||||
? fallback
|
||||
: parts.length === 1 && !plan.fallback && parts[0].relation === 'full'
|
||||
? parts[0].source
|
||||
: null;
|
||||
if (single && z <= single.maxzoom) {
|
||||
const bytes = await fetchBytes(single.url(z, x, y), signal);
|
||||
if (bytes) return bytes;
|
||||
if (single === fallback) throw new Error(`No imagery for tile ${z}/${x}/${y}`);
|
||||
}
|
||||
|
||||
const images = await Promise.all(
|
||||
parts.map((p) => fetchImage(p.source.url, p.source.maxzoom, z, x, y, signal))
|
||||
);
|
||||
const fallbackImage =
|
||||
plan.fallback || images.some((image) => image === null)
|
||||
? await fetchImage(fallback.url, fallback.maxzoom, z, x, y, signal)
|
||||
: null;
|
||||
|
||||
const canvas = new OffscreenCanvas(TILE_SIZE, TILE_SIZE);
|
||||
const context = canvas.getContext('2d')!;
|
||||
if (fallbackImage) {
|
||||
const { image, sx, sy, size } = fallbackImage;
|
||||
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
|
||||
image.close();
|
||||
}
|
||||
parts.forEach((p, i) => {
|
||||
const result = images[i];
|
||||
if (!result) return;
|
||||
context.save();
|
||||
if (p.relation === 'partial') clipTo(context, p.rings);
|
||||
const { image, sx, sy, size } = result;
|
||||
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
|
||||
context.restore();
|
||||
image.close();
|
||||
});
|
||||
return canvas.transferToImageBitmap();
|
||||
}
|
||||
|
||||
export function registerOpenSatelliteProtocol(maptilerKey: string) {
|
||||
const fallback = maptilerSource(maptilerKey);
|
||||
maplibregl.addProtocol(OPEN_SATELLITE_PROTOCOL, async (params, abortController) => {
|
||||
const match = params.url.match(/(\d+)\/(\d+)\/(\d+)$/);
|
||||
if (!match) throw new Error(`Invalid tile URL: ${params.url}`);
|
||||
const [z, x, y] = match.slice(1).map(Number);
|
||||
return { data: await loadTile(z, x, y, fallback, abortController.signal) };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// How the map shows the overlays: here, those of extensions that give the URL of their style.
|
||||
import assert from 'node:assert/strict';
|
||||
import { afterEach, beforeEach, describe, it } from 'node:test';
|
||||
import type { Map as MapLibreMap, StyleSpecification } from 'maplibre-gl';
|
||||
import { writable } from 'svelte/store';
|
||||
import { overlays, type LayerTreeType } from '$lib/data/layers';
|
||||
import { engine } from '$lib/engine';
|
||||
import { settings } from '$lib/state/settings';
|
||||
import { StyleManager } from './style';
|
||||
|
||||
const URL_A = 'https://example.com/a.json';
|
||||
const URL_B = 'https://example.com/b.json';
|
||||
const ID = 'extension-Heatmaps/a';
|
||||
|
||||
const style = (tiles: string): StyleSpecification => ({
|
||||
version: 8,
|
||||
sources: { tiles: { type: 'raster', tiles: [tiles], tileSize: 256 } },
|
||||
layers: [{ id: 'tiles', type: 'raster', source: 'tiles' }],
|
||||
});
|
||||
|
||||
const original = {
|
||||
set: engine.setSetting,
|
||||
delete: engine.deleteSetting,
|
||||
fetch: globalThis.fetch,
|
||||
error: console.error,
|
||||
};
|
||||
|
||||
/** A map that only knows of its overlays. */
|
||||
function fakeMap() {
|
||||
const sources = new Map<string, { tiles: string[] }>([['empty-source', { tiles: [] }]]);
|
||||
const layers = new Map<string, { source: string; paint: Record<string, unknown> }>();
|
||||
return {
|
||||
sources,
|
||||
layers,
|
||||
on: () => {},
|
||||
setStyle: () => {},
|
||||
getPitch: () => 0,
|
||||
getTerrain: () => null,
|
||||
setTerrain: () => {},
|
||||
getSource: (id: string) => sources.get(id),
|
||||
addSource: (id: string, source: { tiles: string[] }) => sources.set(id, source),
|
||||
getLayer: (id: string) => layers.get(id),
|
||||
addLayer: (layer: { id: string; source: string; paint: Record<string, unknown> }) =>
|
||||
layers.set(layer.id, layer),
|
||||
removeLayer: (id: string) => layers.delete(id),
|
||||
setPaintProperty: (id: string, name: string, value: unknown) => {
|
||||
layers.get(id)!.paint[name] = value;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Shows the overlay, and gives the manager of the map. */
|
||||
function setUp(fake: ReturnType<typeof fakeMap>) {
|
||||
settings.currentOverlays.update((tree) => {
|
||||
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: true };
|
||||
return tree;
|
||||
});
|
||||
const store = writable<MapLibreMap | null>(null);
|
||||
const manager = new StyleManager(store, '');
|
||||
store.set(fake as unknown as MapLibreMap);
|
||||
return manager;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
engine.setSetting = () => {};
|
||||
engine.deleteSetting = () => {};
|
||||
settings.connect({});
|
||||
settings.initialize();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete overlays[ID];
|
||||
delete overlays.plainUrl;
|
||||
settings.currentOverlays.update((tree) => {
|
||||
delete (tree.overlays as LayerTreeType).Heatmaps;
|
||||
delete (tree.overlays as LayerTreeType).plainUrl;
|
||||
return tree;
|
||||
});
|
||||
engine.setSetting = original.set;
|
||||
engine.deleteSetting = original.delete;
|
||||
globalThis.fetch = original.fetch;
|
||||
console.error = original.error;
|
||||
});
|
||||
|
||||
/** Answers the style requests with the styles of `responses`, by URL. */
|
||||
function answerWith(responses: Record<string, StyleSpecification>) {
|
||||
globalThis.fetch = (async (url: string) =>
|
||||
Object.hasOwn(responses, url)
|
||||
? new Response(JSON.stringify(responses[url]))
|
||||
: new Response(JSON.stringify(style('https://basemap/{z}')))) as typeof fetch;
|
||||
}
|
||||
|
||||
describe('StyleManager, with the style URL of an extension', () => {
|
||||
it('fetches it, and prefixes the ids of its sources and layers', async () => {
|
||||
answerWith({ [URL_A]: style('https://a/{z}') });
|
||||
overlays[ID] = URL_A;
|
||||
const fake = fakeMap();
|
||||
await setUp(fake).updateOverlays();
|
||||
|
||||
assert.deepEqual(fake.sources.get(`${ID}/tiles`)?.tiles, ['https://a/{z}']);
|
||||
assert.equal(fake.layers.get(`${ID}/tiles`)?.source, `${ID}/tiles`);
|
||||
assert.ok(!fake.sources.has('tiles'));
|
||||
});
|
||||
|
||||
it('uses the opacity of the overlay', async () => {
|
||||
answerWith({ [URL_A]: style('https://a/{z}') });
|
||||
overlays[ID] = URL_A;
|
||||
settings.opacities.update((opacities) => ({ ...opacities, [ID]: 0.3 }));
|
||||
const fake = fakeMap();
|
||||
await setUp(fake).updateOverlays();
|
||||
assert.equal(fake.layers.get(`${ID}/tiles`)?.paint['raster-opacity'], 0.3);
|
||||
});
|
||||
|
||||
it('removes its layers when it is hidden', async () => {
|
||||
answerWith({ [URL_A]: style('https://a/{z}') });
|
||||
overlays[ID] = URL_A;
|
||||
const fake = fakeMap();
|
||||
const manager = setUp(fake);
|
||||
await manager.updateOverlays();
|
||||
assert.ok(fake.layers.has(`${ID}/tiles`));
|
||||
|
||||
settings.currentOverlays.update((tree) => {
|
||||
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: false };
|
||||
return tree;
|
||||
});
|
||||
await manager.updateOverlays();
|
||||
assert.ok(!fake.layers.has(`${ID}/tiles`));
|
||||
});
|
||||
|
||||
it('does not fetch it while the overlay is hidden', async () => {
|
||||
const urls: string[] = [];
|
||||
answerWith({});
|
||||
const answer = globalThis.fetch;
|
||||
globalThis.fetch = ((url: string) => {
|
||||
urls.push(url);
|
||||
return answer(url);
|
||||
}) as typeof fetch;
|
||||
overlays[ID] = URL_A;
|
||||
settings.currentOverlays.update((tree) => {
|
||||
(tree.overlays as LayerTreeType).Heatmaps = { [ID]: false };
|
||||
return tree;
|
||||
});
|
||||
const store = writable<MapLibreMap | null>(null);
|
||||
const manager = new StyleManager(store, '');
|
||||
store.set(fakeMap() as unknown as MapLibreMap);
|
||||
await manager.updateOverlays();
|
||||
assert.ok(!urls.includes(URL_A));
|
||||
});
|
||||
|
||||
it('ignores a style that was replaced or removed while it was fetched', async () => {
|
||||
for (const next of [URL_B, undefined]) {
|
||||
let respond: (response: Response) => void = () => {};
|
||||
const answers: Record<string, StyleSpecification> = {
|
||||
[URL_B]: style('https://b/{z}'),
|
||||
};
|
||||
answerWith(answers);
|
||||
const answer = globalThis.fetch;
|
||||
globalThis.fetch = ((url: string) =>
|
||||
url === URL_A
|
||||
? new Promise((resolve) => (respond = resolve))
|
||||
: answer(url)) as typeof fetch;
|
||||
|
||||
overlays[ID] = URL_A;
|
||||
const fake = fakeMap();
|
||||
const manager = setUp(fake);
|
||||
const pending = manager.updateOverlays();
|
||||
await new Promise((resolve) => setTimeout(resolve));
|
||||
if (next) {
|
||||
overlays[ID] = next;
|
||||
} else {
|
||||
delete overlays[ID];
|
||||
}
|
||||
respond(new Response(JSON.stringify(style('https://a/{z}'))));
|
||||
await pending;
|
||||
assert.ok(!fake.sources.has(`${ID}/tiles`));
|
||||
|
||||
await manager.updateOverlays();
|
||||
assert.deepEqual(
|
||||
fake.sources.get(`${ID}/tiles`)?.tiles,
|
||||
next ? ['https://b/{z}'] : undefined
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('logs a style that cannot be used, which leaves the others alone', async () => {
|
||||
const logged: unknown[] = [];
|
||||
console.error = (...args) => logged.push(args);
|
||||
for (const answer of [
|
||||
new Response('', { status: 404 }),
|
||||
new Response(JSON.stringify({ version: 8, sources: {} })),
|
||||
]) {
|
||||
answerWith({});
|
||||
const basemap = globalThis.fetch;
|
||||
globalThis.fetch = ((url: string) =>
|
||||
url === URL_A ? Promise.resolve(answer.clone()) : basemap(url)) as typeof fetch;
|
||||
overlays[ID] = URL_A;
|
||||
const fake = fakeMap();
|
||||
logged.length = 0;
|
||||
await setUp(fake).updateOverlays();
|
||||
assert.ok(logged.length > 0);
|
||||
assert.equal(fake.layers.size, 0);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not prefix the style URL of anything else', async () => {
|
||||
answerWith({ [URL_A]: style('https://a/{z}') });
|
||||
overlays.plainUrl = URL_A;
|
||||
settings.currentOverlays.update((tree) => {
|
||||
(tree.overlays as LayerTreeType).plainUrl = { plainUrl: true };
|
||||
return tree;
|
||||
});
|
||||
const fake = fakeMap();
|
||||
const store = writable<MapLibreMap | null>(null);
|
||||
const manager = new StyleManager(store, '');
|
||||
store.set(fake as unknown as MapLibreMap);
|
||||
await manager.updateOverlays();
|
||||
assert.ok(fake.sources.has('tiles'));
|
||||
assert.ok(fake.layers.has('tiles'));
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
overlays,
|
||||
terrainSources,
|
||||
} from '$lib/data/layers';
|
||||
import { getLayers } from '$lib/components/map/layer-control/utils';
|
||||
import { getLayers, getOpacityPaint, prefixStyle } from '$lib/components/map/layer-control/utils';
|
||||
import { i18n } from '$lib/i18n/i18n.svelte';
|
||||
|
||||
const { currentBasemap, currentOverlays, customLayers, opacities, terrainSource, distanceUnits } =
|
||||
@@ -147,13 +147,18 @@ export class StyleManager {
|
||||
const custom = get(customLayers);
|
||||
const overlayOpacities = get(opacities);
|
||||
try {
|
||||
// an overlay on the map can be gone from the tree, which has been replaced as a whole
|
||||
const layers = getLayers(get(currentOverlays) ?? {});
|
||||
this._pastOverlays.forEach((id) => (layers[id] ??= false));
|
||||
for (const overlay in layers) {
|
||||
if (!layers[overlay]) {
|
||||
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
|
||||
if (!overlayInfo) {
|
||||
// removed, together with what it had on the map
|
||||
this._pastOverlays.delete(overlay);
|
||||
} else if (!layers[overlay]) {
|
||||
if (this._pastOverlays.has(overlay)) {
|
||||
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
|
||||
try {
|
||||
const overlayStyle = await this.get(overlayInfo);
|
||||
const overlayStyle = await this.getOverlayStyle(overlay, overlayInfo);
|
||||
for (const layer of overlayStyle.layers ?? []) {
|
||||
if (map_.getLayer(layer.id)) {
|
||||
map_.removeLayer(layer.id);
|
||||
@@ -165,9 +170,10 @@ export class StyleManager {
|
||||
this._pastOverlays.delete(overlay);
|
||||
}
|
||||
} else {
|
||||
const overlayInfo = custom[overlay]?.value ?? overlays[overlay];
|
||||
try {
|
||||
const overlayStyle = await this.get(overlayInfo);
|
||||
const overlayStyle = await this.getOverlayStyle(overlay, overlayInfo);
|
||||
// replaced or removed while it was fetched: its new style has its own turn
|
||||
if (!custom[overlay] && overlays[overlay] !== overlayInfo) continue;
|
||||
const opacity = overlayOpacities[overlay];
|
||||
|
||||
for (const sourceId in overlayStyle.sources) {
|
||||
@@ -177,21 +183,24 @@ export class StyleManager {
|
||||
}
|
||||
|
||||
for (const layer of overlayStyle.layers ?? []) {
|
||||
if (!map_.getLayer(layer.id)) {
|
||||
if (opacity !== undefined) {
|
||||
if (layer.type === 'raster') {
|
||||
if (!layer.paint) {
|
||||
layer.paint = {};
|
||||
}
|
||||
layer.paint['raster-opacity'] = opacity;
|
||||
} else if (layer.type === 'hillshade') {
|
||||
if (!layer.paint) {
|
||||
layer.paint = {};
|
||||
}
|
||||
layer.paint['hillshade-exaggeration'] = opacity / 2;
|
||||
}
|
||||
const paint =
|
||||
opacity === undefined ? {} : getOpacityPaint(layer, opacity);
|
||||
if (map_.getLayer(layer.id)) {
|
||||
for (const property in paint) {
|
||||
map_.setPaintProperty(
|
||||
layer.id,
|
||||
property as never,
|
||||
paint[property] as never
|
||||
);
|
||||
}
|
||||
map_.addLayer(layer, ANCHOR_LAYER_KEY.overlays);
|
||||
} else {
|
||||
map_.addLayer(
|
||||
{
|
||||
...layer,
|
||||
paint: { ...layer.paint, ...paint },
|
||||
} as LayerSpecification,
|
||||
ANCHOR_LAYER_KEY.overlays
|
||||
);
|
||||
}
|
||||
}
|
||||
this._pastOverlays.add(overlay);
|
||||
@@ -221,6 +230,17 @@ export class StyleManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** The style of an overlay. The ids of one from an extension's URL still have to be prefixed. */
|
||||
private async getOverlayStyle(
|
||||
overlay: string,
|
||||
styleInfo: StyleSpecification | string
|
||||
): Promise<StyleSpecification> {
|
||||
const style = await this.get(styleInfo);
|
||||
return typeof styleInfo === 'string' && overlay.startsWith('extension-')
|
||||
? prefixStyle(overlay, style)
|
||||
: style;
|
||||
}
|
||||
|
||||
async get(styleInfo: StyleSpecification | string): Promise<StyleSpecification> {
|
||||
if (typeof styleInfo === 'string') {
|
||||
const styleUrl = styleInfo as string;
|
||||
|
||||
@@ -218,6 +218,7 @@
|
||||
</span>
|
||||
{:else}
|
||||
<TimePicker
|
||||
id="speed"
|
||||
bind:value={speed}
|
||||
showHours={false}
|
||||
disabled={!canUpdate}
|
||||
@@ -243,6 +244,7 @@
|
||||
{i18n._('toolbar.time.total_time')}
|
||||
</Label>
|
||||
<TimePicker
|
||||
id="duration"
|
||||
bind:value={movingTime}
|
||||
disabled={!canUpdate}
|
||||
onChange={() => {
|
||||
|
||||
@@ -633,6 +633,11 @@ export class RoutingControls {
|
||||
|
||||
const anchor = this.anchors[e.features![0].properties.anchorIndex];
|
||||
if (!anchor) {
|
||||
// The temporary anchor on the line is not one of the anchors (nor is a feature
|
||||
// still rendered from before they were rebuilt), a click on it adds it
|
||||
if (e.type === 'click') {
|
||||
this.addIntermediateAnchor(e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e.originalEvent.shiftKey) {
|
||||
|
||||
@@ -45,6 +45,19 @@
|
||||
|
||||
let marker: Marker | null = null;
|
||||
|
||||
// A number field holds what is typed, out of range or empty (null) on the way to a
|
||||
// coordinate, and a map click sets strings. MapLibre throws on a latitude past ±90.
|
||||
function inRange(value: number | string | null, limit: number) {
|
||||
if (value === null || value === '') {
|
||||
return false;
|
||||
}
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) && Math.abs(n) <= limit;
|
||||
}
|
||||
let latitudeValid = $derived(inRange(latitude, 90));
|
||||
let longitudeValid = $derived(inRange(longitude, 180));
|
||||
let coordinatesValid = $derived(latitudeValid && longitudeValid);
|
||||
|
||||
function reset() {
|
||||
if ($selectedWaypoint) {
|
||||
selectedWaypoint.reset();
|
||||
@@ -78,6 +91,9 @@
|
||||
});
|
||||
|
||||
async function createOrUpdateWaypoint() {
|
||||
if (!coordinatesValid) {
|
||||
return;
|
||||
}
|
||||
if (typeof latitude === 'string') {
|
||||
latitude = parseFloat(latitude);
|
||||
}
|
||||
@@ -128,7 +144,8 @@
|
||||
marker = null;
|
||||
}
|
||||
} else if (latitude != 0 || longitude != 0) {
|
||||
if ($map) {
|
||||
// while a coordinate is being typed the pin stays where it last was
|
||||
if ($map && coordinatesValid) {
|
||||
if (marker) {
|
||||
marker.setLngLat([longitude, latitude]).getElement().innerHTML =
|
||||
getSvgForSymbol(symbolKey);
|
||||
@@ -248,6 +265,7 @@
|
||||
min={-90}
|
||||
max={90}
|
||||
class="text-xs h-8"
|
||||
aria-invalid={!latitudeValid}
|
||||
disabled={!canCreate && !$selectedWaypoint}
|
||||
/>
|
||||
</div>
|
||||
@@ -261,6 +279,7 @@
|
||||
min={-180}
|
||||
max={180}
|
||||
class="text-xs h-8"
|
||||
aria-invalid={!longitudeValid}
|
||||
disabled={!canCreate && !$selectedWaypoint}
|
||||
/>
|
||||
</div>
|
||||
@@ -269,7 +288,7 @@
|
||||
<div class="flex flex-row gap-1.5 items-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={!canCreate && !$selectedWaypoint}
|
||||
disabled={(!canCreate && !$selectedWaypoint) || !coordinatesValid}
|
||||
class="grow shrink h-fit min-h-8 whitespace-normal py-1"
|
||||
onclick={createOrUpdateWaypoint}
|
||||
>
|
||||
|
||||
@@ -1,63 +1,40 @@
|
||||
<script lang="ts">
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
|
||||
let {
|
||||
id,
|
||||
value = $bindable(),
|
||||
disabled,
|
||||
oninput = () => {},
|
||||
onchange = () => {},
|
||||
onkeypress = () => {},
|
||||
onfocusin = () => {},
|
||||
class: className,
|
||||
}: {
|
||||
id: string;
|
||||
value: string | number;
|
||||
disabled?: boolean;
|
||||
oninput?: (e: Event) => void;
|
||||
onchange?: (e: Event) => void;
|
||||
onkeypress?: (e: KeyboardEvent) => void;
|
||||
onfocusin?: (e: FocusEvent) => void;
|
||||
class?: string;
|
||||
} = $props();
|
||||
<script lang="ts" module>
|
||||
/** Shown by an empty field: real text rather than a placeholder, so that it can be selected. */
|
||||
export const EMPTY_FIELD = '--';
|
||||
</script>
|
||||
|
||||
<div>
|
||||
<Input
|
||||
{id}
|
||||
<script lang="ts">
|
||||
import { cn, type WithElementRef } from '$lib/utils.js';
|
||||
import type { HTMLInputAttributes } from 'svelte/elements';
|
||||
|
||||
let {
|
||||
ref = $bindable(null),
|
||||
value,
|
||||
class: className,
|
||||
...restProps
|
||||
}: WithElementRef<Omit<HTMLInputAttributes, 'type' | 'value'>> & { value: string } = $props();
|
||||
|
||||
// The padding of the fields of a native time input, which is larger in Firefox.
|
||||
const padding = 'px-px [@supports(-moz-appearance:none)]:px-[3px]';
|
||||
</script>
|
||||
|
||||
<!-- The invisible copy of the text sizes the field to its exact width, like in a native time input. -->
|
||||
<span class="relative inline-block">
|
||||
<span aria-hidden="true" class={cn('invisible block whitespace-pre', padding)}>
|
||||
{value || EMPTY_FIELD}
|
||||
</span>
|
||||
<input
|
||||
bind:this={ref}
|
||||
type="text"
|
||||
step={1}
|
||||
bind:value
|
||||
{disabled}
|
||||
{oninput}
|
||||
{onchange}
|
||||
{onkeypress}
|
||||
onfocusin={(e) => {
|
||||
let input = document.activeElement;
|
||||
if (input instanceof HTMLInputElement) {
|
||||
input.select();
|
||||
}
|
||||
onfocusin(e);
|
||||
}}
|
||||
class="w-[22px] {className ?? ''}"
|
||||
inputmode="numeric"
|
||||
autocomplete="off"
|
||||
value={value || EMPTY_FIELD}
|
||||
class={cn(
|
||||
'absolute inset-0 w-full bg-transparent text-center outline-none',
|
||||
padding,
|
||||
className
|
||||
)}
|
||||
onfocus={(e) => e.currentTarget.select()}
|
||||
{...restProps}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<style lang="postcss">
|
||||
@reference "tailwindcss";
|
||||
|
||||
div :global(input) {
|
||||
@apply px-0.5;
|
||||
@apply py-0;
|
||||
@apply bg-transparent;
|
||||
@apply text-right;
|
||||
@apply border-none;
|
||||
@apply shadow-none;
|
||||
@apply focus:ring-0;
|
||||
@apply focus:ring-offset-0;
|
||||
@apply focus:outline-none;
|
||||
@apply focus-visible:ring-0;
|
||||
@apply focus-visible:ring-offset-0;
|
||||
@apply focus-visible:outline-none;
|
||||
}
|
||||
</style>
|
||||
</span>
|
||||
@@ -1,174 +1,176 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import TimeComponentInput from './TimeComponentInput.svelte';
|
||||
import { cn } from '$lib/utils.js';
|
||||
import TimeComponentInput, { EMPTY_FIELD } from './TimeComponentInput.svelte';
|
||||
|
||||
let {
|
||||
id,
|
||||
showHours = true,
|
||||
value = $bindable(),
|
||||
disabled = false,
|
||||
onChange = () => {},
|
||||
}: {
|
||||
/** Set on the first field, so that a label can target the picker. */
|
||||
id?: string;
|
||||
showHours?: boolean;
|
||||
value?: number;
|
||||
disabled?: boolean;
|
||||
onChange?: () => void;
|
||||
} = $props();
|
||||
|
||||
let hours: string | number = $state('--');
|
||||
let minutes: string | number = $state('--');
|
||||
let seconds: string | number = $state('--');
|
||||
let hours = $state('');
|
||||
let minutes = $state('');
|
||||
let seconds = $state('');
|
||||
|
||||
function maybeParseInt(value: string | number): number {
|
||||
if (value === '--' || value === '') {
|
||||
return 0;
|
||||
let hoursInput: HTMLInputElement | null = $state(null);
|
||||
let minutesInput: HTMLInputElement | null = $state(null);
|
||||
let secondsInput: HTMLInputElement | null = $state(null);
|
||||
|
||||
function parseField(field: string): number {
|
||||
return field === '' ? 0 : parseInt(field, 10);
|
||||
}
|
||||
|
||||
function fieldsToSeconds(): number {
|
||||
const total =
|
||||
(showHours ? parseField(hours) * 3600 : 0) +
|
||||
parseField(minutes) * 60 +
|
||||
parseField(seconds);
|
||||
// Callers divide by this value, so it must stay positive.
|
||||
return Math.max(total, 1);
|
||||
}
|
||||
|
||||
function pad(field: number): string {
|
||||
return field.toString().padStart(2, '0');
|
||||
}
|
||||
|
||||
function showValue(newValue: number | undefined) {
|
||||
if (!Number.isFinite(newValue)) {
|
||||
hours = minutes = seconds = '';
|
||||
return;
|
||||
}
|
||||
return typeof value === 'string' ? parseInt(value) : value;
|
||||
}
|
||||
|
||||
function computeValue(): number {
|
||||
return Math.max(
|
||||
maybeParseInt(hours) * 3600 + maybeParseInt(minutes) * 60 + maybeParseInt(seconds),
|
||||
1
|
||||
);
|
||||
const total = Math.max(Math.round(newValue!), 1);
|
||||
const totalMinutes = Math.floor(total / 60);
|
||||
if (showHours) {
|
||||
hours = Math.floor(total / 3600).toString();
|
||||
minutes = pad(totalMinutes % 60);
|
||||
} else {
|
||||
minutes = totalMinutes.toString();
|
||||
}
|
||||
seconds = pad(total % 60);
|
||||
}
|
||||
|
||||
// Only the display follows `value`: it is written back on user input only, so that showing a
|
||||
// value never rounds or overwrites it. A value that matches the fields comes from them, and
|
||||
// must not reformat them during typing.
|
||||
$effect(() => {
|
||||
const val = computeValue();
|
||||
const newValue = value;
|
||||
void showHours;
|
||||
untrack(() => {
|
||||
value = val;
|
||||
if (newValue !== fieldsToSeconds()) {
|
||||
showValue(newValue);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (value === undefined) {
|
||||
untrack(() => {
|
||||
hours = '--';
|
||||
minutes = '--';
|
||||
seconds = '--';
|
||||
});
|
||||
} else {
|
||||
untrack(() => {
|
||||
if (value != computeValue()) {
|
||||
let rounded = Math.max(Math.round(value!), 1);
|
||||
if (showHours) {
|
||||
hours = Math.floor(rounded / 3600);
|
||||
minutes = Math.floor((rounded % 3600) / 60)
|
||||
.toString()
|
||||
.padStart(2, '0');
|
||||
} else {
|
||||
minutes = Math.floor(rounded / 60).toString();
|
||||
}
|
||||
seconds = (rounded % 60).toString().padStart(2, '0');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
/** A field without an upper bound: hours, or minutes when there are no hours. */
|
||||
function normalizeUnbounded(input: string): string {
|
||||
const digits = input.replace(/\D/g, '').slice(-6);
|
||||
return digits === '' ? '' : parseInt(digits, 10).toString();
|
||||
}
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let countKeyPress = 0;
|
||||
function onKeyPress(e: KeyboardEvent) {
|
||||
const target = e.target as HTMLInputElement | null;
|
||||
if (target && ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'].includes(e.key)) {
|
||||
countKeyPress++;
|
||||
if (countKeyPress === 2) {
|
||||
const nextInput =
|
||||
target.id === 'hours'
|
||||
? (container.querySelector('#minutes') as HTMLInputElement)
|
||||
: target.id === 'minutes'
|
||||
? (container.querySelector('#seconds') as HTMLInputElement)
|
||||
: null;
|
||||
if (nextInput) {
|
||||
nextInput.focus();
|
||||
}
|
||||
/** Minutes or seconds: new digits shift in from the right, so "12" then "3" gives "23". */
|
||||
function normalizeSexagesimal(input: string): string {
|
||||
const digits = input.replace(/\D/g, '').slice(-2);
|
||||
return digits === '' ? '' : pad(Math.min(parseInt(digits, 10), 59));
|
||||
}
|
||||
|
||||
let digitsTyped = 0;
|
||||
|
||||
function handleInput(
|
||||
e: Event & { currentTarget: HTMLInputElement },
|
||||
normalize: (input: string) => string,
|
||||
setField: (field: string) => void,
|
||||
nextInput: HTMLInputElement | null
|
||||
) {
|
||||
const input = e.currentTarget;
|
||||
const field = normalize(input.value);
|
||||
// The state is unchanged when the input is rejected (a letter, for example), in which case
|
||||
// Svelte would leave the rejected text in the DOM.
|
||||
input.value = field || EMPTY_FIELD;
|
||||
if (!field) {
|
||||
input.select();
|
||||
}
|
||||
setField(field);
|
||||
|
||||
value = fieldsToSeconds();
|
||||
onChange();
|
||||
|
||||
if (/^\d$/.test((e as unknown as InputEvent).data ?? '')) {
|
||||
digitsTyped++;
|
||||
if (digitsTyped === 2) {
|
||||
nextInput?.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function handlePointerDown(e: PointerEvent) {
|
||||
// Like a native input, the whole box gives focus, not only the text.
|
||||
if (e.target === e.currentTarget) {
|
||||
e.preventDefault();
|
||||
(hoursInput ?? minutesInput)?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function handleFocusOut(e: FocusEvent & { currentTarget: HTMLDivElement }) {
|
||||
// Fill in the fields left empty once the user is done with the picker.
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
|
||||
showValue(value);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
bind:this={container}
|
||||
class="h-9 flex flex-row items-center w-full min-w-fit border rounded-md px-3 focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 {disabled
|
||||
? 'opacity-50 cursor-not-allowed'
|
||||
: ''}"
|
||||
data-slot="time-picker"
|
||||
class={cn(
|
||||
'dark:bg-input/30 border-input focus-within:border-ring focus-within:ring-ring/50 flex h-8 w-full min-w-28 cursor-text items-center justify-end rounded-lg border bg-transparent px-2.5 py-1 text-base transition-colors focus-within:ring-3 md:text-sm',
|
||||
disabled && 'bg-input/50 dark:bg-input/80 pointer-events-none cursor-not-allowed opacity-50'
|
||||
)}
|
||||
onpointerdown={handlePointerDown}
|
||||
onfocusin={() => {
|
||||
digitsTyped = 0;
|
||||
}}
|
||||
onfocusout={handleFocusOut}
|
||||
>
|
||||
{#if showHours}
|
||||
<TimeComponentInput
|
||||
id="hours"
|
||||
bind:value={hours}
|
||||
{id}
|
||||
bind:ref={hoursInput}
|
||||
value={hours}
|
||||
{disabled}
|
||||
class="w-[30px]"
|
||||
oninput={() => {
|
||||
if (typeof hours === 'string') {
|
||||
hours = parseInt(hours);
|
||||
}
|
||||
if (hours < 0) {
|
||||
hours = 0;
|
||||
}
|
||||
onChange();
|
||||
}}
|
||||
onkeypress={onKeyPress}
|
||||
onfocusin={() => {
|
||||
countKeyPress = 0;
|
||||
}}
|
||||
oninput={(e) =>
|
||||
handleInput(e, normalizeUnbounded, (field) => (hours = field), minutesInput)}
|
||||
/>
|
||||
<span class="text-sm">:</span>
|
||||
<span>:</span>
|
||||
{/if}
|
||||
<TimeComponentInput
|
||||
id="minutes"
|
||||
bind:value={minutes}
|
||||
id={showHours ? undefined : id}
|
||||
bind:ref={minutesInput}
|
||||
value={minutes}
|
||||
{disabled}
|
||||
oninput={() => {
|
||||
if (typeof minutes === 'string') {
|
||||
minutes = parseInt(minutes);
|
||||
}
|
||||
if (showHours && minutes > 59) {
|
||||
minutes = 59;
|
||||
} else if (minutes < 0) {
|
||||
minutes = 0;
|
||||
}
|
||||
minutes = minutes.toString().padStart(showHours ? 2 : 1, '0');
|
||||
onChange();
|
||||
}}
|
||||
onkeypress={onKeyPress}
|
||||
onfocusin={() => {
|
||||
countKeyPress = 0;
|
||||
}}
|
||||
oninput={(e) =>
|
||||
handleInput(
|
||||
e,
|
||||
showHours ? normalizeSexagesimal : normalizeUnbounded,
|
||||
(field) => (minutes = field),
|
||||
secondsInput
|
||||
)}
|
||||
/>
|
||||
<span class="text-sm">:</span>
|
||||
<span>:</span>
|
||||
<TimeComponentInput
|
||||
id="seconds"
|
||||
bind:value={seconds}
|
||||
bind:ref={secondsInput}
|
||||
value={seconds}
|
||||
{disabled}
|
||||
oninput={() => {
|
||||
if (typeof seconds === 'string') {
|
||||
seconds = parseInt(seconds);
|
||||
}
|
||||
if (seconds > 59) {
|
||||
seconds = 59;
|
||||
} else if (seconds < 0) {
|
||||
seconds = 0;
|
||||
}
|
||||
seconds = seconds.toString().padStart(2, '0');
|
||||
onChange();
|
||||
}}
|
||||
onkeypress={onKeyPress}
|
||||
onfocusin={() => {
|
||||
countKeyPress = 0;
|
||||
}}
|
||||
oninput={(e) => handleInput(e, normalizeSexagesimal, (field) => (seconds = field), null)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
div :global(input::-webkit-outer-spin-button) {
|
||||
-webkit-appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
div :global(input::-webkit-inner-spin-button) {
|
||||
-webkit-appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
div :global(input[type='number']) {
|
||||
appearance: textfield;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
</style>
|
||||
@@ -32,28 +32,6 @@ export const basemaps: { [key: string]: string | StyleSpecification } = {
|
||||
libertySatellite: 'https://styles.gpx.studio/liberty-satellite.json',
|
||||
osm: 'https://styles.gpx.studio/osm.json',
|
||||
osmTopo: 'https://styles.gpx.studio/osm-topo.json',
|
||||
esriSatellite: {
|
||||
version: 8,
|
||||
sources: {
|
||||
esriSatellite: {
|
||||
type: 'raster',
|
||||
tiles: [
|
||||
'https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/WMTS/tile/1.0.0/World_Imagery/default/default028mm/{z}/{y}/{x}.jpg',
|
||||
],
|
||||
tileSize: 256,
|
||||
maxzoom: 19,
|
||||
attribution:
|
||||
'© <a href="https://www.esri.com/" target="_blank">Esri</a>, Vantor, Earthstar Geographics, and the GIS User Community',
|
||||
},
|
||||
},
|
||||
layers: [
|
||||
{
|
||||
id: 'esriSatellite',
|
||||
type: 'raster',
|
||||
source: 'esriSatellite',
|
||||
},
|
||||
],
|
||||
},
|
||||
openStreetMap: {
|
||||
version: 8,
|
||||
sources: {
|
||||
@@ -365,6 +343,27 @@ export const basemaps: { [key: string]: string | StyleSpecification } = {
|
||||
},
|
||||
],
|
||||
},
|
||||
luxTopo: {
|
||||
version: 8,
|
||||
sources: {
|
||||
luxTopo: {
|
||||
type: 'raster',
|
||||
tiles: [
|
||||
'https://wmts3.geoportail.lu/mapproxy_4_v3/wmts/topogg/GLOBAL_WEBMERCATOR_4_V3/{z}/{x}/{y}.png',
|
||||
],
|
||||
tileSize: 256,
|
||||
maxzoom: 16,
|
||||
attribution: '<a href="https://geoportail.lu/" target="_blank">geoportail.lu</a>',
|
||||
},
|
||||
},
|
||||
layers: [
|
||||
{
|
||||
id: 'luxTopo',
|
||||
type: 'raster',
|
||||
source: 'luxTopo',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export const overlays: { [key: string]: string | StyleSpecification } = {
|
||||
@@ -810,7 +809,6 @@ export const basemapTree: LayerTreeType = {
|
||||
libertySatellite: true,
|
||||
osm: true,
|
||||
osmTopo: true,
|
||||
esriSatellite: true,
|
||||
openStreetMap: true,
|
||||
openTopoMap: true,
|
||||
openHikingMap: true,
|
||||
@@ -833,6 +831,9 @@ export const basemapTree: LayerTreeType = {
|
||||
ignFrScan25: true,
|
||||
ignFrSatellite: true,
|
||||
},
|
||||
luxembourg: {
|
||||
luxTopo: true,
|
||||
},
|
||||
new_zealand: {
|
||||
linz: true,
|
||||
linzTopo: true,
|
||||
@@ -1036,7 +1037,6 @@ export const defaultBasemapTree: LayerTreeType = {
|
||||
libertySatellite: true,
|
||||
osm: true,
|
||||
osmTopo: true,
|
||||
esriSatellite: false,
|
||||
openStreetMap: true,
|
||||
openTopoMap: true,
|
||||
openHikingMap: true,
|
||||
@@ -1059,6 +1059,9 @@ export const defaultBasemapTree: LayerTreeType = {
|
||||
ignFrScan25: false,
|
||||
ignFrSatellite: false,
|
||||
},
|
||||
luxembourg: {
|
||||
luxTopo: false,
|
||||
},
|
||||
new_zealand: {
|
||||
linz: false,
|
||||
linzTopo: false,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"zoom":10,"tiles":[332328,332329,332330,332331,332332,332333,332334,332335,332336,332337,332338,332339,332340,332341,332342,332343,332344,332345,332346,332347,332348,332349,332350,332351,332352,332353,332354,332355,332356,333352,333353,333354,333355,333356,333357,333358,333359,333360,333361,333362,333363,333364,333365,333366,333367,333368,333369,333370,333371,333372,333373,333374,333375,333376,333377,333378,333379,333380,334376,334377,334378,334379,334380,334381,334382,334383,334384,334385,334386,334387,334388,334389,334390,334391,334392,334393,334394,334395,334396,334397,334398,334399,334400,334401,334402,334403,334404,335400,335401,335402,335403,335404,335405,335406,335407,335408,335409,335410,335411,335412,335413,335414,335415,335416,335417,335418,335419,335420,335421,335422,335423,335424,335425,335426,335427,335428,336424,336425,336426,336427,336428,336429,336430,336431,336432,336433,336434,336435,336436,336437,336438,336439,336440,336441,336442,336443,336444,336445,336446,336447,336448,336449,336450,336451,336452,337448,337449,337450,337451,337452,337453,337454,337455,337456,337457,337458,337459,337460,337461,337462,337463,337464,337465,337466,337467,337468,337469,337470,337471,337472,337473,337474,337475,337476,338450,338472,338473,338474,338475,338476,338477,338478,338479,338480,338481,338482,338483,338484,338485,338486,338487,338488,338489,338490,338491,338492,338493,338494,338495,338496,338497,338498,338499,338500,339465,339466,339467,339468,339469,339470,339471,339472,339473,339474,339475,339476,339496,339497,339498,339499,339500,339501,339502,339503,339504,339505,339506,339507,339508,339509,339510,339511,339512,339513,339514,339515,339516,339517,339518,339519,339520,339521,339522,339523,339524,340489,340490,340491,340492,340493,340494,340495,340496,340497,340498,340499,340500,340520,340521,340522,340523,340524,340525,340526,340527,340528,340529,340530,340531,340532,340533,340534,340535,340536,340537,340538,340539,340540,340541,340542,340543,340544,340545,340546,340547,340548,341513,341514,341515,341516,341517,341518,341519,341520,341521,341522,341523,341524,341544,341545,341546,341547,341548,341549,341550,341551,341552,341553,341554,341555,341556,341557,341558,341559,341560,341561,341562,341563,341564,341565,341566,341567,341568,341569,341570,341571,341572,342537,342538,342539,342540,342541,342542,342543,342544,342545,342546,342547,342548,342568,342569,342570,342571,342572,342573,342574,342575,342576,342577,342578,342579,342580,342581,342582,342583,342584,342585,342586,342587,342588,342589,342590,342591,342592,342593,342594,342595,342596,343561,343562,343563,343564,343565,343566,343567,343568,343569,343570,343571,343572,343592,343593,343594,343595,343596,343597,343598,343599,343600,343601,343602,343603,343604,343605,343606,343607,343608,343609,343610,343611,343612,343613,343614,343615,343616,343617,343618,343619,343620,344585,344586,344587,344588,344589,344590,344591,344592,344593,344594,344595,344596,344616,344617,344618,344619,344620,344621,344622,344623,344624,344625,344626,344627,344628,344629,344630,344631,344632,344633,344634,344635,344636,344637,344638,344639,344640,344641,344642,344643,344644,345609,345610,345611,345612,345613,345614,345615,345616,345617,345618,345619,345620,345640,345641,345642,345643,345644,345645,345646,345647,345648,345649,345650,345651,345652,345653,345654,345655,345656,345657,345658,345659,345660,345661,345662,345663,345664,345665,345666,345667,345668,346633,346634,346635,346636,346637,346638,346639,346640,346641,346642,346643,346644,346664,346665,346666,346667,346668,346669,346670,346671,346672,346673,346674,346675,346676,346677,346678,346679,346680,346681,346682,346683,346684,346685,346686,346687,346688,346689,346690,346691,346692,347657,347658,347659,347660,347661,347662,347663,347664,347665,347666,347667,347668,347688,347689,347690,347691,347692,347693,347694,347695,347696,347697,347698,347699,347700,347701,347702,347703,347704,347705,347706,347707,347708,347709,347710,347711,347712,347713,347714,347715,347716,348679,348680,348681,348682,348683,348684,348685,348686,348687,348688,348689,348690,348691,348692,348712,348713,348714,348715,348716,348717,348718,348719,348720,348721,348722,348723,348724,348725,348726,348727,348728,348729,348730,348731,348732,348733,348734,348735,348736,348737,348738,348739,348740,349703,349704,349705,349706,349707,349708,349709,349710,349711,349712,349713,349714,349715,349716,349736,349737,349738,349739,349740,349741,349742,349743,349744,349745,349746,349747,349748,349749,349750,349751,349752,349753,349754,349755,349756,349757,349758,349759,349760,349761,349762,349763,349764,350706,350707,350708,350709,350710,350711,350712,350713,350714,350715,350716,350717,350718,350719,350720,350721,350722,350723,350724,350725,350726,350727,350728,350729,350730,350731,350732,350733,350734,350735,350736,350737,350738,350739,350740,350741,350742,350743,350754,350755,350756,350757,350758,350759,350760,350761,350762,350763,350764,350765,350766,350767,35Line truncated
|
||||
@@ -40,7 +40,7 @@ Además, la selección debe ser un solo archivo.
|
||||
|
||||
### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> New route
|
||||
|
||||
Create a new route in the selected file.
|
||||
Crear una nueva ruta en el archivo seleccionado.
|
||||
|
||||
<DocsNote>
|
||||
|
||||
@@ -62,10 +62,10 @@ Además, la selección debe ser una sola pista.
|
||||
|
||||
### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Convert to route/track
|
||||
|
||||
Convert the selected routes to tracks, or the selected tracks or segments to routes.
|
||||
Since a route has a single segment, a track with multiple segments is converted into one route per segment.
|
||||
Convertir las rutas seleccionadas a recorridos o los recorridos o segmentos seleccionados a rutas.
|
||||
Dado que una ruta tiene un solo segmento, un recorrido con múltiples segmentos se convierte en una ruta por segmento.
|
||||
|
||||
When the selected files contain only routes, or only tracks, you can also convert all of them at once.
|
||||
Cuando los archivos seleccionados solo contienen rutas o pistas, también puede convertir todos a la vez.
|
||||
|
||||
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> Seleccionar todo
|
||||
|
||||
|
||||
@@ -45,8 +45,7 @@ title: 文件和统计
|
||||
|
||||
### 树形布局
|
||||
|
||||
正如 [显示](./menu/view) 中所述,文件列表可切换为树形布局。此布局非常适合管理大量已打开的文件,文件将被组织成一个纵向列表并显示在地图右侧。
|
||||
In addition, the file tree view enables you to inspect the [tracks, segments, routes, and points of interest](./gpx) contained inside the files through collapsible sections.
|
||||
正如 [显示](./menu/view) 中所述,文件列表可切换为树形布局。此布局非常适合管理大量已打开的文件,文件将被组织成一个纵向列表并显示在地图右侧。在文件树中,展开可折叠部分可检查其中所包含的 [轨迹、分段、路线和兴趣点](./gpx) 等要素。
|
||||
|
||||
[编辑](./menu/edit) 和 [工具](./toolbar) 亦可被用于文件内部要素。此外,拖拽内部要素可对其重新排序,或将它们移动到其他层级甚至另一个文件中。
|
||||
|
||||
|
||||
@@ -9,8 +9,7 @@ title: GPX 文件格式
|
||||
|
||||
# { title }
|
||||
|
||||
<a href="https://www.topografix.com/gpx.asp" target="_blank">GPX 文件格式</a> 是应用程序和 GPS 设备之间交换 GPS 数据的一种开放标准。它本质上由一系列 GPS 点组成,用以编码形成一条或多条轨迹,以及兴趣点(可选)。
|
||||
These traces can be stored either as tracks or as routes.
|
||||
<a href="https://www.topografix.com/gpx.asp" target="_blank">GPX 文件格式</a> 是应用程序和 GPS 设备之间交换 GPS 数据的一种开放标准。它本质上由一系列 GPS 点组成,用以编码形成一条或多条轨迹,以及兴趣点(可选)。这些连线可以储存为轨迹或路线。
|
||||
|
||||
还可以包含元数据,其中 **名称(name)** 和 **描述(description)** 字段对用户最有用。
|
||||
|
||||
@@ -26,14 +25,13 @@ GPX 文件通常只包含一条轨迹,且该轨迹仅有一个路段。不过
|
||||
|
||||
### <Route size="16" class="inline-block" style="margin-bottom: 2px" /> Routes
|
||||
|
||||
A **route** is a single continuous path made of a sequence of **route points**.
|
||||
**路线**是一个由**路线点**序列组成的单一连续路径。
|
||||
These are mandatory checkpoints, which correspond to the anchor points of the [routing tool](./toolbar/routing).
|
||||
The points in between are only a suggested path connecting the route points.
|
||||
Like a track, a route can have a **name**, a **description**, and **appearance properties**.
|
||||
两者之间的点只是一条连接路线点的建议路径。像轨迹一样,路线可以有**名称**、**描述**和**路线属性**。
|
||||
|
||||
<DocsNote>
|
||||
|
||||
Nowadays, most apps and GPS devices work perfectly well with tracks, even for navigation.
|
||||
现在,大多数应用和 GPS 设备都与轨迹完全兼容,甚至用于导航。
|
||||
However, some of them only work with routes: in that case, you can [convert](./menu/edit) your tracks to routes, or [create](./menu/file) a route file from the start.
|
||||
|
||||
</DocsNote>
|
||||
|
||||
@@ -37,7 +37,7 @@ Moreover, when the tree layout of the files list is enabled (see [Files and stat
|
||||
|
||||
### <Plus size="16" class="inline-block" style="margin-bottom: 2px" /> New route
|
||||
|
||||
Create a new route in the selected file.
|
||||
在所选文件项中创建一条新路线。
|
||||
|
||||
<DocsNote>
|
||||
|
||||
@@ -57,10 +57,10 @@ Create a new route in the selected file.
|
||||
|
||||
### <ArrowRightLeft size="16" class="inline-block" style="margin-bottom: 2px" /> Convert to route/track
|
||||
|
||||
Convert the selected routes to tracks, or the selected tracks or segments to routes.
|
||||
将选中的路线转换为轨迹,或将选中的轨迹或分段转换为路线。
|
||||
Since a route has a single segment, a track with multiple segments is converted into one route per segment.
|
||||
|
||||
When the selected files contain only routes, or only tracks, you can also convert all of them at once.
|
||||
当选中的文件只包含路线,或只包含轨迹时,你也可以一次性转换所有路线。
|
||||
|
||||
### <FileStack size="16" class="inline-block" style="margin-bottom: 2px" /> 全选
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ To use this tool, you need to [select](../files-and-stats) multiple files, [trac
|
||||
|
||||
- 若要生成一条连续轨迹,请选择 **合并为一条连续轨迹**;
|
||||
- The second option can be used to create or manage files with multiple [tracks, segments or routes](../gpx).
|
||||
Merging files (or tracks) will result in a single file (or track) containing all tracks and routes (or segments) from the selection.
|
||||
并将所有内容存储在一个文件(或轨迹)中,请选择 **合并但保持轨迹和路线(或分段)独立**。
|
||||
|
||||
<DocsNote>
|
||||
|
||||
|
||||
@@ -22,6 +22,6 @@ title: 裁剪和拆分
|
||||
|
||||
若要将轨迹拆分为两部分,请点击轨迹上显示的任意分割标记。若要在指定位置进行拆分,请将鼠标悬停在轨迹上,光标位置将出现剪刀图标,表明可在该处拆分。
|
||||
|
||||
You can choose to split the trace into two GPX files, or to keep the split parts in the same file as [tracks, segments or routes](../gpx).
|
||||
支持将轨迹拆分为两个 GPX 文件,或将它们作为不同的 [轨迹或分段](../gpx) 保留在同一个文件中。
|
||||
|
||||
<DocsImage src="tools/split" alt="鼠标悬停在轨迹上时,光标将变为剪刀式样" />
|
||||
@@ -159,8 +159,6 @@ export async function createTauriBackend(): Promise<Backend> {
|
||||
(await invoke('file_statistics', { fileId })) ?? undefined,
|
||||
waypoint: async (fileId, waypointId) =>
|
||||
(await invoke('waypoint', { fileId, waypointId })) ?? undefined,
|
||||
trackpoint: async (fileId, segmentId, index) =>
|
||||
(await invoke('trackpoint', { fileId, segmentId, index })) ?? undefined,
|
||||
export_file: async (fileId, time, hr, cad, atemp, power, osm) => {
|
||||
const file = await optionalArray('export_file', Uint8Array, {
|
||||
fileId,
|
||||
|
||||
@@ -8,7 +8,6 @@ import type {
|
||||
Selection,
|
||||
SelectionPoint,
|
||||
StorageOpened,
|
||||
TrackpointDetails,
|
||||
WaypointDetails,
|
||||
} from 'gpx-wasm';
|
||||
import type { ExportOptions, MergeType, SelectMode, SplitType } from '../types';
|
||||
@@ -266,11 +265,6 @@ export interface Backend {
|
||||
file_structure(fileId: string): Promise<FileStructure | undefined>;
|
||||
file_statistics(fileId: string): Promise<GlobalStatistics | undefined>;
|
||||
waypoint(fileId: string, waypointId: string): Promise<WaypointDetails | undefined>;
|
||||
trackpoint(
|
||||
fileId: string,
|
||||
segmentId: string,
|
||||
index: number
|
||||
): Promise<TrackpointDetails | undefined>;
|
||||
/** A file as GPX (UTF-8 bytes), `undefined` if it does not exist. */
|
||||
export_file(
|
||||
fileId: string,
|
||||
|
||||
@@ -123,7 +123,6 @@ export async function createWasmBackend(): Promise<Backend> {
|
||||
file_structure: lift(w.file_structure),
|
||||
file_statistics: lift(w.file_statistics),
|
||||
waypoint: lift(w.waypoint),
|
||||
trackpoint: lift(w.trackpoint),
|
||||
// a copy out of the memory of the engine, so a plain ArrayBuffer
|
||||
export_file: lift(
|
||||
(...args: Parameters<Backend['export_file']>) =>
|
||||
|
||||
@@ -259,7 +259,7 @@ describe('statistics', () => {
|
||||
assert.equal(get(engine.statistics).hr, undefined);
|
||||
|
||||
const request = engine.requestStatistics();
|
||||
await request.set(['hr', 'anchors', 'slopeSegment']);
|
||||
await request.set(['hr', 'anchors', 'slopeSegment', 'segments']);
|
||||
const statistics = get(engine.statistics);
|
||||
assert.equal(statistics.slopeSegments!.starts[0], 0);
|
||||
assert.equal(
|
||||
@@ -270,6 +270,8 @@ describe('statistics', () => {
|
||||
assert.ok(statistics.hr!.some((hr) => !Number.isNaN(hr)));
|
||||
assert.equal(statistics.cad, undefined);
|
||||
assert.equal(statistics.anchors!.indices[0], 0);
|
||||
assert.deepEqual([...statistics.segments!.starts], [...statistics.anchors!.segmentStarts]);
|
||||
assert.deepEqual(statistics.segments!.ids, statistics.anchors!.segmentIds);
|
||||
assert.equal(statistics.anchors!.indices.at(-1), statistics.length - 1);
|
||||
|
||||
// they are read again after a change, without being asked again
|
||||
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
type FolderEntry,
|
||||
type UnsavedChoice,
|
||||
type WorkspaceState,
|
||||
type TrackpointDetails,
|
||||
type WaypointDetails,
|
||||
} from './types';
|
||||
|
||||
@@ -881,15 +880,6 @@ class Engine {
|
||||
return this.read((b) => b.waypoint(fileId, waypointId), undefined);
|
||||
}
|
||||
|
||||
/** A trackpoint of a segment, `undefined` if it does not exist. */
|
||||
trackpoint(
|
||||
fileId: string,
|
||||
segmentId: string,
|
||||
index: number
|
||||
): Promise<TrackpointDetails | undefined> {
|
||||
return this.read((b) => b.trackpoint(fileId, segmentId, index), undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* A file as GPX (UTF-8 bytes), `undefined` if it does not exist. The options say which data of the
|
||||
* trackpoints to keep.
|
||||
@@ -935,17 +925,6 @@ class Engine {
|
||||
return this.read((b) => b.reduction_distances(), new Float64Array());
|
||||
}
|
||||
|
||||
// Coordinates, as flat [lng, lat, ...] arrays: copies.
|
||||
// Refetch them when the `rev` of the segment (or the `waypointsRev` of the file) changed.
|
||||
|
||||
segmentCoordinates(segmentId: string): Promise<Float64Array> {
|
||||
return this.read((b) => b.segment_coordinates(segmentId), new Float64Array());
|
||||
}
|
||||
|
||||
waypointCoordinates(fileId: string): Promise<Float64Array> {
|
||||
return this.read((b) => b.waypoint_coordinates(fileId), new Float64Array());
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a consumer of the statistics that needs some of the metrics that are not part of
|
||||
* them by default (see `StatisticsMetric`). The metrics asked for by all the consumers are
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
hasSelectionWithin,
|
||||
isCovered,
|
||||
isInClipboard,
|
||||
isEmpty,
|
||||
isSelected,
|
||||
isSelectionHidden,
|
||||
selectedElementIds,
|
||||
@@ -68,12 +67,6 @@ describe('selection helpers', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('tells whether the selection is empty', () => {
|
||||
assert.equal(isEmpty(empty), true);
|
||||
assert.equal(isEmpty(files('F1')), false);
|
||||
assert.equal(isEmpty(waypoints), false);
|
||||
});
|
||||
|
||||
it('lists the files holding something selected', () => {
|
||||
assert.deepEqual(selectedFileIds(empty), []);
|
||||
assert.deepEqual(selectedFileIds(files('F1', 'F2')), ['F1', 'F2']);
|
||||
|
||||
@@ -65,10 +65,6 @@ export function coversSegments(selection: Selection): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmpty(selection: Selection): boolean {
|
||||
return selection.type === 'empty';
|
||||
}
|
||||
|
||||
/** Ids of the files holding something selected (or selected themselves). */
|
||||
export function selectedFileIds(selection: Selection): string[] {
|
||||
switch (selection.type) {
|
||||
|
||||
@@ -143,6 +143,14 @@ export class StatisticsReader {
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 'segments': {
|
||||
const [starts, ids] = await Promise.all([
|
||||
backend.segment_starts(),
|
||||
backend.segment_ids(),
|
||||
]);
|
||||
statistics.segments = { starts, ids };
|
||||
break;
|
||||
}
|
||||
case 'highway':
|
||||
[statistics.highway, statistics.sacScale, statistics.mtbScale] =
|
||||
await Promise.all([
|
||||
|
||||
@@ -3,52 +3,30 @@ import assert from 'node:assert/strict';
|
||||
import {
|
||||
categoryIntervals,
|
||||
categoryValue,
|
||||
categoryValues,
|
||||
intervalAt,
|
||||
type CategoryIntervals,
|
||||
} from '$lib/engine/trackpoint-categories';
|
||||
|
||||
describe('categoryValues', () => {
|
||||
// asphalt, asphalt, unknown, gravel, gravel, gravel, unknown
|
||||
const intervals: CategoryIntervals = {
|
||||
starts: new Uint32Array([0, 2, 3, 6]),
|
||||
values: new Uint8Array([1, 0, 2, 0]),
|
||||
names: ['asphalt', 'gravel'],
|
||||
};
|
||||
|
||||
it('is the name of the value of the interval of each trackpoint', () => {
|
||||
assert.deepEqual(categoryValues(intervals, 7), [
|
||||
'asphalt',
|
||||
'asphalt',
|
||||
undefined,
|
||||
'gravel',
|
||||
'gravel',
|
||||
'gravel',
|
||||
undefined,
|
||||
]);
|
||||
});
|
||||
|
||||
it('goes on with the last interval until the last trackpoint', () => {
|
||||
const last = { ...intervals, values: new Uint8Array([1, 0, 2, 2]) };
|
||||
assert.deepEqual(categoryValues(last, 9).slice(5), [
|
||||
'gravel',
|
||||
'gravel',
|
||||
'gravel',
|
||||
'gravel',
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not go past the trackpoints', () => {
|
||||
assert.deepEqual(categoryValues(intervals, 3), ['asphalt', 'asphalt', undefined]);
|
||||
assert.deepEqual(categoryValues(intervals, 0), []);
|
||||
});
|
||||
|
||||
it('is undefined without intervals, or for a code without name', () => {
|
||||
assert.deepEqual(categoryValues(undefined, 2), [undefined, undefined]);
|
||||
const unnamed = { starts: new Uint32Array([0]), values: new Uint8Array([3]), names: [] };
|
||||
assert.deepEqual(categoryValues(unnamed, 2), [undefined, undefined]);
|
||||
});
|
||||
});
|
||||
/** The value of each of the `length` trackpoints, to compare with what is expected. */
|
||||
function categoryValues(
|
||||
intervals: CategoryIntervals | undefined,
|
||||
length: number
|
||||
): (string | undefined)[] {
|
||||
const result: (string | undefined)[] = new Array(length).fill(undefined);
|
||||
if (!intervals) {
|
||||
return result;
|
||||
}
|
||||
const { starts, values, names } = intervals;
|
||||
for (let i = 0; i < starts.length; i++) {
|
||||
if (!values[i]) {
|
||||
continue; // unknown, already `undefined`
|
||||
}
|
||||
const name = names[values[i] - 1];
|
||||
const end = i + 1 < starts.length ? Math.min(starts[i + 1], length) : length;
|
||||
result.fill(name, starts[i], end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
describe('categoryIntervals', () => {
|
||||
it('groups the trackpoints that share a value', () => {
|
||||
|
||||
@@ -11,31 +11,6 @@ export type CategoryIntervals = {
|
||||
names: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The value of each of the `length` trackpoints for a category of the engine, `undefined` when it
|
||||
* is unknown, or when the category is missing (it is unknown for every trackpoint). The intervals
|
||||
* are scanned once, so it takes a time linear in `length`.
|
||||
*/
|
||||
export function categoryValues(
|
||||
intervals: CategoryIntervals | undefined,
|
||||
length: number
|
||||
): (string | undefined)[] {
|
||||
const result: (string | undefined)[] = new Array(length).fill(undefined);
|
||||
if (!intervals) {
|
||||
return result;
|
||||
}
|
||||
const { starts, values, names } = intervals;
|
||||
for (let i = 0; i < starts.length; i++) {
|
||||
if (!values[i]) {
|
||||
continue; // unknown, already `undefined`
|
||||
}
|
||||
const name = names[values[i] - 1];
|
||||
const end = i + 1 < starts.length ? Math.min(starts[i + 1], length) : length;
|
||||
result.fill(name, starts[i], end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The index of the interval of `starts` (sorted) that the trackpoint `index` is in, -1 if none. */
|
||||
export function intervalAt(starts: Uint32Array, index: number): number {
|
||||
let low = 0;
|
||||
@@ -66,7 +41,7 @@ export function categoryValue(
|
||||
|
||||
/**
|
||||
* The intervals of the trackpoints that share a value, for a value per trackpoint (`undefined`
|
||||
* when unknown): the inverse of `categoryValues`. The names are in the order of their first
|
||||
* when unknown). The names are in the order of their first
|
||||
* appearance. A value that is unknown everywhere gives no intervals.
|
||||
*/
|
||||
export function categoryIntervals(values: readonly (string | undefined)[]): CategoryIntervals {
|
||||
|
||||
@@ -9,7 +9,6 @@ export type { FileStatus, FolderEntry, UnsavedChoice, WorkspaceState } from './b
|
||||
export type {
|
||||
Clipboard,
|
||||
WaypointDetails,
|
||||
TrackpointDetails,
|
||||
MoveTarget,
|
||||
GlobalStatistics,
|
||||
SelectionPoint,
|
||||
@@ -155,7 +154,9 @@ export type StatisticsMetric =
|
||||
/** `highway`, `sacScale` and `mtbScale`. */
|
||||
| 'highway'
|
||||
/** `anchors`. */
|
||||
| 'anchors';
|
||||
| 'anchors'
|
||||
/** `segments`. */
|
||||
| 'segments';
|
||||
|
||||
/**
|
||||
* The anchors of the routing tool among the trackpoints of the selection: the points that can be
|
||||
@@ -182,6 +183,15 @@ export type SelectionAnchors = {
|
||||
revision: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The segments of the selection that have trackpoints: segment `i` has the id `ids[i]`, and its
|
||||
* trackpoints go from `starts[i]` until the next start (or the last trackpoint).
|
||||
*/
|
||||
export type SelectionSegments = {
|
||||
starts: Uint32Array;
|
||||
ids: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The smoothed elevation segments of the selection, over which the slope is averaged, as the
|
||||
* intervals of trackpoints that belong to the same one: segment `i` starts at the trackpoint
|
||||
@@ -229,6 +239,7 @@ export type SelectionStatistics = {
|
||||
/** Mountain biking scale. */
|
||||
mtbScale?: CategoryIntervals;
|
||||
anchors?: SelectionAnchors;
|
||||
segments?: SelectionSegments;
|
||||
|
||||
/**
|
||||
* Global statistics of the trackpoints from `start` to `end` (both included), for example
|
||||
|
||||
@@ -1,32 +1,6 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { closestPointIndex, closestPointIndexIn } from '$lib/geo/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);
|
||||
});
|
||||
});
|
||||
import { closestPointIndexIn } from '$lib/geo/closest-point';
|
||||
|
||||
describe('closestPointIndexIn', () => {
|
||||
const lng = [0, 1, 2, 2, 5, 6];
|
||||
@@ -39,6 +13,22 @@ describe('closestPointIndexIn', () => {
|
||||
assert.equal(closestPointIndexIn(lng, lat, 4, 6, { lng: 5.9, lat: 5.1 }), 5);
|
||||
});
|
||||
|
||||
it('is the nearest end of the nearest segment', () => {
|
||||
assert.equal(closestPointIndexIn(lng, lat, 0, 4, { lng: 0.2, lat: 0.1 }), 0);
|
||||
assert.equal(closestPointIndexIn(lng, lat, 0, 4, { lng: 1.6, lat: -0.1 }), 2);
|
||||
assert.equal(closestPointIndexIn(lng, lat, 0, 4, { 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 [x, y] = [
|
||||
[0, 10, 10],
|
||||
[0, 0, 5],
|
||||
];
|
||||
assert.equal(closestPointIndexIn(x, y, 0, 3, { lng: 7, lat: 0.01 }), 1);
|
||||
assert.equal(closestPointIndexIn(x, y, 0, 3, { lng: 3, lat: 0.01 }), 0);
|
||||
});
|
||||
|
||||
it('has no point in an empty range', () => {
|
||||
assert.equal(closestPointIndexIn(lng, lat, 3, 3, { lng: 0, lat: 0 }), undefined);
|
||||
assert.equal(closestPointIndexIn(lng, lat, 4, 2, { lng: 0, lat: 0 }), undefined);
|
||||
|
||||
@@ -1,25 +1,10 @@
|
||||
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 {
|
||||
return closestIndex(
|
||||
Math.floor(coordinates.length / 2),
|
||||
(i) => coordinates[2 * i],
|
||||
(i) => coordinates[2 * i + 1],
|
||||
point
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like `closestPointIndex`, for the points `from` (included) to `to` (excluded) of a polyline
|
||||
* given as the arrays of its longitudes and latitudes. The index is the one in the arrays.
|
||||
* Index of the point, among the points `from` (included) to `to` (excluded) of a polyline given as
|
||||
* the arrays of its longitudes and latitudes, that is the closest to `point`: one of the two ends
|
||||
* of the segment of the polyline that passes the closest to it. The index is the one in the arrays,
|
||||
* `undefined` for an empty range. Planar approximation, like the one used to simplify tracks.
|
||||
*/
|
||||
export function closestPointIndexIn(
|
||||
lng: ArrayLike<number>,
|
||||
|
||||
@@ -18,3 +18,9 @@ engine.statistics.subscribe(() => slicedStatistics.set(undefined));
|
||||
|
||||
/** The point of the elevation profile that the pointer is over, shown on the map. */
|
||||
export const hoveredPoint: Writable<Coordinates | null> = writable(null);
|
||||
|
||||
/** The trackpoint of the selection that the pointer is over on the map, shown on the profile. */
|
||||
export const hoveredTrackpoint: Writable<number | null> = writable(null);
|
||||
|
||||
// its index only makes sense for the selection it was found in
|
||||
engine.statistics.subscribe(() => hoveredTrackpoint.set(null));
|
||||
@@ -141,11 +141,13 @@ describe('layer trees', () => {
|
||||
assert.deepEqual(filterLayerTree({}, allowed), allowed);
|
||||
});
|
||||
|
||||
it('drops the layers that are not allowed anymore, but not the custom ones', () => {
|
||||
it('drops the layers that are not allowed anymore and those of extensions, not the custom ones', () => {
|
||||
const filtered = filterLayerTree(
|
||||
{
|
||||
world: { a: true, gone: true, 'custom-1': true, 'extension-x': false },
|
||||
world: { a: true, gone: true, 'custom-1': true, 'extension-x': true },
|
||||
old: { x: true },
|
||||
extension: { 'extension-Name/y': true },
|
||||
custom: { 'custom-2': false },
|
||||
},
|
||||
allowed
|
||||
);
|
||||
@@ -153,10 +155,10 @@ describe('layer trees', () => {
|
||||
a: true,
|
||||
b: false,
|
||||
'custom-1': true,
|
||||
'extension-x': false,
|
||||
});
|
||||
assert.equal('old' in filtered, true);
|
||||
assert.deepEqual(filtered.old, {});
|
||||
assert.equal('old' in filtered, false);
|
||||
assert.equal('extension' in filtered, false);
|
||||
assert.deepEqual(filtered.custom, { 'custom-2': false });
|
||||
});
|
||||
|
||||
it('does not take a branch for a layer, or a layer for a branch', () => {
|
||||
|
||||
@@ -196,7 +196,9 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
|
||||
/**
|
||||
* The saved tree `t`, with the layers of `allowed`: the choices saved for them are kept, the new
|
||||
* ones have their default, and of the others only the custom and extension layers are kept.
|
||||
* ones have their default, and of the others only the custom layers are kept. The layers of
|
||||
* extensions are saved with the others, but not read back: they come again when an extension sets
|
||||
* them, if it is still there.
|
||||
*/
|
||||
export function filterLayerTree(t: unknown, allowed: LayerTreeType | undefined): LayerTreeType {
|
||||
const tree = isRecord(t) ? t : {};
|
||||
@@ -214,11 +216,14 @@ export function filterLayerTree(t: unknown, allowed: LayerTreeType | undefined):
|
||||
Object.entries(tree).forEach(([key, value]) => {
|
||||
if (!Object.hasOwn(filtered, key)) {
|
||||
if (typeof value === 'boolean') {
|
||||
if (key.startsWith('custom-') || key.startsWith('extension-')) {
|
||||
if (key.startsWith('custom-')) {
|
||||
filtered[key] = value;
|
||||
}
|
||||
} else if (isRecord(value)) {
|
||||
filtered[key] = filterLayerTree(value, undefined);
|
||||
const group = filterLayerTree(value, undefined);
|
||||
if (Object.keys(group).length > 0) {
|
||||
filtered[key] = group;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -332,6 +332,7 @@
|
||||
"bulgaria": "Bulgaria",
|
||||
"finland": "Finland",
|
||||
"france": "France",
|
||||
"luxembourg": "Luxembourg",
|
||||
"new_zealand": "New Zealand",
|
||||
"norway": "Norway",
|
||||
"spain": "Spain",
|
||||
@@ -343,7 +344,6 @@
|
||||
"libertySatellite": "Liberty Satellite",
|
||||
"osm": "OpenMapTiles OSM",
|
||||
"osmTopo": "OpenMapTiles OSM Topo",
|
||||
"esriSatellite": "Esri Satellite",
|
||||
"openStreetMap": "OpenStreetMap",
|
||||
"openTopoMap": "OpenTopoMap",
|
||||
"openHikingMap": "OpenHikingMap",
|
||||
@@ -364,6 +364,7 @@
|
||||
"ordnanceSurvey": "Ordnance Survey",
|
||||
"norwayTopo": "Topografisk Norgeskart 4",
|
||||
"finlandTopo": "Lantmäteriverket Terrängkarta",
|
||||
"luxTopo": "Topo",
|
||||
"bgMountains": "BGMountains",
|
||||
"usgs": "USGS",
|
||||
"bikerouterGravel": "bikerouter.de Gravel",
|
||||
|
||||
+44
-37
@@ -9,42 +9,42 @@
|
||||
},
|
||||
"menu": {
|
||||
"new_file": "Nuevo archivo",
|
||||
"new_route_file": "New route file",
|
||||
"new_route_file": "Nuevo archivo de ruta",
|
||||
"new_track": "Nuevo recorrido",
|
||||
"new_route": "New route",
|
||||
"convert_to_route": "Convert to route",
|
||||
"convert_to_track": "Convert to track",
|
||||
"convert_to_routes": "Convert to route file",
|
||||
"convert_to_tracks": "Convert to track file",
|
||||
"new_route": "Nueva ruta",
|
||||
"convert_to_route": "Convertir a ruta",
|
||||
"convert_to_track": "Convertir a recorrido",
|
||||
"convert_to_routes": "Convertir a archivo de ruta",
|
||||
"convert_to_tracks": "Convertir a archivo de recorrido",
|
||||
"new_segment": "Nuevo segmento",
|
||||
"open": "Abrir...",
|
||||
"open_folder": "Open folder...",
|
||||
"explorer": "Explorer",
|
||||
"open_folder": "Abrir carpeta...",
|
||||
"explorer": "Explorador",
|
||||
"explorer_menu": {
|
||||
"open": "Open",
|
||||
"new_file": "New file...",
|
||||
"new_route_file": "New route file...",
|
||||
"new_folder": "New folder...",
|
||||
"rename": "Rename...",
|
||||
"reveal_finder": "Reveal in Finder",
|
||||
"reveal": "Reveal in file explorer",
|
||||
"delete_failed": "The files could not be moved to the trash."
|
||||
"open": "Abrir",
|
||||
"new_file": "Nuevo archivo...",
|
||||
"new_route_file": "Nuevo archivo de ruta...",
|
||||
"new_folder": "Nueva carpeta...",
|
||||
"rename": "Renombrar...",
|
||||
"reveal_finder": "Mostrar en el buscador",
|
||||
"reveal": "Mostrar en explorador de archivos",
|
||||
"delete_failed": "No se pudieron mover los archivos a la papelera."
|
||||
},
|
||||
"workspace": "Workspace",
|
||||
"save": "Save",
|
||||
"save_all": "Save all",
|
||||
"save_as": "Save as...",
|
||||
"workspace": "Espacio de trabajo",
|
||||
"save": "Guardar",
|
||||
"save_all": "Guardar todo",
|
||||
"save_as": "Guardar como…",
|
||||
"close": "Cerrar",
|
||||
"close_all": "Cerrar todo",
|
||||
"close_folder": "Close folder",
|
||||
"reload": "Reload from disk",
|
||||
"discard": "Discard",
|
||||
"cancel": "Cancel",
|
||||
"overwrite": "Overwrite",
|
||||
"unsaved_title": "Unsaved changes",
|
||||
"unsaved_description": "These files have changes that are not saved:",
|
||||
"overwrite_title": "Overwrite changes made elsewhere?",
|
||||
"overwrite_description": "These files have changes, and were also changed on the disk. Overwrite what is on the disk, or reload it and lose your changes?",
|
||||
"close_folder": "Cerrar carpeta",
|
||||
"reload": "Recargar desde el disco",
|
||||
"discard": "Descartar",
|
||||
"cancel": "Cancelar",
|
||||
"overwrite": "Sobreescribir",
|
||||
"unsaved_title": "Cambios sin guardar",
|
||||
"unsaved_description": "Estos archivos tienen cambios que no están guardados:",
|
||||
"overwrite_title": "¿Sobrescribir cambios realizados en otro lugar?",
|
||||
"overwrite_description": "Estos ficheros tienen cambios, y también fueron modificados en el disco. ¿Sobrescribir lo que hay en el disco, o volver a cargarlo y perder los cambios?",
|
||||
"duplicate": "Duplicar track",
|
||||
"copy": "Copiar",
|
||||
"paste": "Pegar",
|
||||
@@ -102,9 +102,9 @@
|
||||
"name": "Nombre",
|
||||
"description": "Descripción",
|
||||
"save": "Guardar",
|
||||
"rename_file": "Rename the file on disk",
|
||||
"name_taken": "A file with this name already exists in the folder.",
|
||||
"rename_failed": "The file could not be renamed."
|
||||
"rename_file": "Renombrar el archivo en disco",
|
||||
"name_taken": "Ya existe un archivo con este nombre en la carpeta.",
|
||||
"rename_failed": "No se pudo renombrar el archivo."
|
||||
},
|
||||
"style": {
|
||||
"button": "Apariencia...",
|
||||
@@ -468,8 +468,8 @@
|
||||
"gpx": {
|
||||
"file": "Archivo",
|
||||
"files": "Archivos",
|
||||
"route": "Route",
|
||||
"routes": "Routes",
|
||||
"route": "Ruta",
|
||||
"routes": "Rutas",
|
||||
"track": "Track",
|
||||
"tracks": "Tracks",
|
||||
"segment": "Segmento",
|
||||
@@ -595,8 +595,15 @@
|
||||
"enable_webgl2": "Aprenda cómo activar WebGL 2 en su navegador",
|
||||
"page_not_found": "página no encontrada",
|
||||
"outdated": {
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
"title": "Esta página está desactualizada",
|
||||
"description": "Tus archivos fueron guardados por una versión más reciente de gpx.studio, que esta página no puede leer. Recarga la página para obtener la última versión.",
|
||||
"reload": "Recargar"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} está disponible",
|
||||
"update_restart": "Actualizar y reiniciar",
|
||||
"update_download": "Descargar",
|
||||
"update_installing": "Instalando la actualización...",
|
||||
"update_failed": "No se pudo instalar la actualización"
|
||||
}
|
||||
}
|
||||
+44
-37
@@ -9,42 +9,42 @@
|
||||
},
|
||||
"menu": {
|
||||
"new_file": "Fitxategi berria",
|
||||
"new_route_file": "New route file",
|
||||
"new_route_file": "Ibilbide fitxategi berria",
|
||||
"new_track": "Arrasto berria",
|
||||
"new_route": "New route",
|
||||
"convert_to_route": "Convert to route",
|
||||
"convert_to_track": "Convert to track",
|
||||
"convert_to_routes": "Convert to route file",
|
||||
"convert_to_tracks": "Convert to track file",
|
||||
"new_route": "Ibilbide berria",
|
||||
"convert_to_route": "Bihurtu ibilbide",
|
||||
"convert_to_track": "Bihurtu arrasto",
|
||||
"convert_to_routes": "Bihurtu ibilbide fitxategi",
|
||||
"convert_to_tracks": "Bihurtu arrasto fitxategi",
|
||||
"new_segment": "Segmentu berria",
|
||||
"open": "Ireki...",
|
||||
"open_folder": "Open folder...",
|
||||
"explorer": "Explorer",
|
||||
"open_folder": "Ireki karpeta...",
|
||||
"explorer": "Arakatzailea",
|
||||
"explorer_menu": {
|
||||
"open": "Open",
|
||||
"new_file": "New file...",
|
||||
"new_route_file": "New route file...",
|
||||
"new_folder": "New folder...",
|
||||
"rename": "Rename...",
|
||||
"reveal_finder": "Reveal in Finder",
|
||||
"reveal": "Reveal in file explorer",
|
||||
"delete_failed": "The files could not be moved to the trash."
|
||||
"open": "Ireki",
|
||||
"new_file": "Fitxategi berria...",
|
||||
"new_route_file": "Ibilbide fitxategi berria...",
|
||||
"new_folder": "Karpeta berria...",
|
||||
"rename": "Aldatu izena...",
|
||||
"reveal_finder": "Erakutsi Finder-en",
|
||||
"reveal": "Erakutsi fitxategi-arakatzailean",
|
||||
"delete_failed": "Fitxategiak ezin dira zakarrontzira mugitu."
|
||||
},
|
||||
"workspace": "Workspace",
|
||||
"save": "Save",
|
||||
"save_all": "Save all",
|
||||
"save_as": "Save as...",
|
||||
"workspace": "Laneko area",
|
||||
"save": "Gorde",
|
||||
"save_all": "Gorde denak",
|
||||
"save_as": "Gorde honela...",
|
||||
"close": "Itxi",
|
||||
"close_all": "Itxi denak",
|
||||
"close_folder": "Close folder",
|
||||
"reload": "Reload from disk",
|
||||
"discard": "Discard",
|
||||
"cancel": "Cancel",
|
||||
"overwrite": "Overwrite",
|
||||
"unsaved_title": "Unsaved changes",
|
||||
"unsaved_description": "These files have changes that are not saved:",
|
||||
"overwrite_title": "Overwrite changes made elsewhere?",
|
||||
"overwrite_description": "These files have changes, and were also changed on the disk. Overwrite what is on the disk, or reload it and lose your changes?",
|
||||
"close_folder": "Itxi karpeta",
|
||||
"reload": "Birkargatu diskotik",
|
||||
"discard": "Baztertu",
|
||||
"cancel": "Utzi",
|
||||
"overwrite": "Gainidatzi",
|
||||
"unsaved_title": "Gorde gabeko aldaketak",
|
||||
"unsaved_description": "Fitxategi hauek gorde gabeko aldaketak dituzte:",
|
||||
"overwrite_title": "Egindako aldaketak gainidatzi nahi dituzu?",
|
||||
"overwrite_description": "Fitxategi hauek aldaketak dituzte, eta diskoan ere aldatu dira. Gainidatzi diskoan dagoena edo berriro kargatu eta zure aldaketak galdu?",
|
||||
"duplicate": "Kopia egin",
|
||||
"copy": "Kopiatu",
|
||||
"paste": "Itsatsi",
|
||||
@@ -102,9 +102,9 @@
|
||||
"name": "Izena",
|
||||
"description": "Deskribapena",
|
||||
"save": "Gorde",
|
||||
"rename_file": "Rename the file on disk",
|
||||
"name_taken": "A file with this name already exists in the folder.",
|
||||
"rename_failed": "The file could not be renamed."
|
||||
"rename_file": "Berrizendatu diskoko fitxategia",
|
||||
"name_taken": "Izen hau duen fitxategi bat dagoeneko badago karpetan.",
|
||||
"rename_failed": "Fitxategia ezin da berrizendatu."
|
||||
},
|
||||
"style": {
|
||||
"button": "Itxura...",
|
||||
@@ -468,8 +468,8 @@
|
||||
"gpx": {
|
||||
"file": "Fitxategia",
|
||||
"files": "Fitxategiak",
|
||||
"route": "Route",
|
||||
"routes": "Routes",
|
||||
"route": "Arrastoa",
|
||||
"routes": "Ibilbideak",
|
||||
"track": "Arrastoa",
|
||||
"tracks": "Arrastoak",
|
||||
"segment": "Sementua",
|
||||
@@ -595,8 +595,15 @@
|
||||
"enable_webgl2": "Ikasi zure nabigatzailean WebGL 2 aktibatzen",
|
||||
"page_not_found": "orrialdea ez da aurkitu",
|
||||
"outdated": {
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
"title": "Orrialde hau zaharkituta dago",
|
||||
"description": "Zure fitxategiak gpx.studio-ren bertsio berriago batek gorde ditu, orrialde honek irakurri ezin duena. Birkargatu orria azken bertsioa lortzeko.",
|
||||
"reload": "Birkargatu"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} eskuragarri dago",
|
||||
"update_restart": "Eguneratu eta berrabiarazi",
|
||||
"update_download": "Deskargatu",
|
||||
"update_installing": "Eguneraketa instalatzen...",
|
||||
"update_failed": "Eguneraketa ezin izan da instalatu"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "Cette page n'est pas à jour",
|
||||
"description": "Vos fichiers ont été enregistrés par une nouvelle version de gpx.studio, que cette page ne peut pas lire. Rechargez la page pour obtenir la dernière version.",
|
||||
"reload": "Recharger"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} est disponible",
|
||||
"update_restart": "Mettre à jour et redémarrer",
|
||||
"update_download": "Télécharger",
|
||||
"update_installing": "Installation de la mise à jour...",
|
||||
"update_failed": "La mise à jour n'a pas pu être installée"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"menu": {
|
||||
"new_file": "Naujas failas",
|
||||
"new_route_file": "New route file",
|
||||
"new_route_file": "Naujas maršruto failas",
|
||||
"new_track": "Nauja trasa",
|
||||
"new_route": "New route",
|
||||
"convert_to_route": "Convert to route",
|
||||
@@ -146,7 +146,7 @@
|
||||
"racing_bike": "Kelių dviračiu",
|
||||
"gravel_bike": "Bekelės dviračiu",
|
||||
"mountain_bike": "Kalnų dviračiu",
|
||||
"foot": "Bėgimas / ėjimas",
|
||||
"foot": "Bėgimas / žygiavimas",
|
||||
"motorcycle": "Motociklu",
|
||||
"water": "Vandeniu",
|
||||
"railway": "Geležinkeliu"
|
||||
@@ -181,7 +181,7 @@
|
||||
"unknown": "Unknown",
|
||||
"motorway": "Highway",
|
||||
"motorway_link": "Highway link",
|
||||
"trunk": "Primary road",
|
||||
"trunk": "Pagrindinis kelias",
|
||||
"trunk_link": "Primary road link",
|
||||
"primary": "Primary road",
|
||||
"primary_link": "Primary road link",
|
||||
@@ -552,7 +552,7 @@
|
||||
},
|
||||
"docs": {
|
||||
"translate": "Improve the translation on Crowdin",
|
||||
"answer_not_found": "Did not find what you were looking for?",
|
||||
"answer_not_found": "Neradote, ko ieškojote?",
|
||||
"ask_on_reddit": "Ask the community on Reddit",
|
||||
"search": {
|
||||
"search": "Search",
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "Nepavyko įdiegti atnaujinimo"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "Deze pagina is verouderd",
|
||||
"description": "Uw bestanden zijn opgeslagen door een nieuwere versie van gpx.studio, die deze pagina niet kan lezen. Herlaad de pagina om de nieuwste versie te krijgen.",
|
||||
"reload": "Vernieuwen"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is beschikbaar",
|
||||
"update_restart": "Bijwerken en opnieuw opstarten",
|
||||
"update_download": "Download",
|
||||
"update_installing": "De update wordt geïnstalleerd...",
|
||||
"update_failed": "De update kon niet worden geïnstalleerd"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
@@ -598,5 +598,12 @@
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} is available",
|
||||
"update_restart": "Update and restart",
|
||||
"update_download": "Download",
|
||||
"update_installing": "Installing the update...",
|
||||
"update_failed": "The update could not be installed"
|
||||
}
|
||||
}
|
||||
+44
-37
@@ -9,42 +9,42 @@
|
||||
},
|
||||
"menu": {
|
||||
"new_file": "新建文件",
|
||||
"new_route_file": "New route file",
|
||||
"new_route_file": "新建路线文件",
|
||||
"new_track": "新建轨迹",
|
||||
"new_route": "New route",
|
||||
"convert_to_route": "Convert to route",
|
||||
"convert_to_track": "Convert to track",
|
||||
"convert_to_routes": "Convert to route file",
|
||||
"convert_to_tracks": "Convert to track file",
|
||||
"new_route": "新路线",
|
||||
"convert_to_route": "转换为路径",
|
||||
"convert_to_track": "转换为轨迹",
|
||||
"convert_to_routes": "转换为路径文件",
|
||||
"convert_to_tracks": "转换为轨迹文件",
|
||||
"new_segment": "新建路段",
|
||||
"open": "打开...",
|
||||
"open_folder": "Open folder...",
|
||||
"explorer": "Explorer",
|
||||
"open_folder": "打开文件夹……",
|
||||
"explorer": "资源管理器",
|
||||
"explorer_menu": {
|
||||
"open": "Open",
|
||||
"new_file": "New file...",
|
||||
"new_route_file": "New route file...",
|
||||
"new_folder": "New folder...",
|
||||
"rename": "Rename...",
|
||||
"reveal_finder": "Reveal in Finder",
|
||||
"reveal": "Reveal in file explorer",
|
||||
"delete_failed": "The files could not be moved to the trash."
|
||||
"open": "打开",
|
||||
"new_file": "新建文件……",
|
||||
"new_route_file": "新建路线文件……",
|
||||
"new_folder": "新建文件夹……",
|
||||
"rename": "重命名……",
|
||||
"reveal_finder": "在 Finder 中查看",
|
||||
"reveal": "在资源管理器中显示文件",
|
||||
"delete_failed": "无法将文件移动到回收站。"
|
||||
},
|
||||
"workspace": "Workspace",
|
||||
"save": "Save",
|
||||
"save_all": "Save all",
|
||||
"save_as": "Save as...",
|
||||
"workspace": "工作区",
|
||||
"save": "保存",
|
||||
"save_all": "全部保存",
|
||||
"save_as": "另存为……",
|
||||
"close": "关闭",
|
||||
"close_all": "关闭全部",
|
||||
"close_folder": "Close folder",
|
||||
"reload": "Reload from disk",
|
||||
"discard": "Discard",
|
||||
"cancel": "Cancel",
|
||||
"overwrite": "Overwrite",
|
||||
"unsaved_title": "Unsaved changes",
|
||||
"unsaved_description": "These files have changes that are not saved:",
|
||||
"overwrite_title": "Overwrite changes made elsewhere?",
|
||||
"overwrite_description": "These files have changes, and were also changed on the disk. Overwrite what is on the disk, or reload it and lose your changes?",
|
||||
"close_folder": "关闭文件夹",
|
||||
"reload": "从硬盘重新加载",
|
||||
"discard": "丢弃",
|
||||
"cancel": "取消",
|
||||
"overwrite": "覆盖",
|
||||
"unsaved_title": "未保存的更改",
|
||||
"unsaved_description": "这些文件的更改未保存:",
|
||||
"overwrite_title": "覆盖其他地方的更改?",
|
||||
"overwrite_description": "这些文件有更改,也在磁盘上被更改。覆盖磁盘上的内容,或重新加载它并丢失您的更改?",
|
||||
"duplicate": "创建副本",
|
||||
"copy": "复制",
|
||||
"paste": "粘贴",
|
||||
@@ -102,9 +102,9 @@
|
||||
"name": "名称",
|
||||
"description": "说明",
|
||||
"save": "保存",
|
||||
"rename_file": "Rename the file on disk",
|
||||
"name_taken": "A file with this name already exists in the folder.",
|
||||
"rename_failed": "The file could not be renamed."
|
||||
"rename_file": "重命名硬盘上的文件",
|
||||
"name_taken": "此文件夹中已存在具有该名称的文件。",
|
||||
"rename_failed": "无法重命名文件。"
|
||||
},
|
||||
"style": {
|
||||
"button": "外观...",
|
||||
@@ -468,8 +468,8 @@
|
||||
"gpx": {
|
||||
"file": "文件",
|
||||
"files": "文件",
|
||||
"route": "Route",
|
||||
"routes": "Routes",
|
||||
"route": "路线",
|
||||
"routes": "路线",
|
||||
"track": "轨迹",
|
||||
"tracks": "轨迹",
|
||||
"segment": "路段",
|
||||
@@ -595,8 +595,15 @@
|
||||
"enable_webgl2": "学习如何在浏览器中启用 WebGL 2",
|
||||
"page_not_found": "无法找到页面",
|
||||
"outdated": {
|
||||
"title": "This page is out of date",
|
||||
"description": "Your files were saved by a newer version of gpx.studio, which this page cannot read. Reload the page to get the latest version.",
|
||||
"reload": "Reload"
|
||||
"title": "此页面已过期",
|
||||
"description": "你的文件已被新版本的 gpx.studio 保存,这个页面无法读取该文件。重新加载页面以获取最新版本的页面。",
|
||||
"reload": "重新加载"
|
||||
},
|
||||
"desktop": {
|
||||
"update_available": "gpx.studio {version} 现已可用",
|
||||
"update_restart": "更新并重启",
|
||||
"update_download": "下载",
|
||||
"update_installing": "正在安装更新……",
|
||||
"update_failed": "无法安装更新"
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,11 @@
|
||||
import { getURLForLanguage } from '$lib/utils';
|
||||
import { inDesktopApp } from '$lib/engine/backend';
|
||||
import { openLinksInBrowser } from '$lib/desktop/links';
|
||||
import { hoveredPoint, slicedStatistics } from '$lib/state/selection-statistics';
|
||||
import {
|
||||
hoveredPoint,
|
||||
hoveredTrackpoint,
|
||||
slicedStatistics,
|
||||
} from '$lib/state/selection-statistics';
|
||||
import { engine } from '$lib/engine';
|
||||
import { boundsManager } from '$lib/state/bounds';
|
||||
import { getURLForGoogleDriveFile } from '$lib/components/embedding/embedding';
|
||||
@@ -195,6 +199,7 @@
|
||||
statistics={engine.statistics}
|
||||
{slicedStatistics}
|
||||
{hoveredPoint}
|
||||
{hoveredTrackpoint}
|
||||
{additionalDatasets}
|
||||
{elevationFill}
|
||||
/>
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user