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

+100 -7
View File
@@ -29,6 +29,7 @@ module Maptool
class NotFound < StandardError; end
class InvalidPath < StandardError; end
class ParseError < StandardError; end
class InvalidValue < StandardError; end
ROOT = "root" # folder id in a node key for items with no folder
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_parent ON items(parent_id);
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);
SQL
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(<<~SQL)]
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
SQL
end
@@ -104,9 +106,10 @@ module Maptool
end
own = items_in[id] || []
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,
"kinds" => kinds, "original" => !source.nil? }
"kinds" => kinds, "original" => !source.nil?, "layer" => type == "layer", "color" => props["color"] }.compact
end
loose = own.count { |i| %w[point shape].include?(i[3]) && i[2].nil? }
if loose.positive?
@@ -140,9 +143,9 @@ module Maptool
rows = connect do |db|
case kind
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
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])
when "points"
@@ -192,6 +195,47 @@ module Maptool
add_features([feature], folder).first
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
# still live in its legacy .geojson file, so those go to GpxStore.
def update_feature(key, id, feature)
@@ -275,6 +319,40 @@ module Maptool
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
# `create`; nil when it doesn't exist and isn't created.
def folder_id(path, create:)
@@ -307,6 +385,20 @@ module Maptool
id == ROOT ? nil : id
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)
kind, id = key.to_s.split(":", 2)
return nil unless kind == "item"
@@ -338,8 +430,9 @@ module Maptool
end
end
def add_features(features, folder, source: nil)
target = folder_id(folder, create: true)
# `folder` is a path, or with by_id: true already an id (nil = top).
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) }
lines = features.count { |f| %w[track route].include?(item_type(f)) }
parent = nil