Tracks and routes as containers of points: listed (collapsed) under them in the tree, added via a point's popup, a new note or the route planner's navigation pins, and written as course points into the FIT course
This commit is contained in:
1 parent
6aa7b34f92
commit
4265421457
10 files changed
+354
-20
No files matched your search
@@ -218,7 +218,11 @@ module Maptool
|
||||
when "foot" then vehicle["speed"].to_f >= 7 ? "running" : "hiking"
|
||||
else props["activity_type"]
|
||||
end
|
||||
FitCourse.encode(coordinates, name: props["name"] || name, sport: sport, duration: props["duration_secs"])
|
||||
points = JSON.parse(geojson)["features"].select { |f| f.dig("geometry", "type") == "Point" }.map do |f|
|
||||
p = f["properties"] || {}
|
||||
{ coordinate: f["geometry"]["coordinates"], name: p["name"], hint: [p["name"], p["category"], p["icon"]].compact.join(" ") }
|
||||
end
|
||||
FitCourse.encode(coordinates, name: props["name"] || name, sport: sport, duration: props["duration_secs"], points: points)
|
||||
rescue ArgumentError
|
||||
nil
|
||||
end
|
||||
@@ -689,6 +693,17 @@ module Maptool
|
||||
halt 404
|
||||
end
|
||||
|
||||
# A point into a track/route (body: a GeoJSON Point Feature, as for notes).
|
||||
post "/api/library/node/:key/points" do
|
||||
require_login!
|
||||
id = LIBRARY.add_point(params[:key], parse_feature)
|
||||
json id: id, tree: LIBRARY.tree
|
||||
rescue Library::InvalidValue
|
||||
halt 400, json(error: "a Point feature is required")
|
||||
rescue Library::NotFound
|
||||
halt 404
|
||||
end
|
||||
|
||||
# A migrated layer → ordinary items (Library#split_layer).
|
||||
post "/api/library/node/:key/split" do
|
||||
require_login!
|
||||
|
||||
@@ -247,6 +247,21 @@ phone can't skip a change.
|
||||
car 10) and laps; the segments are shaded in the charts, listed in the
|
||||
table and marked as numbered posts on the map.
|
||||
|
||||
=== Points in a track or route
|
||||
|
||||
A track/route is a container for points (`parent_id`), like a GPX's own
|
||||
waypoints: shown, moved, deleted and exported with it. `POST
|
||||
/api/library/node/:key/points` adds one (the popup's "Add to …" copies a
|
||||
point into any shown track/route); the tree lists them under the
|
||||
track, collapsed. In a FIT course they become course points, placed at
|
||||
the nearest point of the line, the type (water, food, summit, danger,
|
||||
first aid, valley) guessed from the name/category/icon.
|
||||
|
||||
Points get in three ways: "Add to …" in a point's popup (a copy), a new
|
||||
note saved "Into a track / route", and the route planner's 📍 points
|
||||
(on by default for named places): saving the route syncs those as
|
||||
points marked `from_route`, leaving hand-added ones alone.
|
||||
|
||||
=== FIT course out
|
||||
|
||||
`GET /api/library/node/:key?download=fit` writes the node's first line
|
||||
|
||||
@@ -18,10 +18,23 @@ module Maptool
|
||||
[7, 0x86, "L<"], [8, 0x86, "L<"], [9, 0x86, "L<"]]].freeze
|
||||
EVENT = [21, [[253, 0x86, "L<"], [0, 0x00, "C"], [1, 0x00, "C"]]].freeze
|
||||
RECORD = [20, [[253, 0x86, "L<"], [0, 0x85, "l<"], [1, 0x85, "l<"], [2, 0x84, "S<"], [5, 0x86, "L<"]]].freeze
|
||||
COURSE_POINT = [32, [[254, 0x84, "S<"], [1, 0x86, "L<"], [2, 0x85, "l<"], [3, 0x85, "l<"], [4, 0x86, "L<"], [5, 0x00, "C"], [6, 0x07, "a16"]]].freeze
|
||||
DEFAULT_SPEED = 4.0 # m/s, when the line has no time of its own
|
||||
# FIT course_point types, guessed from a point's name/category/icon
|
||||
# (English and Slovak words); anything else is generic (0).
|
||||
POINT_TYPES = [
|
||||
[3, /water|spring|fountain|drink|voda|prame|studni/i],
|
||||
[4, /food|restaurant|caf|shop|bakery|jedlo|reštaur|krčm|obchod/i],
|
||||
[9, /first.?aid|hospital|pharmac|doctor|lekár|nemocn/i],
|
||||
[5, /danger|warning|caution|pozor|nebezpe/i],
|
||||
[1, /summit|peak|top\b|vrch|štít|kopec/i],
|
||||
[2, /valley|saddle|pass\b|údoli|sedlo/i],
|
||||
].freeze
|
||||
|
||||
# coordinates: [[lon, lat(, ele)], ...]; duration: seconds or nil.
|
||||
def self.encode(coordinates, name:, sport: nil, duration: nil)
|
||||
# coordinates: [[lon, lat(, ele)], ...]; duration: seconds or nil;
|
||||
# points: [{ coordinate:, name:, hint: }] shown along the course (each
|
||||
# placed at the nearest point of the line).
|
||||
def self.encode(coordinates, name:, sport: nil, duration: nil, points: [])
|
||||
raise ArgumentError, "a course needs at least two points" if coordinates.size < 2
|
||||
|
||||
distances = [0.0]
|
||||
@@ -41,6 +54,15 @@ module Maptool
|
||||
at = start + (total.positive? ? duration * distances[i] / total : 0).round
|
||||
body << data(4, RECORD, [at, *semicircles([lon, lat]), ele ? ((ele + 500) * 5).round.clamp(0, 0xFFFE) : 0xFFFF, (distances[i] * 100).round])
|
||||
end
|
||||
unless points.empty?
|
||||
body << definition(5, COURSE_POINT)
|
||||
at_index = ->(i) { start + (total.positive? ? duration * distances[i] / total : 0).round }
|
||||
points.map { |point| [nearest(coordinates, point[:coordinate]), point] }.sort_by(&:first).each_with_index do |(i, point), n|
|
||||
type = POINT_TYPES.find { |_, pattern| point[:hint].to_s.match?(pattern) }&.first || 0
|
||||
label = point[:name].to_s.byteslice(0, 15).scrub("")
|
||||
body << data(5, COURSE_POINT, [n, at_index.(i), *semicircles(point[:coordinate]), (distances[i] * 100).round, type, label])
|
||||
end
|
||||
end
|
||||
body << data(3, EVENT, [finish, 0, 9]) # timer, stop_disable_all
|
||||
|
||||
header = [14, 0x10, 2132, body.bytesize].pack("CCS<L<") + ".FIT"
|
||||
@@ -49,6 +71,12 @@ module Maptool
|
||||
file + [crc(file)].pack("S<")
|
||||
end
|
||||
|
||||
# ponytail: linear scan per point; fine for hundreds of points on a few thousand.
|
||||
def self.nearest(coordinates, (lon, lat))
|
||||
coordinates.each_index.min_by { |i| (coordinates[i][0] - lon)**2 + (coordinates[i][1] - lat)**2 }
|
||||
end
|
||||
private_class_method :nearest
|
||||
|
||||
def self.semicircles((lon, lat))
|
||||
[(lat * SEMICIRCLES).round, (lon * SEMICIRCLES).round]
|
||||
end
|
||||
@@ -59,7 +87,7 @@ module Maptool
|
||||
end
|
||||
private_class_method :message
|
||||
|
||||
SIZES = { "C" => 1, "S<" => 2, "L<" => 4, "l<" => 4, "a32" => 32 }.freeze
|
||||
SIZES = { "C" => 1, "S<" => 2, "L<" => 4, "l<" => 4, "a16" => 16, "a32" => 32 }.freeze
|
||||
|
||||
def self.definition(local, (global, fields))
|
||||
[0x40 | local, 0, 0, global, fields.size].pack("CCCS<C") +
|
||||
@@ -68,7 +96,7 @@ module Maptool
|
||||
private_class_method :definition
|
||||
|
||||
def self.data(local, (_, fields), values)
|
||||
[local].pack("C") + fields.zip(values).map { |(_, _, format), value| [format == "a32" ? value : value.round].pack(format) }.join
|
||||
[local].pack("C") + fields.zip(values).map { |(_, _, format), value| [format.start_with?("a") ? value : value.round].pack(format) }.join
|
||||
end
|
||||
private_class_method :data
|
||||
|
||||
|
||||
+24
-4
@@ -133,13 +133,14 @@ module Maptool
|
||||
[db.execute("SELECT id, parent_id, name FROM folders WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE"),
|
||||
db.execute(<<~SQL)]
|
||||
SELECT id, folder_id, parent_id, type, name, source_path,
|
||||
CASE WHEN type IN ('layer', 'track', 'route') THEN properties END
|
||||
CASE WHEN type IN ('layer', 'track', 'route') THEN properties END,
|
||||
CASE WHEN parent_id IS NOT NULL THEN geometry END
|
||||
FROM items WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE
|
||||
SQL
|
||||
end
|
||||
children_of = folders.group_by { |f| f[1] }
|
||||
items_in = items.group_by { |i| i[1] }
|
||||
has_children = items.filter_map { |i| i[2] }.to_set
|
||||
children = items.select { |i| i[2] && i[3] == "point" }.group_by { |i| i[2] }
|
||||
build = lambda do |id, path|
|
||||
subfolders = (children_of[id] || []).map do |fid, _, name|
|
||||
sub = path.empty? ? name : "#{path}/#{name}"
|
||||
@@ -148,9 +149,11 @@ module Maptool
|
||||
own = items_in[id] || []
|
||||
nodes = own.select { |i| %w[track route layer].include?(i[3]) }.map do |iid, _, _, type, name, source, props|
|
||||
props = JSON.parse(props)
|
||||
kinds = type == "layer" ? props["kinds"] || [] : [type, *("waypoint" if has_children.include?(iid))]
|
||||
points = (children[iid] || []).map { |pid, *, pname, _, _, geometry| { "id" => pid, "name" => pname.to_s.empty? ? "Point" : pname, "coordinates" => JSON.parse(geometry)["coordinates"] } }
|
||||
kinds = type == "layer" ? props["kinds"] || [] : [type, *("waypoint" if points.any?)]
|
||||
{ "type" => "file", "path" => "item:#{iid}", "name" => name.to_s.empty? ? type.capitalize : name,
|
||||
"kinds" => kinds, "original" => !source.nil?, "layer" => type == "layer", "color" => props["color"] }.compact
|
||||
"kinds" => kinds, "original" => !source.nil?, "layer" => type == "layer", "color" => props["color"],
|
||||
"points" => (points if points.any?) }.compact
|
||||
end
|
||||
loose = own.count { |i| %w[point shape].include?(i[3]) && i[2].nil? }
|
||||
if loose.positive?
|
||||
@@ -237,6 +240,23 @@ module Maptool
|
||||
File.basename(source, ".*")
|
||||
end
|
||||
|
||||
# A point into a track/route (`key` "item:<id>"), kept with it like a
|
||||
# GPX's own waypoints: shown, moved, deleted and exported together.
|
||||
def add_point(key, feature)
|
||||
kind, id = key.to_s.split(":", 2)
|
||||
raise NotFound unless kind == "item"
|
||||
raise InvalidValue unless feature.dig("geometry", "type") == "Point"
|
||||
|
||||
props = (feature["properties"] || {}).except("id").compact
|
||||
write do |db, rev, now|
|
||||
folder = db.get_first_row("SELECT folder_id FROM items WHERE id = ? AND type IN ('track', 'route') AND deleted_at IS NULL", [id]) or raise NotFound
|
||||
point = SecureRandom.uuid
|
||||
db.execute("INSERT INTO items VALUES (?, ?, ?, 'point', ?, ?, ?, ?, NULL, ?, ?, NULL, ?)",
|
||||
[point, folder[0], id, props["name"], JSON.generate(feature["geometry"]), JSON.generate(props), point, now, now, rev])
|
||||
point
|
||||
end
|
||||
end
|
||||
|
||||
# One hand-drawn note (notes.js) into `folder`; returns its node key.
|
||||
def add_note(feature, folder)
|
||||
add_features([feature], folder).first
|
||||
|
||||
@@ -979,6 +979,63 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
|
||||
outline: 1px dashed #4a90d9;
|
||||
}
|
||||
|
||||
/* A track/route holding points: its row is the summary, a small
|
||||
triangle (not the browser's marker, gone with display:flex) opens the
|
||||
point list. */
|
||||
.gpx-tree__track > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-weight: normal;
|
||||
list-style: none;
|
||||
margin-left: -12px;
|
||||
}
|
||||
|
||||
.gpx-tree__track > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.gpx-tree__track > summary::before {
|
||||
content: "▸";
|
||||
width: 12px;
|
||||
flex: none;
|
||||
color: #888;
|
||||
font-size: 10px;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
|
||||
.gpx-tree__track[open] > summary::before {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.gpx-tree__track > summary > .gpx-tree__file {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.gpx-tree__point {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.gpx-tree__point-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
padding: 1px 0;
|
||||
border: none;
|
||||
background: none;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.gpx-tree__point-name:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.gpx-tree__file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -2402,6 +2459,18 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
|
||||
color: #e63946;
|
||||
}
|
||||
|
||||
/* 📍 off: a faded pin; on: saved as a navigation point. */
|
||||
.route-panel__nav {
|
||||
filter: grayscale(1);
|
||||
opacity: 0.35;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.route-panel__nav.active {
|
||||
filter: none;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.route-panel__buttons {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
|
||||
+89
-1
@@ -251,6 +251,9 @@ export class GpxPanelControl {
|
||||
}
|
||||
|
||||
_renderTree(node) {
|
||||
this._files = new Map();
|
||||
const index = (n) => (n.children || []).forEach((c) => (c.type === "folder" ? index(c) : this._files.set(c.path, c)));
|
||||
index(node);
|
||||
this._treeContainer.innerHTML = "";
|
||||
this._treeContainer.appendChild(this._renderChildren(node.children));
|
||||
}
|
||||
@@ -269,6 +272,8 @@ export class GpxPanelControl {
|
||||
const li = document.createElement("li");
|
||||
if (child.type === "folder") {
|
||||
li.appendChild(this._renderFolder(child));
|
||||
} else if (child.points) {
|
||||
li.appendChild(this._renderTrackWithPoints(child));
|
||||
} else {
|
||||
li.appendChild(this._renderFile(child));
|
||||
}
|
||||
@@ -278,6 +283,62 @@ export class GpxPanelControl {
|
||||
return ul;
|
||||
}
|
||||
|
||||
// A track/route holding points: collapsed by default (there can be many),
|
||||
// each point zooms to itself and can be taken out again.
|
||||
_renderTrackWithPoints(file) {
|
||||
this._openTracks ||= new Set();
|
||||
const details = document.createElement("details");
|
||||
details.className = "gpx-tree__track";
|
||||
details.open = this._openTracks.has(file.path);
|
||||
details.addEventListener("toggle", () => (details.open ? this._openTracks.add(file.path) : this._openTracks.delete(file.path)));
|
||||
const summary = document.createElement("summary");
|
||||
summary.appendChild(this._renderFile(file));
|
||||
details.appendChild(summary);
|
||||
|
||||
const ul = document.createElement("ul");
|
||||
ul.className = "gpx-tree__points";
|
||||
file.points.forEach((point) => {
|
||||
const li = document.createElement("li");
|
||||
li.className = "gpx-tree__point";
|
||||
const name = document.createElement("button");
|
||||
name.type = "button";
|
||||
name.className = "gpx-tree__point-name";
|
||||
name.textContent = point.name;
|
||||
name.addEventListener("click", () => this._goToPoint(file.path, point));
|
||||
li.appendChild(name);
|
||||
if (isLoggedIn()) li.appendChild(this._deleteButton(() => this._removePoint(file, point)));
|
||||
ul.appendChild(li);
|
||||
});
|
||||
details.appendChild(ul);
|
||||
return details;
|
||||
}
|
||||
|
||||
async _goToPoint(path, point) {
|
||||
await this.show(path);
|
||||
this._map.flyTo({ center: point.coordinates, zoom: Math.max(this._map.getZoom(), 15) });
|
||||
const feature = this._pointsByPath.get(path)?.features.find((f) => f.properties.id === point.id);
|
||||
if (feature) this._openPointPopup(path, feature, point.coordinates);
|
||||
}
|
||||
|
||||
async _removePoint(file, point) {
|
||||
if (!window.confirm(`Remove "${point.name}" from "${file.name}"?`)) return;
|
||||
const response = await fetch(`/api/library/notes?${new URLSearchParams({ path: file.path, id: point.id })}`, { method: "DELETE" });
|
||||
if (!response.ok) return window.alert("Could not remove the point.");
|
||||
await this._loadTree();
|
||||
if (this._visible.has(file.path)) await this._reloadFile(file.path);
|
||||
}
|
||||
|
||||
// A copy of the point into a shown track/route, which keeps it from
|
||||
// then on (exported with it, a course point in its FIT course).
|
||||
async _addPointTo(target, feature) {
|
||||
const { id, ...properties } = feature.properties;
|
||||
const body = new URLSearchParams({ feature: JSON.stringify({ type: "Feature", geometry: { type: "Point", coordinates: feature.geometry.coordinates }, properties }) });
|
||||
const response = await fetch(`${gpxFileUrl(target)}/points`, { method: "POST", body });
|
||||
if (!response.ok) return window.alert("Could not add the point.");
|
||||
this._renderTree((await response.json()).tree);
|
||||
await this._reloadFile(target);
|
||||
}
|
||||
|
||||
_renderFolder(folder) {
|
||||
const details = document.createElement("details");
|
||||
details.open = true;
|
||||
@@ -831,10 +892,37 @@ export class GpxPanelControl {
|
||||
addRoutePoint(feature.geometry.coordinates, feature.properties.name);
|
||||
popup.remove();
|
||||
});
|
||||
popup.getElement().querySelector(".maplibregl-popup-content").appendChild(button);
|
||||
const content = popup.getElement().querySelector(".maplibregl-popup-content");
|
||||
content.appendChild(button);
|
||||
if (isLoggedIn()) {
|
||||
// Into any track/route shown right now, or out of the one holding it.
|
||||
const holder = this._files?.get(path)?.points?.some((p) => p.id === feature.properties.id) && this._files.get(path);
|
||||
const targets = [...this._visible].filter((p) => p !== path && p.startsWith("item:") && this._files?.get(p)?.kinds?.some((k) => k === "track" || k === "route") && !this._files.get(p).layer);
|
||||
targets.forEach((target) => {
|
||||
content.appendChild(this._popupButton(`Add to "${this._files.get(target).name}"`, async () => {
|
||||
popup.remove();
|
||||
await this._addPointTo(target, feature);
|
||||
}));
|
||||
});
|
||||
if (holder) {
|
||||
content.appendChild(this._popupButton(`Remove from "${holder.name}"`, async () => {
|
||||
popup.remove();
|
||||
await this._removePoint(holder, { id: feature.properties.id, name: feature.properties.name || "Point" });
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_popupButton(label, onClick) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "gpx-popup__route";
|
||||
button.textContent = label;
|
||||
button.addEventListener("click", onClick);
|
||||
return button;
|
||||
}
|
||||
|
||||
// Edit swaps the popup's content for a plain textarea + Save/Cancel (the
|
||||
// note's location doesn't change, just its text, so there's no need for
|
||||
// NoteSaveForm's fuller target-file picker here). Delete just confirms
|
||||
|
||||
+21
-5
@@ -130,9 +130,11 @@ export class NoteSaveForm {
|
||||
async _populateTargets() {
|
||||
const previousValue = this._target.value;
|
||||
let folders = [];
|
||||
let lines = [];
|
||||
try {
|
||||
const tree = await (await fetch("/api/library/tree")).json();
|
||||
folders = folderPaths(tree);
|
||||
lines = this._geometry?.type === "Point" ? trackNodes(tree) : [];
|
||||
} catch (err) {
|
||||
// Tree fetch failed — still usable with the top level or a new folder.
|
||||
}
|
||||
@@ -140,8 +142,11 @@ export class NoteSaveForm {
|
||||
this._target.innerHTML =
|
||||
`<option value="">Top level</option>` +
|
||||
folders.map((path) => `<option value="${escapeAttr(path)}">${escapeText(path)}</option>`).join("") +
|
||||
`<option value="${NEW_FOLDER_VALUE}">+ New folder…</option>`;
|
||||
this._target.value = folders.includes(previousValue) || previousValue === NEW_FOLDER_VALUE ? previousValue : "";
|
||||
`<option value="${NEW_FOLDER_VALUE}">+ New folder…</option>` +
|
||||
// A point can go straight into a track/route (kept and exported with it).
|
||||
(lines.length ? `<optgroup label="Into a track / route">${lines.map(([key, label]) => `<option value="${escapeAttr(key)}">${escapeText(label)}</option>`).join("")}</optgroup>` : "");
|
||||
const values = [...this._target.options].map((o) => o.value);
|
||||
this._target.value = values.includes(previousValue) ? previousValue : "";
|
||||
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
|
||||
}
|
||||
|
||||
@@ -170,14 +175,16 @@ export class NoteSaveForm {
|
||||
geometry: this._geometry,
|
||||
};
|
||||
|
||||
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature), folder });
|
||||
const intoLine = folder.startsWith("item:");
|
||||
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature), ...(intoLine ? {} : { folder }) });
|
||||
|
||||
this._saveButton.disabled = true;
|
||||
try {
|
||||
const response = await fetch("/api/library/notes", { method: "POST", body: requestBody });
|
||||
const url = intoLine ? `/api/library/node/${encodeURIComponent(folder)}/points` : "/api/library/notes";
|
||||
const response = await fetch(url, { method: "POST", body: requestBody });
|
||||
if (!response.ok) throw new Error(`save failed: ${response.status}`);
|
||||
const { path } = await response.json();
|
||||
notifyGpxStoreChanged(path);
|
||||
notifyGpxStoreChanged(intoLine ? folder : path);
|
||||
this.close();
|
||||
this._onSaved?.();
|
||||
} catch (err) {
|
||||
@@ -276,6 +283,15 @@ function folderPaths(node) {
|
||||
return (node.children || []).filter((child) => child.type === "folder").flatMap((child) => [child.path, ...folderPaths(child)]);
|
||||
}
|
||||
|
||||
// Tracks/routes of the library as [key, "folder / name"].
|
||||
function trackNodes(node, folder = "") {
|
||||
return (node.children || []).flatMap((child) => {
|
||||
if (child.type === "folder") return trackNodes(child, child.path);
|
||||
const line = child.path.startsWith("item:") && !child.layer && child.kinds?.some((k) => k === "track" || k === "route");
|
||||
return line ? [[child.path, [folder, child.name].filter(Boolean).join(" / ")]] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function escapeAttr(value) {
|
||||
return value.replace(/&/g, "&").replace(/"/g, """);
|
||||
}
|
||||
|
||||
+55
-5
@@ -36,7 +36,7 @@ export class RoutePanelControl {
|
||||
.then((r) => r.json())
|
||||
.then((d) => d.available)
|
||||
.catch(() => false);
|
||||
this._points = []; // [{ lngLat: [lon, lat], name, marker }]
|
||||
this._points = []; // [{ lngLat: [lon, lat], name, nav, marker }]; nav: saved as a point the device shows
|
||||
this._route = null; // the last /api/route Feature
|
||||
this._request = 0; // so a slow older response can't overwrite a newer one
|
||||
this._editing = null; // { key, id, name } of a saved route being edited
|
||||
@@ -111,11 +111,13 @@ export class RoutePanelControl {
|
||||
|
||||
// --- points ---------------------------------------------------------------
|
||||
|
||||
_addPoint(lngLat, name, { quiet = false } = {}) {
|
||||
// A named place (a saved point, a search result) is shown in navigation
|
||||
// by default; a plain map click only shapes the route.
|
||||
_addPoint(lngLat, name, { quiet = false, nav = !!name && name !== "My position" } = {}) {
|
||||
const element = document.createElement("div");
|
||||
element.className = "route-marker";
|
||||
const marker = new Marker({ element, draggable: true }).setLngLat(lngLat).addTo(this._map);
|
||||
const point = { lngLat, name, marker };
|
||||
const point = { lngLat, name, nav, marker };
|
||||
marker.on("dragend", () => {
|
||||
const { lng, lat } = marker.getLngLat();
|
||||
point.lngLat = [lng, lat];
|
||||
@@ -153,7 +155,8 @@ export class RoutePanelControl {
|
||||
this._clear();
|
||||
// Back to the vehicle it was planned for, if that profile still exists.
|
||||
if (this._vehicles?.some((v) => v.id === feature.properties.vehicle?.id)) this._selectVehicle(feature.properties.vehicle.id);
|
||||
feature.properties.via.forEach((lngLat) => this._addPoint(lngLat, null, { quiet: true }));
|
||||
const named = feature.properties.via_points || [];
|
||||
feature.properties.via.forEach((lngLat, i) => this._addPoint(lngLat, named[i]?.name || null, { quiet: true, nav: !!named[i]?.nav }));
|
||||
this._editing = { key, id: feature.properties.id, name: feature.properties.name };
|
||||
this._setOpen(true);
|
||||
this._changed();
|
||||
@@ -188,6 +191,7 @@ export class RoutePanelControl {
|
||||
text.textContent = `${label} · ${point.name || `${point.lngLat[1].toFixed(5)}, ${point.lngLat[0].toFixed(5)}`}`;
|
||||
li.append(
|
||||
text,
|
||||
this._navButton(point, label),
|
||||
this._pointButton("↑", "Move up", index > 0, () => this._move(point, -1)),
|
||||
this._pointButton("↓", "Move down", index < this._points.length - 1, () => this._move(point, 1)),
|
||||
this._pointButton("×", "Remove", true, () => this._removePoint(point)),
|
||||
@@ -202,6 +206,24 @@ export class RoutePanelControl {
|
||||
this._saveButton.textContent = this._editing ? "Save changes" : "Save to library";
|
||||
}
|
||||
|
||||
// Toggles whether the point is saved into the route as a navigation
|
||||
// point (a course point on a Garmin); an unnamed one asks for a name.
|
||||
_navButton(point, label) {
|
||||
const button = this._pointButton("📍", "Show in navigation", true, () => {
|
||||
if (!point.nav && !point.name) {
|
||||
const name = window.prompt("Name shown in navigation:", label);
|
||||
if (!name?.trim()) return;
|
||||
point.name = name.trim();
|
||||
}
|
||||
point.nav = !point.nav;
|
||||
this._renderPoints();
|
||||
});
|
||||
button.classList.add("route-panel__nav");
|
||||
button.classList.toggle("active", !!point.nav);
|
||||
button.setAttribute("aria-pressed", !!point.nav);
|
||||
return button;
|
||||
}
|
||||
|
||||
_pointButton(text, title, enabled, onClick) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
@@ -372,7 +394,14 @@ export class RoutePanelControl {
|
||||
type: "Feature",
|
||||
geometry: this._route.geometry,
|
||||
// The elevation profile too, so the library shows it like a track's.
|
||||
properties: { ...properties, ...this._profileProperties(), name: name.trim(), via: this._points.map((p) => p.lngLat), vehicle: this._vehicle },
|
||||
properties: {
|
||||
...properties,
|
||||
...this._profileProperties(),
|
||||
name: name.trim(),
|
||||
via: this._points.map((p) => p.lngLat),
|
||||
via_points: this._points.map((p) => ({ name: p.name || null, nav: !!p.nav })),
|
||||
vehicle: this._vehicle,
|
||||
},
|
||||
};
|
||||
const editing = this._editing;
|
||||
const response = await fetch(NOTES_URL, {
|
||||
@@ -393,12 +422,33 @@ export class RoutePanelControl {
|
||||
return;
|
||||
}
|
||||
const path = editing ? editing.key : (await response.json()).path;
|
||||
await this._saveNavPoints(path);
|
||||
notifyGpxStoreChanged(path);
|
||||
this._editing = { key: path, id: editing?.id ?? (await this._savedId(path)), name: name.trim() };
|
||||
this._renderPoints();
|
||||
this._summary.textContent += " · saved";
|
||||
}
|
||||
|
||||
// The route's points marked 📍 as points inside the route item (marked
|
||||
// from_route, so points added to it by hand stay untouched): missing
|
||||
// ones added, unmarked or moved ones removed.
|
||||
async _saveNavPoints(key) {
|
||||
const url = `/api/library/node/${encodeURIComponent(key)}`;
|
||||
const id = (p) => `${p.lngLat[0].toFixed(6)},${p.lngLat[1].toFixed(6)},${p.name}`;
|
||||
const { features } = await (await fetch(url)).json();
|
||||
const existing = new Map(features.filter((f) => f.geometry.type === "Point" && f.properties.from_route).map((f) => [id({ lngLat: f.geometry.coordinates, name: f.properties.name }), f]));
|
||||
const wanted = this._points.map((p, i) => ({ ...p, name: p.name || `Via ${i}` })).filter((p) => p.nav);
|
||||
const wantedIds = new Set(wanted.map(id));
|
||||
for (const [key2, f] of existing) {
|
||||
if (!wantedIds.has(key2)) await fetch(`/api/library/notes?${new URLSearchParams({ path: key, id: f.properties.id })}`, { method: "DELETE" });
|
||||
}
|
||||
for (const p of wanted) {
|
||||
if (existing.has(id(p))) continue;
|
||||
const feature = { type: "Feature", geometry: { type: "Point", coordinates: p.lngLat }, properties: { name: p.name, from_route: true } };
|
||||
await fetch(`${url}/points`, { method: "POST", body: new URLSearchParams({ feature: JSON.stringify(feature) }) });
|
||||
}
|
||||
}
|
||||
|
||||
// The id of the route just saved, so a second Save updates it instead of
|
||||
// adding another copy.
|
||||
async _savedId(key) {
|
||||
|
||||
@@ -158,4 +158,21 @@ class FitTest < Minitest::Test
|
||||
assert_equal 0, Maptool::FitCourse.send(:crc, bytes)
|
||||
assert_equal 0xBB3D, Maptool::FitCourse.send(:crc, "123456789")
|
||||
end
|
||||
|
||||
def test_a_fit_course_carries_its_points_as_course_points
|
||||
coordinates = [[17.1, 48.1], [17.11, 48.11], [17.12, 48.1]]
|
||||
points = [{ coordinate: [17.12, 48.1001], name: "Summit cross with a long name", hint: "summit" }, { coordinate: [17.1101, 48.11], name: "Spring", hint: "Spring water" }]
|
||||
bytes = Maptool::FitCourse.encode(coordinates, name: "Loop", points: points)
|
||||
path = File.join(Dir.mktmpdir, "course.fit")
|
||||
File.binwrite(path, bytes)
|
||||
|
||||
assert_equal 3, Maptool::Fit.to_geojson(path)["features"][0]["geometry"]["coordinates"][0].size # still parses
|
||||
assert_equal 0, Maptool::FitCourse.send(:crc, bytes)
|
||||
# course_point data: message_index, timestamp, lat, lon, distance, type, name — in order along the line
|
||||
spring = bytes.index("Spring")
|
||||
summit = bytes.index("Summit cross wi\0")
|
||||
assert spring < summit
|
||||
assert_equal 3, bytes.getbyte(spring - 1) # water
|
||||
assert_equal 1, bytes.getbyte(summit - 1) # summit
|
||||
end
|
||||
end
|
||||
@@ -177,6 +177,22 @@ class LibraryTest < Minitest::Test
|
||||
assert_raises(Maptool::Library::NotFound) { library.export_gpx("nope") }
|
||||
end
|
||||
|
||||
def test_points_added_to_a_track_live_in_it
|
||||
library = open_library
|
||||
key = library.import(folder: "trips", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx"))).find { |k| k.start_with?("item:") }
|
||||
before = library.tree["children"][0]["children"].find { |n| n["path"] == key }["points"].to_a.size
|
||||
|
||||
id = library.add_point(key, { "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => [17.1, 48.1] }, "properties" => { "name" => "Spring", "id" => "x" } })
|
||||
node = library.tree["children"][0]["children"].find { |n| n["path"] == key }
|
||||
assert_equal before + 1, node["points"].size
|
||||
assert_includes node["points"], { "id" => id, "name" => "Spring", "coordinates" => [17.1, 48.1] }
|
||||
assert_includes JSON.parse(library.geojson(key))["features"].map { |f| f["properties"]["name"] }, "Spring"
|
||||
assert_raises(Maptool::Library::InvalidValue) { library.add_point(key, { "geometry" => { "type" => "LineString", "coordinates" => [] } }) }
|
||||
|
||||
library.delete_feature(key, id)
|
||||
assert_equal before, library.tree["children"][0]["children"].find { |n| n["path"] == key }["points"].to_a.size
|
||||
end
|
||||
|
||||
def test_reparse_rereads_old_profiles_once_and_keeps_the_name
|
||||
library = open_library
|
||||
key = library.import(folder: "", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx"))).find { |k| k.start_with?("item:") }
|
||||
|
||||
Reference in new issue
Block a user