Library phase 2: rename/recolor nodes, rename and move folders, split a layer into items; offline routing design

This commit is contained in:
randy committed 2026-11-13 21:16:35 +01:00
1 parent 4d838395b8
commit 6f5f11cb4d
9 files changed
+467 -39

No files matched your search

+2 -2
View File
@@ -74,7 +74,7 @@ independence from connectivity.
* [x] Installable PWA with a share target — `public/manifest.webmanifest`, `public/sw.js` parks files shared from Android's share sheet (OsmAnd, Locus, mapy.com — the last has no API at all), `public/js/share_import.js` offers to import them into a Tracks & Points folder (login required, files wait until then) * [x] Installable PWA with a share target — `public/manifest.webmanifest`, `public/sw.js` parks files shared from Android's share sheet (OsmAnd, Locus, mapy.com — the last has no API at all), `public/js/share_import.js` offers to import them into a Tracks & Points folder (login required, files wait until then)
* [x] Item-based library replacing the file-based `GpxStore`, phase 1 — `lib/maptool/library.rb`, design in `docs/library-design.adoc`; old files migrated as layers in subfolders * [x] Item-based library replacing the file-based `GpxStore`, phase 1 — `lib/maptool/library.rb`, design in `docs/library-design.adoc`; old files migrated as layers in subfolders
* [ ] Library phase 2 — rename/style items and folders, split a layer into items, notes inside layers as items * [x] Library phase 2 — rename/recolor tracks, routes and layers, rename and move (drag) folders, split a migrated layer into items (its notes become items, keeping their ids)
* [ ] Change feed + GPX export flavors for OsmAnd/Locus * [ ] Change feed + GPX export flavors for OsmAnd/Locus
* [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data) * [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data)
@@ -84,7 +84,7 @@ Deprioritized for now — revisit after the sections above land.
=== Vanlife features === Vanlife features
* [ ] Offline routing (Valhalla/OSRM) with vehicle parameters (height, weight, width) * [ ] Offline routing with vehicle parameters (height, weight, width) — Valhalla in its own container, design in `docs/routing-design.adoc`
* [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation * [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation
=== HW integration === HW integration
+36
View File
@@ -571,6 +571,27 @@ module Maptool
halt 404 halt 404
end end
# Rename/recolor a track, route or layer.
patch "/api/library/node/:key" do
require_login!
LIBRARY.update_node(params[:key], name: params[:name], color: params[:color])
json tree: LIBRARY.tree
rescue Library::InvalidValue
halt 400, json(error: "invalid name or color")
rescue Library::NotFound
halt 404
end
# A migrated layer → ordinary items (Library#split_layer).
post "/api/library/node/:key/split" do
require_login!
json paths: LIBRARY.split_layer(params[:key]), tree: LIBRARY.tree
rescue Library::ParseError
halt 422, json(error: "could not parse file")
rescue Library::NotFound
halt 404
end
post "/api/library/move" do post "/api/library/move" do
require_login! require_login!
key = LIBRARY.move_node(params[:key].to_s, params[:to_folder].to_s) key = LIBRARY.move_node(params[:key].to_s, params[:to_folder].to_s)
@@ -589,6 +610,21 @@ module Maptool
halt 400, json(error: "invalid path") halt 400, json(error: "invalid path")
end end
# Rename (`name`) and/or move (`to_folder`, "" = top level) a folder.
patch "/api/library/folder/*" do
require_login!
path = params[:splat].first
path = LIBRARY.rename_folder(path, params[:name]) if params[:name]
path = LIBRARY.move_folder(path, params[:to_folder].to_s) if params.key?("to_folder")
json path: path, tree: LIBRARY.tree
rescue Library::InvalidPath
halt 400, json(error: "invalid folder")
rescue Library::InvalidValue
halt 409, json(error: "a folder with that name already exists there")
rescue Library::NotFound
halt 404
end
delete "/api/library/folder/*" do delete "/api/library/folder/*" do
require_login! require_login!
LIBRARY.delete_folder(params[:splat].first) LIBRARY.delete_folder(params[:splat].first)
+18 -1
View File
@@ -2,7 +2,7 @@
:toc: :toc:
:toclevels: 2 :toclevels: 2
Status: *phase 1 implemented* (`lib/maptool/library.rb`, see Decisions); phases 2–4 proposed. Replaces the file-based store behind Status: *phases 1–2 implemented* (`lib/maptool/library.rb`, see Decisions); phases 3–4 proposed. Replaces the file-based store behind
Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus
Map and the MapTool web app can all be synced against. Map and the MapTool web app can all be synced against.
@@ -324,6 +324,23 @@ removed once nothing uses them.
* Migration runs on first start (no `library.sqlite` yet); `rake * Migration runs on first start (no `library.sqlite` yet); `rake
library:migrate` re-runs it (idempotent). library:migrate` re-runs it (idempotent).
== Decisions (phase 2)
* Rename and color apply to tracks, routes and layers (the node in the
tree). Color is stored as `properties.color` and drawn as the line
color. A layer's color is laid over its legacy GeoJSON when it's served.
Single points keep their category color from the GPX.
* Folders: rename, and move by dragging one onto another folder (or onto
the tree's blank space for the top level). Moving into a folder's own
subfolder, or next to a sibling of the same name, is refused.
* "Split into items" turns a migrated layer into ordinary items in its
folder. Its notes keep their ids, the legacy file is copied to
`sources/` as their "original", and the layer is tombstoned.
`data/gpx/` isn't touched. A note edited in an unsplit layer still
goes to its legacy file.
* `GpxStore` stays, since unsplit layers are still drawn from it. It goes
away once nothing is a layer any more.
== Open questions == Open questions
* Folder depth over 3 — fine to require Locus Premium? * Folder depth over 3 — fine to require Locus Premium?
+113
View File
@@ -0,0 +1,113 @@
= Offline routing — design
:toc:
:toclevels: 1
Status: proposal, nothing implemented yet.
== Goal
Car/camper routing that works with no internet, from the same OSM
extracts the offline map is built from, with the vehicle's dimensions
(height, width, length, weight) respected, so the route doesn't go
under a 3 m bridge or over a 3.5 t bridge. Later on the same engine:
an elevation profile of the route and isochrones ("how far in 2 hours").
== Engine: Valhalla
[cols="1,3"]
|===
| Valhalla
| `truck` costing takes height/width/length/weight/axle load per
*request*, so one graph serves any vehicle. Has `/isochrone`,
`/height` and `/optimized_route` built in. Tiles are a memory-mapped
tar, so RAM stays modest even for many countries. Chosen.
| GraphHopper
| Java is already in the image (Planetiler), and custom models can do
dimensions too, but the import for ~16 GB of PBF wants a heap close
to the server's 30 GB RAM.
| OSRM
| Fastest queries, but restrictions are baked in at build time: one
graph per vehicle profile, no dimension parameters per request.
|===
== Data
The PBF files are already there: `data/geofabrik_cache/<CC>.osm.pbf`,
one per country selected for the offline map (`data/offline_regions.json`,
currently 14 countries, ~16 GB). Routing uses exactly that set, so
there's no second region picker. The files are hard-linked into
`data/routing/pbf/` (same file system, no copies, and Geofabrik refreshes
don't change a build that's in progress).
Measured on the server: 16 cores, 30 GB RAM, 780 GB free. Rough
expectation for this set: tiles 15–25 GB, a build of a few hours. The
build runs at a low priority and the old tiles keep serving while it
runs.
== Containers
Valhalla isn't packaged for Debian trixie, so it doesn't go into the
maptool image. Instead there's one more compose service, the same pattern
as `kiwix`:
[source,yaml]
----
valhalla:
image: ghcr.io/valhalla/valhalla:<pinned tag> # renovate bumps it
restart: unless-stopped
command: ["/app/bin/routing-service.sh"]
volumes:
- ./data/routing:/routing:z
- ./build/bin/routing-service.sh:/app/bin/routing-service.sh:ro,z
----
It uses the base image (binaries only), not `valhalla-scripted`. The
scripted image only rebuilds when the container restarts, and maptool
can't restart containers. Instead `bin/routing-service.sh` (~40 lines of
shell) runs inside it:
. Serve `valhalla_service` from `tiles.tar`, if one exists.
. Poll for `data/routing/build-request.json`. When it shows up, build
into `staging/` (`valhalla_build_config`, `valhalla_build_admins`,
`valhalla_build_timezones`, `valhalla_build_tiles`,
`valhalla_build_extract`), writing the current step to `status.json`.
. When the build succeeds, swap `staging/tiles.tar` in and restart
`valhalla_service`. When it fails, keep the old tiles and put the log
in `status.json`.
maptool reaches it at `http://valhalla:8002` (`VALHALLA_URL`), server
side only, like `KIWIX_URL`.
== maptool side
* "Build routing" next to the existing offline/terrain builds, login
required. It writes `build-request.json` and links the PBF files.
Status and history appear in the same build panel (`build_history`).
* `POST /api/route` proxies to Valhalla `/route` with `costing: truck`
and the vehicle profile filled in. It's open to everyone, like the
map. Login is required only to save the result.
* Vehicle profile: height, width, length, weight. Stored server-side,
one for now, editable in the route panel.
* Route panel: start, end and via points (map click, search result, GPS
position, a library point), the route drawn with distance, time and
turn list. "Save to library" stores it as a `route` item, so the
route goes to OsmAnd/Locus through the same export as everything
else.
== Phases
. Container + build script + "Build routing" + status. Done when
`curl valhalla:8002/route` answers on the server.
. `/api/route`, the vehicle profile, the route panel, save to library.
. Elevation profile of the route (sampled from `terrain.pmtiles`, which
is already there, instead of Valhalla's own SRTM download), then
isochrones.
== Open questions
* Pin a Valhalla version: take the latest `ghcr.io/valhalla/valhalla`
release tag at implementation time and add it to Renovate (a docker
image in compose is tracked by default).
* Trailer / several vehicle profiles: one profile until it's needed.
+100 -7
View File
@@ -29,6 +29,7 @@ module Maptool
class NotFound < StandardError; end class NotFound < StandardError; end
class InvalidPath < StandardError; end class InvalidPath < StandardError; end
class ParseError < StandardError; end class ParseError < StandardError; end
class InvalidValue < StandardError; end
ROOT = "root" # folder id in a node key for items with no folder ROOT = "root" # folder id in a node key for items with no folder
EXTENSIONS = %w[.gpx .fit .geojson].freeze EXTENSIONS = %w[.gpx .fit .geojson].freeze
@@ -56,6 +57,7 @@ module Maptool
CREATE INDEX IF NOT EXISTS items_folder ON items(folder_id); CREATE INDEX IF NOT EXISTS items_folder ON items(folder_id);
CREATE INDEX IF NOT EXISTS items_parent ON items(parent_id); CREATE INDEX IF NOT EXISTS items_parent ON items(parent_id);
CREATE INDEX IF NOT EXISTS items_rev ON items(rev); CREATE INDEX IF NOT EXISTS items_rev ON items(rev);
CREATE INDEX IF NOT EXISTS items_fingerprint ON items(folder_id, fingerprint);
CREATE INDEX IF NOT EXISTS folders_rev ON folders(rev); CREATE INDEX IF NOT EXISTS folders_rev ON folders(rev);
SQL SQL
end end
@@ -90,7 +92,7 @@ module Maptool
[db.execute("SELECT id, parent_id, name FROM folders WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE"), [db.execute("SELECT id, parent_id, name FROM folders WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE"),
db.execute(<<~SQL)] db.execute(<<~SQL)]
SELECT id, folder_id, parent_id, type, name, source_path, SELECT id, folder_id, parent_id, type, name, source_path,
CASE WHEN type = 'layer' THEN properties END CASE WHEN type IN ('layer', 'track', 'route') THEN properties END
FROM items WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE FROM items WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE
SQL SQL
end end
@@ -104,9 +106,10 @@ module Maptool
end end
own = items_in[id] || [] own = items_in[id] || []
nodes = own.select { |i| %w[track route layer].include?(i[3]) }.map do |iid, _, _, type, name, source, props| nodes = own.select { |i| %w[track route layer].include?(i[3]) }.map do |iid, _, _, type, name, source, props|
kinds = type == "layer" ? JSON.parse(props)["kinds"] || [] : [type, *("waypoint" if has_children.include?(iid))] props = JSON.parse(props)
kinds = type == "layer" ? props["kinds"] || [] : [type, *("waypoint" if has_children.include?(iid))]
{ "type" => "file", "path" => "item:#{iid}", "name" => name.to_s.empty? ? type.capitalize : name, { "type" => "file", "path" => "item:#{iid}", "name" => name.to_s.empty? ? type.capitalize : name,
"kinds" => kinds, "original" => !source.nil? } "kinds" => kinds, "original" => !source.nil?, "layer" => type == "layer", "color" => props["color"] }.compact
end end
loose = own.count { |i| %w[point shape].include?(i[3]) && i[2].nil? } loose = own.count { |i| %w[point shape].include?(i[3]) && i[2].nil? }
if loose.positive? if loose.positive?
@@ -140,9 +143,9 @@ module Maptool
rows = connect do |db| rows = connect do |db|
case kind case kind
when "item" when "item"
item = db.get_first_row("SELECT type, source_path FROM items WHERE id = ? AND deleted_at IS NULL", [id]) item = db.get_first_row("SELECT type, source_path, properties FROM items WHERE id = ? AND deleted_at IS NULL", [id])
raise NotFound unless item raise NotFound unless item
return @gpx_store.geojson(item[1]) if item[0] == "layer" return layer_geojson(item[1], JSON.parse(item[2])["color"]) if item[0] == "layer"
db.execute("#{FEATURE_SQL} AND (id = ? OR parent_id = ?) ORDER BY parent_id IS NOT NULL", [id, id]) db.execute("#{FEATURE_SQL} AND (id = ? OR parent_id = ?) ORDER BY parent_id IS NOT NULL", [id, id])
when "points" when "points"
@@ -192,6 +195,47 @@ module Maptool
add_features([feature], folder).first add_features([feature], folder).first
end end
# Rename and/or recolor a track, route or layer (nil leaves it as is,
# an empty color goes back to the default).
def update_node(key, name: nil, color: nil)
kind, id = key.to_s.split(":", 2)
raise NotFound unless kind == "item"
raise InvalidValue if color && !color.empty? && !color.match?(/\A#\h{6}\z/)
raise InvalidValue if name && name.strip.empty?
write do |db, rev, now|
row = db.get_first_row("SELECT name, properties FROM items WHERE id = ? AND type IN ('track', 'route', 'layer') AND deleted_at IS NULL", [id])
raise NotFound unless row
props = JSON.parse(row[1])
props = color.empty? ? props.except("color") : props.merge("color" => color) if color
db.execute("UPDATE items SET name = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?",
[name ? name.strip : row[0], JSON.generate(props), now, rev, id])
end
end
# A migrated layer → ordinary items in its folder (its notes included,
# keeping their ids), the legacy file copied as their original. The
# layer is tombstoned; data/gpx/ itself stays untouched.
def split_layer(key)
kind, id = key.to_s.split(":", 2)
row = connect { |db| db.get_first_row("SELECT folder_id, source_path, properties FROM items WHERE id = ? AND type = 'layer' AND deleted_at IS NULL", [id]) }
raise NotFound unless kind == "item" && row
folder, legacy, props = row
features = begin
JSON.parse(layer_geojson(legacy, JSON.parse(props)["color"]))["features"]
rescue Gpx::ParseError, Fit::ParseError, JSON::ParserError => e
raise ParseError, e.message
end
relative = File.join(SecureRandom.uuid, File.basename(legacy))
FileUtils.mkdir_p(File.join(@sources_dir, File.dirname(relative)))
FileUtils.cp(@gpx_store.resolve_file(legacy), File.join(@sources_dir, relative))
keys = add_features(features, folder, source: relative, by_id: true)
write { |db, rev, now| tombstone(db, "id = ?", [id], rev, now) }
keys
end
# Edit/delete one feature of a node (a note's popup). A layer's notes # Edit/delete one feature of a node (a note's popup). A layer's notes
# still live in its legacy .geojson file, so those go to GpxStore. # still live in its legacy .geojson file, so those go to GpxStore.
def update_feature(key, id, feature) def update_feature(key, id, feature)
@@ -275,6 +319,40 @@ module Maptool
end end
end end
# Returns the folder's new path.
def rename_folder(path, name)
name = name.to_s.strip
raise InvalidPath if name.empty? || name.include?("/") || %w[. ..].include?(name)
id = folder_id(path, create: false) or raise NotFound
write do |db, rev, now|
parent = db.get_first_value("SELECT parent_id FROM folders WHERE id = ?", [id])
raise InvalidValue if sibling?(db, parent, name, id)
db.execute("UPDATE folders SET name = ?, updated_at = ?, rev = ? WHERE id = ?", [name, now, rev, id])
end
[*path.split("/")[0...-1], name].join("/")
end
# Into `to_folder` ("" = top level); returns the folder's new path.
def move_folder(path, to_folder)
id = folder_id(path, create: false) or raise NotFound
target = folder_id(to_folder, create: true)
write do |db, rev, now|
ancestor = target
while ancestor
raise InvalidPath if ancestor == id # into itself or its own subfolder
ancestor = db.get_first_value("SELECT parent_id FROM folders WHERE id = ?", [ancestor])
end
name = db.get_first_value("SELECT name FROM folders WHERE id = ?", [id])
raise InvalidValue if sibling?(db, target, name, id)
db.execute("UPDATE folders SET parent_id = ?, updated_at = ?, rev = ? WHERE id = ?", [target, now, rev, id])
end
[*to_folder.to_s.split("/").map(&:strip).reject(&:empty?), path.split("/").last].join("/")
end
# "a/b" → folder id (nil for the top level), created along the way if # "a/b" → folder id (nil for the top level), created along the way if
# `create`; nil when it doesn't exist and isn't created. # `create`; nil when it doesn't exist and isn't created.
def folder_id(path, create:) def folder_id(path, create:)
@@ -307,6 +385,20 @@ module Maptool
id == ROOT ? nil : id id == ROOT ? nil : id
end end
def sibling?(db, parent, name, except)
db.get_first_value("SELECT 1 FROM folders WHERE parent_id IS ? AND name = ? AND id != ? AND deleted_at IS NULL", [parent, name, except])
end
# A layer's legacy GeoJSON with its node color on the lines.
def layer_geojson(source, color)
body = @gpx_store.geojson(source)
return body unless color
data = JSON.parse(body)
data["features"].each { |f| f["properties"] = (f["properties"] || {}).merge("color" => color) unless f.dig("geometry", "type") == "Point" }
JSON.generate(data)
end
def layer_source(key) def layer_source(key)
kind, id = key.to_s.split(":", 2) kind, id = key.to_s.split(":", 2)
return nil unless kind == "item" return nil unless kind == "item"
@@ -338,8 +430,9 @@ module Maptool
end end
end end
def add_features(features, folder, source: nil) # `folder` is a path, or with by_id: true already an id (nil = top).
target = folder_id(folder, create: true) def add_features(features, folder, source: nil, by_id: false)
target = by_id ? folder : folder_id(folder, create: true)
features = features.select { |f| f.is_a?(Hash) && f.dig("geometry", "coordinates").is_a?(Array) } features = features.select { |f| f.is_a?(Hash) && f.dig("geometry", "coordinates").is_a?(Array) }
lines = features.count { |f| %w[track route].include?(item_type(f)) } lines = features.count { |f| %w[track route].include?(item_type(f)) }
parent = nil parent = nil
+10
View File
@@ -940,6 +940,10 @@ html, body {
width: calc(100% - 18px); width: calc(100% - 18px);
} }
.gpx-tree__folder-row > :first-child {
flex: 1;
}
.gpx-tree summary.gpx-drop-hover { .gpx-tree summary.gpx-drop-hover {
background: #eef5fd; background: #eef5fd;
outline: 1px dashed #4a90d9; outline: 1px dashed #4a90d9;
@@ -1022,6 +1026,7 @@ html, body {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
padding: 4px; padding: 4px;
font-size: 13px; font-size: 13px;
font-weight: normal;
} }
.gpx-tree__download-menu[hidden] { .gpx-tree__download-menu[hidden] {
@@ -1030,6 +1035,11 @@ html, body {
.gpx-tree__download-menu-item { .gpx-tree__download-menu-item {
display: block; display: block;
width: 100%;
border: none;
background: none;
font: inherit;
text-align: left;
padding: 6px 10px; padding: 6px 10px;
border-radius: 4px; border-radius: 4px;
color: inherit; color: inherit;
+129 -29
View File
@@ -30,6 +30,7 @@ const BADGE_IMAGE_PREFIX = "badge-"; // one registered image per distinct badge
// folders, as opposed to an OS file drag (type "Files") for uploading a new // folders, as opposed to an OS file drag (type "Files") for uploading a new
// one — both land on the same drop targets, told apart by this. // one — both land on the same drop targets, told apart by this.
const MOVE_MIME = "application/x-gpx-path"; const MOVE_MIME = "application/x-gpx-path";
const FOLDER_DRAG_PREFIX = "folder:"; // a dragged folder's MOVE_MIME payload, vs. a node key
// A sidebar icon that opens a side panel for uploading GPX files (via // A sidebar icon that opens a side panel for uploading GPX files (via
// drag & drop, stored server-side in a folder hierarchy the user can add to // drag & drop, stored server-side in a folder hierarchy the user can add to
@@ -278,7 +279,16 @@ export class GpxPanelControl {
const name = document.createElement("span"); const name = document.createElement("span");
name.textContent = folder.name; name.textContent = folder.name;
row.appendChild(name); row.appendChild(name);
if (isLoggedIn()) row.appendChild(this._deleteButton(() => this._deleteFolder(folder.path))); if (isLoggedIn()) {
row.appendChild(this._menuButton("⋯", "Edit", [{ label: "Rename…", run: () => this._renameFolder(folder) }]));
row.appendChild(this._deleteButton(() => this._deleteFolder(folder.path)));
// Dragged onto another folder (or the tree's blank space) moves it.
summary.draggable = true;
summary.addEventListener("dragstart", (event) => {
event.dataTransfer.setData(MOVE_MIME, `${FOLDER_DRAG_PREFIX}${folder.path}`);
event.dataTransfer.effectAllowed = "move";
});
}
summary.appendChild(row); summary.appendChild(row);
this._wireFolderDropTarget(summary, folder.path); this._wireFolderDropTarget(summary, folder.path);
@@ -314,6 +324,8 @@ export class GpxPanelControl {
// rather than shown-but-failing-on-click. // rather than shown-but-failing-on-click.
if (loggedIn) { if (loggedIn) {
row.appendChild(this._downloadButton(file)); row.appendChild(this._downloadButton(file));
// A folder's "Points (N)" node has no name or color of its own.
if (file.path.startsWith("item:")) row.appendChild(this._editButton(file));
row.appendChild(this._deleteButton(() => this._deleteFile(file))); row.appendChild(this._deleteButton(() => this._deleteFile(file)));
} }
@@ -338,35 +350,60 @@ export class GpxPanelControl {
// One button, one obvious place for both download kinds — clicking it // One button, one obvious place for both download kinds — clicking it
// opens a small menu (Original / GeoJSON) instead of splitting them // opens a small menu (Original / GeoJSON) instead of splitting them
// across two differently-shaped click targets (the file name used to be // across two differently-shaped click targets.
// a GeoJSON-only download link; easy to miss it was a link at all, and
// it only ever covered half the story). Costs a click for the common
// case of downloading several files in a row, in exchange for both
// formats actually being reachable from one, discoverable place.
_downloadButton(file) { _downloadButton(file) {
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`;
return this._menuButton(DOWNLOAD_ICON, "Download", [
// A folder's loose points have no single file they came from.
file.original && { label: "Original file", run: () => this._download(`${gpxFileUrl(file.path)}?download=original`, file.name) },
{ label: "GeoJSON", run: () => this._download(geojsonUrl, `${file.name}.geojson`) },
]);
}
_editButton(file) {
return this._menuButton("⋯", "Edit", [
{ label: "Rename…", run: () => this._renameFile(file) },
{ label: "Color…", run: () => this._pickColor(file) },
file.color && { label: "Default color", run: () => this._patchNode(file.path, { color: "" }) },
file.layer && { label: "Split into items", run: () => this._splitLayer(file) },
]);
}
// A button opening a small menu of `entries` ({ label, run }, falsy ones
// skipped).
_menuButton(content, title, entries) {
const wrapper = document.createElement("span"); const wrapper = document.createElement("span");
wrapper.className = "gpx-tree__download-wrapper"; wrapper.className = "gpx-tree__download-wrapper";
const button = document.createElement("button"); const button = document.createElement("button");
button.type = "button"; button.type = "button";
button.className = "gpx-tree__download"; button.className = "gpx-tree__download";
button.title = "Download"; button.title = title;
button.setAttribute("aria-label", "Download"); button.setAttribute("aria-label", title);
button.innerHTML = DOWNLOAD_ICON; button.innerHTML = content;
const menu = document.createElement("div"); const menu = document.createElement("div");
menu.className = "gpx-tree__download-menu"; menu.className = "gpx-tree__download-menu";
menu.hidden = true; menu.hidden = true;
// A folder's loose points have no single file they came from. entries.filter(Boolean).forEach(({ label, run }) => {
if (file.original) menu.appendChild(this._downloadMenuItem("Original file", `${gpxFileUrl(file.path)}?download=original`, file.name)); const item = document.createElement("button");
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`; item.type = "button";
menu.appendChild(this._downloadMenuItem("GeoJSON", geojsonUrl, `${file.name}.geojson`)); item.className = "gpx-tree__download-menu-item";
item.textContent = label;
item.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
this._closeDownloadMenu();
run();
});
menu.appendChild(item);
});
// stopPropagation so this click doesn't immediately reach the // stopPropagation so this click doesn't immediately reach the
// document-level listener (mount()) that closes whichever menu is // document-level listener (mount()) that closes whichever menu is
// open on an outside click — otherwise it would close right back up // open on an outside click, nor toggle a folder's <details>.
// the instant it opened.
button.addEventListener("click", (event) => { button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation(); event.stopPropagation();
this._toggleDownloadMenu(menu); this._toggleDownloadMenu(menu);
}); });
@@ -376,19 +413,6 @@ export class GpxPanelControl {
return wrapper; return wrapper;
} }
_downloadMenuItem(label, url, filename) {
const item = document.createElement("a");
item.className = "gpx-tree__download-menu-item";
item.href = url;
item.textContent = label;
item.addEventListener("click", (event) => {
event.preventDefault();
this._closeDownloadMenu();
this._download(url, filename);
});
return item;
}
// Only one menu open at a time — opening a second one closes whichever // Only one menu open at a time — opening a second one closes whichever
// was already open, same as onlyOneSidePanelOpen does for the sidebar's // was already open, same as onlyOneSidePanelOpen does for the sidebar's
// own panels (panels.js), just scoped to this one control instead of // own panels (panels.js), just scoped to this one control instead of
@@ -557,7 +581,7 @@ export class GpxPanelControl {
source: linesId, source: linesId,
filter: ["any", ["!has", "category"], ["!=", ["get", "category"], "Note"]], filter: ["any", ["!has", "category"], ["!=", ["get", "category"], "Note"]],
layout: { "line-cap": "round", "line-join": "round" }, layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": TRACK_COLOR, "line-width": 3 }, paint: { "line-color": ["coalesce", ["get", "color"], TRACK_COLOR], "line-width": 3 },
}); });
this._registerLineInteractivity(`${linesId}-line`); this._registerLineInteractivity(`${linesId}-line`);
@@ -1025,6 +1049,10 @@ export class GpxPanelControl {
} }
async _moveFile(from, toFolder) { async _moveFile(from, toFolder) {
if (from.startsWith(FOLDER_DRAG_PREFIX)) {
await this._patchFolder(from.slice(FOLDER_DRAG_PREFIX.length), { to_folder: toFolder });
return;
}
const response = await fetch(MOVE_URL, { const response = await fetch(MOVE_URL, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" }, headers: { "Content-Type": "application/x-www-form-urlencoded" },
@@ -1043,6 +1071,78 @@ export class GpxPanelControl {
this._renderTree(tree); this._renderTree(tree);
} }
async _renameFolder(folder) {
const name = window.prompt("Rename folder:", folder.name);
if (name && name.trim() && name.trim() !== folder.name) await this._patchFolder(folder.path, { name: name.trim() });
}
// Node keys are ids, so nothing shown on the map changes with its folder.
async _patchFolder(path, fields) {
const response = await fetch(`${FOLDER_URL}/${path.split("/").map(encodeURIComponent).join("/")}`, {
method: "PATCH",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(fields),
});
if (redirectIfUnauthorized(response)) return;
if (response.status === 409) window.alert("A folder with that name already exists there.");
if (!response.ok) return;
this._renderTree((await response.json()).tree);
}
async _renameFile(file) {
const name = window.prompt("Rename:", file.name);
if (name && name.trim() && name.trim() !== file.name) await this._patchNode(file.path, { name: name.trim() });
}
// The native color picker; one hidden input reused for every node.
_pickColor(file) {
if (!this._colorInput) {
this._colorInput = document.createElement("input");
this._colorInput.type = "color";
this._colorInput.hidden = true;
this._panel.appendChild(this._colorInput);
this._colorInput.addEventListener("change", () => this._patchNode(this._colorInput.dataset.path, { color: this._colorInput.value }));
}
this._colorInput.dataset.path = file.path;
this._colorInput.value = file.color || TRACK_COLOR;
this._colorInput.click();
}
async _patchNode(path, fields) {
const response = await fetch(gpxFileUrl(path), {
method: "PATCH",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(fields),
});
if (redirectIfUnauthorized(response)) return;
if (!response.ok) return;
this._renderTree((await response.json()).tree);
if (this._visible.has(path)) {
this._removeLayers(path);
await this._addLayers(path);
}
}
async _splitLayer(file) {
if (!window.confirm(`Split "${file.name}" into separate points and tracks? This can't be undone.`)) return;
this._setStatus("Splitting…");
const response = await fetch(`${gpxFileUrl(file.path)}/split`, { method: "POST" });
if (redirectIfUnauthorized(response)) return;
if (!response.ok) {
this._setStatus("Split failed.");
return;
}
const { paths, tree } = await response.json();
this._renderTree(tree);
this._setStatus("Split.");
if (this._visible.has(file.path)) {
this._visible.delete(file.path);
this._removeLayers(file.path);
await Promise.all(paths.map((path) => this.show(path)));
}
}
_setStatus(text) { _setStatus(text) {
this._uploadStatus.hidden = false; this._uploadStatus.hidden = false;
this._uploadStatus.textContent = text; this._uploadStatus.textContent = text;
+14
View File
@@ -216,6 +216,20 @@ class AppTest < Minitest::Test
assert_equal 404, request.get(node_url(key)).status assert_equal 404, request.get(node_url(key)).status
end end
def test_renaming_a_node_and_a_folder_needs_login
key = json_body(upload("ride.gpx", File.read(fixture_path("sample.gpx")), folder: "trips"))["paths"].first
assert_equal 401, request.patch(node_url(key), params: { name: "x" }).status
renamed = request.patch(node_url(key), params: { name: "Evening", color: "#123456" }, **logged_in_env)
assert_equal [["Evening", "#123456"]], json_body(renamed)["tree"]["children"][0]["children"].map { |c| c.values_at("name", "color") }
assert_equal 400, request.patch(node_url(key), params: { color: "red" }, **logged_in_env).status
folder = request.patch("/api/library/folder/trips", params: { name: "2026", to_folder: "Van" }, **logged_in_env)
assert_equal "Van/2026", json_body(folder)["path"]
request.post("/api/library/folder?path=Bus", **logged_in_env)
assert_equal 409, request.patch("/api/library/folder/Van", params: { name: "Bus" }, **logged_in_env).status
end
def test_invalid_folder_path_is_rejected def test_invalid_folder_path_is_rejected
assert_equal 400, request.post("/api/library/folder?path=..%2F..%2Fescape", **logged_in_env).status assert_equal 400, request.post("/api/library/folder?path=..%2F..%2Fescape", **logged_in_env).status
end end
+45
View File
@@ -85,6 +85,51 @@ class LibraryTest < Minitest::Test
assert_raises(Maptool::Library::InvalidPath) { library.create_folder("../x") } assert_raises(Maptool::Library::InvalidPath) { library.create_folder("../x") }
end end
def test_renaming_and_recoloring_a_track_and_a_layer
@store.save(folder: "", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx")))
library = open_library
layer = library.tree["children"].first["children"].first["path"]
track = library.import(folder: "t", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx"))).first
library.update_node(track, name: "Morning ride", color: "#00ff00")
library.update_node(layer, color: "#0000ff")
nodes = library.tree["children"].flat_map { |f| f["children"].flat_map { |c| c["children"] || [c] } }
assert_includes nodes.map { |n| n.values_at("name", "color") }, ["Morning ride", "#00ff00"]
lines = JSON.parse(library.geojson(layer))["features"].reject { |f| f["geometry"]["type"] == "Point" }
assert_equal ["#0000ff"], lines.map { |f| f["properties"]["color"] }.uniq
library.update_node(track, color: "")
assert_nil JSON.parse(library.geojson(track))["features"].first["properties"]["color"]
assert_raises(Maptool::Library::InvalidValue) { library.update_node(track, color: "red") }
end
def test_splitting_a_layer_turns_it_into_items_and_keeps_note_ids
@store.append_feature(feature: note("Gate", "n1"), folder: "", name: "My Notes")
library = open_library
folder = library.tree["children"].first
key = folder["children"].first["path"]
keys = library.split_layer(key)
assert_equal ["Points (1)"], library.tree["children"].first["children"].map { |c| c["name"] }
assert_equal ["n1"], JSON.parse(library.geojson(keys.first))["features"].map { |f| f["properties"]["id"] }
assert_equal ["My Notes.geojson"], Dir.glob("*/*", base: File.join(@dir, "sources")).map { |f| File.basename(f) }
assert_raises(Maptool::Library::NotFound) { library.geojson(key) }
end
def test_renaming_and_moving_folders
library = open_library
key = library.add_note(note("Gate"), "a/b")
library.create_folder("c")
assert_equal "a/x", library.rename_folder("a/b", "x")
assert_equal "c/x", library.move_folder("a/x", "c")
assert_equal ["a", "c"], library.tree["children"].map { |f| f["name"] }
assert_equal ["Gate"], JSON.parse(library.geojson(key))["features"].map { |f| f["properties"]["name"] }
assert_raises(Maptool::Library::InvalidPath) { library.move_folder("c", "c/x") }
library.create_folder("a/x")
assert_raises(Maptool::Library::InvalidValue) { library.move_folder("c/x", "a") }
end
private private
def open_library def open_library